summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Help/command/LINK_OPTIONS_LINKER.txt22
-rw-r--r--Help/command/OPTIONS_SHELL.txt9
-rw-r--r--Help/command/add_compile_definitions.rst23
-rw-r--r--Help/command/add_link_options.rst31
-rw-r--r--Help/command/include_guard.rst46
-rw-r--r--Help/command/target_link_directories.rst55
-rw-r--r--Help/command/target_link_options.rst48
-rw-r--r--Help/cpack_gen/archive.rst35
-rw-r--r--Help/cpack_gen/bundle.rst66
-rw-r--r--Help/cpack_gen/cygwin.rst23
-rw-r--r--Help/cpack_gen/deb.rst557
-rw-r--r--Help/cpack_gen/dmg.rst101
-rw-r--r--Help/cpack_gen/external.rst283
-rw-r--r--Help/cpack_gen/freebsd.rst138
-rw-r--r--Help/cpack_gen/ifw.rst339
-rw-r--r--Help/cpack_gen/nsis.rst130
-rw-r--r--Help/cpack_gen/nuget.rst189
-rw-r--r--Help/cpack_gen/packagemaker.rst23
-rw-r--r--Help/cpack_gen/productbuild.rst68
-rw-r--r--Help/cpack_gen/rpm.rst955
-rw-r--r--Help/cpack_gen/wix.rst284
-rw-r--r--Help/dev/documentation.rst530
-rw-r--r--Help/envvar/ASM_DIALECT.rst14
-rw-r--r--Help/envvar/ASM_DIALECTFLAGS.rst13
-rw-r--r--Help/envvar/CC.rst11
-rw-r--r--Help/envvar/CFLAGS.rst11
-rw-r--r--Help/envvar/CMAKE_BUILD_PARALLEL_LEVEL.rst11
-rw-r--r--Help/envvar/CMAKE_CONFIG_TYPE.rst7
-rw-r--r--Help/envvar/CMAKE_GENERATOR.rst16
-rw-r--r--Help/envvar/CMAKE_GENERATOR_INSTANCE.rst7
-rw-r--r--Help/envvar/CMAKE_GENERATOR_PLATFORM.rst8
-rw-r--r--Help/envvar/CMAKE_GENERATOR_TOOLSET.rst8
-rw-r--r--Help/envvar/CMAKE_MSVCIDE_RUN_PATH.rst10
-rw-r--r--Help/envvar/CMAKE_NO_VERBOSE.rst8
-rw-r--r--Help/envvar/CMAKE_OSX_ARCHITECTURES.rst10
-rw-r--r--Help/envvar/CSFLAGS.rst11
-rw-r--r--Help/envvar/CTEST_INTERACTIVE_DEBUG_MODE.rst7
-rw-r--r--Help/envvar/CTEST_OUTPUT_ON_FAILURE.rst9
-rw-r--r--Help/envvar/CTEST_PARALLEL_LEVEL.rst7
-rw-r--r--Help/envvar/CTEST_PROGRESS_OUTPUT.rst16
-rw-r--r--Help/envvar/CTEST_USE_LAUNCHERS_DEFAULT.rst6
-rw-r--r--Help/envvar/CUDACXX.rst11
-rw-r--r--Help/envvar/CUDAFLAGS.rst11
-rw-r--r--Help/envvar/CUDAHOSTCXX.rst15
-rw-r--r--Help/envvar/CXX.rst11
-rw-r--r--Help/envvar/CXXFLAGS.rst11
-rw-r--r--Help/envvar/DASHBOARD_TEST_FROM_CTEST.rst8
-rw-r--r--Help/envvar/DESTDIR.rst21
-rw-r--r--Help/envvar/ENV_VAR.txt3
-rw-r--r--Help/envvar/FC.rst12
-rw-r--r--Help/envvar/FFLAGS.rst11
-rw-r--r--Help/envvar/LDFLAGS.rst12
-rw-r--r--Help/envvar/MACOSX_DEPLOYMENT_TARGET.rst10
-rw-r--r--Help/envvar/PackageName_ROOT.rst17
-rw-r--r--Help/envvar/RC.rst11
-rw-r--r--Help/envvar/RCFLAGS.rst11
-rw-r--r--Help/envvar/SWIFTC.rst11
-rw-r--r--Help/envvar/VERBOSE.rst10
-rw-r--r--Help/generator/Visual Studio 16 2019.rst54
-rw-r--r--Help/manual/cmake-env-variables.7.rst73
-rw-r--r--Help/manual/cmake-file-api.7.rst1113
-rw-r--r--Help/manual/cpack-generators.7.rst29
-rw-r--r--Help/module/CPackFreeBSD.rst4
-rw-r--r--Help/module/CPackNuGet.rst4
-rw-r--r--Help/module/CheckFortranSourceRuns.rst1
-rw-r--r--Help/module/CheckPIESupported.rst1
-rw-r--r--Help/module/FetchContent.rst1
-rw-r--r--Help/module/FindEnvModules.rst1
-rw-r--r--Help/module/FindFontconfig.rst1
-rw-r--r--Help/module/FindIconv.rst1
-rw-r--r--Help/module/FindLibinput.rst1
-rw-r--r--Help/module/FindODBC.rst1
-rw-r--r--Help/module/FindOpenACC.rst1
-rw-r--r--Help/module/FindPatch.rst1
-rw-r--r--Help/module/FindPython.rst1
-rw-r--r--Help/module/FindPython2.rst1
-rw-r--r--Help/module/FindPython3.rst1
-rw-r--r--Help/module/FindSQLite3.rst1
-rw-r--r--Help/policy/CMP0070.rst25
-rw-r--r--Help/policy/CMP0071.rst42
-rw-r--r--Help/policy/CMP0072.rst26
-rw-r--r--Help/policy/CMP0073.rst25
-rw-r--r--Help/policy/CMP0074.rst23
-rw-r--r--Help/policy/CMP0075.rst26
-rw-r--r--Help/policy/CMP0076.rst26
-rw-r--r--Help/policy/CMP0077.rst52
-rw-r--r--Help/policy/CMP0078.rst24
-rw-r--r--Help/policy/CMP0079.rst40
-rw-r--r--Help/policy/CMP0080.rst25
-rw-r--r--Help/policy/CMP0081.rst22
-rw-r--r--Help/policy/CMP0082.rst26
-rw-r--r--Help/policy/CMP0083.rst69
-rw-r--r--Help/policy/CMP0084.rst26
-rw-r--r--Help/policy/CMP0085.rst21
-rw-r--r--Help/policy/CMP0086.rst20
-rw-r--r--Help/policy/CMP0087.rst29
-rw-r--r--Help/policy/CMP0088.rst29
-rw-r--r--Help/policy/CMP0089.rst30
-rw-r--r--Help/policy/CMP0090.rst27
-rw-r--r--Help/policy/CMP0091.rst49
-rw-r--r--Help/policy/CMP0092.rst38
-rw-r--r--Help/policy/CMP0093.rst24
-rw-r--r--Help/policy/CMP0094.rst22
-rw-r--r--Help/prop_dir/ADDITIONAL_CLEAN_FILES.rst21
-rw-r--r--Help/prop_dir/LABELS.rst13
-rw-r--r--Help/prop_dir/LINK_OPTIONS.rst17
-rw-r--r--Help/prop_dir/TESTS.rst8
-rw-r--r--Help/prop_dir/TEST_INCLUDE_FILES.rst7
-rw-r--r--Help/prop_gbl/CMAKE_ROLE.rst20
-rw-r--r--Help/prop_gbl/ECLIPSE_EXTRA_CPROJECT_CONTENTS.rst12
-rw-r--r--Help/prop_sf/COMPILE_OPTIONS.rst21
-rw-r--r--Help/prop_sf/INCLUDE_DIRECTORIES.rst18
-rw-r--r--Help/prop_sf/Swift_DEPENDENCIES_FILE.rst5
-rw-r--r--Help/prop_sf/Swift_DIAGNOSTICS_FILE.rst4
-rw-r--r--Help/prop_sf/VS_SHADER_DISABLE_OPTIMIZATIONS.rst6
-rw-r--r--Help/prop_sf/VS_SHADER_ENABLE_DEBUG.rst6
-rw-r--r--Help/prop_sf/VS_SHADER_OBJECT_FILE_NAME.rst6
-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/PROCESSOR_AFFINITY.rst11
-rw-r--r--Help/prop_tgt/ADDITIONAL_CLEAN_FILES.rst23
-rw-r--r--Help/prop_tgt/AUTOGEN_ORIGIN_DEPENDS.rst38
-rw-r--r--Help/prop_tgt/AUTOGEN_PARALLEL.rst21
-rw-r--r--Help/prop_tgt/AUTOMOC_COMPILER_PREDEFINES.rst24
-rw-r--r--Help/prop_tgt/AUTOMOC_EXECUTABLE.rst15
-rw-r--r--Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst32
-rw-r--r--Help/prop_tgt/AUTORCC_EXECUTABLE.rst15
-rw-r--r--Help/prop_tgt/AUTOUIC_EXECUTABLE.rst15
-rw-r--r--Help/prop_tgt/BUILD_RPATH_USE_ORIGIN.rst24
-rw-r--r--Help/prop_tgt/COMMON_LANGUAGE_RUNTIME.rst22
-rw-r--r--Help/prop_tgt/DEPLOYMENT_ADDITIONAL_FILES.rst18
-rw-r--r--Help/prop_tgt/DOTNET_TARGET_FRAMEWORK_VERSION.rst13
-rw-r--r--Help/prop_tgt/EXPORT_PROPERTIES.rst14
-rw-r--r--Help/prop_tgt/GHS_INTEGRITY_APP.rst10
-rw-r--r--Help/prop_tgt/GHS_NO_SOURCE_GROUP_FILE.rst13
-rw-r--r--Help/prop_tgt/IMPORTED_COMMON_LANGUAGE_RUNTIME.rst8
-rw-r--r--Help/prop_tgt/IMPORTED_GLOBAL.rst22
-rw-r--r--Help/prop_tgt/INTERFACE_LINK_DEPENDS.rst32
-rw-r--r--Help/prop_tgt/INTERFACE_LINK_DIRECTORIES.rst9
-rw-r--r--Help/prop_tgt/INTERFACE_LINK_OPTIONS.rst9
-rw-r--r--Help/prop_tgt/LANG_CPPCHECK.rst15
-rw-r--r--Help/prop_tgt/LINK_DIRECTORIES.rst18
-rw-r--r--Help/prop_tgt/LINK_LIBRARIES_INDIRECTION.txt10
-rw-r--r--Help/prop_tgt/LINK_OPTIONS.rst24
-rw-r--r--Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt20
-rw-r--r--Help/prop_tgt/MSVC_RUNTIME_LIBRARY.rst29
-rw-r--r--Help/prop_tgt/STATIC_LIBRARY_OPTIONS.rst20
-rw-r--r--Help/prop_tgt/Swift_DEPENDENCIES_FILE.rst5
-rw-r--r--Help/prop_tgt/Swift_MODULE_DIRECTORY.rst10
-rw-r--r--Help/prop_tgt/Swift_MODULE_NAME.rst5
-rw-r--r--Help/prop_tgt/VS_DEBUGGER_COMMAND.rst11
-rw-r--r--Help/prop_tgt/VS_DEBUGGER_COMMAND_ARGUMENTS.rst11
-rw-r--r--Help/prop_tgt/VS_DEBUGGER_ENVIRONMENT.rst11
-rw-r--r--Help/prop_tgt/VS_DOTNET_REFERENCEPROP_refname_TAG_tagname.rst14
-rw-r--r--Help/prop_tgt/VS_JUST_MY_CODE_DEBUGGING.rst10
-rw-r--r--Help/prop_tgt/VS_NO_SOLUTION_DEPLOY.rst46
-rw-r--r--Help/prop_tgt/VS_PACKAGE_REFERENCES.rst13
-rw-r--r--Help/prop_tgt/VS_PROJECT_IMPORT.rst8
-rw-r--r--Help/prop_tgt/XCODE_GENERATE_SCHEME.rst39
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_ADDRESS_SANITIZER.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_ARGUMENTS.rst10
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_DEBUG_AS_ROOT.rst7
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_ENVIRONMENT.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_EXECUTABLE.rst9
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_GUARD_MALLOC.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP.rst13
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_MALLOC_GUARD_EDGES.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_MALLOC_SCRIBBLE.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_MALLOC_STACK.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_THREAD_SANITIZER.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_THREAD_SANITIZER_STOP.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER.rst12
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP.rst13
-rw-r--r--Help/prop_tgt/XCODE_SCHEME_ZOMBIE_OBJECTS.rst12
-rw-r--r--Help/release/3.10.rst282
-rw-r--r--Help/release/3.11.rst307
-rw-r--r--Help/release/3.12.rst305
-rw-r--r--Help/release/3.13.rst289
-rw-r--r--Help/release/3.14.rst438
-rw-r--r--Help/release/3.15.rst387
-rw-r--r--Help/variable/CACHE.rst18
-rw-r--r--Help/variable/CMAKE_AUTOGEN_ORIGIN_DEPENDS.rst11
-rw-r--r--Help/variable/CMAKE_AUTOGEN_PARALLEL.rst10
-rw-r--r--Help/variable/CMAKE_AUTOGEN_VERBOSE.rst13
-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_BUILD_RPATH_USE_ORIGIN.rst7
-rw-r--r--Help/variable/CMAKE_CODEBLOCKS_COMPILER_ID.rst13
-rw-r--r--Help/variable/CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES.rst7
-rw-r--r--Help/variable/CMAKE_CPACK_COMMAND.rst8
-rw-r--r--Help/variable/CMAKE_CUDA_HOST_COMPILER.rst7
-rw-r--r--Help/variable/CMAKE_CUDA_SEPARABLE_COMPILATION.rst6
-rw-r--r--Help/variable/CMAKE_DIRECTORY_LABELS.rst6
-rw-r--r--Help/variable/CMAKE_DOTNET_TARGET_FRAMEWORK_VERSION.rst16
-rw-r--r--Help/variable/CMAKE_EXECUTE_PROCESS_COMMAND_ECHO.rst6
-rw-r--r--Help/variable/CMAKE_EXPORT_PACKAGE_REGISTRY.rst15
-rw-r--r--Help/variable/CMAKE_FIND_PACKAGE_PREFER_CONFIG.rst27
-rw-r--r--Help/variable/CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS.rst10
-rw-r--r--Help/variable/CMAKE_FOLDER.rst7
-rw-r--r--Help/variable/CMAKE_FRAMEWORK.rst7
-rw-r--r--Help/variable/CMAKE_GENERATOR_INSTANCE.rst25
-rw-r--r--Help/variable/CMAKE_GHS_NO_SOURCE_GROUP_FILE.rst6
-rw-r--r--Help/variable/CMAKE_GLOBAL_AUTOGEN_TARGET.rst26
-rw-r--r--Help/variable/CMAKE_GLOBAL_AUTOGEN_TARGET_NAME.rst13
-rw-r--r--Help/variable/CMAKE_GLOBAL_AUTORCC_TARGET.rst18
-rw-r--r--Help/variable/CMAKE_GLOBAL_AUTORCC_TARGET_NAME.rst13
-rw-r--r--Help/variable/CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS.rst29
-rw-r--r--Help/variable/CMAKE_JOB_POOLS.rst6
-rw-r--r--Help/variable/CMAKE_LANG_COMPILER_ARCHITECTURE_ID.rst8
-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_LANG_FLAGS_CONFIG.rst4
-rw-r--r--Help/variable/CMAKE_LANG_FLAGS_CONFIG_INIT.rst10
-rw-r--r--Help/variable/CMAKE_LANG_LINKER_WRAPPER_FLAG.rst39
-rw-r--r--Help/variable/CMAKE_LANG_LINKER_WRAPPER_FLAG_SEP.rst9
-rw-r--r--Help/variable/CMAKE_LINK_DIRECTORIES_BEFORE.rst9
-rw-r--r--Help/variable/CMAKE_MAXIMUM_RECURSION_DEPTH.rst33
-rw-r--r--Help/variable/CMAKE_MSVCIDE_RUN_PATH.rst10
-rw-r--r--Help/variable/CMAKE_MSVC_RUNTIME_LIBRARY.rst32
-rw-r--r--Help/variable/CMAKE_NETRC.rst9
-rw-r--r--Help/variable/CMAKE_NETRC_FILE.rst9
-rw-r--r--Help/variable/CMAKE_PROJECT_HOMEPAGE_URL.rst35
-rw-r--r--Help/variable/CMAKE_PROJECT_INCLUDE.rst9
-rw-r--r--Help/variable/CMAKE_PROJECT_INCLUDE_BEFORE.rst9
-rw-r--r--Help/variable/CMAKE_PROJECT_VERSION.rst35
-rw-r--r--Help/variable/CMAKE_PROJECT_VERSION_MAJOR.rst9
-rw-r--r--Help/variable/CMAKE_PROJECT_VERSION_MINOR.rst9
-rw-r--r--Help/variable/CMAKE_PROJECT_VERSION_PATCH.rst9
-rw-r--r--Help/variable/CMAKE_PROJECT_VERSION_TWEAK.rst9
-rw-r--r--Help/variable/CMAKE_RULE_MESSAGES.rst8
-rw-r--r--Help/variable/CMAKE_SUPPRESS_REGENERATION.rst11
-rw-r--r--Help/variable/CMAKE_Swift_MODULE_DIRECTORY.rst8
-rw-r--r--Help/variable/CMAKE_Swift_NUM_THREADS.rst8
-rw-r--r--Help/variable/CMAKE_VS_GLOBALS.rst21
-rw-r--r--Help/variable/CMAKE_VS_JUST_MY_CODE_DEBUGGING.rst8
-rw-r--r--Help/variable/CMAKE_VS_PLATFORM_NAME_DEFAULT.rst9
-rw-r--r--Help/variable/CMAKE_VS_PLATFORM_TOOLSET_VERSION.rst11
-rw-r--r--Help/variable/CMAKE_VS_SDK_EXCLUDE_DIRECTORIES.rst4
-rw-r--r--Help/variable/CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES.rst4
-rw-r--r--Help/variable/CMAKE_VS_SDK_INCLUDE_DIRECTORIES.rst4
-rw-r--r--Help/variable/CMAKE_VS_SDK_LIBRARY_DIRECTORIES.rst4
-rw-r--r--Help/variable/CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES.rst5
-rw-r--r--Help/variable/CMAKE_VS_SDK_REFERENCE_DIRECTORIES.rst4
-rw-r--r--Help/variable/CMAKE_VS_SDK_SOURCE_DIRECTORIES.rst4
-rw-r--r--Help/variable/CMAKE_VS_WINRT_BY_DEFAULT.rst8
-rw-r--r--Help/variable/CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY.rst9
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_GUARD_MALLOC.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP.rst13
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_MALLOC_GUARD_EDGES.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_MALLOC_SCRIBBLE.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_MALLOC_STACK.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_THREAD_SANITIZER.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_THREAD_SANITIZER_STOP.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER.rst12
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP.rst13
-rw-r--r--Help/variable/CMAKE_XCODE_SCHEME_ZOMBIE_OBJECTS.rst12
-rw-r--r--Help/variable/CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS.rst11
-rw-r--r--Help/variable/CTEST_CUSTOM_TESTS_IGNORE.rst7
-rw-r--r--Help/variable/CTEST_LABELS_FOR_SUBPROJECTS.rst5
-rw-r--r--Help/variable/CTEST_RUN_CURRENT_SCRIPT.rst5
-rw-r--r--Help/variable/CTEST_SUBMIT_URL.rst5
-rw-r--r--Help/variable/CTEST_UPDATE_VERSION_OVERRIDE.rst5
-rw-r--r--Help/variable/IOS.rst4
-rw-r--r--Help/variable/MSVC_TOOLSET_VERSION.rst22
-rw-r--r--Help/variable/MSYS.rst4
-rw-r--r--Help/variable/PROJECT-NAME_DESCRIPTION.rst5
-rw-r--r--Help/variable/PROJECT-NAME_HOMEPAGE_URL.rst5
-rw-r--r--Help/variable/PROJECT_HOMEPAGE_URL.rst9
-rw-r--r--Help/variable/PackageName_ROOT.rst14
-rw-r--r--Modules/BasicConfigVersion-SameMinorVersion.cmake.in55
-rw-r--r--Modules/CMakeFindSublimeText2.cmake23
-rw-r--r--Modules/CMakeInitializeConfigs.cmake39
-rw-r--r--Modules/CMakeParseImplicitIncludeInfo.cmake247
-rw-r--r--Modules/CPack.NuGet.nuspec.in24
-rw-r--r--Modules/CheckFortranSourceRuns.cmake175
-rw-r--r--Modules/CheckPIESupported.cmake134
-rw-r--r--Modules/Compiler/ARMClang-ASM.cmake9
-rw-r--r--Modules/Compiler/ARMClang-C-FeatureTests.cmake1
-rw-r--r--Modules/Compiler/ARMClang-C.cmake15
-rw-r--r--Modules/Compiler/ARMClang-CXX-FeatureTests.cmake1
-rw-r--r--Modules/Compiler/ARMClang-CXX.cmake3
-rw-r--r--Modules/Compiler/ARMClang-DetermineCompiler.cmake10
-rw-r--r--Modules/Compiler/ARMClang.cmake71
-rw-r--r--Modules/Compiler/Flang-FindBinUtils.cmake1
-rw-r--r--Modules/Compiler/Flang-Fortran.cmake13
-rw-r--r--Modules/Compiler/IAR-FindBinUtils.cmake61
-rw-r--r--Modules/Compiler/MSVC-ASM.cmake1
-rw-r--r--Modules/Compiler/MSVC-C-FeatureTests.cmake8
-rw-r--r--Modules/Compiler/MSVC-C.cmake38
-rw-r--r--Modules/Compiler/QCC-ASM.cmake2
-rw-r--r--Modules/Compiler/QCC-C-FeatureTests.cmake1
-rw-r--r--Modules/Compiler/QCC-CXX-FeatureTests.cmake1
-rw-r--r--Modules/Compiler/XLClang-C-DetermineCompiler.cmake8
-rw-r--r--Modules/Compiler/XLClang-C.cmake20
-rw-r--r--Modules/Compiler/XLClang-CXX-DetermineCompiler.cmake8
-rw-r--r--Modules/Compiler/XLClang-CXX.cmake27
-rw-r--r--Modules/Compiler/XLClang.cmake22
-rw-r--r--Modules/CompilerId/GHS_default.gpj.in8
-rw-r--r--Modules/CompilerId/GHS_lib.gpj.in3
-rw-r--r--Modules/FetchContent.cmake1061
-rw-r--r--Modules/FetchContent/CMakeLists.cmake.in23
-rw-r--r--Modules/FindEnvModules.cmake333
-rw-r--r--Modules/FindFontconfig.cmake101
-rw-r--r--Modules/FindIconv.cmake133
-rw-r--r--Modules/FindLibinput.cmake82
-rw-r--r--Modules/FindMPI/fortranparam_mpi.f90.in4
-rw-r--r--Modules/FindMPI/libver_mpi.c20
-rw-r--r--Modules/FindMPI/libver_mpi.f90.in7
-rw-r--r--Modules/FindMPI/mpiver.f90.in10
-rw-r--r--Modules/FindMPI/test_mpi.c38
-rw-r--r--Modules/FindMPI/test_mpi.f90.in6
-rw-r--r--Modules/FindODBC.cmake229
-rw-r--r--Modules/FindOpenACC.cmake257
-rw-r--r--Modules/FindPatch.cmake69
-rw-r--r--Modules/FindPython.cmake258
-rw-r--r--Modules/FindPython/Support.cmake1835
-rw-r--r--Modules/FindPython2.cmake223
-rw-r--r--Modules/FindPython3.cmake223
-rw-r--r--Modules/FindSQLite3.cmake66
-rw-r--r--Modules/GoogleTestAddTests.cmake106
-rw-r--r--Modules/Internal/CMakeCheckCompilerFlag.cmake158
-rw-r--r--Modules/Internal/CPack/CPackDeb.cmake681
-rw-r--r--Modules/Internal/CPack/CPackExternal.cmake53
-rw-r--r--Modules/Internal/CPack/CPackFreeBSD.cmake107
-rw-r--r--Modules/Internal/CPack/CPackNuGet.cmake363
-rw-r--r--Modules/Internal/CPack/CPackRPM.cmake1881
-rw-r--r--Modules/Internal/CPack/CPackWIX.cmake20
-rw-r--r--Modules/Internal/CPack/CPackZIP.cmake30
-rw-r--r--Modules/Platform/AIX-XLClang-C.cmake2
-rw-r--r--Modules/Platform/AIX-XLClang-CXX.cmake2
-rw-r--r--Modules/Platform/AIX-XLClang.cmake15
-rw-r--r--Modules/Platform/Apple-Absoft-Fortran.cmake7
-rw-r--r--Modules/Platform/Apple-AppleClang-C.cmake6
-rw-r--r--Modules/Platform/Apple-AppleClang-CXX.cmake6
-rw-r--r--Modules/Platform/Apple-Clang-C.cmake2
-rw-r--r--Modules/Platform/Apple-Clang-CXX.cmake2
-rw-r--r--Modules/Platform/Apple-Clang.cmake32
-rw-r--r--Modules/Platform/Apple-GNU-C.cmake4
-rw-r--r--Modules/Platform/Apple-GNU-CXX.cmake4
-rw-r--r--Modules/Platform/Apple-GNU-Fortran.cmake10
-rw-r--r--Modules/Platform/Apple-GNU.cmake57
-rw-r--r--Modules/Platform/Apple-Intel-C.cmake2
-rw-r--r--Modules/Platform/Apple-Intel-CXX.cmake2
-rw-r--r--Modules/Platform/Apple-Intel-Fortran.cmake8
-rw-r--r--Modules/Platform/Apple-Intel.cmake19
-rw-r--r--Modules/Platform/Apple-NAG-Fortran.cmake15
-rw-r--r--Modules/Platform/Apple-NVIDIA-CUDA.cmake19
-rw-r--r--Modules/Platform/Apple-PGI-C.cmake2
-rw-r--r--Modules/Platform/Apple-PGI-CXX.cmake2
-rw-r--r--Modules/Platform/Apple-PGI-Fortran.cmake2
-rw-r--r--Modules/Platform/Apple-PGI.cmake11
-rw-r--r--Modules/Platform/Apple-VisualAge-C.cmake1
-rw-r--r--Modules/Platform/Apple-VisualAge-CXX.cmake1
-rw-r--r--Modules/Platform/Apple-XL-C.cmake8
-rw-r--r--Modules/Platform/Apple-XL-CXX.cmake8
-rw-r--r--Modules/Platform/FreeBSD-Determine-CXX.cmake3
-rw-r--r--Modules/Platform/GHS-MULTI-Determine.cmake56
-rw-r--r--Modules/Platform/Midipix.cmake1
-rw-r--r--Modules/Platform/Windows-Flang-Fortran.cmake8
-rw-r--r--Modules/Platform/WindowsPhone-Clang-C.cmake1
-rw-r--r--Modules/Platform/WindowsPhone-Clang-CXX.cmake1
-rw-r--r--Modules/Platform/WindowsPhone-GNU-C.cmake1
-rw-r--r--Modules/Platform/WindowsPhone-GNU-CXX.cmake1
-rw-r--r--Modules/Platform/WindowsStore-Clang-C.cmake1
-rw-r--r--Modules/Platform/WindowsStore-Clang-CXX.cmake1
-rw-r--r--Modules/Platform/WindowsStore-GNU-C.cmake1
-rw-r--r--Modules/Platform/WindowsStore-GNU-CXX.cmake1
-rw-r--r--Modules/Platform/iOS-Determine-CXX.cmake1
-rw-r--r--Modules/Platform/iOS-Initialize.cmake9
-rw-r--r--Modules/Platform/iOS.cmake1
-rw-r--r--Modules/Platform/tvOS-Determine-CXX.cmake1
-rw-r--r--Modules/Platform/tvOS-Initialize.cmake7
-rw-r--r--Modules/Platform/tvOS.cmake1
-rw-r--r--Modules/Platform/watchOS-Determine-CXX.cmake1
-rw-r--r--Modules/Platform/watchOS-Initialize.cmake7
-rw-r--r--Modules/Platform/watchOS.cmake1
-rw-r--r--Modules/UseSWIG/ManageSupportFiles.cmake31
-rw-r--r--Source/CMakeInstallSignTool.cmake.in51
-rw-r--r--Source/CMakeVersion.rc.in28
-rw-r--r--Source/CPack/WiX/cmCMakeToWixPath.cxx39
-rw-r--r--Source/CPack/WiX/cmCMakeToWixPath.h12
-rw-r--r--Source/CPack/cmCPackExternalGenerator.cxx323
-rw-r--r--Source/CPack/cmCPackExternalGenerator.h89
-rw-r--r--Source/CPack/cmCPackFreeBSDGenerator.cxx345
-rw-r--r--Source/CPack/cmCPackFreeBSDGenerator.h37
-rw-r--r--Source/CPack/cmCPackNuGetGenerator.cxx141
-rw-r--r--Source/CPack/cmCPackNuGetGenerator.h37
-rw-r--r--Source/Checks/Curses.cmake41
-rw-r--r--Source/Checks/Curses/CMakeLists.txt25
-rw-r--r--Source/Checks/Curses/CheckCurses.c15
-rw-r--r--Source/Checks/cm_cxx14_check.cmake36
-rw-r--r--Source/Checks/cm_cxx14_check.cpp15
-rw-r--r--Source/Checks/cm_cxx17_check.cmake36
-rw-r--r--Source/Checks/cm_cxx17_check.cpp31
-rw-r--r--Source/Modules/CheckCXXLinkerFlag.cmake25
-rw-r--r--Source/Modules/FindLibUUID.cmake85
-rw-r--r--Source/Modules/OverrideC.cmake3
-rw-r--r--Source/Modules/OverrideCXX.cmake3
-rw-r--r--Source/cmAddCompileDefinitionsCommand.cxx20
-rw-r--r--Source/cmAddCompileDefinitionsCommand.h31
-rw-r--r--Source/cmAddLinkOptionsCommand.cxx20
-rw-r--r--Source/cmAddLinkOptionsCommand.h31
-rw-r--r--Source/cmAffinity.cxx64
-rw-r--r--Source/cmAffinity.h12
-rw-r--r--Source/cmArgumentParser.cxx93
-rw-r--r--Source/cmArgumentParser.h143
-rw-r--r--Source/cmConnection.cxx163
-rw-r--r--Source/cmConnection.h136
-rw-r--r--Source/cmDuration.cxx27
-rw-r--r--Source/cmDuration.h24
-rw-r--r--Source/cmFSPermissions.cxx34
-rw-r--r--Source/cmFSPermissions.h45
-rw-r--r--Source/cmFileAPI.cxx835
-rw-r--r--Source/cmFileAPI.h209
-rw-r--r--Source/cmFileAPICMakeFiles.cxx114
-rw-r--r--Source/cmFileAPICMakeFiles.h15
-rw-r--r--Source/cmFileAPICache.cxx106
-rw-r--r--Source/cmFileAPICache.h15
-rw-r--r--Source/cmFileAPICodemodel.cxx1250
-rw-r--r--Source/cmFileAPICodemodel.h15
-rw-r--r--Source/cmFileCopier.cxx713
-rw-r--r--Source/cmFileCopier.h122
-rw-r--r--Source/cmFileInstaller.cxx350
-rw-r--r--Source/cmFileInstaller.h55
-rw-r--r--Source/cmFileTime.cxx49
-rw-r--r--Source/cmFileTime.h130
-rw-r--r--Source/cmFileTimeCache.cxx62
-rw-r--r--Source/cmFileTimeCache.h56
-rw-r--r--Source/cmFileTimes.cxx127
-rw-r--r--Source/cmFileTimes.h40
-rw-r--r--Source/cmGetPipes.cxx48
-rw-r--r--Source/cmGetPipes.h8
-rw-r--r--Source/cmGlobVerificationManager.cxx178
-rw-r--r--Source/cmGlobVerificationManager.h85
-rw-r--r--Source/cmGlobalVisualStudioVersionedGenerator.cxx519
-rw-r--r--Source/cmGlobalVisualStudioVersionedGenerator.h65
-rw-r--r--Source/cmIncludeGuardCommand.cxx108
-rw-r--r--Source/cmIncludeGuardCommand.h37
-rw-r--r--Source/cmInstallSubdirectoryGenerator.cxx76
-rw-r--r--Source/cmInstallSubdirectoryGenerator.h41
-rw-r--r--Source/cmJsonObjectDictionary.h45
-rw-r--r--Source/cmJsonObjects.cxx693
-rw-r--r--Source/cmJsonObjects.h27
-rw-r--r--Source/cmLinkItem.cxx64
-rw-r--r--Source/cmMessageType.h21
-rw-r--r--Source/cmNinjaLinkLineDeviceComputer.cxx20
-rw-r--r--Source/cmNinjaLinkLineDeviceComputer.h34
-rw-r--r--Source/cmPipeConnection.cxx71
-rw-r--r--Source/cmPipeConnection.h28
-rw-r--r--Source/cmQtAutoGen.cxx410
-rw-r--r--Source/cmQtAutoGen.h138
-rw-r--r--Source/cmQtAutoGenGlobalInitializer.cxx303
-rw-r--r--Source/cmQtAutoGenGlobalInitializer.h86
-rw-r--r--Source/cmQtAutoGenInitializer.cxx1712
-rw-r--r--Source/cmQtAutoGenInitializer.h241
-rw-r--r--Source/cmQtAutoGenerator.cxx332
-rw-r--r--Source/cmQtAutoGenerator.h109
-rw-r--r--Source/cmQtAutoMocUic.cxx2193
-rw-r--r--Source/cmQtAutoMocUic.h576
-rw-r--r--Source/cmQtAutoRcc.cxx523
-rw-r--r--Source/cmQtAutoRcc.h81
-rw-r--r--Source/cmRange.h239
-rw-r--r--Source/cmSourceFileLocationKind.h15
-rw-r--r--Source/cmString.cxx152
-rw-r--r--Source/cmString.hxx815
-rw-r--r--Source/cmStringReplaceHelper.cxx120
-rw-r--r--Source/cmStringReplaceHelper.h68
-rw-r--r--Source/cmTargetLinkDirectoriesCommand.cxx61
-rw-r--r--Source/cmTargetLinkDirectoriesCommand.h41
-rw-r--r--Source/cmTargetLinkOptionsCommand.cxx41
-rw-r--r--Source/cmTargetLinkOptionsCommand.h41
-rw-r--r--Source/cmUVHandlePtr.cxx267
-rw-r--r--Source/cmUVHandlePtr.h271
-rw-r--r--Source/cmUVProcessChain.cxx395
-rw-r--r--Source/cmUVProcessChain.h100
-rw-r--r--Source/cmUVSignalHackRAII.h45
-rw-r--r--Source/cmUVStreambuf.h219
-rw-r--r--Source/cmWorkerPool.cxx763
-rw-r--r--Source/cmWorkerPool.h226
-rw-r--r--Source/cm_static_string_view.hxx41
-rw-r--r--Source/cm_string_view.cxx301
-rw-r--r--Source/cm_string_view.hxx217
-rw-r--r--Source/cm_thread.hxx48
-rw-r--r--Source/kwsys/testConfigure.cxx30
-rw-r--r--Source/kwsys/testDirectory.cxx110
-rw-r--r--Source/kwsys/testDynloadImpl.c10
-rw-r--r--Source/kwsys/testDynloadImpl.h15
-rw-r--r--Source/kwsys/testDynloadUse.c15
-rw-r--r--Templates/MSBuild/FlagTables/v10_CL.json981
-rw-r--r--Templates/MSBuild/FlagTables/v10_CSharp.json574
-rw-r--r--Templates/MSBuild/FlagTables/v10_Cuda.json224
-rw-r--r--Templates/MSBuild/FlagTables/v10_CudaHost.json149
-rw-r--r--Templates/MSBuild/FlagTables/v10_LIB.json297
-rw-r--r--Templates/MSBuild/FlagTables/v10_Link.json1137
-rw-r--r--Templates/MSBuild/FlagTables/v10_MASM.json295
-rw-r--r--Templates/MSBuild/FlagTables/v10_NASM.json201
-rw-r--r--Templates/MSBuild/FlagTables/v10_RC.json69
-rw-r--r--Templates/MSBuild/FlagTables/v11_CL.json1063
-rw-r--r--Templates/MSBuild/FlagTables/v11_CSharp.json574
-rw-r--r--Templates/MSBuild/FlagTables/v11_LIB.json297
-rw-r--r--Templates/MSBuild/FlagTables/v11_Link.json1272
-rw-r--r--Templates/MSBuild/FlagTables/v11_MASM.json295
-rw-r--r--Templates/MSBuild/FlagTables/v11_RC.json69
-rw-r--r--Templates/MSBuild/FlagTables/v12_CL.json1077
-rw-r--r--Templates/MSBuild/FlagTables/v12_CSharp.json574
-rw-r--r--Templates/MSBuild/FlagTables/v12_LIB.json297
-rw-r--r--Templates/MSBuild/FlagTables/v12_Link.json1272
-rw-r--r--Templates/MSBuild/FlagTables/v12_MASM.json295
-rw-r--r--Templates/MSBuild/FlagTables/v12_RC.json69
-rw-r--r--Templates/MSBuild/FlagTables/v140_CL.json1184
-rw-r--r--Templates/MSBuild/FlagTables/v140_CSharp.json574
-rw-r--r--Templates/MSBuild/FlagTables/v140_Link.json1316
-rw-r--r--Templates/MSBuild/FlagTables/v141_CL.json1268
-rw-r--r--Templates/MSBuild/FlagTables/v141_CSharp.json574
-rw-r--r--Templates/MSBuild/FlagTables/v141_Link.json1323
-rw-r--r--Templates/MSBuild/FlagTables/v142_CL.json1212
-rw-r--r--Templates/MSBuild/FlagTables/v142_CSharp.json574
-rw-r--r--Templates/MSBuild/FlagTables/v142_Link.json1323
-rw-r--r--Templates/MSBuild/FlagTables/v14_LIB.json304
-rw-r--r--Templates/MSBuild/FlagTables/v14_MASM.json295
-rw-r--r--Templates/MSBuild/FlagTables/v14_RC.json69
-rw-r--r--Tests/CMakeCommands/add_compile_definitions/CMakeLists.txt15
-rw-r--r--Tests/CMakeCommands/add_compile_definitions/main.cpp17
-rw-r--r--Tests/CMakeCommands/add_link_options/CMakeLists.txt20
-rw-r--r--Tests/CMakeCommands/add_link_options/LinkOptionsExe.c4
-rw-r--r--Tests/CMakeCommands/link_directories/CMakeLists.txt30
-rw-r--r--Tests/CMakeCommands/link_directories/LinkDirectoriesExe.c4
-rw-r--r--Tests/CMakeCommands/target_link_directories/CMakeLists.txt40
-rw-r--r--Tests/CMakeCommands/target_link_directories/LinkDirectoriesLib.c7
-rw-r--r--Tests/CMakeCommands/target_link_directories/subdir/CMakeLists.txt2
-rw-r--r--Tests/CMakeCommands/target_link_libraries/SubDirA/CMakeLists.txt15
-rw-r--r--Tests/CMakeCommands/target_link_libraries/SubDirA/SubDirA.c14
-rw-r--r--Tests/CMakeCommands/target_link_libraries/SubDirB/CMakeLists.txt15
-rw-r--r--Tests/CMakeCommands/target_link_libraries/SubDirB/SubDirB.c14
-rw-r--r--Tests/CMakeCommands/target_link_libraries/SubDirC/CMakeLists.txt9
-rw-r--r--Tests/CMakeCommands/target_link_libraries/SubDirC/SubDirC.c11
-rw-r--r--Tests/CMakeCommands/target_link_libraries/TopDir.c20
-rw-r--r--Tests/CMakeCommands/target_link_options/CMakeLists.txt34
-rw-r--r--Tests/CMakeCommands/target_link_options/LinkOptionsLib.c7
-rw-r--r--Tests/CMakeCommands/target_sources/CMakeLists.txt36
-rw-r--r--Tests/CMakeCommands/target_sources/empty_1.cpp21
-rw-r--r--Tests/CMakeCommands/target_sources/empty_2.cpp7
-rw-r--r--Tests/CMakeCommands/target_sources/empty_3.cpp7
-rw-r--r--Tests/CMakeCommands/target_sources/main.cpp16
-rw-r--r--Tests/CMakeCommands/target_sources/subdir/CMakeLists.txt6
-rw-r--r--Tests/CMakeCommands/target_sources/subdir/subdir_empty_1.cpp21
-rw-r--r--Tests/CMakeCommands/target_sources/subdir/subdir_empty_2.cpp21
-rw-r--r--Tests/CMakeLib/testAffinity.cxx18
-rw-r--r--Tests/CMakeLib/testArgumentParser.cxx148
-rw-r--r--Tests/CMakeLib/testRange.cxx45
-rw-r--r--Tests/CMakeLib/testString.cxx1347
-rw-r--r--Tests/CMakeLib/testUVProcessChain.cxx335
-rw-r--r--Tests/CMakeLib/testUVProcessChainHelper.cxx72
-rw-r--r--Tests/CMakeLib/testUVRAII.cxx230
-rw-r--r--Tests/CMakeLib/testUVStreambuf.cxx457
-rw-r--r--Tests/CMakeOnly/ProjectIncludeAny/CMakeLists.txt4
-rw-r--r--Tests/CMakeOnly/ProjectIncludeBefore/CMakeLists.txt5
-rw-r--r--Tests/CMakeOnly/ProjectIncludeBefore/include.cmake9
-rw-r--r--Tests/CMakeServerLib/CMakeLists.txt21
-rw-r--r--Tests/CMakeServerLib/testServerBuffering.cpp85
-rw-r--r--Tests/CPackUseDefaultVersion/CMakeLists.txt6
-rw-r--r--Tests/CPackUseProjectVersion/CMakeLists.txt6
-rw-r--r--Tests/CPackUseShortProjectVersion/CMakeLists.txt6
-rw-r--r--Tests/CSharpLinkFromCxx/CMakeLists.txt19
-rw-r--r--Tests/CSharpLinkFromCxx/CSharpLinkFromCxx.cs16
-rw-r--r--Tests/CSharpLinkFromCxx/UsefulCSharpClass.cs12
-rw-r--r--Tests/CSharpLinkFromCxx/UsefulManagedCppClass.cpp15
-rw-r--r--Tests/CSharpLinkFromCxx/UsefulManagedCppClass.hpp16
-rw-r--r--Tests/CSharpLinkToCxx/cpp_static.cpp3
-rw-r--r--Tests/CSharpOnly/empty.cs0
-rw-r--r--Tests/CSharpOnly/empty.txt0
-rw-r--r--Tests/CheckSwift.cmake61
-rw-r--r--Tests/CommandLength/CMakeLists.txt17
-rw-r--r--Tests/CommandLength/test.c4
-rw-r--r--Tests/Contracts/Home.cmake19
-rw-r--r--Tests/Contracts/PLplot/CMakeLists.txt18
-rw-r--r--Tests/Contracts/PLplot/Configure.cmake4
-rw-r--r--Tests/Contracts/Trilinos/Configure.cmake7
-rw-r--r--Tests/Contracts/VTK/Configure.cmake3
-rw-r--r--Tests/Cuda/MixedStandardLevels/CMakeLists.txt14
-rw-r--r--Tests/Cuda/MixedStandardLevels/main.cu10
-rw-r--r--Tests/Cuda/NotEnabled/CMakeLists.txt14
-rw-r--r--Tests/Cuda/NotEnabled/lib.cxx5
-rw-r--r--Tests/Cuda/NotEnabled/main.cxx9
-rw-r--r--Tests/Cuda/ObjectLibrary/Conflicts/CMakeLists.txt2
-rw-r--r--Tests/Cuda/ObjectLibrary/Conflicts/static.cu17
-rw-r--r--Tests/Cuda/ProperDeviceLibraries/CMakeLists.txt45
-rw-r--r--Tests/Cuda/ProperDeviceLibraries/main.cu92
-rw-r--r--Tests/Cuda/ProperDeviceLibraries/use_pthreads.cu9
-rw-r--r--Tests/Cuda/ProperDeviceLibraries/use_pthreads.cxx9
-rw-r--r--Tests/CudaOnly/CircularLinkLine/CMakeLists.txt34
-rw-r--r--Tests/CudaOnly/CircularLinkLine/file1.cu6
-rw-r--r--Tests/CudaOnly/CircularLinkLine/file2.cu6
-rw-r--r--Tests/CudaOnly/CircularLinkLine/file3.cu8
-rw-r--r--Tests/CudaOnly/CircularLinkLine/main.cu5
-rw-r--r--Tests/CudaOnly/DontResolveDeviceSymbols/CMakeLists.txt50
-rw-r--r--Tests/CudaOnly/DontResolveDeviceSymbols/file1.cu69
-rw-r--r--Tests/CudaOnly/DontResolveDeviceSymbols/main.cu7
-rw-r--r--Tests/CudaOnly/DontResolveDeviceSymbols/verify.cmake14
-rw-r--r--Tests/CudaOnly/GPUDebugFlag/CMakeLists.txt23
-rw-r--r--Tests/CudaOnly/GPUDebugFlag/main.cu71
-rw-r--r--Tests/CudaOnly/PDB/CMakeLists.txt19
-rw-r--r--Tests/CudaOnly/PDB/check_pdbs.cmake10
-rw-r--r--Tests/CudaOnly/PDB/main.cu4
-rw-r--r--Tests/CudaOnly/WithDefs/inc_cuda/inc_cuda.h1
-rw-r--r--Tests/ExportImport/Export/SubDirLinkA/CMakeLists.txt6
-rw-r--r--Tests/ExportImport/Export/SubDirLinkA/SubDirLinkA.c11
-rw-r--r--Tests/ExportImport/Export/SubDirLinkB/CMakeLists.txt4
-rw-r--r--Tests/ExportImport/Export/testLib9.c15
-rw-r--r--Tests/ExportImport/Export/testLib9ObjIface.c11
-rw-r--r--Tests/ExportImport/Export/testLib9ObjPriv.c4
-rw-r--r--Tests/ExportImport/Export/testLib9ObjPub.c4
-rw-r--r--Tests/ExportImport/Export/testTopDirLib.c11
-rw-r--r--Tests/ExportImport/Import/A/SubDirLink.c14
-rw-r--r--Tests/ExportImport/Import/A/imp_testLib9.c16
-rw-r--r--Tests/ExportImport/Import/A/imp_testLinkOptions.cpp8
-rw-r--r--Tests/ExternalProjectLocal/Step5/CMakeLists.txt71
-rw-r--r--Tests/ExternalProjectLocal/Step5/MathFunctions/CMakeLists.txt17
-rw-r--r--Tests/ExternalProjectLocal/Step5/MathFunctions/MakeTable.cxx32
-rw-r--r--Tests/ExternalProjectLocal/Step5/MathFunctions/MathFunctions.h1
-rw-r--r--Tests/ExternalProjectLocal/Step5/MathFunctions/mysqrt.cxx40
-rw-r--r--Tests/ExternalProjectLocal/Step5/TutorialConfig.h.in8
-rw-r--r--Tests/ExternalProjectLocal/Step5/tutorial.cxx33
-rw-r--r--Tests/ExternalProjectSourceSubdirNotCMake/CMakeLists.txt20
-rw-r--r--Tests/ExternalProjectSourceSubdirNotCMake/Example/subdir/Makefile2
-rw-r--r--Tests/FindALSA/CMakeLists.txt10
-rw-r--r--Tests/FindALSA/Test/CMakeLists.txt16
-rw-r--r--Tests/FindALSA/Test/main.c10
-rw-r--r--Tests/FindBoost/TestFail/CMakeLists.txt18
-rw-r--r--Tests/FindBoost/TestFail/main.cxx24
-rw-r--r--Tests/FindBoost/TestPython/CMakeLists.txt17
-rw-r--r--Tests/FindCURL/CMakeLists.txt10
-rw-r--r--Tests/FindCURL/Test/CMakeLists.txt16
-rw-r--r--Tests/FindCURL/Test/main.c17
-rw-r--r--Tests/FindCups/CMakeLists.txt10
-rw-r--r--Tests/FindCups/Test/CMakeLists.txt16
-rw-r--r--Tests/FindCups/Test/main.c12
-rw-r--r--Tests/FindDoxygen/AllTarget/CMakeLists.txt42
-rw-r--r--Tests/FindDoxygen/QuotingTest/CMakeLists.txt34
-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/FindEnvModules/CMakeLists.txt3
-rw-r--r--Tests/FindEnvModules/EnvModules.cmake35
-rw-r--r--Tests/FindFontconfig/CMakeLists.txt10
-rw-r--r--Tests/FindFontconfig/Test/CMakeLists.txt16
-rw-r--r--Tests/FindFontconfig/Test/main.c17
-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/FindGDAL/CMakeLists.txt10
-rw-r--r--Tests/FindGDAL/Test/CMakeLists.txt16
-rw-r--r--Tests/FindGDAL/Test/main.c11
-rw-r--r--Tests/FindGIF/CMakeLists.txt10
-rw-r--r--Tests/FindGIF/Test/CMakeLists.txt16
-rw-r--r--Tests/FindGIF/Test/main.c35
-rw-r--r--Tests/FindGLEW/CMakeLists.txt10
-rw-r--r--Tests/FindGLEW/Test/CMakeLists.txt18
-rw-r--r--Tests/FindGLEW/Test/main.cpp8
-rw-r--r--Tests/FindGit/CMakeLists.txt10
-rw-r--r--Tests/FindGit/Test/CMakeLists.txt13
-rw-r--r--Tests/FindGit/Test/RunGit.cmake20
-rw-r--r--Tests/FindIconv/CMakeLists.txt10
-rw-r--r--Tests/FindIconv/Test/CMakeLists.txt16
-rw-r--r--Tests/FindIconv/Test/main.cxx52
-rw-r--r--Tests/FindJPEG/CMakeLists.txt10
-rw-r--r--Tests/FindJPEG/Test/CMakeLists.txt16
-rw-r--r--Tests/FindJPEG/Test/main.c16
-rw-r--r--Tests/FindLibLZMA/CMakeLists.txt10
-rw-r--r--Tests/FindLibLZMA/Test/CMakeLists.txt14
-rw-r--r--Tests/FindLibLZMA/Test/main.c15
-rw-r--r--Tests/FindLibXml2/CMakeLists.txt10
-rw-r--r--Tests/FindLibXml2/Test/CMakeLists.txt16
-rw-r--r--Tests/FindLibXml2/Test/main.c19
-rw-r--r--Tests/FindLibinput/CMakeLists.txt10
-rw-r--r--Tests/FindLibinput/Test/CMakeLists.txt14
-rw-r--r--Tests/FindLibinput/Test/main.c13
-rw-r--r--Tests/FindMatlab/cmake_matlab_unit_tests4.m28
-rw-r--r--Tests/FindMatlab/cmake_matlab_unit_tests5.m20
-rw-r--r--Tests/FindMatlab/failure_reports/CMakeLists.txt55
-rw-r--r--Tests/FindMatlab/matlab_wrapper2.cpp22
-rw-r--r--Tests/FindMatlab/matlab_wrapper3.cpp29
-rw-r--r--Tests/FindMatlab/r2018a_check/CMakeLists.txt84
-rw-r--r--Tests/FindODBC/CMakeLists.txt10
-rw-r--r--Tests/FindODBC/Test/CMakeLists.txt14
-rw-r--r--Tests/FindODBC/Test/main.c12
-rw-r--r--Tests/FindPackageTest/PreferConfig/ABCConfig.cmake1
-rw-r--r--Tests/FindPackageTest/PreferConfig/FindABC.cmake1
-rw-r--r--Tests/FindPackageTest/PreferConfigOnlyModule/FindACME.cmake1
-rw-r--r--Tests/FindPackageTest/PreferConfigRecurse/ACMEConfig.cmake1
-rw-r--r--Tests/FindPackageTest/PreferConfigRecurse/FindACME.cmake1
-rw-r--r--Tests/FindPackageTest/cmake/SetFoundResolvedConfig.cmake1
-rw-r--r--Tests/FindPatch/CMakeLists.txt8
-rw-r--r--Tests/FindPatch/Test/CMakeLists.txt77
-rw-r--r--Tests/FindPostgreSQL/CMakeLists.txt10
-rw-r--r--Tests/FindPostgreSQL/Test/CMakeLists.txt16
-rw-r--r--Tests/FindPostgreSQL/Test/main.c24
-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/FindPython/CMakeLists.txt147
-rw-r--r--Tests/FindPython/FindPythonScript.cmake1
-rw-r--r--Tests/FindPython/MultiplePackages/CMakeLists.txt33
-rw-r--r--Tests/FindPython/NumPy/CMakeLists.txt22
-rw-r--r--Tests/FindPython/NumPy/arraytest.c58
-rw-r--r--Tests/FindPython/NumPyOnly/CMakeLists.txt14
-rw-r--r--Tests/FindPython/Python/CMakeLists.txt32
-rw-r--r--Tests/FindPython/Python2/CMakeLists.txt37
-rw-r--r--Tests/FindPython/Python2Embedded/CMakeLists.txt29
-rw-r--r--Tests/FindPython/Python2Fail/CMakeLists.txt14
-rw-r--r--Tests/FindPython/Python3/CMakeLists.txt37
-rw-r--r--Tests/FindPython/Python3Embedded/CMakeLists.txt29
-rw-r--r--Tests/FindPython/Python3Fail/CMakeLists.txt14
-rw-r--r--Tests/FindPython/VirtualEnv/CMakeLists.txt42
-rw-r--r--Tests/FindPython/VirtualEnv/VirtualEnvDefault.cmake6
-rw-r--r--Tests/FindPython/VirtualEnv/VirtualEnvOnly.cmake16
-rw-r--r--Tests/FindPython/VirtualEnv/VirtualEnvStandard.cmake7
-rw-r--r--Tests/FindPython/display_time.c36
-rw-r--r--Tests/FindPython/display_time.h2
-rw-r--r--Tests/FindPython/main.c7
-rw-r--r--Tests/FindPython/spam.c41
-rw-r--r--Tests/FindSQLite3/CMakeLists.txt10
-rw-r--r--Tests/FindSQLite3/Test/CMakeLists.txt16
-rw-r--r--Tests/FindSQLite3/Test/main.c10
-rw-r--r--Tests/FindX11/CMakeLists.txt10
-rw-r--r--Tests/FindX11/Test/CMakeLists.txt89
-rw-r--r--Tests/FindX11/Test/main.c405
-rw-r--r--Tests/FortranModules/Submodules/child.f9010
-rw-r--r--Tests/FortranModules/Submodules/grandchild.f908
-rw-r--r--Tests/FortranModules/Submodules/greatgrandchild.f908
-rw-r--r--Tests/FortranModules/Submodules/parent.f9022
-rw-r--r--Tests/FortranModules/Submodules/sibling.f909
-rw-r--r--Tests/FortranOnly/testRC.rc0
-rw-r--r--Tests/GeneratorExpression/srcgenex.c.in12
-rw-r--r--Tests/GeneratorExpression/srcgenex_includes.c.in12
-rw-r--r--Tests/GeneratorExpression/srcgenex_includes.h.in7
-rw-r--r--Tests/GhsMulti/GhsMultiCompilerOptions/CMakeLists.txt92
-rw-r--r--Tests/GhsMulti/GhsMultiCompilerOptions/CMakeLists.txt.in32
-rw-r--r--Tests/GhsMulti/GhsMultiCompilerOptions/test.c4
-rw-r--r--Tests/GhsMulti/GhsMultiCopyFile/CMakeLists.txt30
-rw-r--r--Tests/GhsMulti/GhsMultiCopyFile/test.c4
-rw-r--r--Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt110
-rw-r--r--Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt.in108
-rw-r--r--Tests/GhsMulti/GhsMultiCustomTarget/exe1.c5
-rw-r--r--Tests/GhsMulti/GhsMultiCustomTarget/lib1.c4
-rw-r--r--Tests/GhsMulti/GhsMultiDepOrder/CMakeLists.txt12
-rw-r--r--Tests/GhsMulti/GhsMultiDepOrder/exec/CMakeLists.txt11
-rw-r--r--Tests/GhsMulti/GhsMultiDepOrder/exec/exe1.c8
-rw-r--r--Tests/GhsMulti/GhsMultiDepOrder/lib/CMakeLists.txt17
-rw-r--r--Tests/GhsMulti/GhsMultiDepOrder/lib/func1.c17
-rw-r--r--Tests/GhsMulti/GhsMultiDepOrder/lib/lib1.h3
-rw-r--r--Tests/GhsMulti/GhsMultiDepOrder/protolib/CMakeLists.txt28
-rw-r--r--Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.c.in16
-rw-r--r--Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.h.in7
-rw-r--r--Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/CMakeLists.txt17
-rw-r--r--Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/main.c17
-rw-r--r--Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder/test.c4
-rw-r--r--Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder/testcase.c4
-rw-r--r--Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder_test.c4
-rw-r--r--Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder_test_0.c4
-rw-r--r--Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/test.c4
-rw-r--r--Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/testCase.c4
-rw-r--r--Tests/GhsMulti/GhsMultiExclude/CMakeLists.txt17
-rw-r--r--Tests/GhsMulti/GhsMultiExclude/exe1.c4
-rw-r--r--Tests/GhsMulti/GhsMultiExclude/lib1.c4
-rw-r--r--Tests/GhsMulti/GhsMultiExclude/verify.cmake54
-rw-r--r--Tests/GhsMulti/GhsMultiExternalProject/CMakeLists.txt14
-rw-r--r--Tests/GhsMulti/GhsMultiExternalProject/empty/CMakeLists.txt8
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/CMakeLists.txt19
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/exe.c5
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/func.c4
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/CMakeLists.txt3
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/Main.c8
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/CMakeLists.txt6
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Int/AppDD.int12
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Int/CMakeLists.txt1
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/CMakeLists.txt2
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/HelperFun.c4
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/HelperFun.h1
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/CMakeLists.txt21
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/exe.c5
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/func.c5
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/kernel.c15
-rw-r--r--Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/test.int8
-rw-r--r--Tests/GhsMulti/GhsMultiInterface/CMakeLists.txt8
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTest/CMakeLists.txt92
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTest/CMakeLists.txt.in43
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTest/exe1.c6
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTest/exe1.h6
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTest/func2.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTest/func3.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTest/func4.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTest/func5.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTest/func6.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTest/func7.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/CMakeLists.txt9
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/CMakeLists.txt12
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/exe1.c6
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/exe1.h6
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/CMakeLists.txt7
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func2.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func3.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func4.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func5.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func6.c4
-rw-r--r--Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func7.c4
-rw-r--r--Tests/GhsMulti/GhsMultiMultipleProjects/CMakeLists.txt17
-rw-r--r--Tests/GhsMulti/GhsMultiMultipleProjects/exe1.c5
-rw-r--r--Tests/GhsMulti/GhsMultiMultipleProjects/lib1.c4
-rw-r--r--Tests/GhsMulti/GhsMultiMultipleProjects/sub/CMakeLists.txt10
-rw-r--r--Tests/GhsMulti/GhsMultiMultipleProjects/sub/exe2.c6
-rw-r--r--Tests/GhsMulti/GhsMultiMultipleProjects/sub/lib2.c4
-rw-r--r--Tests/GhsMulti/GhsMultiMultipleProjects/sub2/CMakeLists.txt10
-rw-r--r--Tests/GhsMulti/GhsMultiMultipleProjects/sub2/exe3.c6
-rw-r--r--Tests/GhsMulti/GhsMultiMultipleProjects/sub2/lib3.c4
-rw-r--r--Tests/GhsMulti/GhsMultiMultipleProjects/verify.cmake58
-rw-r--r--Tests/GhsMulti/GhsMultiObjectLibrary/CMakeLists.txt13
-rw-r--r--Tests/GhsMulti/GhsMultiObjectLibrary/exe.c8
-rw-r--r--Tests/GhsMulti/GhsMultiObjectLibrary/sub/testOBJ.c4
-rw-r--r--Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ.c4
-rw-r--r--Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ.h1
-rw-r--r--Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ2.c4
-rw-r--r--Tests/GhsMulti/GhsMultiPlatform/CMakeLists.txt34
-rw-r--r--Tests/GhsMulti/GhsMultiRenameInstall/CMakeLists.txt42
-rw-r--r--Tests/GhsMulti/GhsMultiRenameInstall/exe.c4
-rw-r--r--Tests/GhsMulti/GhsMultiRenameInstall/exe1.c5
-rw-r--r--Tests/GhsMulti/GhsMultiRenameInstall/lib1.c4
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/Atest3.c4
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/CMakeLists.txt45
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/cmake.rule1
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/object.o1
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/resource.pdf0
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/s2.h6
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/s4.h6
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/s5.h6
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/standard.h1
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/sub/testOBJ.c6
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/sub/testOBJ.h6
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/test1.c6
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/test1.h6
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/test2a.c4
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/test3.c4
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/test3.h1
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/test4.c4
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/test5.c4
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/test6.c4
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/test7.c4
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/testOBJ.c11
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/testOBJ.h6
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/textfile.txt1
-rw-r--r--Tests/GhsMulti/GhsMultiSrcGroups/textfile2.txt1
-rw-r--r--Tests/GhsMulti/GhsMultiUnsupportedTargets/CMakeLists.txt10
-rw-r--r--Tests/GhsMulti/GhsMultiUnsupportedTargets/file.c4
-rw-r--r--Tests/GoogleTest/Test/empty.cxx0
-rw-r--r--Tests/ImportedSameName/A/CMakeLists.txt8
-rw-r--r--Tests/ImportedSameName/A/a.c3
-rw-r--r--Tests/ImportedSameName/B/CMakeLists.txt8
-rw-r--r--Tests/ImportedSameName/B/b.c3
-rw-r--r--Tests/ImportedSameName/CMakeLists.txt8
-rw-r--r--Tests/ImportedSameName/main.c16
-rw-r--r--Tests/IncludeDirectories/SystemIncludeDirectories/systemlib/ordertest.h1
-rw-r--r--Tests/IncludeDirectories/SystemIncludeDirectories/userlib/ordertest.h1
-rw-r--r--Tests/IncludeDirectories/ordertest.cpp1
-rw-r--r--Tests/IncludeDirectoriesCPATH/CMakeLists.txt22
-rw-r--r--Tests/IncludeDirectoriesCPATH/consumer.cpp6
-rw-r--r--Tests/IncludeDirectoriesCPATH/viacpath/systemlib.h15
-rw-r--r--Tests/InterfaceLibrary/excluded/CMakeLists.txt1
-rw-r--r--Tests/JavaNativeHeaders/CMakeLists.txt18
-rw-r--r--Tests/JavaNativeHeaders/D.cpp10
-rw-r--r--Tests/JavaNativeHeaders/D.java19
-rw-r--r--Tests/JavaNativeHeaders/E.cpp10
-rw-r--r--Tests/JavaNativeHeaders/E.java19
-rw-r--r--Tests/JavaNativeHeaders/HelloWorld3.java15
-rw-r--r--Tests/MSVCRuntimeLibrary/CMakeLists.txt71
-rw-r--r--Tests/MSVCRuntimeLibrary/Fortran/CMakeLists.txt58
-rw-r--r--Tests/MSVCRuntimeLibrary/Fortran/verify.F901
-rw-r--r--Tests/MSVCRuntimeLibrary/verify.c1
-rw-r--r--Tests/MSVCRuntimeLibrary/verify.cu1
-rw-r--r--Tests/MSVCRuntimeLibrary/verify.cxx1
-rw-r--r--Tests/MSVCRuntimeLibrary/verify.h29
-rw-r--r--Tests/MakeClean/ToClean/EmptySubDir/CMakeLists.txt17
-rw-r--r--Tests/Module/ExternalData/Data5/Data5.dat.md51
-rw-r--r--Tests/Module/FindDependency/packages/Pack7/Pack7Config.cmake14
-rw-r--r--Tests/Module/FindDependency/packages/Pack8/Pack8Config.cmake7
-rw-r--r--Tests/Module/WriteCompilerDetectionHeader/main_bare.cpp23
-rw-r--r--Tests/OutName/CMakeLists.txt6
-rw-r--r--Tests/OutName/main.c4
-rw-r--r--Tests/Qt4Autogen/CMakeLists.txt9
-rw-r--r--Tests/Qt5Autogen/CMakeLists.txt6
-rw-r--r--Tests/QtAutogen/AutogenCoreTest.cmake55
-rw-r--r--Tests/QtAutogen/AutogenGuiTest.cmake55
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/CMakeLists.txt71
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/a_mc.hpp.in9
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/a_qt.cpp28
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/a_qt.hpp25
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/b_mc.cpp.in9
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/b_mc.hpp9
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/b_qt.cpp28
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/b_qt.hpp25
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/config.hpp.in8
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/configure_content.cmake10
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOff/main.cpp15
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOn/CMakeLists.txt91
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOn/object_invalid.hpp.in1
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOn/object_valid.hpp.in14
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOn/simpleLib.cpp.in9
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOn/simpleLib.hpp.in14
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOn/testGenFile.cpp8
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOn/testGenLib.cpp12
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOn/testGenLib.hpp16
-rw-r--r--Tests/QtAutogen/AutogenOriginDependsOn/testGenTarget.cpp9
-rw-r--r--Tests/QtAutogen/AutogenTargetDepends/CMakeLists.txt54
-rw-r--r--Tests/QtAutogen/AutogenTargetDepends/object_invalid.hpp.in1
-rw-r--r--Tests/QtAutogen/AutogenTargetDepends/object_valid.hpp.in14
-rw-r--r--Tests/QtAutogen/AutogenTargetDepends/testATDFile.cpp9
-rw-r--r--Tests/QtAutogen/AutogenTargetDepends/testATDTarget.cpp9
-rw-r--r--Tests/QtAutogen/Complex/Adir/CMakeLists.txt8
-rw-r--r--Tests/QtAutogen/Complex/Adir/libA.cpp12
-rw-r--r--Tests/QtAutogen/Complex/Adir/libA.h18
-rw-r--r--Tests/QtAutogen/Complex/Bdir/CMakeLists.txt9
-rw-r--r--Tests/QtAutogen/Complex/Bdir/libB.cpp12
-rw-r--r--Tests/QtAutogen/Complex/Bdir/libB.h22
-rw-r--r--Tests/QtAutogen/Complex/CMakeLists.txt85
-rw-r--r--Tests/QtAutogen/Complex/abc.cpp39
-rw-r--r--Tests/QtAutogen/Complex/abc.h17
-rw-r--r--Tests/QtAutogen/Complex/abc_p.h19
-rw-r--r--Tests/QtAutogen/Complex/bar.cpp17
-rw-r--r--Tests/QtAutogen/Complex/blub.cpp31
-rw-r--r--Tests/QtAutogen/Complex/blub.h15
-rw-r--r--Tests/QtAutogen/Complex/calwidget.cpp436
-rw-r--r--Tests/QtAutogen/Complex/calwidget.h127
-rw-r--r--Tests/QtAutogen/Complex/calwidget.ui32
-rw-r--r--Tests/QtAutogen/Complex/codeeditor.cpp146
-rw-r--r--Tests/QtAutogen/Complex/codeeditor.h100
-rw-r--r--Tests/QtAutogen/Complex/debug_class.cpp10
-rw-r--r--Tests/QtAutogen/Complex/debug_class.h19
-rw-r--r--Tests/QtAutogen/Complex/debug_class.ui45
-rw-r--r--Tests/QtAutogen/Complex/debug_resource.qrc5
-rw-r--r--Tests/QtAutogen/Complex/foo.cpp30
-rw-r--r--Tests/QtAutogen/Complex/foo.h20
-rw-r--r--Tests/QtAutogen/Complex/gadget.cpp4
-rw-r--r--Tests/QtAutogen/Complex/gadget.h19
-rw-r--r--Tests/QtAutogen/Complex/generated.cpp9
-rw-r--r--Tests/QtAutogen/Complex/generated.h21
-rw-r--r--Tests/QtAutogen/Complex/generated.txt.in1
-rw-r--r--Tests/QtAutogen/Complex/generated_resource.qrc.in5
-rw-r--r--Tests/QtAutogen/Complex/libC.cpp12
-rw-r--r--Tests/QtAutogen/Complex/libC.h22
-rw-r--r--Tests/QtAutogen/Complex/main.cpp93
-rw-r--r--Tests/QtAutogen/Complex/multiplewidgets.cpp19
-rw-r--r--Tests/QtAutogen/Complex/multiplewidgets.h35
-rw-r--r--Tests/QtAutogen/Complex/myinterface.h.in14
-rw-r--r--Tests/QtAutogen/Complex/myotherinterface.h.in14
-rw-r--r--Tests/QtAutogen/Complex/private_slot.cpp16
-rw-r--r--Tests/QtAutogen/Complex/private_slot.h20
-rw-r--r--Tests/QtAutogen/Complex/resourcetester.cpp26
-rw-r--r--Tests/QtAutogen/Complex/resourcetester.h17
-rw-r--r--Tests/QtAutogen/Complex/second_resource.qrc5
-rw-r--r--Tests/QtAutogen/Complex/second_widget.cpp15
-rw-r--r--Tests/QtAutogen/Complex/second_widget.h18
-rw-r--r--Tests/QtAutogen/Complex/second_widget.ui32
-rw-r--r--Tests/QtAutogen/Complex/sub/bar.h17
-rw-r--r--Tests/QtAutogen/Complex/targetObjectsTest.cpp5
-rw-r--r--Tests/QtAutogen/Complex/test.qrc5
-rw-r--r--Tests/QtAutogen/Complex/widget1.ui45
-rw-r--r--Tests/QtAutogen/Complex/widget2.ui29
-rw-r--r--Tests/QtAutogen/Complex/xyz.cpp15
-rw-r--r--Tests/QtAutogen/Complex/xyz.h17
-rw-r--r--Tests/QtAutogen/Complex/yaf.cpp19
-rw-r--r--Tests/QtAutogen/Complex/yaf.h15
-rw-r--r--Tests/QtAutogen/Complex/yaf_p.h19
-rw-r--r--Tests/QtAutogen/DefinesTest/CMakeLists.txt13
-rw-r--r--Tests/QtAutogen/DefinesTest/defines_test.cpp38
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/CMakeLists.txt126
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/CMakeLists.txt28
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/data.qrc5
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/item.cpp20
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/item.hpp15
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/main.cpp15
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/CMakeLists.txt2
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/sda.cpp6
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/sda.hpp6
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/CMakeLists.txt5
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/sdb.cpp6
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/sdb.hpp6
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/CMakeLists.txt5
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/sdc.cpp6
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/sdc.hpp6
-rw-r--r--Tests/QtAutogen/GlobalAutogenTarget/GAT/view.ui24
-rw-r--r--Tests/QtAutogen/LowMinimumVersion/CMakeLists.txt16
-rw-r--r--Tests/QtAutogen/LowMinimumVersion/example.qrc5
-rw-r--r--Tests/QtAutogen/LowMinimumVersion/item.cpp19
-rw-r--r--Tests/QtAutogen/LowMinimumVersion/item.hpp15
-rw-r--r--Tests/QtAutogen/LowMinimumVersion/main.cpp10
-rw-r--r--Tests/QtAutogen/LowMinimumVersion/someText.txt1
-rw-r--r--Tests/QtAutogen/LowMinimumVersion/view.ui24
-rw-r--r--Tests/QtAutogen/MacOsFW/CMakeLists.txt21
-rw-r--r--Tests/QtAutogen/MacOsFW/src/CMakeLists.txt33
-rw-r--r--Tests/QtAutogen/MacOsFW/src/macos_fw_lib.cpp17
-rw-r--r--Tests/QtAutogen/MacOsFW/src/macos_fw_lib.h18
-rw-r--r--Tests/QtAutogen/MacOsFW/test/CMakeLists.txt19
-rw-r--r--Tests/QtAutogen/MacOsFW/test/testMacosFWLib.cpp42
-rw-r--r--Tests/QtAutogen/MacOsFW/test/testMacosFWLib.h7
-rw-r--r--Tests/QtAutogen/ManySources/CMakeLists.txt35
-rw-r--r--Tests/QtAutogen/ManySources/data.qrc.in7
-rw-r--r--Tests/QtAutogen/ManySources/item.cpp.in27
-rw-r--r--Tests/QtAutogen/ManySources/item.h.in15
-rw-r--r--Tests/QtAutogen/ManySources/main.cpp.in7
-rw-r--r--Tests/QtAutogen/ManySources/object.h.in15
-rw-r--r--Tests/QtAutogen/ManySources/view.ui.in24
-rw-r--r--Tests/QtAutogen/MocCMP0071/CMakeLists.txt6
-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/MocInclude/EObjA.cpp44
-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.hpp14
-rw-r--r--Tests/QtAutogen/MocInclude/EObjA_p.hpp14
-rw-r--r--Tests/QtAutogen/MocInclude/EObjB.cpp45
-rw-r--r--Tests/QtAutogen/MocInclude/EObjB.hpp19
-rw-r--r--Tests/QtAutogen/MocInclude/EObjB_p.hpp14
-rw-r--r--Tests/QtAutogen/MocInclude/LObjA.cpp39
-rw-r--r--Tests/QtAutogen/MocInclude/LObjA.hpp19
-rw-r--r--Tests/QtAutogen/MocInclude/LObjA_p.h14
-rw-r--r--Tests/QtAutogen/MocInclude/LObjB.cpp40
-rw-r--r--Tests/QtAutogen/MocInclude/LObjB.hpp19
-rw-r--r--Tests/QtAutogen/MocInclude/LObjB_p.h14
-rw-r--r--Tests/QtAutogen/MocInclude/ObjA.cpp20
-rw-r--r--Tests/QtAutogen/MocInclude/ObjA.hpp19
-rw-r--r--Tests/QtAutogen/MocInclude/ObjA_p.h14
-rw-r--r--Tests/QtAutogen/MocInclude/ObjB.cpp22
-rw-r--r--Tests/QtAutogen/MocInclude/ObjB.hpp19
-rw-r--r--Tests/QtAutogen/MocInclude/ObjB_p.h14
-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/subExtra/EObjBExtra.cpp20
-rw-r--r--Tests/QtAutogen/MocInclude/subExtra/EObjBExtra.hpp18
-rw-r--r--Tests/QtAutogen/MocInclude/subExtra/EObjBExtra_p.hpp14
-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.hpp17
-rw-r--r--Tests/QtAutogen/MocIncludeRelaxed/CMakeLists.txt20
-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.cpp26
-rw-r--r--Tests/QtAutogen/MocIncludeStrict/CMakeLists.txt10
-rw-r--r--Tests/QtAutogen/MocIncludeStrict/main.cpp26
-rw-r--r--Tests/QtAutogen/MocMacroName/CMakeLists.txt17
-rw-r--r--Tests/QtAutogen/MocMacroName/CustomMacros.hpp8
-rw-r--r--Tests/QtAutogen/MocMacroName/Gadget.cpp6
-rw-r--r--Tests/QtAutogen/MocMacroName/Gadget.hpp19
-rw-r--r--Tests/QtAutogen/MocMacroName/Object.cpp10
-rw-r--r--Tests/QtAutogen/MocMacroName/Object.hpp22
-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/MocOnly/CMakeLists.txt17
-rw-r--r--Tests/QtAutogen/MocOnly/IncA.cpp19
-rw-r--r--Tests/QtAutogen/MocOnly/IncA.hpp15
-rw-r--r--Tests/QtAutogen/MocOnly/IncB.cpp19
-rw-r--r--Tests/QtAutogen/MocOnly/IncB.hpp15
-rw-r--r--Tests/QtAutogen/MocOnly/StyleA.cpp5
-rw-r--r--Tests/QtAutogen/MocOnly/StyleA.hpp17
-rw-r--r--Tests/QtAutogen/MocOnly/StyleB.cpp5
-rw-r--r--Tests/QtAutogen/MocOnly/StyleB.hpp16
-rw-r--r--Tests/QtAutogen/MocOnly/main.cpp18
-rw-r--r--Tests/QtAutogen/MocOptions/CMakeLists.txt9
-rw-r--r--Tests/QtAutogen/MocOptions/Object.cpp5
-rw-r--r--Tests/QtAutogen/MocOptions/Object.hpp13
-rw-r--r--Tests/QtAutogen/MocOptions/main.cpp7
-rw-r--r--Tests/QtAutogen/MocOsMacros/CMakeLists.txt32
-rw-r--r--Tests/QtAutogen/MocOsMacros/TestClass.cpp82
-rw-r--r--Tests/QtAutogen/MocOsMacros/TestClass.hpp57
-rw-r--r--Tests/QtAutogen/MocOsMacros/main.cpp32
-rw-r--r--Tests/QtAutogen/MocSkipSource/CMakeLists.txt36
-rw-r--r--Tests/QtAutogen/MocSkipSource/qItemA.cpp5
-rw-r--r--Tests/QtAutogen/MocSkipSource/qItemA.hpp13
-rw-r--r--Tests/QtAutogen/MocSkipSource/qItemB.cpp5
-rw-r--r--Tests/QtAutogen/MocSkipSource/qItemB.hpp13
-rw-r--r--Tests/QtAutogen/MocSkipSource/qItemC.cpp17
-rw-r--r--Tests/QtAutogen/MocSkipSource/qItemC.hpp13
-rw-r--r--Tests/QtAutogen/MocSkipSource/qItemD.cpp17
-rw-r--r--Tests/QtAutogen/MocSkipSource/qItemD.hpp13
-rw-r--r--Tests/QtAutogen/MocSkipSource/skipMoc.cpp16
-rw-r--r--Tests/QtAutogen/ObjectLibrary/CMakeLists.txt18
-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/Parallel/CMakeLists.txt10
-rw-r--r--Tests/QtAutogen/Parallel/aaa/bbb/data.qrc6
-rw-r--r--Tests/QtAutogen/Parallel/aaa/bbb/item.cpp22
-rw-r--r--Tests/QtAutogen/Parallel/aaa/bbb/item.hpp18
-rw-r--r--Tests/QtAutogen/Parallel/aaa/data.qrc6
-rw-r--r--Tests/QtAutogen/Parallel/aaa/item.cpp22
-rw-r--r--Tests/QtAutogen/Parallel/aaa/item.hpp18
-rw-r--r--Tests/QtAutogen/Parallel/aaa/view.ui24
-rw-r--r--Tests/QtAutogen/Parallel/bbb/aaa/data.qrc6
-rw-r--r--Tests/QtAutogen/Parallel/bbb/aaa/item.cpp22
-rw-r--r--Tests/QtAutogen/Parallel/bbb/aaa/item.hpp18
-rw-r--r--Tests/QtAutogen/Parallel/bbb/data.qrc6
-rw-r--r--Tests/QtAutogen/Parallel/bbb/item.cpp23
-rw-r--r--Tests/QtAutogen/Parallel/bbb/item.hpp17
-rw-r--r--Tests/QtAutogen/Parallel/bbb/view.ui24
-rw-r--r--Tests/QtAutogen/Parallel/ccc/data.qrc6
-rw-r--r--Tests/QtAutogen/Parallel/ccc/item.cpp25
-rw-r--r--Tests/QtAutogen/Parallel/ccc/item.hpp18
-rw-r--r--Tests/QtAutogen/Parallel/ccc/view.ui24
-rw-r--r--Tests/QtAutogen/Parallel/data.qrc5
-rw-r--r--Tests/QtAutogen/Parallel/item.cpp20
-rw-r--r--Tests/QtAutogen/Parallel/item.hpp15
-rw-r--r--Tests/QtAutogen/Parallel/main.cpp16
-rw-r--r--Tests/QtAutogen/Parallel/parallel.cmake24
-rw-r--r--Tests/QtAutogen/Parallel/view.ui24
-rw-r--r--Tests/QtAutogen/Parallel1/CMakeLists.txt10
-rw-r--r--Tests/QtAutogen/Parallel2/CMakeLists.txt10
-rw-r--r--Tests/QtAutogen/Parallel3/CMakeLists.txt10
-rw-r--r--Tests/QtAutogen/Parallel4/CMakeLists.txt10
-rw-r--r--Tests/QtAutogen/ParallelAUTO/CMakeLists.txt10
-rw-r--r--Tests/QtAutogen/RccEmpty/CMakeLists.txt8
-rw-r--r--Tests/QtAutogen/RccEmpty/rccEmpty.cpp9
-rw-r--r--Tests/QtAutogen/RccEmpty/rccEmptyRes.qrc4
-rw-r--r--Tests/QtAutogen/RccOffMocLibrary/CMakeLists.txt17
-rw-r--r--Tests/QtAutogen/RccOffMocLibrary/empty.cpp1
-rw-r--r--Tests/QtAutogen/RccOffMocLibrary/empty.h9
-rw-r--r--Tests/QtAutogen/RccOffMocLibrary/not_generated_file.qrc5
-rw-r--r--Tests/QtAutogen/RccOnly/CMakeLists.txt8
-rw-r--r--Tests/QtAutogen/RccOnly/rccOnly.cpp9
-rw-r--r--Tests/QtAutogen/RccOnly/rccOnlyRes.qrc5
-rw-r--r--Tests/QtAutogen/RccSkipSource/CMakeLists.txt23
-rw-r--r--Tests/QtAutogen/RccSkipSource/skipRcc.cpp9
-rw-r--r--Tests/QtAutogen/RccSkipSource/skipRccBad1.qrc5
-rw-r--r--Tests/QtAutogen/RccSkipSource/skipRccBad2.qrc5
-rw-r--r--Tests/QtAutogen/RccSkipSource/skipRccGood.qrc6
-rw-r--r--Tests/QtAutogen/RerunMocBasic/CMakeLists.txt102
-rw-r--r--Tests/QtAutogen/RerunMocBasic/MocBasic/CMakeLists.txt24
-rw-r--r--Tests/QtAutogen/RerunMocBasic/MocBasic/input.txt1
-rw-r--r--Tests/QtAutogen/RerunMocBasic/MocBasic/main.cpp.in23
-rw-r--r--Tests/QtAutogen/RerunMocBasic/MocBasic/res1.qrc5
-rw-r--r--Tests/QtAutogen/RerunMocBasic/MocBasic/test1a.h.in8
-rw-r--r--Tests/QtAutogen/RerunMocBasic/MocBasic/test1b.h.in7
-rw-r--r--Tests/QtAutogen/RerunMocBasic/dummy.cpp5
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/CMakeLists.txt134
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/CMakeLists.txt31
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.cpp6
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.hpp17
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.json1
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA_Custom.json1
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleB.cpp6
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleB.hpp17
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleC.cpp6
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleC.hpp17
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleD.cpp6
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleD.hpp17
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleE.cpp9
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleE.hpp10
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleEInclude.hpp17
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/UtilityMacros.hpp7
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleB.json1
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleB_Custom.json1
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleC.json1
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleD.json1
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleE.json1
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/MocPlugin/main.cpp6
-rw-r--r--Tests/QtAutogen/RerunMocPlugin/dummy.cpp5
-rw-r--r--Tests/QtAutogen/RerunRccConfigChange/CMakeLists.txt47
-rw-r--r--Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/CMakeLists.txt26
-rw-r--r--Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/main.cpp5
-rw-r--r--Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen.qrc.in6
-rw-r--r--Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen/input1.txt.in1
-rw-r--r--Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen/input2.txt.in1
-rw-r--r--Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain.qrc6
-rw-r--r--Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain/input1.txt1
-rw-r--r--Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain/input2.txt1
-rw-r--r--Tests/QtAutogen/RerunRccConfigChange/dummy.cpp5
-rw-r--r--Tests/QtAutogen/RerunRccDepends/CMakeLists.txt153
-rw-r--r--Tests/QtAutogen/RerunRccDepends/RccDepends/CMakeLists.txt33
-rw-r--r--Tests/QtAutogen/RerunRccDepends/RccDepends/main.cpp5
-rw-r--r--Tests/QtAutogen/RerunRccDepends/RccDepends/resGen/input.txt.in1
-rw-r--r--Tests/QtAutogen/RerunRccDepends/RccDepends/resGen/inputAdded.txt.in1
-rw-r--r--Tests/QtAutogen/RerunRccDepends/RccDepends/resGenA.qrc.in5
-rw-r--r--Tests/QtAutogen/RerunRccDepends/RccDepends/resGenB.qrc.in6
-rw-r--r--Tests/QtAutogen/RerunRccDepends/RccDepends/resPlain/input.txt.in1
-rw-r--r--Tests/QtAutogen/RerunRccDepends/RccDepends/resPlain/inputAdded.txt.in1
-rw-r--r--Tests/QtAutogen/RerunRccDepends/RccDepends/resPlainA.qrc.in5
-rw-r--r--Tests/QtAutogen/RerunRccDepends/RccDepends/resPlainB.qrc.in6
-rw-r--r--Tests/QtAutogen/RerunRccDepends/dummy.cpp5
-rw-r--r--Tests/QtAutogen/SameName/CMakeLists.txt43
-rw-r--r--Tests/QtAutogen/SameName/aaa/bbb/data.qrc6
-rw-r--r--Tests/QtAutogen/SameName/aaa/bbb/item.cpp22
-rw-r--r--Tests/QtAutogen/SameName/aaa/bbb/item.hpp18
-rw-r--r--Tests/QtAutogen/SameName/aaa/data.qrc6
-rw-r--r--Tests/QtAutogen/SameName/aaa/item.cpp22
-rw-r--r--Tests/QtAutogen/SameName/aaa/item.hpp18
-rw-r--r--Tests/QtAutogen/SameName/aaa/view.ui24
-rw-r--r--Tests/QtAutogen/SameName/bbb/aaa/data.qrc6
-rw-r--r--Tests/QtAutogen/SameName/bbb/aaa/item.cpp22
-rw-r--r--Tests/QtAutogen/SameName/bbb/aaa/item.hpp18
-rw-r--r--Tests/QtAutogen/SameName/bbb/data.qrc6
-rw-r--r--Tests/QtAutogen/SameName/bbb/item.cpp23
-rw-r--r--Tests/QtAutogen/SameName/bbb/item.hpp17
-rw-r--r--Tests/QtAutogen/SameName/bbb/view.ui24
-rw-r--r--Tests/QtAutogen/SameName/ccc/data.qrc6
-rw-r--r--Tests/QtAutogen/SameName/ccc/item.cpp25
-rw-r--r--Tests/QtAutogen/SameName/ccc/item.hpp18
-rw-r--r--Tests/QtAutogen/SameName/ccc/view.ui24
-rw-r--r--Tests/QtAutogen/SameName/data.qrc5
-rw-r--r--Tests/QtAutogen/SameName/item.cpp20
-rw-r--r--Tests/QtAutogen/SameName/item.hpp15
-rw-r--r--Tests/QtAutogen/SameName/main.cpp27
-rw-r--r--Tests/QtAutogen/SameName/object.h13
-rw-r--r--Tests/QtAutogen/SameName/object.h++13
-rw-r--r--Tests/QtAutogen/SameName/object.hpp13
-rw-r--r--Tests/QtAutogen/SameName/object.hxx13
-rw-r--r--Tests/QtAutogen/SameName/view.ui24
-rw-r--r--Tests/QtAutogen/StaticLibraryCycle/CMakeLists.txt20
-rw-r--r--Tests/QtAutogen/StaticLibraryCycle/a.cpp12
-rw-r--r--Tests/QtAutogen/StaticLibraryCycle/a.h15
-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/QtAutogen/TestMacros.cmake61
-rw-r--r--Tests/QtAutogen/Tests.cmake48
-rw-r--r--Tests/QtAutogen/UicInclude/CMakeLists.txt11
-rw-r--r--Tests/QtAutogen/UicInclude/PageC.ui24
-rw-r--r--Tests/QtAutogen/UicInclude/PageC2.ui24
-rw-r--r--Tests/QtAutogen/UicInclude/dirA/PageA.ui24
-rw-r--r--Tests/QtAutogen/UicInclude/dirB/PageB.ui24
-rw-r--r--Tests/QtAutogen/UicInclude/dirB/PageB2.ui24
-rw-r--r--Tests/QtAutogen/UicInclude/dirB/subB/PageBsub.ui24
-rw-r--r--Tests/QtAutogen/UicInclude/main.cpp18
-rw-r--r--Tests/QtAutogen/UicInclude/main.hpp6
-rw-r--r--Tests/QtAutogen/UicInclude/subC/PageCsub.ui24
-rw-r--r--Tests/QtAutogen/UicInterface/CMakeLists.txt58
-rw-r--r--Tests/QtAutogen/UicInterface/klocalizedstring.cpp12
-rw-r--r--Tests/QtAutogen/UicInterface/klocalizedstring.h17
-rw-r--r--Tests/QtAutogen/UicInterface/libwidget.cpp14
-rw-r--r--Tests/QtAutogen/UicInterface/libwidget.h25
-rw-r--r--Tests/QtAutogen/UicInterface/libwidget.ui32
-rw-r--r--Tests/QtAutogen/UicInterface/main.cpp67
-rw-r--r--Tests/QtAutogen/UicInterface/mywidget.cpp14
-rw-r--r--Tests/QtAutogen/UicInterface/mywidget.h25
-rw-r--r--Tests/QtAutogen/UicInterface/mywidget.ui32
-rw-r--r--Tests/QtAutogen/UicNoGui/CMakeLists.txt16
-rw-r--r--Tests/QtAutogen/UicNoGui/MocOnly/CMakeLists.txt3
-rw-r--r--Tests/QtAutogen/UicNoGui/MocOnly/main.cpp15
-rw-r--r--Tests/QtAutogen/UicNoGui/NoQt/CMakeLists.txt2
-rw-r--r--Tests/QtAutogen/UicNoGui/NoQt/main.cpp4
-rw-r--r--Tests/QtAutogen/UicNoGui/main.cpp9
-rw-r--r--Tests/QtAutogen/UicOnly/CMakeLists.txt8
-rw-r--r--Tests/QtAutogen/UicOnly/UicOnly.cpp18
-rw-r--r--Tests/QtAutogen/UicOnly/UicOnly.hpp15
-rw-r--r--Tests/QtAutogen/UicOnly/main.cpp7
-rw-r--r--Tests/QtAutogen/UicOnly/uiA.ui24
-rw-r--r--Tests/QtAutogen/UicOnly/uiB.ui24
-rw-r--r--Tests/QtAutogen/UicOnly/uiC.ui24
-rw-r--r--Tests/QtAutogen/UicOnly/uiD.ui24
-rw-r--r--Tests/QtAutogen/UicSkipSource/CMakeLists.txt22
-rw-r--r--Tests/QtAutogen/UicSkipSource/skipUic.cpp22
-rw-r--r--Tests/QtAutogen/UicSkipSource/skipUicGen.cpp7
-rw-r--r--Tests/QtAutogen/UicSkipSource/skipUicGen.hpp8
-rw-r--r--Tests/QtAutogen/UicSkipSource/skipUicNoGen1.cpp7
-rw-r--r--Tests/QtAutogen/UicSkipSource/skipUicNoGen1.hpp8
-rw-r--r--Tests/QtAutogen/UicSkipSource/skipUicNoGen2.cpp7
-rw-r--r--Tests/QtAutogen/UicSkipSource/skipUicNoGen2.hpp8
-rw-r--r--Tests/QtAutogen/UicSkipSource/ui_nogen1.h6
-rw-r--r--Tests/QtAutogen/UicSkipSource/ui_nogen2.h6
-rw-r--r--Tests/QtAutogen/UicSkipSource/uigen1.ui24
-rw-r--r--Tests/QtAutogen/UicSkipSource/uigen2.ui24
-rw-r--r--Tests/README.rst31
-rw-r--r--Tests/RunCMake/Android/android_lib.cxx4
-rw-r--r--Tests/RunCMake/Android/check_binary.cmake8
-rw-r--r--Tests/RunCMake/Autogen/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/Autogen/NoQt-stderr.txt8
-rw-r--r--Tests/RunCMake/Autogen/NoQt.cmake6
-rw-r--r--Tests/RunCMake/Autogen/QtInFunction.cmake13
-rw-r--r--Tests/RunCMake/Autogen/QtInFunctionNested-stderr.txt8
-rw-r--r--Tests/RunCMake/Autogen/QtInFunctionNested.cmake17
-rw-r--r--Tests/RunCMake/Autogen/QtInFunctionProperty.cmake21
-rw-r--r--Tests/RunCMake/Autogen/RunCMakeTest.cmake8
-rw-r--r--Tests/RunCMake/Autogen/empty.cpp0
-rw-r--r--Tests/RunCMake/BuildDepends/BuildUnderSource.c5
-rw-r--r--Tests/RunCMake/BuildDepends/BuildUnderSource.cmake9
-rw-r--r--Tests/RunCMake/BuildDepends/BuildUnderSource.step1.cmake3
-rw-r--r--Tests/RunCMake/BuildDepends/BuildUnderSource.step2.cmake3
-rw-r--r--Tests/RunCMake/BundleUtilities/CMP0080-COMMAND.cmake5
-rw-r--r--Tests/RunCMake/BundleUtilities/CMP0080-NEW-result.txt1
-rw-r--r--Tests/RunCMake/BundleUtilities/CMP0080-NEW-stderr.txt2
-rw-r--r--Tests/RunCMake/BundleUtilities/CMP0080-NEW.cmake2
-rw-r--r--Tests/RunCMake/BundleUtilities/CMP0080-OLD.cmake2
-rw-r--r--Tests/RunCMake/BundleUtilities/CMP0080-WARN-stderr.txt10
-rw-r--r--Tests/RunCMake/BundleUtilities/CMP0080-WARN.cmake1
-rw-r--r--Tests/RunCMake/BundleUtilities/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/BundleUtilities/RunCMakeTest.cmake11
-rw-r--r--Tests/RunCMake/Byproducts/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/Byproducts/CleanByproducts.cmake93
-rw-r--r--Tests/RunCMake/Byproducts/RunCMakeTest.cmake58
-rw-r--r--Tests/RunCMake/Byproducts/files.cmake.in2
-rw-r--r--Tests/RunCMake/Byproducts/foo.cpp14
-rw-r--r--Tests/RunCMake/CMP0037/CMP0037-OLD-reserved-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0037/CMP0037-OLD-space-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0037/CMP0037-WARN-reserved-stderr.txt36
-rw-r--r--Tests/RunCMake/CMP0037/CMP0037-WARN-reserved.cmake4
-rw-r--r--Tests/RunCMake/CMP0037/NEW-cond-package-result.txt1
-rw-r--r--Tests/RunCMake/CMP0037/NEW-cond-package-stderr.txt4
-rw-r--r--Tests/RunCMake/CMP0037/NEW-cond-package.cmake5
-rw-r--r--Tests/RunCMake/CMP0037/NEW-cond-package_source-result.txt1
-rw-r--r--Tests/RunCMake/CMP0037/NEW-cond-package_source-stderr.txt5
-rw-r--r--Tests/RunCMake/CMP0037/NEW-cond-package_source.cmake5
-rw-r--r--Tests/RunCMake/CMP0037/NEW-cond-test-result.txt1
-rw-r--r--Tests/RunCMake/CMP0037/NEW-cond-test-stderr.txt4
-rw-r--r--Tests/RunCMake/CMP0037/NEW-cond-test.cmake5
-rw-r--r--Tests/RunCMake/CMP0037/NEW-cond.cmake4
-rw-r--r--Tests/RunCMake/CMP0037/OLD-cond-package-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0037/OLD-cond-package.cmake5
-rw-r--r--Tests/RunCMake/CMP0037/OLD-cond-package_source-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0037/OLD-cond-package_source.cmake5
-rw-r--r--Tests/RunCMake/CMP0037/OLD-cond-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0037/OLD-cond-test-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0037/OLD-cond-test.cmake5
-rw-r--r--Tests/RunCMake/CMP0037/OLD-cond.cmake5
-rw-r--r--Tests/RunCMake/CMP0037/WARN-cond-package-stderr.txt11
-rw-r--r--Tests/RunCMake/CMP0037/WARN-cond-package.cmake5
-rw-r--r--Tests/RunCMake/CMP0037/WARN-cond-package_source-stderr.txt11
-rw-r--r--Tests/RunCMake/CMP0037/WARN-cond-package_source.cmake5
-rw-r--r--Tests/RunCMake/CMP0037/WARN-cond-test-stderr.txt11
-rw-r--r--Tests/RunCMake/CMP0037/WARN-cond-test.cmake5
-rw-r--r--Tests/RunCMake/CMP0037/WARN-cond.cmake4
-rw-r--r--Tests/RunCMake/CMP0038/CMP0038-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0039/CMP0039-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0040/CMP0040-OLD-existing-target-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0040/CMP0040-OLD-missing-target-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0041/CMP0041-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0041/CMP0041-tid-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0042/CMP0042-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0043/CMP0043-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0045/CMP0045-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0046/CMP0046-OLD-existing-dependency-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0046/CMP0046-OLD-missing-dependency-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0049/CMP0049-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0050/CMP0050-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0055/CMP0055-OLD-Out-of-Scope-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0055/CMP0055-OLD-Reject-Arguments-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0060/CMP0060-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0064/CMP0064-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0081/CMP0081-Common.cmake5
-rw-r--r--Tests/RunCMake/CMP0081/CMP0081-NEW-result.txt1
-rw-r--r--Tests/RunCMake/CMP0081/CMP0081-NEW-stderr.txt4
-rw-r--r--Tests/RunCMake/CMP0081/CMP0081-NEW.cmake4
-rw-r--r--Tests/RunCMake/CMP0081/CMP0081-OLD-result.txt1
-rw-r--r--Tests/RunCMake/CMP0081/CMP0081-OLD.cmake4
-rw-r--r--Tests/RunCMake/CMP0081/CMP0081-WARN-result.txt1
-rw-r--r--Tests/RunCMake/CMP0081/CMP0081-WARN-stderr.txt10
-rw-r--r--Tests/RunCMake/CMP0081/CMP0081-WARN.cmake2
-rw-r--r--Tests/RunCMake/CMP0081/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/CMP0081/RunCMakeTest.cmake5
-rw-r--r--Tests/RunCMake/CMP0081/empty.cpp7
-rw-r--r--Tests/RunCMake/CMakeRoleGlobalProperty/BuildAndTest/CMakeLists.txt10
-rw-r--r--Tests/RunCMake/CMakeRoleGlobalProperty/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/CMakeRoleGlobalProperty/CMakeLists.txt.in4
-rw-r--r--Tests/RunCMake/CMakeRoleGlobalProperty/FindDummyPackage.cmake8
-rw-r--r--Tests/RunCMake/CMakeRoleGlobalProperty/Project.cmake10
-rw-r--r--Tests/RunCMake/CMakeRoleGlobalProperty/RunCMakeTest.cmake17
-rw-r--r--Tests/RunCMake/CMakeRoleGlobalProperty/Script.cmake6
-rw-r--r--Tests/RunCMake/CMakeRoleGlobalProperty/sub/CMakeLists.txt4
-rw-r--r--Tests/RunCMake/CMakeRoleGlobalProperty/test.cmake.in7
-rw-r--r--Tests/RunCMake/CPack/External/Helpers.cmake31
-rw-r--r--Tests/RunCMake/CPack/External/Prerequirements.cmake0
-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/DEFAULT_PERMISSIONS/ExpectedFiles.cmake6
-rw-r--r--Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/VerifyResult.cmake39
-rw-r--r--Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/invalid_CMAKE_var-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/invalid_CPACK_var-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/test.cmake34
-rw-r--r--Tests/RunCMake/CPack/tests/EXTERNAL/ExpectedFiles.cmake7
-rw-r--r--Tests/RunCMake/CPack/tests/EXTERNAL/VerifyResult.cmake3
-rw-r--r--Tests/RunCMake/CPack/tests/EXTERNAL/bad_major-stderr.txt6
-rw-r--r--Tests/RunCMake/CPack/tests/EXTERNAL/bad_minor-stderr.txt6
-rw-r--r--Tests/RunCMake/CPack/tests/EXTERNAL/create_package.cmake31
-rw-r--r--Tests/RunCMake/CPack/tests/EXTERNAL/expected-json-1.0.txt176
-rw-r--r--Tests/RunCMake/CPack/tests/EXTERNAL/invalid_bad-stderr.txt6
-rw-r--r--Tests/RunCMake/CPack/tests/EXTERNAL/stage_and_package-stderr.txt1
-rw-r--r--Tests/RunCMake/CPack/tests/EXTERNAL/stage_and_package-stdout.txt1
-rw-r--r--Tests/RunCMake/CPack/tests/EXTERNAL/test.cmake86
-rw-r--r--Tests/RunCMake/CPack/tests/TIMESTAMPS/ExpectedFiles.cmake2
-rw-r--r--Tests/RunCMake/CPack/tests/TIMESTAMPS/VerifyResult.cmake58
-rw-r--r--Tests/RunCMake/CPack/tests/TIMESTAMPS/test.cmake3
-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/CPackCommandLine/NotAGenerator-result.txt1
-rw-r--r--Tests/RunCMake/CPackCommandLine/NotAGenerator-stderr.txt1
-rw-r--r--Tests/RunCMake/CPackCommandLine/RunCMakeTest.cmake10
-rw-r--r--Tests/RunCMake/CPackConfig/Version1-check.cmake6
-rw-r--r--Tests/RunCMake/CPackConfig/Version1.cmake1
-rw-r--r--Tests/RunCMake/CPackConfig/Version2-check.cmake6
-rw-r--r--Tests/RunCMake/CPackConfig/Version2.cmake1
-rw-r--r--Tests/RunCMake/CPackConfig/Version3-check.cmake6
-rw-r--r--Tests/RunCMake/CPackConfig/Version3.cmake1
-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.cmake42
-rw-r--r--Tests/RunCMake/CSharpCustomCommand/TargetWithCommand-build-stdout.txt1
-rw-r--r--Tests/RunCMake/CSharpCustomCommand/TargetWithCommand.cmake4
-rw-r--r--Tests/RunCMake/CSharpCustomCommand/dummy.cs0
-rw-r--r--Tests/RunCMake/CSharpCustomCommand/test.cs.in8
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ImportLib.cmake45
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ImportLib.cs8
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ImportLibMixed.cxx8
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ImportLibMixedNative.cxx8
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ImportLibMixedNative.h13
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ImportLibNative.cxx8
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ImportLibNative.h13
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ImportLibPure.cxx8
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ImportLibSafe.cxx8
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ReferenceImport.cmake88
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ReferenceImport.cs13
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ReferenceImportMixed.cxx20
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ReferenceImportNative.cxx13
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ReferenceImportPure.cxx17
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/ReferenceImportSafe.cxx17
-rw-r--r--Tests/RunCMake/CSharpReferenceImport/RunCMakeTest.cmake41
-rw-r--r--Tests/RunCMake/CTest/CTestTestfile.cmake.in1
-rw-r--r--Tests/RunCMake/CTest/NotOn-check.cmake8
-rw-r--r--Tests/RunCMake/CTest/NotOn.cmake3
-rw-r--r--Tests/RunCMake/CTestCommandLine/TestAffinity-stdout.txt1
-rw-r--r--Tests/RunCMake/CTestCommandLine/TestStdin-stdin.txt1
-rw-r--r--Tests/RunCMake/CTestCommandLine/TestStdin-stdout.txt1
-rw-r--r--Tests/RunCMake/CTestCommandLine/show-only_bad-result.txt1
-rw-r--r--Tests/RunCMake/CTestCommandLine/show-only_bad-stderr.txt1
-rw-r--r--Tests/RunCMake/CTestCommandLine/show-only_human-stdout.txt1
-rw-r--r--Tests/RunCMake/CTestCommandLine/show-only_json-v1-check.cmake1
-rw-r--r--Tests/RunCMake/CTestCommandLine/show-only_json-v1_check.py116
-rw-r--r--Tests/RunCMake/CTestCommandLine/show_only_json_check.py24
-rw-r--r--Tests/RunCMake/CTestCommandLine/test-load-wait-stdout.txt8
-rw-r--r--Tests/RunCMake/CacheNewline/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/CacheNewline/CacheNewline-check.cmake16
-rw-r--r--Tests/RunCMake/CacheNewline/CacheNewline-stderr.txt2
-rw-r--r--Tests/RunCMake/CacheNewline/CacheNewline.cmake5
-rw-r--r--Tests/RunCMake/CacheNewline/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/CacheNewline/cache-regex.txt6
-rw-r--r--Tests/RunCMake/CheckModules/CMP0075-stderr.txt50
-rw-r--r--Tests/RunCMake/CheckModules/CMP0075.cmake124
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage-result.txt1
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage-stderr.txt8
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage.cmake3
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesOk.cmake6
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesOkNoC.cmake4
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument-result.txt1
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument-stderr.txt8
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument.cmake3
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage-result.txt1
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage-stderr.txt10
-rw-r--r--Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage.cmake3
-rw-r--r--Tests/RunCMake/CommandLine/B-no-arg-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/B-no-arg-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/B-no-arg2-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/B-no-arg2-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-bad-number-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-bad-number-stderr.txt3
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-good-number-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-good-number-trailing--target-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-large-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-large-stderr.txt3
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-number-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-number-trailing--target-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-bad-number-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-bad-number-stderr.txt3
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-good-number-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-good-number-trailing--target-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-zero-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build--parallel-zero-stderr.txt3
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-bad-number-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-bad-number-stderr.txt3
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-good-number-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-good-number-trailing--target-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-large-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-large-stderr.txt3
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-number-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-number-trailing--target-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-bad-number-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-bad-number-stderr.txt3
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-good-number-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-good-number-trailing--target-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-zero-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-jobs-zero-stderr.txt3
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-jobs-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-first-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-first-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-second-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-second-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Cno-file-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Cno-file-stderr.txt3
-rw-r--r--Tests/RunCMake/CommandLine/D-no-src-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/D-no-src-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Dno-src-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Dno-src-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-no----result.txt1
-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.txt1
-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.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-stderr.txt6
-rw-r--r--Tests/RunCMake/CommandLine/E_compare_files-different-eol-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_compare_files-different-eol-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_compare_files-ignore-eol-nonexistent-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_compare_files-ignore-eol-nonexistent-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_make_directory-directory-with-parent-check.cmake3
-rw-r--r--Tests/RunCMake/CommandLine/E_make_directory-three-directories-check.cmake6
-rw-r--r--Tests/RunCMake/CommandLine/E_make_directory-two-directories-and-file-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_make_directory-two-directories-and-file-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_remove_directory-directory-with-parent-check.cmake3
-rw-r--r--Tests/RunCMake/CommandLine/E_remove_directory-directory-with-parent-stderr.txt0
-rw-r--r--Tests/RunCMake/CommandLine/E_remove_directory-three-directories-check.cmake6
-rw-r--r--Tests/RunCMake/CommandLine/E_remove_directory-three-directories-stderr.txt0
-rw-r--r--Tests/RunCMake/CommandLine/E_remove_directory-two-directories-and-file-check.cmake3
-rw-r--r--Tests/RunCMake/CommandLine/E_remove_directory-two-directories-and-file-stderr.txt0
-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/E_touch-nonexistent-dir-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_touch-nonexistent-dir-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/EnvGenerator/CMakeLists.txt10
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-A-platform-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-A-platform-stderr-vs9.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-A-platform-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-G-implicit-platform-stdout.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-T-toolset-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-T-toolset-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-bad-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-bad-stderr.txt5
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-instance-invalid-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-instance-invalid-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-ninja-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-ninja-stderr.txt4
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-platform-invalid-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-platform-invalid-stderr-vs9.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-platform-invalid-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-toolset-invalid-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-toolset-invalid-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-unset-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-unset-stderr.txt4
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-warnings-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Envgen-warnings-stderr.txt7
-rw-r--r--Tests/RunCMake/CommandLine/ExplicitDirs/CMakeLists.txt9
-rw-r--r--Tests/RunCMake/CommandLine/S-no-arg-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/S-no-arg-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/S-no-arg2-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/S-no-arg2-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/U-no-src-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/U-no-src-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Uno-src-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Uno-src-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/Wizard-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/Wizard-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/compare_files/crlf1
-rw-r--r--Tests/RunCMake/CommandLine/compare_files/empty10
-rw-r--r--Tests/RunCMake/CommandLine/compare_files/empty20
-rw-r--r--Tests/RunCMake/CommandLine/compare_files/lf1
-rw-r--r--Tests/RunCMake/CommandLine/dir-install-options-to-vars/cmake_install.cmake15
-rw-r--r--Tests/RunCMake/CommandLine/install-bad-dir-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/install-bad-dir-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/install-no-dir-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/install-no-dir-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/install-options-to-vars-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/install-options-to-vars-stderr.txt4
-rw-r--r--Tests/RunCMake/CommandLine/no-S-B-stderr.txt4
-rw-r--r--Tests/RunCMake/CommandLine/trace-expand-warn-uninitialized-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/trace-expand-warn-uninitialized.cmake4
-rw-r--r--Tests/RunCMake/CommandLine/warn-uninitialized-stderr.txt53
-rw-r--r--Tests/RunCMake/CommandLine/warn-uninitialized.cmake18
-rw-r--r--Tests/RunCMake/CommandLineTar/bad-file-result.txt1
-rw-r--r--Tests/RunCMake/CommandLineTar/bad-file-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLineTar/bad-without-action-result.txt1
-rw-r--r--Tests/RunCMake/CommandLineTar/bad-without-action-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLineTar/bad-wrong-flag-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLineTar/end-opt2-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLineTar/pax-zstd.cmake10
-rw-r--r--Tests/RunCMake/CommandLineTar/test-file.txt0
-rw-r--r--Tests/RunCMake/CommandLineTar/without-files-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLineTar/zip-filtered.cmake28
-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/Fortran-Build-stdout.txt1
-rw-r--r--Tests/RunCMake/CompilerLauncher/Fortran-launch-Build-stdout.txt1
-rw-r--r--Tests/RunCMake/CompilerLauncher/Fortran-launch.cmake3
-rw-r--r--Tests/RunCMake/CompilerLauncher/Fortran.cmake4
-rw-r--r--Tests/RunCMake/CompilerLauncher/main.F2
-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-error-Build-result.txt1
-rw-r--r--Tests/RunCMake/Cppcheck/C-error-Build-stdout.txt1
-rw-r--r--Tests/RunCMake/Cppcheck/C-error.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.cmake24
-rw-r--r--Tests/RunCMake/Cppcheck/main.c4
-rw-r--r--Tests/RunCMake/Cppcheck/main.cxx4
-rw-r--r--Tests/RunCMake/CrosscompilingEmulator/AddCustomCommandWithArg-build-check.cmake3
-rw-r--r--Tests/RunCMake/CrosscompilingEmulator/AddCustomCommandWithArg.cmake14
-rw-r--r--Tests/RunCMake/CrosscompilingEmulator/AddCustomTargetWithArg-build-check.cmake1
-rw-r--r--Tests/RunCMake/CrosscompilingEmulator/AddCustomTargetWithArg.cmake9
-rw-r--r--Tests/RunCMake/ExternalProject/IncludeScope-Add-result.txt1
-rw-r--r--Tests/RunCMake/ExternalProject/IncludeScope-Add-stderr.txt7
-rw-r--r--Tests/RunCMake/ExternalProject/IncludeScope-Add.cmake12
-rw-r--r--Tests/RunCMake/ExternalProject/IncludeScope-Add_Step-result.txt1
-rw-r--r--Tests/RunCMake/ExternalProject/IncludeScope-Add_Step-stderr.txt7
-rw-r--r--Tests/RunCMake/ExternalProject/IncludeScope-Add_Step.cmake13
-rw-r--r--Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-result.txt1
-rw-r--r--Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-stderr.txt1
-rw-r--r--Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-stdout.txt8
-rw-r--r--Tests/RunCMake/ExternalProject/LogOutputOnFailure.cmake20
-rw-r--r--Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-result.txt1
-rw-r--r--Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-stderr.txt1
-rw-r--r--Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-stdout.txt7
-rw-r--r--Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged.cmake21
-rw-r--r--Tests/RunCMake/ExternalProject/MultiCommand-build-stdout.txt15
-rw-r--r--Tests/RunCMake/ExternalProject/MultiCommand.cmake30
-rw-r--r--Tests/RunCMake/ExternalProject/Substitutions-build-stdout.txt7
-rw-r--r--Tests/RunCMake/ExternalProject/Substitutions.cmake25
-rw-r--r--Tests/RunCMake/FPHSA/FindPseudoNoVersionVar.cmake6
-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/FetchContent/CMakeLists.txt7
-rw-r--r--Tests/RunCMake/FetchContent/DirOverrides.cmake46
-rw-r--r--Tests/RunCMake/FetchContent/DirectIgnoresDetails-stdout.txt1
-rw-r--r--Tests/RunCMake/FetchContent/DirectIgnoresDetails.cmake12
-rw-r--r--Tests/RunCMake/FetchContent/DownloadTwice-result.txt1
-rw-r--r--Tests/RunCMake/FetchContent/DownloadTwice-stderr.txt1
-rw-r--r--Tests/RunCMake/FetchContent/DownloadTwice.cmake9
-rw-r--r--Tests/RunCMake/FetchContent/FirstDetailsWin-stdout.txt1
-rw-r--r--Tests/RunCMake/FetchContent/FirstDetailsWin.cmake16
-rw-r--r--Tests/RunCMake/FetchContent/GetProperties.cmake67
-rw-r--r--Tests/RunCMake/FetchContent/MakeAvailable-stdout.txt2
-rw-r--r--Tests/RunCMake/FetchContent/MakeAvailable.cmake20
-rw-r--r--Tests/RunCMake/FetchContent/MakeAvailableTwice-stdout.txt4
-rw-r--r--Tests/RunCMake/FetchContent/MakeAvailableTwice.cmake12
-rw-r--r--Tests/RunCMake/FetchContent/MakeAvailableUndeclared-result.txt1
-rw-r--r--Tests/RunCMake/FetchContent/MakeAvailableUndeclared-stderr.txt1
-rw-r--r--Tests/RunCMake/FetchContent/MakeAvailableUndeclared.cmake3
-rw-r--r--Tests/RunCMake/FetchContent/MissingDetails-result.txt1
-rw-r--r--Tests/RunCMake/FetchContent/MissingDetails-stderr.txt1
-rw-r--r--Tests/RunCMake/FetchContent/MissingDetails.cmake3
-rw-r--r--Tests/RunCMake/FetchContent/RunCMakeTest.cmake32
-rw-r--r--Tests/RunCMake/FetchContent/SameGenerator.cmake17
-rw-r--r--Tests/RunCMake/FetchContent/ScriptMode.cmake35
-rw-r--r--Tests/RunCMake/FetchContent/UsesTerminalOverride-stdout.txt2
-rw-r--r--Tests/RunCMake/FetchContent/UsesTerminalOverride.cmake17
-rw-r--r--Tests/RunCMake/FetchContent/VarDefinitions.cmake75
-rw-r--r--Tests/RunCMake/FetchContent/WithProject/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/FetchContent/WithoutProject/confirmMessage.cmake1
-rw-r--r--Tests/RunCMake/FileAPI/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/FileAPI/ClientStateful-check.cmake68
-rw-r--r--Tests/RunCMake/FileAPI/ClientStateful-check.py258
-rw-r--r--Tests/RunCMake/FileAPI/ClientStateful-prep.cmake73
-rw-r--r--Tests/RunCMake/FileAPI/ClientStateful.cmake0
-rw-r--r--Tests/RunCMake/FileAPI/ClientStateless-check.cmake15
-rw-r--r--Tests/RunCMake/FileAPI/ClientStateless-check.py26
-rw-r--r--Tests/RunCMake/FileAPI/ClientStateless-prep.cmake5
-rw-r--r--Tests/RunCMake/FileAPI/ClientStateless.cmake0
-rw-r--r--Tests/RunCMake/FileAPI/DuplicateStateless-check.cmake20
-rw-r--r--Tests/RunCMake/FileAPI/DuplicateStateless-check.py31
-rw-r--r--Tests/RunCMake/FileAPI/DuplicateStateless-prep.cmake10
-rw-r--r--Tests/RunCMake/FileAPI/DuplicateStateless.cmake0
-rw-r--r--Tests/RunCMake/FileAPI/Empty-check.cmake8
-rw-r--r--Tests/RunCMake/FileAPI/Empty-check.py15
-rw-r--r--Tests/RunCMake/FileAPI/Empty-prep.cmake1
-rw-r--r--Tests/RunCMake/FileAPI/Empty.cmake0
-rw-r--r--Tests/RunCMake/FileAPI/EmptyClient-check.cmake9
-rw-r--r--Tests/RunCMake/FileAPI/EmptyClient-check.py20
-rw-r--r--Tests/RunCMake/FileAPI/EmptyClient-prep.cmake2
-rw-r--r--Tests/RunCMake/FileAPI/EmptyClient.cmake0
-rw-r--r--Tests/RunCMake/FileAPI/MixedStateless-check.cmake16
-rw-r--r--Tests/RunCMake/FileAPI/MixedStateless-check.py27
-rw-r--r--Tests/RunCMake/FileAPI/MixedStateless-prep.cmake6
-rw-r--r--Tests/RunCMake/FileAPI/MixedStateless.cmake0
-rw-r--r--Tests/RunCMake/FileAPI/Nothing-check.cmake1
-rw-r--r--Tests/RunCMake/FileAPI/Nothing-prep.cmake1
-rw-r--r--Tests/RunCMake/FileAPI/Nothing.cmake0
-rw-r--r--Tests/RunCMake/FileAPI/RunCMakeTest.cmake58
-rw-r--r--Tests/RunCMake/FileAPI/SharedStateless-check.cmake15
-rw-r--r--Tests/RunCMake/FileAPI/SharedStateless-check.py22
-rw-r--r--Tests/RunCMake/FileAPI/SharedStateless-prep.cmake6
-rw-r--r--Tests/RunCMake/FileAPI/SharedStateless.cmake0
-rw-r--r--Tests/RunCMake/FileAPI/Stale-check.cmake4
-rw-r--r--Tests/RunCMake/FileAPI/Stale-prep.cmake1
-rw-r--r--Tests/RunCMake/FileAPI/Stale.cmake0
-rw-r--r--Tests/RunCMake/FileAPI/alias/CMakeLists.txt10
-rw-r--r--Tests/RunCMake/FileAPI/cache-v2-ClientStateful-check.cmake11
-rw-r--r--Tests/RunCMake/FileAPI/cache-v2-ClientStateful-prep.cmake4
-rw-r--r--Tests/RunCMake/FileAPI/cache-v2-ClientStateless-check.cmake11
-rw-r--r--Tests/RunCMake/FileAPI/cache-v2-ClientStateless-prep.cmake2
-rw-r--r--Tests/RunCMake/FileAPI/cache-v2-SharedStateless-check.cmake10
-rw-r--r--Tests/RunCMake/FileAPI/cache-v2-SharedStateless-prep.cmake2
-rw-r--r--Tests/RunCMake/FileAPI/cache-v2-check.py134
-rw-r--r--Tests/RunCMake/FileAPI/cache-v2.cmake14
-rw-r--r--Tests/RunCMake/FileAPI/check_index.py163
-rw-r--r--Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateful-check.cmake11
-rw-r--r--Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateful-prep.cmake4
-rw-r--r--Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateless-check.cmake11
-rw-r--r--Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateless-prep.cmake2
-rw-r--r--Tests/RunCMake/FileAPI/cmakeFiles-v1-SharedStateless-check.cmake10
-rw-r--r--Tests/RunCMake/FileAPI/cmakeFiles-v1-SharedStateless-prep.cmake2
-rw-r--r--Tests/RunCMake/FileAPI/cmakeFiles-v1-check.py94
-rw-r--r--Tests/RunCMake/FileAPI/cmakeFiles-v1.cmake8
-rw-r--r--Tests/RunCMake/FileAPI/codemodel-v2-ClientStateful-check.cmake12
-rw-r--r--Tests/RunCMake/FileAPI/codemodel-v2-ClientStateful-prep.cmake4
-rw-r--r--Tests/RunCMake/FileAPI/codemodel-v2-ClientStateless-check.cmake12
-rw-r--r--Tests/RunCMake/FileAPI/codemodel-v2-ClientStateless-prep.cmake2
-rw-r--r--Tests/RunCMake/FileAPI/codemodel-v2-SharedStateless-check.cmake11
-rw-r--r--Tests/RunCMake/FileAPI/codemodel-v2-SharedStateless-prep.cmake2
-rw-r--r--Tests/RunCMake/FileAPI/codemodel-v2-check.py5118
-rw-r--r--Tests/RunCMake/FileAPI/codemodel-v2.cmake37
-rw-r--r--Tests/RunCMake/FileAPI/custom/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/FileAPI/cxx/CMakeLists.txt15
-rw-r--r--Tests/RunCMake/FileAPI/dir/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/FileAPI/dir/dir/CMakeLists.txt0
-rw-r--r--Tests/RunCMake/FileAPI/dir/dirtest.cmake0
-rw-r--r--Tests/RunCMake/FileAPI/empty.c0
-rw-r--r--Tests/RunCMake/FileAPI/empty.cxx0
-rw-r--r--Tests/RunCMake/FileAPI/imported/CMakeLists.txt24
-rw-r--r--Tests/RunCMake/FileAPI/include_test.cmake9
-rw-r--r--Tests/RunCMake/FileAPI/object/CMakeLists.txt13
-rw-r--r--Tests/RunCMake/FileAPIDummyFile.cmake0
-rw-r--r--Tests/RunCMake/FileAPIExternalSource/CMakeLists.txt12
-rw-r--r--Tests/RunCMake/FileAPIExternalSource/empty.c0
-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/relative-input-NEW.txt1
-rw-r--r--Tests/RunCMake/FindBoost/CMP0093-NEW-stdout.txt1
-rw-r--r--Tests/RunCMake/FindBoost/CMP0093-NEW.cmake2
-rw-r--r--Tests/RunCMake/FindBoost/CMP0093-OLD-stdout.txt1
-rw-r--r--Tests/RunCMake/FindBoost/CMP0093-OLD.cmake2
-rw-r--r--Tests/RunCMake/FindBoost/CMP0093-UNSET-stdout.txt1
-rw-r--r--Tests/RunCMake/FindBoost/CMP0093-UNSET.cmake1
-rw-r--r--Tests/RunCMake/FindBoost/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage-stdout.txt2
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage.cmake2
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage/BoostConfig.cmake4
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage/BoostConfigVersion.cmake7
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/Boost-1.70.0/BoostConfig.cmake140
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/Boost-1.70.0/BoostConfigVersion.cmake12
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/BoostDetectToolset-1.70.0.cmake1
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/boost_chrono-config-version.cmake12
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/boost_chrono-config.cmake98
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/libboost_chrono-variant-shared.cmake62
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/libboost_chrono-variant-static.cmake58
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_headers-1.70.0/boost_headers-config-version.cmake12
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_headers-1.70.0/boost_headers-config.cmake20
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/boost_system-config-version.cmake12
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/boost_system-config.cmake98
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/libboost_system-variant-shared.cmake62
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/libboost_system-variant-static.cmake58
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/boost_timer-config-version.cmake12
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/boost_timer-config.cmake98
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/libboost_timer-variant-shared.cmake62
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/libboost_timer-variant-static.cmake58
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/BoostConfig.cmake26
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/BoostConfigVersion.cmake7
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/include/boost/version.hpp34
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/BoostConfig.cmake7
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/BoostConfigVersion.cmake7
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/include/boost/version.hpp34
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_New/BoostConfig.cmake29
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_New/BoostConfigVersion.cmake7
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_New/include/boost/version.hpp34
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_date_time.a0
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_mpi_python.a0
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_python.a0
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_python_release.a0
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/BoostConfig.cmake25
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/BoostConfigVersion.cmake7
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/include/boost/version.hpp34
-rw-r--r--Tests/RunCMake/FindBoost/CommonNotFound-stderr.txt1
-rw-r--r--Tests/RunCMake/FindBoost/CommonNotFound-stdout.txt1
-rw-r--r--Tests/RunCMake/FindBoost/CommonNotFound.cmake2
-rw-r--r--Tests/RunCMake/FindBoost/CommonResults-stdout.txt13
-rw-r--r--Tests/RunCMake/FindBoost/CommonResults.cmake25
-rw-r--r--Tests/RunCMake/FindBoost/ConfigMode.cmake2
-rw-r--r--Tests/RunCMake/FindBoost/ConfigModeNotFound.cmake2
-rw-r--r--Tests/RunCMake/FindBoost/LegacyVars-LowercaseTargetPrefix-stdout.txt34
-rw-r--r--Tests/RunCMake/FindBoost/LegacyVars-LowercaseTargetPrefix.cmake6
-rw-r--r--Tests/RunCMake/FindBoost/LegacyVars-NoHeaderTarget.cmake6
-rw-r--r--Tests/RunCMake/FindBoost/LegacyVars-TargetsDefined-stdout.txt34
-rw-r--r--Tests/RunCMake/FindBoost/LegacyVars-TargetsDefined.cmake6
-rw-r--r--Tests/RunCMake/FindBoost/LegacyVars.cmake28
-rw-r--r--Tests/RunCMake/FindBoost/MissingTarget-stdout.txt22
-rw-r--r--Tests/RunCMake/FindBoost/MissingTarget.cmake25
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/chrono.hpp0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/config.hpp0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/system/config.hpp0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/timer.hpp0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/version.hpp34
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_chrono-mt-1_70.lib0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_system-mt-1_70.lib0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_timer-mt-1_70.lib0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono-mt-1_70.lib0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono.a0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono.so.1.70.00
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system-mt-1_70.lib0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system.a0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system.so.1.70.00
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer-mt-1_70.lib0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer.a0
-rw-r--r--Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer.so.1.70.00
-rw-r--r--Tests/RunCMake/FindBoost/ModuleMode.cmake4
-rw-r--r--Tests/RunCMake/FindBoost/ModuleModeNotFound.cmake4
-rw-r--r--Tests/RunCMake/FindBoost/NoCXX-stderr.txt1
-rw-r--r--Tests/RunCMake/FindBoost/NoCXX.cmake1
-rw-r--r--Tests/RunCMake/FindBoost/RunCMakeTest.cmake28
-rw-r--r--Tests/RunCMake/FindLua/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/FindLua/FindLuaTest.cmake87
-rw-r--r--Tests/RunCMake/FindLua/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/FindLua/prefix1/include/lua.h8
-rw-r--r--Tests/RunCMake/FindLua/prefix2/include/lua5.1/lua.h8
-rw-r--r--Tests/RunCMake/FindLua/prefix2/include/lua5.2/lua.h8
-rw-r--r--Tests/RunCMake/FindLua/prefix2/include/lua5.3/lua.h8
-rw-r--r--Tests/RunCMake/FindLua/prefix2/include/lua5.9/lua.h8
-rw-r--r--Tests/RunCMake/FindOpenGL/CMP0072-NEW-stdout.txt3
-rw-r--r--Tests/RunCMake/FindOpenGL/CMP0072-NEW.cmake2
-rw-r--r--Tests/RunCMake/FindOpenGL/CMP0072-OLD-stdout.txt3
-rw-r--r--Tests/RunCMake/FindOpenGL/CMP0072-OLD.cmake2
-rw-r--r--Tests/RunCMake/FindOpenGL/CMP0072-WARN-stderr.txt21
-rw-r--r--Tests/RunCMake/FindOpenGL/CMP0072-WARN-stdout.txt3
-rw-r--r--Tests/RunCMake/FindOpenGL/CMP0072-WARN.cmake1
-rw-r--r--Tests/RunCMake/FindOpenGL/CMP0072-common.cmake13
-rw-r--r--Tests/RunCMake/FindOpenGL/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/FindOpenGL/RunCMakeTest.cmake5
-rw-r--r--Tests/RunCMake/FindPkgConfig/FindPkgConfig_GET_VARIABLE_PKGCONFIG_PATH.cmake21
-rw-r--r--Tests/RunCMake/FindPkgConfig/FindPkgConfig_GET_VARIABLE_PREFIX_PATH.cmake21
-rw-r--r--Tests/RunCMake/FindPkgConfig/FindPkgConfig_VERSION_OPERATORS.cmake83
-rw-r--r--Tests/RunCMake/FindPkgConfig/pc-bletch/lib/pkgconfig/bletch.pc12
-rw-r--r--Tests/RunCMake/FindPkgConfig/target_subdir/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/Framework/InstallBeforeFramework-stderr.txt7
-rw-r--r--Tests/RunCMake/Framework/InstallBeforeFramework.cmake5
-rw-r--r--Tests/RunCMake/GNUInstallDirs/Opt-FreeBSD-stderr.txt30
-rw-r--r--Tests/RunCMake/GNUInstallDirs/Root-FreeBSD-stderr.txt30
-rw-r--r--Tests/RunCMake/GNUInstallDirs/Usr-FreeBSD-stderr.txt30
-rw-r--r--Tests/RunCMake/GNUInstallDirs/UsrLocal-FreeBSD-stderr.txt30
-rw-r--r--Tests/RunCMake/GenerateExportHeader/includeguard/CMakeLists.txt19
-rw-r--r--Tests/RunCMake/GenerateExportHeader/includeguard/libincludeguard.cpp0
-rw-r--r--Tests/RunCMake/GenerateExportHeader/includeguard/main.cpp.in10
-rw-r--r--Tests/RunCMake/GeneratorExpression/CMP0085-NEW-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/CMP0085-NEW.cmake4
-rw-r--r--Tests/RunCMake/GeneratorExpression/CMP0085-OLD-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/CMP0085-OLD.cmake4
-rw-r--r--Tests/RunCMake/GeneratorExpression/CMP0085-WARN-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/CMP0085-WARN-stderr.txt33
-rw-r--r--Tests/RunCMake/GeneratorExpression/CMP0085-WARN.cmake4
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command.cmake4
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target-stderr.txt11
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target.cmake4
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable-stderr.txt11
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable.cmake5
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library-stderr.txt11
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test-stderr.txt11
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test.cmake5
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install-stderr.txt9
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install.cmake5
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-unknown-lang.cmake4
-rw-r--r--Tests/RunCMake/GeneratorExpression/FILTER-Exclude-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/FILTER-Exclude.cmake4
-rw-r--r--Tests/RunCMake/GeneratorExpression/FILTER-Include-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/FILTER-Include.cmake4
-rw-r--r--Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator.cmake3
-rw-r--r--Tests/RunCMake/GeneratorExpression/FILTER-empty-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/FILTER-empty.cmake3
-rw-r--r--Tests/RunCMake/GeneratorExpression/GENEX_EVAL-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-stderr.txt26
-rw-r--r--Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1.cmake9
-rw-r--r--Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-stderr.txt26
-rw-r--r--Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2.cmake10
-rw-r--r--Tests/RunCMake/GeneratorExpression/GENEX_EVAL.cmake12
-rw-r--r--Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME.cmake9
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID-stderr.txt9
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID.cmake4
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION-stderr.txt9
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION.cmake4
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt9
-rw-r--r--Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake9
-rw-r--r--Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-1-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-1.cmake3
-rw-r--r--Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-2-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-2.cmake3
-rw-r--r--Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-3-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-3.cmake3
-rw-r--r--Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-4-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-4.cmake3
-rw-r--r--Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-empty-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-empty.cmake3
-rw-r--r--Tests/RunCMake/GeneratorExpression/ResultValidator.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_EXISTS.cmake3
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-check.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target-check.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target.cmake106
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-stderr.txt6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target.cmake7
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME.cmake135
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-check.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-imported-target-check.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-imported-target.cmake49
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target-stderr.txt6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target.cmake7
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX.cmake49
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-check.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-imported-target-check.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-imported-target.cmake49
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target-stderr.txt6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target.cmake7
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX.cmake49
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-stderr.txt9
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg.cmake7
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-stderr.txt9
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target.cmake5
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target.cmake5
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-stderr.txt9
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1.cmake9
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-stderr.txt26
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2.cmake12
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL.cmake10
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-stderr.txt6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target.cmake7
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target-stderr.txt6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target.cmake7
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target-stderr.txt6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target.cmake7
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-check.cmake6
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-stderr.txt9
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target-check.cmake5
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target.cmake2
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS.cmake3
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-INCLUDE_DIRECTORIES.cmake18
-rw-r--r--Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME-check.cmake7
-rw-r--r--Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake16
-rw-r--r--Tests/RunCMake/GeneratorInstance/BadInstance-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorInstance/BadInstance-stderr.txt10
-rw-r--r--Tests/RunCMake/GeneratorInstance/BadInstance-toolchain.cmake1
-rw-r--r--Tests/RunCMake/GeneratorInstance/BadInstance.cmake1
-rw-r--r--Tests/RunCMake/GeneratorInstance/BadInstanceToolchain-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorInstance/BadInstanceToolchain-stderr.txt10
-rw-r--r--Tests/RunCMake/GeneratorInstance/BadInstanceToolchain.cmake1
-rw-r--r--Tests/RunCMake/GeneratorInstance/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/GeneratorInstance/DefaultInstance.cmake13
-rw-r--r--Tests/RunCMake/GeneratorInstance/MissingInstance-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorInstance/MissingInstance-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorInstance/MissingInstance-toolchain.cmake1
-rw-r--r--Tests/RunCMake/GeneratorInstance/MissingInstance.cmake1
-rw-r--r--Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain-stderr.txt8
-rw-r--r--Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain.cmake1
-rw-r--r--Tests/RunCMake/GeneratorInstance/NoInstance-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorInstance/NoInstance-stderr.txt4
-rw-r--r--Tests/RunCMake/GeneratorInstance/NoInstance.cmake7
-rw-r--r--Tests/RunCMake/GeneratorInstance/RunCMakeTest.cmake22
-rw-r--r--Tests/RunCMake/GeneratorToolset/BadToolsetVersion-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorToolset/BadToolsetVersion-stderr.txt10
-rw-r--r--Tests/RunCMake/GeneratorToolset/BadToolsetVersion.cmake1
-rw-r--r--Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice-result.txt1
-rw-r--r--Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice-stderr.txt10
-rw-r--r--Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice.cmake1
-rw-r--r--Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x64-stdout.txt2
-rw-r--r--Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x64.cmake2
-rw-r--r--Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x86-stdout.txt2
-rw-r--r--Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x86.cmake2
-rw-r--r--Tests/RunCMake/GeneratorToolset/TestToolsetVersionBoth-stdout.txt2
-rw-r--r--Tests/RunCMake/GeneratorToolset/TestToolsetVersionBoth.cmake2
-rw-r--r--Tests/RunCMake/GeneratorToolset/TestToolsetVersionOnly-stdout.txt2
-rw-r--r--Tests/RunCMake/GeneratorToolset/TestToolsetVersionOnly.cmake2
-rw-r--r--Tests/RunCMake/GetPrerequisites/ExecutableScripts-stdout.txt3
-rw-r--r--Tests/RunCMake/GetPrerequisites/ExecutableScripts.cmake19
-rw-r--r--Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake4
-rw-r--r--Tests/RunCMake/GetPrerequisites/TargetMissing-stderr.txt3
-rw-r--r--Tests/RunCMake/GetPrerequisites/TargetMissing.cmake4
-rwxr-xr-xTests/RunCMake/GetPrerequisites/script3
-rwxr-xr-xTests/RunCMake/GetPrerequisites/script.bat3
-rwxr-xr-xTests/RunCMake/GetPrerequisites/script.sh3
-rw-r--r--Tests/RunCMake/GoogleTest/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-discovery-timeout-result.txt1
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-discovery-timeout-stdout.txt7
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-result.txt1
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-stderr.txt1
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-stdout.txt10
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-result.txt1
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-stderr.txt1
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-stdout.txt10
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-test-missing-result.txt1
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-test-missing-stderr.txt2
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-test1-stdout.txt25
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-test2-stdout.txt25
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest.cmake59
-rw-r--r--Tests/RunCMake/GoogleTest/RunCMakeTest.cmake74
-rw-r--r--Tests/RunCMake/GoogleTest/fake_gtest.cpp41
-rw-r--r--Tests/RunCMake/GoogleTest/no_tests_defined.cpp4
-rw-r--r--Tests/RunCMake/GoogleTest/timeout_test.cpp39
-rw-r--r--Tests/RunCMake/IfacePaths/BinInInstallPrefix-CMP0052-OLD-stderr.txt8
-rw-r--r--Tests/RunCMake/IfacePaths/SrcInInstallPrefix-CMP0052-OLD-stderr.txt8
-rw-r--r--Tests/RunCMake/Languages/ExternalCUDA.cmake8
-rw-r--r--Tests/RunCMake/Languages/empty.c0
-rw-r--r--Tests/RunCMake/LinkStatic/LinkOptionsLib.c7
-rw-r--r--Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-basic-check.cmake4
-rw-r--r--Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-basic-result.txt1
-rw-r--r--Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-genex-check.cmake7
-rw-r--r--Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-genex-result.txt1
-rw-r--r--Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-shared-check.cmake4
-rw-r--r--Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-shared-result.txt1
-rw-r--r--Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS.cmake21
-rw-r--r--Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-result.txt1
-rw-r--r--Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-stderr.txt4
-rw-r--r--Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW.cmake2
-rw-r--r--Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-OLD.cmake2
-rw-r--r--Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-WARN.cmake2
-rw-r--r--Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-common.cmake37
-rw-r--r--Tests/RunCMake/MSVCRuntimeLibrary/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/MSVCRuntimeLibrary/RunCMakeTest.cmake5
-rw-r--r--Tests/RunCMake/MSVCRuntimeLibrary/empty.c0
-rw-r--r--Tests/RunCMake/MSVCWarningFlags/CMP0092-NEW.cmake2
-rw-r--r--Tests/RunCMake/MSVCWarningFlags/CMP0092-OLD.cmake2
-rw-r--r--Tests/RunCMake/MSVCWarningFlags/CMP0092-WARN.cmake2
-rw-r--r--Tests/RunCMake/MSVCWarningFlags/CMP0092-common.cmake12
-rw-r--r--Tests/RunCMake/MSVCWarningFlags/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/MSVCWarningFlags/RunCMakeTest.cmake5
-rw-r--r--Tests/RunCMake/Make/IncludeRegexSubdir-check.cmake4
-rw-r--r--Tests/RunCMake/Make/IncludeRegexSubdir.cmake3
-rw-r--r--Tests/RunCMake/Make/IncludeRegexSubdir/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/Make/VerboseBuild-build-stdout.txt1
-rw-r--r--Tests/RunCMake/Make/VerboseBuild-build-watcom-stdout.txt1
-rw-r--r--Tests/RunCMake/Make/VerboseBuild-nowork-gnu-stdout.txt1
-rw-r--r--Tests/RunCMake/Make/VerboseBuild.cmake8
-rw-r--r--Tests/RunCMake/Make/hello.c7
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/CMakeLists.txt.in2
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/CTestCustom.cmake3
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/FindRecursivePackage.cmake3
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/RunCMakeTest.cmake49
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/add_subdirectory-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/add_subdirectory-var-stderr.txt10
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/add_subdirectory.cmake2
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/add_subdirectory/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-default-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-default-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-invalid-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-invalid-var-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-var-stderr.txt34
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/ctest_run_script-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/ctest_run_script-var-stderr.txt51
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/ctest_run_script.cmake.in14
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-default-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-default-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-default-script-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-default-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-script-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-var-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-var-script-stderr.txt21
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package-var-stderr.txt21
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/find_package.cmake2
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-default-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-default-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-default-script-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-default-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-invalid-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-invalid-var-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-invalid-var-script-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-invalid-var-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-var-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-var-script-stderr.txt21
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function-var-stderr.txt21
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/function.cmake7
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-default-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-default-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-default-script-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-default-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-invalid-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-invalid-var-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-invalid-var-script-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-invalid-var-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-var-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-var-script-stderr.txt21
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include-var-stderr.txt21
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include.cmake2
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/include_recursive.cmake3
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-default-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-default-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-default-script-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-default-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-script-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-stderr.txt5
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-var-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-var-script-stderr.txt21
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro-var-stderr.txt21
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/macro.cmake7
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/test.cmake.in21
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/try_compile-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/try_compile-var-stderr.txt48
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/try_compile.cmake6
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists.txt13
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-default-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-default-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-default-script-stderr.txt6
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-default-stderr.txt6
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-script-stderr.txt6
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-stderr.txt6
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-var-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-var-script-result.txt1
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-var-script-stderr.txt22
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch-var-stderr.txt22
-rw-r--r--Tests/RunCMake/MaxRecursionDepth/variable_watch.cmake9
-rw-r--r--Tests/RunCMake/MetaCompileFeatures/C.cmake27
-rw-r--r--Tests/RunCMake/MetaCompileFeatures/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/MetaCompileFeatures/CXX.cmake27
-rw-r--r--Tests/RunCMake/MetaCompileFeatures/RunCMakeTest.cmake4
-rw-r--r--Tests/RunCMake/MetaCompileFeatures/a.c0
-rw-r--r--Tests/RunCMake/MetaCompileFeatures/a.cxx0
-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/Ninja/CMP0058-OLD-by-stderr.txt10
-rw-r--r--Tests/RunCMake/Ninja/CMP0058-OLD-no-stderr.txt10
-rw-r--r--Tests/RunCMake/Ninja/CustomCommandJobPool-check.cmake8
-rw-r--r--Tests/RunCMake/Ninja/CustomCommandJobPool.cmake17
-rw-r--r--Tests/RunCMake/Ninja/JobPoolUsesTerminal-result.txt1
-rw-r--r--Tests/RunCMake/Ninja/JobPoolUsesTerminal-stderr.txt9
-rw-r--r--Tests/RunCMake/Ninja/JobPoolUsesTerminal.cmake2
-rw-r--r--Tests/RunCMake/Ninja/NoWorkToDo-nowork-stdout.txt1
-rw-r--r--Tests/RunCMake/Ninja/NoWorkToDo.cmake2
-rw-r--r--Tests/RunCMake/Ninja/PreventConfigureFileDupBuildRule.cmake5
-rw-r--r--Tests/RunCMake/Ninja/PreventTargetAliasesDupBuildRule.cmake41
-rw-r--r--Tests/RunCMake/Ninja/RspFileC.cmake2
-rw-r--r--Tests/RunCMake/Ninja/RspFileCXX.cmake2
-rw-r--r--Tests/RunCMake/Ninja/RspFileFortran.cmake2
-rw-r--r--Tests/RunCMake/Ninja/SubDirConfigureFileDup/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/Ninja/VerboseBuild-build-stdout.txt1
-rw-r--r--Tests/RunCMake/Ninja/VerboseBuild-nowork-stdout.txt1
-rw-r--r--Tests/RunCMake/Ninja/VerboseBuild.cmake3
-rw-r--r--Tests/RunCMake/ObjectLibrary/CheckTargetObjects.cmake32
-rw-r--r--Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-result.txt1
-rw-r--r--Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-stderr.txt1
-rw-r--r--Tests/RunCMake/ObjectLibrary/InstallLinkedObj1.cmake6
-rw-r--r--Tests/RunCMake/ObjectLibrary/InstallLinkedObj2.cmake6
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjLHSShared.cmake7
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjLHSStatic.cmake7
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-result.txt1
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-stdout.txt1
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjRHSObject.cmake12
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2-build-result.txt1
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2.cmake12
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjRHSShared.cmake13
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjRHSShared2.cmake14
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic.cmake10
-rw-r--r--Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic2.cmake11
-rw-r--r--Tests/RunCMake/ObjectLibrary/TransitiveDependencies.cmake7
-rw-r--r--Tests/RunCMake/ObjectLibrary/check_object_files.cmake17
-rw-r--r--Tests/RunCMake/ObjectLibrary/exe.c14
-rw-r--r--Tests/RunCMake/ObjectLibrary/exe2.c6
-rw-r--r--Tests/RunCMake/ObjectLibrary/requires.c8
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/ParseImplicitIncludeInfo.cmake118
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/CMakeLists.txt90
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/README25
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XL-13.1.3.input40
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XL-13.1.3.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XLClang-16.1.0.1.input40
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XLClang-16.1.0.1.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XL-13.1.3.input44
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XL-13.1.3.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XLClang-16.1.0.1.input44
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XLClang-16.1.0.1.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-8.7.input53
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-8.7.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-9.0-hlist-ad.input54
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-9.0-hlist-ad.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-GNU-7.3.0.input79
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-GNU-7.3.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Intel-18.0.2.20180210.input40
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Intel-18.0.2.20180210.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-8.7.input53
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-8.7.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-9.0-hlist-ad.input54
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-9.0-hlist-ad.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-GNU-7.3.0.input82
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-GNU-7.3.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Intel-18.0.2.20180210.input43
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Intel-18.0.2.20180210.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-8.7.input52
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-8.7.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-9.0-hlist-ad.input53
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-9.0-hlist-ad.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-GNU-7.3.0.input83
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-GNU-7.3.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Intel-18.0.2.20180210.input80
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Intel-18.0.2.20180210.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-C-AppleClang-8.0.0.8000042.input50
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-C-AppleClang-8.0.0.8000042.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-CXX-AppleClang-8.0.0.8000042.input52
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-CXX-AppleClang-8.0.0.8000042.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-C-AppleClang-8.0.0.8000042.input44
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-C-AppleClang-8.0.0.8000042.output0
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-CXX-AppleClang-8.0.0.8000042.input44
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-CXX-AppleClang-8.0.0.8000042.output0
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-C-Clang-3.3.0.input38
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-C-Clang-3.3.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-CXX-Clang-3.3.0.input45
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-CXX-Clang-3.3.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-Fortran-GNU-4.6.4.input78
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-Fortran-GNU-4.6.4.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-empty.input14
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-empty.output0
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-relative.input21
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-relative.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-empty.input14
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-empty.output0
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-relative.input21
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-relative.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-GNU-7.3.0.input72
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-GNU-7.3.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-Intel-18.0.0.20170811.input43
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-Intel-18.0.0.20170811.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-PGI-18.10.1.input36
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-PGI-18.10.1.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-12.1.0.input42
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-12.1.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-16.1.0.0.input40
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-16.1.0.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CUDA-NVIDIA-9.2.148.input124
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CUDA-NVIDIA-9.2.148.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-GNU-7.3.0.input76
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-GNU-7.3.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-Intel-18.0.0.20170811.input46
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-Intel-18.0.0.20170811.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-PGI-18.10.1.input40
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-PGI-18.10.1.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-12.1.0.input42
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-12.1.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-16.1.0.0.input40
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-16.1.0.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-GNU-7.3.0.input76
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-GNU-7.3.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-PGI-18.10.1.input47
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-PGI-18.10.1.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-XL-14.1.0.input50
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-XL-14.1.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-PGI-18.10.1.input36
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-PGI-18.10.1.output0
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-XL-12.1.0.input42
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-XL-12.1.0.output0
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-PGI-18.10.1.input40
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-PGI-18.10.1.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-XL-12.1.0.input42
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-XL-12.1.0.output0
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-Fortran-PGI-18.10.1.input47
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-Fortran-PGI-18.10.1.output0
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-C-XL-12.1.0.input42
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-C-XL-12.1.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-CXX-XL-12.1.0.input42
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-CXX-XL-12.1.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_pgf77-Fortran-PGI-18.10.1.input35
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_pgf77-Fortran-PGI-18.10.1.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-C-GNU-4.9.3.input70
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-C-GNU-4.9.3.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-CXX-GNU-4.9.3.input76
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-CXX-GNU-4.9.3.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-C-GNU-4.8.5.input60
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-C-GNU-4.8.5.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-CXX-GNU-4.8.5.input62
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-CXX-GNU-4.8.5.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-C-GNU-4.8.5.input58
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-C-GNU-4.8.5.output0
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-CXX-GNU-4.8.5.input58
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-CXX-GNU-4.8.5.output0
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-C-Clang-5.0.1.input37
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-C-Clang-5.0.1.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-CXX-Clang-5.0.1.input38
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-CXX-Clang-5.0.1.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-C-SunPro-5.13.0.input35
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-C-SunPro-5.13.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-CXX-SunPro-5.13.0.input38
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-CXX-SunPro-5.13.0.output1
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-Fortran-SunPro-8.8.0.input40
-rw-r--r--Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-Fortran-SunPro-8.8.0.output1
-rw-r--r--Tests/RunCMake/PositionIndependentCode/CMP0083-cmp0083_new-check.cmake22
-rw-r--r--Tests/RunCMake/PositionIndependentCode/CMP0083-cmp0083_old-check.cmake20
-rw-r--r--Tests/RunCMake/PositionIndependentCode/CMP0083.cmake47
-rw-r--r--Tests/RunCMake/PositionIndependentCode/CheckPIESupported.cmake18
-rw-r--r--Tests/RunCMake/PositionIndependentCode/Genex1-result.txt1
-rw-r--r--Tests/RunCMake/PositionIndependentCode/Genex1-stderr.txt3
-rw-r--r--Tests/RunCMake/PositionIndependentCode/Genex1.cmake9
-rw-r--r--Tests/RunCMake/PositionIndependentCode/Genex2-result.txt1
-rw-r--r--Tests/RunCMake/PositionIndependentCode/Genex2-stderr.txt3
-rw-r--r--Tests/RunCMake/PositionIndependentCode/Genex2.cmake9
-rw-r--r--Tests/RunCMake/PositionIndependentCode/PIE-pie_off-check.cmake7
-rw-r--r--Tests/RunCMake/PositionIndependentCode/PIE-pie_on-check.cmake7
-rw-r--r--Tests/RunCMake/PositionIndependentCode/PIE.cmake22
-rw-r--r--Tests/RunCMake/PositionIndependentCode/PIE_validator.cmake32
-rw-r--r--Tests/RunCMake/RuntimePath/Relative.cmake69
-rw-r--r--Tests/RunCMake/RuntimePath/RelativeCheck.cmake4
-rw-r--r--Tests/RunCMake/ScriptMode/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/ScriptMode/set_directory_properties.cmake1
-rw-r--r--Tests/RunCMake/SourceProperties/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/SourceProperties/RelativeIncludeDir-result.txt1
-rw-r--r--Tests/RunCMake/SourceProperties/RelativeIncludeDir-stderr.txt4
-rw-r--r--Tests/RunCMake/SourceProperties/RelativeIncludeDir.cmake4
-rw-r--r--Tests/RunCMake/SourceProperties/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/SourceProperties/empty.c5
-rw-r--r--Tests/RunCMake/Swift/E.swift2
-rw-r--r--Tests/RunCMake/Swift/Win32ExecutableDisallowed-result.txt1
-rw-r--r--Tests/RunCMake/Swift/Win32ExecutableDisallowed-stderr.txt4
-rw-r--r--Tests/RunCMake/Swift/Win32ExecutableDisallowed.cmake4
-rw-r--r--Tests/RunCMake/Syntax/CMP0053-Dollar-NEW-stderr.txt2
-rw-r--r--Tests/RunCMake/Syntax/CMP0053-Dollar-NEW.cmake6
-rw-r--r--Tests/RunCMake/Syntax/CMP0053-Dollar-OLD-result.txt1
-rw-r--r--Tests/RunCMake/Syntax/CMP0053-Dollar-OLD-stderr.txt24
-rw-r--r--Tests/RunCMake/Syntax/CMP0053-Dollar-OLD.cmake6
-rw-r--r--Tests/RunCMake/Syntax/NullAfterBackslash-result.txt1
-rw-r--r--Tests/RunCMake/Syntax/NullAfterBackslash-stderr.txt5
-rw-r--r--Tests/RunCMake/Syntax/NullAfterBackslash.cmakebin0 -> 113 bytes
-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/QueryCache-stderr.txt2
-rw-r--r--Tests/RunCMake/Syntax/QueryCache.cmake6
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName-result.txt1
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName-stderr.txt52
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName.cmake8
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName1/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName2/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName3/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName4/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName5/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName6/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName7/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName8/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference-result.txt1
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference-stderr.txt39
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference.cmake6
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference1/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference2/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference3/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference4/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference5/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference6/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/TargetPropertyGeneratorExpressions/main.cpp4
-rw-r--r--Tests/RunCMake/TargetSources/CMP0076-OLD-result.txt1
-rw-r--r--Tests/RunCMake/TargetSources/CMP0076-OLD-stderr.txt4
-rw-r--r--Tests/RunCMake/TargetSources/CMP0076-OLD.cmake10
-rw-r--r--Tests/RunCMake/TargetSources/CMP0076-WARN-result.txt1
-rw-r--r--Tests/RunCMake/TargetSources/CMP0076-WARN-stderr.txt21
-rw-r--r--Tests/RunCMake/TargetSources/CMP0076-WARN.cmake8
-rw-r--r--Tests/RunCMake/TargetSources/CMP0076-WARN/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/TargetSources/CMP0076-WARN/subdir_empty_1.cpp7
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInInterface-stdout.txt1
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx-stdout.txt1
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx.cmake10
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx/CMakeLists.txt4
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx/subdir_empty_1.cpp7
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirInclude-stdout.txt1
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirInclude.cmake8
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirInclude/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirInclude/subdir_empty_1.cpp7
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirInterface-stdout.txt1
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirInterface.cmake11
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/subdir_empty_1.cpp7
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/subdir_empty_2.cpp7
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate-stdout.txt1
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate.cmake8
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/subdir_empty_1.cpp7
-rw-r--r--Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/subdir_empty_2.cpp7
-rw-r--r--Tests/RunCMake/ToolchainFile/IncludeDirectories-toolchain.cmake1
-rw-r--r--Tests/RunCMake/ToolchainFile/IncludeDirectories.c5
-rw-r--r--Tests/RunCMake/ToolchainFile/IncludeDirectories.cmake2
-rw-r--r--Tests/RunCMake/ToolchainFile/IncludeDirectories/IncDir.h1
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0078-NEW-stdout.txt2
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0078-NEW.cmake2
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0078-OLD-stdout.txt2
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0078-OLD.cmake2
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0078-WARN-stderr.txt10
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0078-WARN-stdout.txt2
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0078-WARN.cmake1
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0078-common.cmake12
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0086-NEW-nuild-check.cmake4
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0086-NEW.cmake2
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0086-OLD-build-check.cmake4
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0086-OLD.cmake2
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0086-WARN-stderr.txt11
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0086-WARN.cmake1
-rw-r--r--Tests/RunCMake/UseSWIG/CMP0086-common.cmake11
-rw-r--r--Tests/RunCMake/UseSWIG/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/UseSWIG/RunCMakeTest.cmake25
-rw-r--r--Tests/RunCMake/UseSWIG/example.i2
-rw-r--r--Tests/RunCMake/VS10Project/ExplicitCMakeLists-check.cmake25
-rw-r--r--Tests/RunCMake/VS10Project/ExplicitCMakeLists.cmake3
-rw-r--r--Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake36
-rw-r--r--Tests/RunCMake/VS10Project/RuntimeLibrary.cmake20
-rw-r--r--Tests/RunCMake/VS10Project/SourceGroupCMakeLists-check.cmake33
-rw-r--r--Tests/RunCMake/VS10Project/SourceGroupCMakeLists.cmake3
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpCompilerOpts-check.cmake64
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpCompilerOpts.cmake14
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpCustomTags-stderr.txt3
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpDefines-check.cmake64
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpDefines.cmake18
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpDeployFiles-check.cmake67
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpDeployFiles.cmake27
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpReferenceProps-check.cmake49
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpReferenceProps-stderr.txt8
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpReferenceProps.cmake19
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpWithoutSources-check.cmake5
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpWithoutSources.cmake7
-rw-r--r--Tests/RunCMake/VS10Project/VsDebuggerCommand-check.cmake24
-rw-r--r--Tests/RunCMake/VS10Project/VsDebuggerCommand.cmake6
-rw-r--r--Tests/RunCMake/VS10Project/VsDebuggerCommandArguments-check.cmake24
-rw-r--r--Tests/RunCMake/VS10Project/VsDebuggerCommandArguments.cmake6
-rw-r--r--Tests/RunCMake/VS10Project/VsDebuggerEnvironment-check.cmake24
-rw-r--r--Tests/RunCMake/VS10Project/VsDebuggerEnvironment.cmake6
-rw-r--r--Tests/RunCMake/VS10Project/VsGlobals-check.cmake44
-rw-r--r--Tests/RunCMake/VS10Project/VsGlobals.cmake8
-rw-r--r--Tests/RunCMake/VS10Project/VsJustMyCode-check.cmake38
-rw-r--r--Tests/RunCMake/VS10Project/VsJustMyCode.cmake24
-rw-r--r--Tests/RunCMake/VS10Project/VsPackageReferences-check.cmake39
-rw-r--r--Tests/RunCMake/VS10Project/VsPackageReferences.cmake4
-rw-r--r--Tests/RunCMake/VS10Project/VsProjectImport-check.cmake28
-rw-r--r--Tests/RunCMake/VS10Project/VsProjectImport.cmake11
-rw-r--r--Tests/RunCMake/VS10Project/VsSdkDirectories-check.cmake88
-rw-r--r--Tests/RunCMake/VS10Project/VsSdkDirectories.cmake11
-rw-r--r--Tests/RunCMake/VS10Project/VsSpectreMitigation-check.cmake30
-rw-r--r--Tests/RunCMake/VS10Project/VsSpectreMitigation.cmake8
-rw-r--r--Tests/RunCMake/VS10Project/empty.c0
-rw-r--r--Tests/RunCMake/VS10Project/empty.cxx0
-rw-r--r--Tests/RunCMake/VS10ProjectWinCE/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/VS10ProjectWinCE/RunCMakeTest.cmake9
-rw-r--r--Tests/RunCMake/VS10ProjectWinCE/VsCEDebuggerDeploy-check.cmake101
-rw-r--r--Tests/RunCMake/VS10ProjectWinCE/VsCEDebuggerDeploy.cmake14
-rw-r--r--Tests/RunCMake/VS10ProjectWinCE/VsCSharpCFProject-check.cmake54
-rw-r--r--Tests/RunCMake/VS10ProjectWinCE/VsCSharpCFProject.cmake8
-rw-r--r--Tests/RunCMake/VS10ProjectWinCE/foo.cpp3
-rw-r--r--Tests/RunCMake/VS10ProjectWinCE/foo.cs3
-rw-r--r--Tests/RunCMake/VisibilityPreset/CMP0063-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/WorkingDirectory/CMakeLists.txt.in3
-rw-r--r--Tests/RunCMake/WorkingDirectory/RunCMakeTest.cmake9
-rw-r--r--Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-check.cmake3
-rw-r--r--Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-result.txt1
-rw-r--r--Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-stdout.txt1
-rw-r--r--Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir.cmake7
-rw-r--r--Tests/RunCMake/WorkingDirectory/dirNotExist-result.txt1
-rw-r--r--Tests/RunCMake/WorkingDirectory/dirNotExist-stderr.txt1
-rw-r--r--Tests/RunCMake/WorkingDirectory/dirNotExist-stdout.txt10
-rw-r--r--Tests/RunCMake/WorkingDirectory/dirNotExist.cmake6
-rw-r--r--Tests/RunCMake/WorkingDirectory/test.cmake.in15
-rw-r--r--Tests/RunCMake/WriteBasicConfigVersionFile/All.cmake884
-rw-r--r--Tests/RunCMake/WriteBasicConfigVersionFile/ArchIndependent.cmake63
-rw-r--r--Tests/RunCMake/WriteBasicConfigVersionFile/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/WriteBasicConfigVersionFile/RunCMakeTest.cmake4
-rw-r--r--Tests/RunCMake/XcodeProject/DeploymentTarget.c26
-rw-r--r--Tests/RunCMake/XcodeProject/DeploymentTarget.cmake25
-rw-r--r--Tests/RunCMake/XcodeProject/ExplicitCMakeLists-check.cmake20
-rw-r--r--Tests/RunCMake/XcodeProject/ExplicitCMakeLists.cmake2
-rw-r--r--Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions-result.txt1
-rw-r--r--Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions-stderr.txt10
-rw-r--r--Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions.cmake3
-rw-r--r--Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs-result.txt1
-rw-r--r--Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs-stderr.txt10
-rw-r--r--Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs.cmake3
-rw-r--r--Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions-result.txt1
-rw-r--r--Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions-stderr.txt10
-rw-r--r--Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions.cmake3
-rw-r--r--Tests/RunCMake/XcodeProject/XCTestLookup.cmake3
-rw-r--r--Tests/RunCMake/XcodeProject/XcodeDependOnZeroCheck-build-stdout.txt1
-rw-r--r--Tests/RunCMake/XcodeProject/XcodeDependOnZeroCheck.cmake4
-rw-r--r--Tests/RunCMake/XcodeProject/XcodeGenerateTopLevelProjectOnly-check.cmake3
-rw-r--r--Tests/RunCMake/XcodeProject/XcodeGenerateTopLevelProjectOnly.cmake3
-rw-r--r--Tests/RunCMake/XcodeProject/XcodeSchemaProperty-check.cmake52
-rw-r--r--Tests/RunCMake/XcodeProject/XcodeSchemaProperty.cmake42
-rw-r--r--Tests/RunCMake/XcodeProject/subproject/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/XcodeProject/zerocheck/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/add_custom_command/AssigningMultipleTargets.cmake13
-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/a.c3
-rw-r--r--Tests/RunCMake/add_custom_command/generate-once.cmake8
-rw-r--r--Tests/RunCMake/add_custom_target/CommandExpandsEmpty.cmake1
-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.txt6
-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.txt6
-rw-r--r--Tests/RunCMake/add_executable/NoSourcesButLinkObjects.cmake5
-rw-r--r--Tests/RunCMake/add_executable/OnlyObjectSources.cmake5
-rw-r--r--Tests/RunCMake/add_executable/RunCMakeTest.cmake7
-rw-r--r--Tests/RunCMake/add_executable/test.cpp0
-rw-r--r--Tests/RunCMake/add_library/CMP0073-stdout.txt3
-rw-r--r--Tests/RunCMake/add_library/CMP0073.cmake18
-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.txt6
-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.txt6
-rw-r--r--Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects.cmake5
-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.txt6
-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.cmake5
-rw-r--r--Tests/RunCMake/add_library/RunCMakeTest.cmake26
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithNoSources-result.txt1
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithNoSources-stderr.txt6
-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.txt6
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects.cmake5
-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.txt6
-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.txt6
-rw-r--r--Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects.cmake5
-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.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/empty.c0
-rw-r--r--Tests/RunCMake/add_library/test.cpp0
-rw-r--r--Tests/RunCMake/add_link_options/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/add_link_options/LINKER_SHELL_expansion-build-check.cmake2
-rw-r--r--Tests/RunCMake/add_link_options/LINKER_SHELL_expansion.cmake4
-rw-r--r--Tests/RunCMake/add_link_options/LINKER_expansion-build-check.cmake2
-rw-r--r--Tests/RunCMake/add_link_options/LINKER_expansion-list.cmake36
-rw-r--r--Tests/RunCMake/add_link_options/LINKER_expansion-validation.cmake15
-rw-r--r--Tests/RunCMake/add_link_options/LINKER_expansion.cmake4
-rw-r--r--Tests/RunCMake/add_link_options/LINK_OPTIONS-exe-check.cmake7
-rw-r--r--Tests/RunCMake/add_link_options/LINK_OPTIONS-exe-result.txt1
-rw-r--r--Tests/RunCMake/add_link_options/LINK_OPTIONS-mod-check.cmake7
-rw-r--r--Tests/RunCMake/add_link_options/LINK_OPTIONS-mod-result.txt1
-rw-r--r--Tests/RunCMake/add_link_options/LINK_OPTIONS-shared-check.cmake7
-rw-r--r--Tests/RunCMake/add_link_options/LINK_OPTIONS-shared-result.txt1
-rw-r--r--Tests/RunCMake/add_link_options/LINK_OPTIONS.cmake17
-rw-r--r--Tests/RunCMake/add_link_options/LinkOptionsExe.c4
-rw-r--r--Tests/RunCMake/add_link_options/LinkOptionsLib.c7
-rw-r--r--Tests/RunCMake/add_link_options/RunCMakeTest.cmake38
-rw-r--r--Tests/RunCMake/add_link_options/bad_SHELL_usage-result.txt1
-rw-r--r--Tests/RunCMake/add_link_options/bad_SHELL_usage-stderr.txt4
-rw-r--r--Tests/RunCMake/add_link_options/bad_SHELL_usage.cmake6
-rw-r--r--Tests/RunCMake/add_link_options/dump.c13
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-ExcludeFromAll/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-NEW-install-component-stdout.txt4
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-NEW-install-stdout.txt3
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-NEW.cmake3
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-Nested/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-Nested/sub/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-NestedSub/CMakeLists.txt2
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-NestedSub/sub/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-None/CMakeLists.txt0
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-OLD-install-component-stdout.txt4
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-OLD-install-stdout.txt3
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-OLD.cmake3
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-install-component-stdout.txt4
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-install-stdout.txt3
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-stderr.txt7
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested.cmake2
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-install-component-stdout.txt4
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-install-stdout.txt3
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-stderr.txt7
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub.cmake1
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall-install-component-stdout.txt3
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall-install-stdout.txt2
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall.cmake1
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-None-install-component-stdout.txt3
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-None-install-stdout.txt2
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-None.cmake2
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-install-component-stdout.txt4
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-install-stdout.txt3
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN-stderr.txt7
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082-WARN.cmake3
-rw-r--r--Tests/RunCMake/add_subdirectory/CMP0082/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/add_subdirectory/ExcludeFromAll-build-sub-stderr.txt1
-rw-r--r--Tests/RunCMake/add_subdirectory/ExcludeFromAll/check-sub.cmake32
-rw-r--r--Tests/RunCMake/add_subdirectory/ExcludeFromAll/check.cmake35
-rw-r--r--Tests/RunCMake/add_subdirectory/ExcludeFromAll/subinc.cpp4
-rw-r--r--Tests/RunCMake/add_subdirectory/ExcludeFromAll/zot.cpp4
-rw-r--r--Tests/RunCMake/alias_targets/imported-global-target-stderr.txt2
-rw-r--r--Tests/RunCMake/alias_targets/imported-global-target.cmake46
-rw-r--r--Tests/RunCMake/cmake_minimum_required/Future.cmake1
-rw-r--r--Tests/RunCMake/cmake_minimum_required/Range-stderr.txt4
-rw-r--r--Tests/RunCMake/cmake_minimum_required/Range.cmake6
-rw-r--r--Tests/RunCMake/cmake_minimum_required/RangeBad-result.txt1
-rw-r--r--Tests/RunCMake/cmake_minimum_required/RangeBad-stderr.txt56
-rw-r--r--Tests/RunCMake/cmake_minimum_required/RangeBad.cmake10
-rw-r--r--Tests/RunCMake/cmake_minimum_required/Unknown-result.txt1
-rw-r--r--Tests/RunCMake/cmake_minimum_required/Unknown-stderr.txt4
-rw-r--r--Tests/RunCMake/cmake_minimum_required/Unknown.cmake1
-rw-r--r--Tests/RunCMake/cmake_parse_arguments/KeyWordsMissingValues.cmake133
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CMakeLists.txt.in5
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CTestConfig.cmake.in1
-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
-rw-r--r--Tests/RunCMake/ctest_start/AppendDifferentModel-check.cmake1
-rw-r--r--Tests/RunCMake/ctest_start/AppendDifferentModel-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_start/AppendDifferentModel-stdout.txt7
-rw-r--r--Tests/RunCMake/ctest_start/AppendDifferentTrack-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_start/AppendDifferentTrack-stdout.txt8
-rw-r--r--Tests/RunCMake/ctest_start/AppendNoMatchingTrack-stdout.txt7
-rw-r--r--Tests/RunCMake/ctest_start/AppendNoModel-check.cmake1
-rw-r--r--Tests/RunCMake/ctest_start/AppendNoModel-stdout.txt7
-rw-r--r--Tests/RunCMake/ctest_start/AppendOldContinuous-stdout.txt7
-rw-r--r--Tests/RunCMake/ctest_start/AppendOldNoModel-result.txt1
-rw-r--r--Tests/RunCMake/ctest_start/AppendOldNoModel-stderr.txt3
-rw-r--r--Tests/RunCMake/ctest_start/AppendOldNoModel-stdout.txt5
-rw-r--r--Tests/RunCMake/ctest_start/AppendSameModel-check.cmake1
-rw-r--r--Tests/RunCMake/ctest_start/AppendSameModel-stdout.txt7
-rw-r--r--Tests/RunCMake/ctest_start/FunctionScope-stdout.txt1
-rw-r--r--Tests/RunCMake/ctest_start/MissingTrackArg-result.txt1
-rw-r--r--Tests/RunCMake/ctest_start/MissingTrackArg-stderr.txt2
-rw-r--r--Tests/RunCMake/ctest_start/MissingTrackArgAppend-result.txt1
-rw-r--r--Tests/RunCMake/ctest_start/MissingTrackArgAppend-stderr.txt2
-rw-r--r--Tests/RunCMake/ctest_start/MissingTrackArgQuiet-result.txt1
-rw-r--r--Tests/RunCMake/ctest_start/MissingTrackArgQuiet-stderr.txt2
-rw-r--r--Tests/RunCMake/ctest_start/NoAppendDifferentTrack-stdout.txt7
-rw-r--r--Tests/RunCMake/ctest_start/NoModel-result.txt1
-rw-r--r--Tests/RunCMake/ctest_start/NoModel-stderr.txt3
-rw-r--r--Tests/RunCMake/ctest_start/TooManyArgs-result.txt1
-rw-r--r--Tests/RunCMake/ctest_start/TooManyArgs-stderr.txt2
-rw-r--r--Tests/RunCMake/ctest_start/WriteModelToTagContinuous-check.cmake1
-rw-r--r--Tests/RunCMake/ctest_start/WriteModelToTagExperimental-check.cmake1
-rw-r--r--Tests/RunCMake/ctest_start/WriteModelToTagNightly-check.cmake1
-rw-r--r--Tests/RunCMake/ctest_start/WriteModelToTagNoMatchingTrack-check.cmake1
-rw-r--r--Tests/RunCMake/ctest_submit/CDashSubmitVerbose-result.txt1
-rw-r--r--Tests/RunCMake/ctest_submit/CDashSubmitVerbose-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_submit/CDashSubmitVerbose-stdout.txt1
-rw-r--r--Tests/RunCMake/ctest_submit/FILESNoBuildId-result.txt1
-rw-r--r--Tests/RunCMake/ctest_submit/FILESNoBuildId-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_submit/FILESNoBuildId-stdout.txt1
-rw-r--r--Tests/RunCMake/ctest_submit/PARTSDone-result.txt1
-rw-r--r--Tests/RunCMake/ctest_submit/PARTSDone-stderr.txt3
-rw-r--r--Tests/RunCMake/ctest_test/CTestTestLoadWait-stdout.txt8
-rw-r--r--Tests/RunCMake/ctest_test/TestLoadWait-stdout.txt8
-rw-r--r--Tests/RunCMake/ctest_update/CMakeLists.txt.in4
-rw-r--r--Tests/RunCMake/ctest_update/RunCMakeTest.cmake25
-rw-r--r--Tests/RunCMake/ctest_update/UpdateActualVersion-check.cmake12
-rw-r--r--Tests/RunCMake/ctest_update/UpdateChangeId-check.cmake12
-rw-r--r--Tests/RunCMake/ctest_update/test.cmake.in18
-rw-r--r--Tests/RunCMake/execute_process/EchoCommand-result.txt1
-rw-r--r--Tests/RunCMake/execute_process/EchoCommand-stderr.txt5
-rw-r--r--Tests/RunCMake/execute_process/EchoCommand-stdout.txt12
-rw-r--r--Tests/RunCMake/execute_process/EchoCommand.cmake41
-rw-r--r--Tests/RunCMake/execute_process/EchoCommand2-result.txt1
-rw-r--r--Tests/RunCMake/execute_process/EchoCommand2-stderr.txt5
-rw-r--r--Tests/RunCMake/execute_process/EchoCommand2-stdout.txt12
-rw-r--r--Tests/RunCMake/execute_process/EchoCommand3-result.txt1
-rw-r--r--Tests/RunCMake/execute_process/EchoCommand3-stderr.txt2
-rw-r--r--Tests/RunCMake/execute_process/EncodingUTF-8-stderr.txt1
-rw-r--r--Tests/RunCMake/execute_process/ExitValues-stdout.txt14
-rw-r--r--Tests/RunCMake/execute_process/ExitValues.cmake120
-rw-r--r--Tests/RunCMake/exit_code.c30
-rw-r--r--Tests/RunCMake/export/Empty.cmake1
-rw-r--r--Tests/RunCMake/export/ExportPropertiesUndefined.cmake11
-rw-r--r--Tests/RunCMake/export/ForbiddenToExportImportedProperties-result.txt1
-rw-r--r--Tests/RunCMake/export/ForbiddenToExportImportedProperties-stderr.txt3
-rw-r--r--Tests/RunCMake/export/ForbiddenToExportImportedProperties.cmake12
-rw-r--r--Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-result.txt1
-rw-r--r--Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-stderr.txt3
-rw-r--r--Tests/RunCMake/export/ForbiddenToExportInterfaceProperties.cmake12
-rw-r--r--Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-result.txt1
-rw-r--r--Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-stderr.txt3
-rw-r--r--Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp.cmake12
-rw-r--r--Tests/RunCMake/export/empty.cpp7
-rw-r--r--Tests/RunCMake/file/CREATE_LINK-COPY_ON_ERROR.cmake11
-rw-r--r--Tests/RunCMake/file/CREATE_LINK-SYMBOLIC-noexist.cmake4
-rw-r--r--Tests/RunCMake/file/CREATE_LINK-SYMBOLIC.cmake4
-rw-r--r--Tests/RunCMake/file/CREATE_LINK-noarg-result.txt1
-rw-r--r--Tests/RunCMake/file/CREATE_LINK-noarg-stderr.txt4
-rw-r--r--Tests/RunCMake/file/CREATE_LINK-noarg.cmake1
-rw-r--r--Tests/RunCMake/file/CREATE_LINK-noexist-stderr.txt1
-rw-r--r--Tests/RunCMake/file/CREATE_LINK-noexist.cmake4
-rw-r--r--Tests/RunCMake/file/CREATE_LINK.cmake11
-rw-r--r--Tests/RunCMake/file/DOWNLOAD-netrc-bad-result.txt1
-rw-r--r--Tests/RunCMake/file/DOWNLOAD-netrc-bad-stderr.txt19
-rw-r--r--Tests/RunCMake/file/DOWNLOAD-netrc-bad.cmake15
-rw-r--r--Tests/RunCMake/file/DOWNLOAD-netrc-bad.txt0
-rw-r--r--Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-build-stdout.txt1
-rw-r--r--Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_first-stdout.txt2
-rw-r--r--Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_second-stdout.txt2
-rw-r--r--Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-stdout.txt1
-rw-r--r--Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake.cmake10
-rw-r--r--Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-result.txt1
-rw-r--r--Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-stderr.txt1
-rw-r--r--Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE.cmake1
-rw-r--r--Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-result.txt1
-rw-r--r--Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-stderr.txt7
-rw-r--r--Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified.cmake21
-rw-r--r--Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-result.txt1
-rw-r--r--Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-stderr.txt4
-rw-r--r--Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg.cmake1
-rw-r--r--Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-result.txt1
-rw-r--r--Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-stderr.txt4
-rw-r--r--Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS.cmake1
-rw-r--r--Tests/RunCMake/file/GLOB-noexp-FOLLOW_SYMLINKS.cmake1
-rw-r--r--Tests/RunCMake/file/GLOB-noexp-RELATIVE-result.txt1
-rw-r--r--Tests/RunCMake/file/GLOB-noexp-RELATIVE-stderr.txt4
-rw-r--r--Tests/RunCMake/file/GLOB-noexp-RELATIVE.cmake1
-rw-r--r--Tests/RunCMake/file/GLOB-sort-dedup-stderr.txt2
-rw-r--r--Tests/RunCMake/file/GLOB-sort-dedup.cmake21
-rw-r--r--Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late-stderr.txt6
-rw-r--r--Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late.cmake11
-rw-r--r--Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-result.txt1
-rw-r--r--Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-stderr.txt4
-rw-r--r--Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS.cmake1
-rw-r--r--Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version-stderr.txt13
-rw-r--r--Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version.cmake6
-rw-r--r--Tests/RunCMake/file/INSTALL-FOLLOW_SYMLINK_CHAIN.cmake168
-rw-r--r--Tests/RunCMake/file/READ_SYMLINK-noexist-result.txt1
-rw-r--r--Tests/RunCMake/file/READ_SYMLINK-noexist-stderr.txt6
-rw-r--r--Tests/RunCMake/file/READ_SYMLINK-noexist.cmake1
-rw-r--r--Tests/RunCMake/file/READ_SYMLINK-notsymlink-result.txt1
-rw-r--r--Tests/RunCMake/file/READ_SYMLINK-notsymlink-stderr.txt6
-rw-r--r--Tests/RunCMake/file/READ_SYMLINK-notsymlink.cmake2
-rw-r--r--Tests/RunCMake/file/READ_SYMLINK.cmake13
-rw-r--r--Tests/RunCMake/file/REMOVE-empty-stderr.txt11
-rw-r--r--Tests/RunCMake/file/REMOVE-empty.cmake2
-rw-r--r--Tests/RunCMake/file/SIZE-error-does-not-exist-result.txt1
-rw-r--r--Tests/RunCMake/file/SIZE-error-does-not-exist-stderr.txt6
-rw-r--r--Tests/RunCMake/file/SIZE-error-does-not-exist.cmake3
-rw-r--r--Tests/RunCMake/file/SIZE.cmake9
-rw-r--r--Tests/RunCMake/file/TOUCH-error-in-source-directory-result.txt1
-rw-r--r--Tests/RunCMake/file/TOUCH-error-in-source-directory-stderr.txt1
-rw-r--r--Tests/RunCMake/file/TOUCH-error-in-source-directory.cmake2
-rw-r--r--Tests/RunCMake/file/TOUCH-error-missing-directory-result.txt1
-rw-r--r--Tests/RunCMake/file/TOUCH-error-missing-directory-stderr.txt1
-rw-r--r--Tests/RunCMake/file/TOUCH-error-missing-directory.cmake1
-rw-r--r--Tests/RunCMake/file/TOUCH-result.txt1
-rw-r--r--Tests/RunCMake/file/TOUCH-stderr.txt9
-rw-r--r--Tests/RunCMake/file/TOUCH.cmake16
-rw-r--r--Tests/RunCMake/file/UPLOAD-netrc-bad-result.txt1
-rw-r--r--Tests/RunCMake/file/UPLOAD-netrc-bad-stderr.txt19
-rw-r--r--Tests/RunCMake/file/UPLOAD-netrc-bad.cmake15
-rw-r--r--Tests/RunCMake/file/UPLOAD-netrc-bad.txt0
-rw-r--r--Tests/RunCMake/find_package/CMP0074-OLD-stderr.txt12
-rw-r--r--Tests/RunCMake/find_package/CMP0074-OLD.cmake2
-rw-r--r--Tests/RunCMake/find_package/CMP0074-WARN-stderr.txt32
-rw-r--r--Tests/RunCMake/find_package/CMP0074-WARN.cmake2
-rw-r--r--Tests/RunCMake/find_package/CMP0074-common.cmake46
-rw-r--r--Tests/RunCMake/find_package/CMP0084-NEW-stderr.txt20
-rw-r--r--Tests/RunCMake/find_package/CMP0084-NEW.cmake7
-rw-r--r--Tests/RunCMake/find_package/CMP0084-OLD.cmake7
-rw-r--r--Tests/RunCMake/find_package/CMP0084-WARN-stderr.txt8
-rw-r--r--Tests/RunCMake/find_package/CMP0084-WARN.cmake6
-rw-r--r--Tests/RunCMake/find_package/PackageRoot/ResolvedConfig.cmake1
-rw-r--r--Tests/RunCMake/find_package/SetFoundResolved-stderr.txt10
-rw-r--r--Tests/RunCMake/find_package/SetFoundResolved.cmake17
-rw-r--r--Tests/RunCMake/find_path/EmptyOldStyle-stdout.txt1
-rw-r--r--Tests/RunCMake/find_path/EmptyOldStyle.cmake2
-rw-r--r--Tests/RunCMake/find_program/RelAndAbsPath-stdout.txt6
-rw-r--r--Tests/RunCMake/find_program/RelAndAbsPath.cmake63
-rwxr-xr-xTests/RunCMake/find_program/testCWD1
-rw-r--r--Tests/RunCMake/foreach/BadRangeInFunction-result.txt1
-rw-r--r--Tests/RunCMake/foreach/BadRangeInFunction-stderr.txt5
-rw-r--r--Tests/RunCMake/foreach/BadRangeInFunction.cmake5
-rw-r--r--Tests/RunCMake/foreach/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/foreach/RunCMakeTest.cmake3
-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/install/CMP0062-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/install/CMP0087-NEW-check.cmake7
-rw-r--r--Tests/RunCMake/install/CMP0087-NEW.cmake3
-rw-r--r--Tests/RunCMake/install/CMP0087-NEW/CMakeLists.txt7
-rw-r--r--Tests/RunCMake/install/CMP0087-OLD-check.cmake8
-rw-r--r--Tests/RunCMake/install/CMP0087-OLD.cmake3
-rw-r--r--Tests/RunCMake/install/CMP0087-OLD/CMakeLists.txt6
-rw-r--r--Tests/RunCMake/install/CMP0087-WARN-stderr.txt5
-rw-r--r--Tests/RunCMake/install/CMP0087-WARN.cmake2
-rw-r--r--Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE-result.txt1
-rw-r--r--Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE-stderr.txt5
-rw-r--r--Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE.cmake1
-rw-r--r--Tests/RunCMake/install/DIRECTORY-OPTIONAL-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/DIRECTORY-OPTIONAL.cmake1
-rw-r--r--Tests/RunCMake/install/DIRECTORY-PATTERN-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/DIRECTORY-PATTERN.cmake36
-rw-r--r--Tests/RunCMake/install/DIRECTORY-TYPE-Cache-all-check.cmake42
-rw-r--r--Tests/RunCMake/install/DIRECTORY-TYPE-Cache.cmake13
-rw-r--r--Tests/RunCMake/install/DIRECTORY-TYPE-CacheDependent-all-check.cmake24
-rw-r--r--Tests/RunCMake/install/DIRECTORY-TYPE-CacheDependent.cmake7
-rw-r--r--Tests/RunCMake/install/DIRECTORY-TYPE-all-check.cmake42
-rw-r--r--Tests/RunCMake/install/DIRECTORY-TYPE.cmake13
-rw-r--r--Tests/RunCMake/install/Deprecated-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/Deprecated.cmake13
-rw-r--r--Tests/RunCMake/install/FILES-DESTINATION-TYPE-result.txt1
-rw-r--r--Tests/RunCMake/install/FILES-DESTINATION-TYPE-stderr.txt5
-rw-r--r--Tests/RunCMake/install/FILES-DESTINATION-TYPE.cmake1
-rw-r--r--Tests/RunCMake/install/FILES-OPTIONAL-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/FILES-OPTIONAL.cmake1
-rw-r--r--Tests/RunCMake/install/FILES-PERMISSIONS-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/FILES-PERMISSIONS.cmake5
-rw-r--r--Tests/RunCMake/install/FILES-TYPE-Cache-all-check.cmake29
-rw-r--r--Tests/RunCMake/install/FILES-TYPE-Cache.cmake13
-rw-r--r--Tests/RunCMake/install/FILES-TYPE-CacheDependent-all-check.cmake17
-rw-r--r--Tests/RunCMake/install/FILES-TYPE-CacheDependent.cmake7
-rw-r--r--Tests/RunCMake/install/FILES-TYPE-all-check.cmake29
-rw-r--r--Tests/RunCMake/install/FILES-TYPE.cmake13
-rw-r--r--Tests/RunCMake/install/InstallRequiredSystemLibraries-stderr.txt1
-rw-r--r--Tests/RunCMake/install/InstallRequiredSystemLibraries.cmake10
-rw-r--r--Tests/RunCMake/install/PRE_POST_INSTALL_SCRIPT-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/PRE_POST_INSTALL_SCRIPT.cmake7
-rw-r--r--Tests/RunCMake/install/SCRIPT-COMPONENT-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/SCRIPT-COMPONENT-dev-check.cmake1
-rw-r--r--Tests/RunCMake/install/SCRIPT-COMPONENT-uns-check.cmake1
-rw-r--r--Tests/RunCMake/install/SCRIPT-COMPONENT.cmake5
-rw-r--r--Tests/RunCMake/install/SCRIPT-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/SCRIPT.cmake4
-rw-r--r--Tests/RunCMake/install/TARGETS-Apple-Defaults-result.txt1
-rw-r--r--Tests/RunCMake/install/TARGETS-Apple-Defaults-stderr.txt12
-rw-r--r--Tests/RunCMake/install/TARGETS-Apple-Defaults.cmake8
-rw-r--r--Tests/RunCMake/install/TARGETS-CONFIGURATIONS-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/TARGETS-CONFIGURATIONS.cmake2
-rw-r--r--Tests/RunCMake/install/TARGETS-Defaults-Cache-all-check.cmake49
-rw-r--r--Tests/RunCMake/install/TARGETS-Defaults-Cache.cmake19
-rw-r--r--Tests/RunCMake/install/TARGETS-Defaults-all-check.cmake55
-rw-r--r--Tests/RunCMake/install/TARGETS-Defaults.cmake27
-rw-r--r--Tests/RunCMake/install/TARGETS-ImportedGlobal-result.txt1
-rw-r--r--Tests/RunCMake/install/TARGETS-ImportedGlobal-stderr.txt4
-rw-r--r--Tests/RunCMake/install/TARGETS-ImportedGlobal.cmake3
-rw-r--r--Tests/RunCMake/install/TARGETS-InstallFromSubDir-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/TARGETS-InstallFromSubDir.cmake4
-rw-r--r--Tests/RunCMake/install/TARGETS-InstallFromSubDir/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-all-check.cmake73
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all-result.txt1
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all-stderr.txt5
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all.cmake9
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc-result.txt1
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc-stderr.txt5
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc.cmake10
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-dev-check.cmake11
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-lib-check.cmake50
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-uns-check.cmake38
-rw-r--r--Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT.cmake68
-rw-r--r--Tests/RunCMake/install/TARGETS-OPTIONAL-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/TARGETS-OPTIONAL.cmake4
-rw-r--r--Tests/RunCMake/install/TARGETS-OUTPUT_NAME-all-check.cmake13
-rw-r--r--Tests/RunCMake/install/TARGETS-OUTPUT_NAME.cmake27
-rw-r--r--Tests/RunCMake/install/TARGETS-Parts-all-check.cmake1
-rw-r--r--Tests/RunCMake/install/TARGETS-Parts.cmake7
-rw-r--r--Tests/RunCMake/install/TARGETS-RPATH-all-check.cmake14
-rw-r--r--Tests/RunCMake/install/TARGETS-RPATH.cmake14
-rw-r--r--Tests/RunCMake/install/install_script.cmake5
-rw-r--r--Tests/RunCMake/install/obj1.h6
-rw-r--r--Tests/RunCMake/install/obj2.h6
-rw-r--r--Tests/RunCMake/install/obj3.c7
-rw-r--r--Tests/RunCMake/install/obj3.h6
-rw-r--r--Tests/RunCMake/install/obj4.c7
-rw-r--r--Tests/RunCMake/install/obj4.h6
-rw-r--r--Tests/RunCMake/install/obj5.c7
-rw-r--r--Tests/RunCMake/install/obj5.h6
-rw-r--r--Tests/RunCMake/install/pattern/empty.c0
-rw-r--r--Tests/RunCMake/install/pattern/empty.h0
-rw-r--r--Tests/RunCMake/install/pattern/empty.txt0
-rw-r--r--Tests/RunCMake/install/postinstall.cmake1
-rw-r--r--Tests/RunCMake/install/preinstall.cmake1
-rwxr-xr-xTests/RunCMake/install/script2
-rwxr-xr-xTests/RunCMake/install/script.bat1
-rw-r--r--Tests/RunCMake/install/testobj1.c9
-rw-r--r--Tests/RunCMake/list/JOIN-NoArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/JOIN-NoArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/JOIN-NoArguments.cmake1
-rw-r--r--Tests/RunCMake/list/JOIN-NoVariable-result.txt1
-rw-r--r--Tests/RunCMake/list/JOIN-NoVariable-stderr.txt4
-rw-r--r--Tests/RunCMake/list/JOIN-NoVariable.cmake1
-rw-r--r--Tests/RunCMake/list/JOIN-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/JOIN-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/JOIN-TooManyArguments.cmake1
-rw-r--r--Tests/RunCMake/list/JOIN.cmake18
-rw-r--r--Tests/RunCMake/list/POP_BACK-NoArgs-result.txt1
-rw-r--r--Tests/RunCMake/list/POP_BACK-NoArgs-stderr.txt1
-rw-r--r--Tests/RunCMake/list/POP_BACK-NoArgs.cmake1
-rw-r--r--Tests/RunCMake/list/POP_BACK.cmake79
-rw-r--r--Tests/RunCMake/list/POP_FRONT-NoArgs-result.txt1
-rw-r--r--Tests/RunCMake/list/POP_FRONT-NoArgs-stderr.txt1
-rw-r--r--Tests/RunCMake/list/POP_FRONT-NoArgs.cmake1
-rw-r--r--Tests/RunCMake/list/POP_FRONT.cmake92
-rw-r--r--Tests/RunCMake/list/PREPEND-NoArgs-result.txt1
-rw-r--r--Tests/RunCMake/list/PREPEND-NoArgs-stderr.txt1
-rw-r--r--Tests/RunCMake/list/PREPEND-NoArgs.cmake1
-rw-r--r--Tests/RunCMake/list/PREPEND.cmake33
-rw-r--r--Tests/RunCMake/list/REMOVE_AT-EmptyList-result.txt1
-rw-r--r--Tests/RunCMake/list/REMOVE_AT-EmptyList-stderr.txt4
-rw-r--r--Tests/RunCMake/list/REMOVE_AT-EmptyList.cmake6
-rw-r--r--Tests/RunCMake/list/REMOVE_DUPLICATES-PreserveOrder.cmake5
-rw-r--r--Tests/RunCMake/list/SORT-BadCaseOption-result.txt1
-rw-r--r--Tests/RunCMake/list/SORT-BadCaseOption-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SORT-BadCaseOption.cmake1
-rw-r--r--Tests/RunCMake/list/SORT-BadCompareOption-result.txt1
-rw-r--r--Tests/RunCMake/list/SORT-BadCompareOption-stderr.txt5
-rw-r--r--Tests/RunCMake/list/SORT-BadCompareOption.cmake1
-rw-r--r--Tests/RunCMake/list/SORT-BadOrderOption-result.txt1
-rw-r--r--Tests/RunCMake/list/SORT-BadOrderOption-stderr.txt5
-rw-r--r--Tests/RunCMake/list/SORT-BadOrderOption.cmake1
-rw-r--r--Tests/RunCMake/list/SORT-DuplicateCaseOption-result.txt1
-rw-r--r--Tests/RunCMake/list/SORT-DuplicateCaseOption-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SORT-DuplicateCaseOption.cmake2
-rw-r--r--Tests/RunCMake/list/SORT-DuplicateCompareOption-result.txt1
-rw-r--r--Tests/RunCMake/list/SORT-DuplicateCompareOption-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SORT-DuplicateCompareOption.cmake2
-rw-r--r--Tests/RunCMake/list/SORT-DuplicateOrderOption-result.txt1
-rw-r--r--Tests/RunCMake/list/SORT-DuplicateOrderOption-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SORT-DuplicateOrderOption.cmake2
-rw-r--r--Tests/RunCMake/list/SORT-NoCaseOption-result.txt1
-rw-r--r--Tests/RunCMake/list/SORT-NoCaseOption-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SORT-NoCaseOption.cmake1
-rw-r--r--Tests/RunCMake/list/SORT-WrongOption-result.txt1
-rw-r--r--Tests/RunCMake/list/SORT-WrongOption-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SORT-WrongOption.cmake1
-rw-r--r--Tests/RunCMake/list/SORT.cmake114
-rw-r--r--Tests/RunCMake/list/SUBLIST-InvalidIndex-result.txt1
-rw-r--r--Tests/RunCMake/list/SUBLIST-InvalidIndex-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SUBLIST-InvalidIndex.cmake2
-rw-r--r--Tests/RunCMake/list/SUBLIST-InvalidLength-result.txt1
-rw-r--r--Tests/RunCMake/list/SUBLIST-InvalidLength-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SUBLIST-InvalidLength.cmake2
-rw-r--r--Tests/RunCMake/list/SUBLIST-NoArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/SUBLIST-NoArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SUBLIST-NoArguments.cmake1
-rw-r--r--Tests/RunCMake/list/SUBLIST-NoVariable-result.txt1
-rw-r--r--Tests/RunCMake/list/SUBLIST-NoVariable-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SUBLIST-NoVariable.cmake2
-rw-r--r--Tests/RunCMake/list/SUBLIST-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/SUBLIST-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/SUBLIST-TooManyArguments.cmake1
-rw-r--r--Tests/RunCMake/list/SUBLIST.cmake46
-rw-r--r--Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-APPEND.cmake48
-rw-r--r--Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-GENEX_STRIP.cmake49
-rw-r--r--Tests/RunCMake/list/TRANSFORM-InvalidAction-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-InvalidAction-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-InvalidAction.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-NoAction-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-NoAction-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-NoAction.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-PREPEND.cmake48
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-stderr.txt5
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-stderr.txt5
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-stderr.txt5
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-REPLACE.cmake48
-rw-r--r--Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-STRIP.cmake49
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-stderr.txt5
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-stderr.txt5
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-stderr.txt5
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-TOLOWER.cmake48
-rw-r--r--Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments.cmake2
-rw-r--r--Tests/RunCMake/list/TRANSFORM-TOUPPER.cmake48
-rw-r--r--Tests/RunCMake/math/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/math/MATH-DivideByZero-result.txt1
-rw-r--r--Tests/RunCMake/math/MATH-DivideByZero-stderr.txt4
-rw-r--r--Tests/RunCMake/math/MATH-DivideByZero.cmake1
-rw-r--r--Tests/RunCMake/math/MATH-DoubleOption-result.txt1
-rw-r--r--Tests/RunCMake/math/MATH-DoubleOption-stderr.txt4
-rw-r--r--Tests/RunCMake/math/MATH-DoubleOption.cmake1
-rw-r--r--Tests/RunCMake/math/MATH-InvalidExpression-result.txt1
-rw-r--r--Tests/RunCMake/math/MATH-InvalidExpression-stderr.txt5
-rw-r--r--Tests/RunCMake/math/MATH-InvalidExpression.cmake1
-rw-r--r--Tests/RunCMake/math/MATH-ToleratedExpression-stderr.txt8
-rw-r--r--Tests/RunCMake/math/MATH-ToleratedExpression.cmake4
-rw-r--r--Tests/RunCMake/math/MATH-TooManyArguments-result.txt1
-rw-r--r--Tests/RunCMake/math/MATH-TooManyArguments-stderr.txt4
-rw-r--r--Tests/RunCMake/math/MATH-TooManyArguments.cmake1
-rw-r--r--Tests/RunCMake/math/MATH-WrongArgument-result.txt1
-rw-r--r--Tests/RunCMake/math/MATH-WrongArgument-stderr.txt4
-rw-r--r--Tests/RunCMake/math/MATH-WrongArgument.cmake1
-rw-r--r--Tests/RunCMake/math/MATH.cmake12
-rw-r--r--Tests/RunCMake/math/RunCMakeTest.cmake9
-rw-r--r--Tests/RunCMake/message/message-all-loglevels.cmake10
-rw-r--r--Tests/RunCMake/message/message-loglevel-debug-stderr.txt12
-rw-r--r--Tests/RunCMake/message/message-loglevel-debug-stdout.txt3
-rw-r--r--Tests/RunCMake/message/message-loglevel-default-stderr.txt12
-rw-r--r--Tests/RunCMake/message/message-loglevel-default-stdout.txt1
-rw-r--r--Tests/RunCMake/message/message-loglevel-invalid-result.txt1
-rw-r--r--Tests/RunCMake/message/message-loglevel-invalid-stderr.txt1
-rw-r--r--Tests/RunCMake/message/message-loglevel-notice-stderr.txt12
-rw-r--r--Tests/RunCMake/message/message-loglevel-status-stderr.txt12
-rw-r--r--Tests/RunCMake/message/message-loglevel-status-stdout.txt1
-rw-r--r--Tests/RunCMake/message/message-loglevel-trace-stderr.txt12
-rw-r--r--Tests/RunCMake/message/message-loglevel-trace-stdout.txt4
-rw-r--r--Tests/RunCMake/message/message-loglevel-verbose-stderr.txt12
-rw-r--r--Tests/RunCMake/message/message-loglevel-verbose-stdout.txt2
-rw-r--r--Tests/RunCMake/message/message-loglevel-warning-stderr.txt9
-rw-r--r--Tests/RunCMake/option/CMP0077-NEW.cmake14
-rw-r--r--Tests/RunCMake/option/CMP0077-OLD.cmake9
-rw-r--r--Tests/RunCMake/option/CMP0077-SECOND-PASS.cmake14
-rw-r--r--Tests/RunCMake/option/CMP0077-WARN-stderr.txt7
-rw-r--r--Tests/RunCMake/option/CMP0077-WARN.cmake5
-rw-r--r--Tests/RunCMake/option/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/option/RunCMakeTest.cmake6
-rw-r--r--Tests/RunCMake/print_stdin.c18
-rw-r--r--Tests/RunCMake/project/CMP0048-OLD-stderr.txt10
-rw-r--r--Tests/RunCMake/project/LanguagesUnordered-stderr.txt1
-rw-r--r--Tests/RunCMake/project/LanguagesUnordered.cmake1
-rw-r--r--Tests/RunCMake/project/ProjectDescriptionNoArg-stderr.txt2
-rw-r--r--Tests/RunCMake/project/ProjectDescriptionNoArg.cmake2
-rw-r--r--Tests/RunCMake/project/ProjectDescriptionNoArg2-stderr.txt2
-rw-r--r--Tests/RunCMake/project/ProjectDescriptionNoArg2.cmake2
-rw-r--r--Tests/RunCMake/project/ProjectHomepage-stdout.txt3
-rw-r--r--Tests/RunCMake/project/ProjectHomepage.cmake14
-rw-r--r--Tests/RunCMake/project/ProjectHomepage2-result.txt1
-rw-r--r--Tests/RunCMake/project/ProjectHomepage2-stderr.txt4
-rw-r--r--Tests/RunCMake/project/ProjectHomepage2.cmake2
-rw-r--r--Tests/RunCMake/project/ProjectHomepageNoArg-stderr.txt5
-rw-r--r--Tests/RunCMake/project/ProjectHomepageNoArg.cmake2
-rw-r--r--Tests/RunCMake/project/ProjectTwice.cmake26
-rw-r--r--Tests/RunCMake/project/VersionMissingValueOkay-stderr.txt2
-rw-r--r--Tests/RunCMake/project_injected/CMP0048-WARN-stderr.txt12
-rw-r--r--Tests/RunCMake/project_injected/CMP0048-WARN.cmake0
-rw-r--r--Tests/RunCMake/project_injected/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/project_injected/RunCMakeTest.cmake12
-rw-r--r--Tests/RunCMake/pseudo_cppcheck.c39
-rw-r--r--Tests/RunCMake/pseudo_emulator_custom_command_arg.c30
-rw-r--r--Tests/RunCMake/set/ExtraEnvValue-stderr.txt6
-rw-r--r--Tests/RunCMake/set/ExtraEnvValue.cmake1
-rw-r--r--Tests/RunCMake/set/UnknownCacheType-stderr.txt5
-rw-r--r--Tests/RunCMake/set/UnknownCacheType.cmake1
-rw-r--r--Tests/RunCMake/set_property/IMPORTED_GLOBAL-result.txt1
-rw-r--r--Tests/RunCMake/set_property/IMPORTED_GLOBAL-stderr.txt61
-rw-r--r--Tests/RunCMake/set_property/IMPORTED_GLOBAL-stdout.txt17
-rw-r--r--Tests/RunCMake/set_property/IMPORTED_GLOBAL.cmake53
-rw-r--r--Tests/RunCMake/set_property/IMPORTED_GLOBAL/CMakeLists.txt8
-rw-r--r--Tests/RunCMake/set_property/LINK_DIRECTORIES-stdout.txt2
-rw-r--r--Tests/RunCMake/set_property/LINK_DIRECTORIES.cmake3
-rw-r--r--Tests/RunCMake/set_property/LINK_OPTIONS-stdout.txt2
-rw-r--r--Tests/RunCMake/set_property/LINK_OPTIONS.cmake3
-rw-r--r--Tests/RunCMake/set_property/USER_PROP_INHERITED-stdout.txt29
-rw-r--r--Tests/RunCMake/set_property/USER_PROP_INHERITED.cmake83
-rw-r--r--Tests/RunCMake/set_property/USER_PROP_INHERITED/CMakeLists.txt21
-rw-r--r--Tests/RunCMake/set_property/test.cpp0
-rw-r--r--Tests/RunCMake/string/Join.cmake16
-rw-r--r--Tests/RunCMake/string/JoinNoArgs-result.txt1
-rw-r--r--Tests/RunCMake/string/JoinNoArgs-stderr.txt4
-rw-r--r--Tests/RunCMake/string/JoinNoArgs.cmake1
-rw-r--r--Tests/RunCMake/string/JoinNoVar-result.txt1
-rw-r--r--Tests/RunCMake/string/JoinNoVar-stderr.txt4
-rw-r--r--Tests/RunCMake/string/JoinNoVar.cmake1
-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/Repeat.cmake45
-rw-r--r--Tests/RunCMake/string/RepeatNegativeCount-result.txt1
-rw-r--r--Tests/RunCMake/string/RepeatNegativeCount-stderr.txt4
-rw-r--r--Tests/RunCMake/string/RepeatNegativeCount.cmake1
-rw-r--r--Tests/RunCMake/string/RepeatNoArgs-result.txt1
-rw-r--r--Tests/RunCMake/string/RepeatNoArgs-stderr.txt4
-rw-r--r--Tests/RunCMake/string/RepeatNoArgs.cmake1
-rw-r--r--Tests/RunCMake/target_compile_definitions/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/target_compile_definitions/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/target_compile_definitions/empty_keyword_args.cmake5
-rw-r--r--Tests/RunCMake/target_compile_features/empty_keyword_args.cmake5
-rw-r--r--Tests/RunCMake/target_compile_options/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/target_compile_options/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/target_compile_options/empty_keyword_args.cmake5
-rw-r--r--Tests/RunCMake/target_include_directories/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/target_include_directories/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/target_include_directories/empty_keyword_args.cmake5
-rw-r--r--Tests/RunCMake/target_link_directories/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/target_link_directories/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/target_link_directories/empty_keyword_args.cmake5
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-iface-NEW-stdout.txt1
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-iface-NEW.cmake2
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-iface-OLD-stdout.txt1
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-iface-OLD.cmake2
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN-stderr.txt17
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN-stdout.txt1
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN.cmake1
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-iface-common.cmake6
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-iface/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus-result.txt1
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus-stderr.txt6
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus.cmake6
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-stdout.txt1
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-NEW.cmake2
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-OLD-result.txt1
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-OLD-stderr.txt5
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-OLD.cmake2
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-WARN-result.txt1
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-WARN-stderr.txt5
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-WARN.cmake1
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link-common.cmake6
-rw-r--r--Tests/RunCMake/target_link_libraries/CMP0079-link/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/target_link_libraries/ImportedTarget.cmake2
-rw-r--r--Tests/RunCMake/target_link_libraries/ImportedTargetFailure-result.txt1
-rw-r--r--Tests/RunCMake/target_link_libraries/ImportedTargetFailure-stderr.txt5
-rw-r--r--Tests/RunCMake/target_link_libraries/ImportedTargetFailure.cmake2
-rw-r--r--Tests/RunCMake/target_link_libraries/UNKNOWN-IMPORTED-GLOBAL.cmake4
-rw-r--r--Tests/RunCMake/target_link_libraries/empty_keyword_args.cmake4
-rw-r--r--Tests/RunCMake/target_link_options/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/target_link_options/LINKER_expansion-LINKER-check.cmake2
-rw-r--r--Tests/RunCMake/target_link_options/LINKER_expansion-LINKER_SHELL-check.cmake2
-rw-r--r--Tests/RunCMake/target_link_options/LINKER_expansion-validation.cmake15
-rw-r--r--Tests/RunCMake/target_link_options/LINKER_expansion.cmake49
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-basic-check.cmake7
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-basic-result.txt1
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-exe-check.cmake7
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-exe-result.txt1
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-check.cmake4
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-result.txt1
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-static-check.cmake4
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-static-result.txt1
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-mod-check.cmake7
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-mod-result.txt1
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-shared-check.cmake7
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-shared-result.txt1
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-static-check.cmake7
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS-static-result.txt1
-rw-r--r--Tests/RunCMake/target_link_options/LINK_OPTIONS.cmake55
-rw-r--r--Tests/RunCMake/target_link_options/LinkOptionsExe.c4
-rw-r--r--Tests/RunCMake/target_link_options/LinkOptionsLib.c7
-rw-r--r--Tests/RunCMake/target_link_options/RunCMakeTest.cmake43
-rw-r--r--Tests/RunCMake/target_link_options/bad_SHELL_usage-result.txt1
-rw-r--r--Tests/RunCMake/target_link_options/bad_SHELL_usage-stderr.txt4
-rw-r--r--Tests/RunCMake/target_link_options/bad_SHELL_usage.cmake5
-rw-r--r--Tests/RunCMake/target_link_options/dump.c13
-rw-r--r--Tests/RunCMake/target_link_options/empty_keyword_args.cmake5
-rw-r--r--Tests/RunCMake/target_sources/CMakeLists.txt5
-rw-r--r--Tests/RunCMake/target_sources/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/target_sources/empty_keyword_args.cmake5
-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/try_compile/LinkOptions.cmake40
-rw-r--r--Tests/RunCMake/try_compile/lib.c4
-rw-r--r--Tests/RunCMake/try_compile/main.c8
-rw-r--r--Tests/RunCMake/try_run/LinkOptions.cmake44
-rw-r--r--Tests/RunCMake/try_run/lib.c4
-rw-r--r--Tests/RunCMake/try_run/main.c8
-rw-r--r--Tests/RunCMake/variable_watch/ModifyWatchInCallback.cmake17
-rw-r--r--Tests/RunCMake/variable_watch/RaiseInParentScope-stderr.txt2
-rw-r--r--Tests/RunCMake/variable_watch/RaiseInParentScope.cmake15
-rw-r--r--Tests/Server/tc_cache.json24
-rw-r--r--Tests/SourceFileIncludeDirProperty/CMakeLists.txt15
-rw-r--r--Tests/SourceFileIncludeDirProperty/main.c7
-rw-r--r--Tests/SourceFileIncludeDirProperty/source/header.h2
-rw-r--r--Tests/SourceFileIncludeDirProperty/target/header.h2
-rw-r--r--Tests/SourceGroups/tree_empty_prefix_bar.c4
-rw-r--r--Tests/SourceGroups/tree_empty_prefix_foo.c4
-rw-r--r--Tests/TryCompile/check_a_b.c10
-rw-r--r--Tests/Tutorial/Complete/CMakeLists.txt116
-rw-r--r--Tests/Tutorial/Complete/Config.cmake.in4
-rw-r--r--Tests/Tutorial/Complete/License.txt2
-rw-r--r--Tests/Tutorial/Complete/MathFunctions/CMakeLists.txt68
-rw-r--r--Tests/Tutorial/Complete/MathFunctions/MakeTable.cxx25
-rw-r--r--Tests/Tutorial/Complete/MathFunctions/MathFunctions.cxx18
-rw-r--r--Tests/Tutorial/Complete/MathFunctions/MathFunctions.h14
-rw-r--r--Tests/Tutorial/Complete/MathFunctions/mysqrt.cxx45
-rw-r--r--Tests/Tutorial/Complete/MathFunctions/mysqrt.h6
-rw-r--r--Tests/Tutorial/Complete/TutorialConfig.h.in3
-rw-r--r--Tests/Tutorial/Complete/tutorial.cxx25
-rw-r--r--Tests/Tutorial/Consumer/CMakeLists.txt51
-rw-r--r--Tests/Tutorial/Consumer/Config.cmake.in14
-rw-r--r--Tests/Tutorial/Consumer/consumer.cxx11
-rw-r--r--Tests/Tutorial/Consumer/directions.txt6
-rw-r--r--Tests/Tutorial/MultiPackage/CMakeLists.txt109
-rw-r--r--Tests/Tutorial/MultiPackage/Config.cmake.in4
-rw-r--r--Tests/Tutorial/MultiPackage/License.txt2
-rw-r--r--Tests/Tutorial/MultiPackage/MathFunctions/CMakeLists.txt68
-rw-r--r--Tests/Tutorial/MultiPackage/MathFunctions/MakeTable.cxx25
-rw-r--r--Tests/Tutorial/MultiPackage/MathFunctions/MathFunctions.cxx18
-rw-r--r--Tests/Tutorial/MultiPackage/MathFunctions/MathFunctions.h14
-rw-r--r--Tests/Tutorial/MultiPackage/MathFunctions/mysqrt.cxx45
-rw-r--r--Tests/Tutorial/MultiPackage/MathFunctions/mysqrt.h6
-rw-r--r--Tests/Tutorial/MultiPackage/MultiCPackConfig.cmake7
-rw-r--r--Tests/Tutorial/MultiPackage/TutorialConfig.h.in3
-rw-r--r--Tests/Tutorial/MultiPackage/directions.txt34
-rw-r--r--Tests/Tutorial/MultiPackage/tutorial.cxx25
-rw-r--r--Tests/Tutorial/Readme.txt16
-rw-r--r--Tests/Tutorial/Step1/directions.txt95
-rw-r--r--Tests/Tutorial/Step10/CMakeLists.txt77
-rw-r--r--Tests/Tutorial/Step10/License.txt2
-rw-r--r--Tests/Tutorial/Step10/MathFunctions/CMakeLists.txt61
-rw-r--r--Tests/Tutorial/Step10/MathFunctions/MakeTable.cxx25
-rw-r--r--Tests/Tutorial/Step10/MathFunctions/MathFunctions.cxx18
-rw-r--r--Tests/Tutorial/Step10/MathFunctions/MathFunctions.h14
-rw-r--r--Tests/Tutorial/Step10/MathFunctions/mysqrt.cxx45
-rw-r--r--Tests/Tutorial/Step10/MathFunctions/mysqrt.h6
-rw-r--r--Tests/Tutorial/Step10/TutorialConfig.h.in3
-rw-r--r--Tests/Tutorial/Step10/directions.txt38
-rw-r--r--Tests/Tutorial/Step10/tutorial.cxx25
-rw-r--r--Tests/Tutorial/Step11/CMakeLists.txt77
-rw-r--r--Tests/Tutorial/Step11/License.txt2
-rw-r--r--Tests/Tutorial/Step11/MathFunctions/CMakeLists.txt60
-rw-r--r--Tests/Tutorial/Step11/MathFunctions/MakeTable.cxx25
-rw-r--r--Tests/Tutorial/Step11/MathFunctions/MathFunctions.cxx18
-rw-r--r--Tests/Tutorial/Step11/MathFunctions/MathFunctions.h14
-rw-r--r--Tests/Tutorial/Step11/MathFunctions/mysqrt.cxx45
-rw-r--r--Tests/Tutorial/Step11/MathFunctions/mysqrt.h6
-rw-r--r--Tests/Tutorial/Step11/TutorialConfig.h.in3
-rw-r--r--Tests/Tutorial/Step11/directions.txt104
-rw-r--r--Tests/Tutorial/Step11/tutorial.cxx25
-rw-r--r--Tests/Tutorial/Step2/directions.txt102
-rw-r--r--Tests/Tutorial/Step3/directions.txt26
-rw-r--r--Tests/Tutorial/Step4/directions.txt72
-rw-r--r--Tests/Tutorial/Step5/directions.txt69
-rw-r--r--Tests/Tutorial/Step6/directions.txt104
-rw-r--r--Tests/Tutorial/Step7/directions.txt40
-rw-r--r--Tests/Tutorial/Step8/CMakeLists.txt82
-rw-r--r--Tests/Tutorial/Step8/License.txt2
-rw-r--r--Tests/Tutorial/Step8/MathFunctions/CMakeLists.txt29
-rw-r--r--Tests/Tutorial/Step8/MathFunctions/MakeTable.cxx25
-rw-r--r--Tests/Tutorial/Step8/MathFunctions/MathFunctions.h1
-rw-r--r--Tests/Tutorial/Step8/MathFunctions/mysqrt.cxx42
-rw-r--r--Tests/Tutorial/Step8/TutorialConfig.h.in8
-rw-r--r--Tests/Tutorial/Step8/directions.txt38
-rw-r--r--Tests/Tutorial/Step8/tutorial.cxx32
-rw-r--r--Tests/Tutorial/Step9/CMakeLists.txt81
-rw-r--r--Tests/Tutorial/Step9/CTestConfig.cmake15
-rw-r--r--Tests/Tutorial/Step9/License.txt2
-rw-r--r--Tests/Tutorial/Step9/MathFunctions/CMakeLists.txt35
-rw-r--r--Tests/Tutorial/Step9/MathFunctions/MakeTable.cxx25
-rw-r--r--Tests/Tutorial/Step9/MathFunctions/MathFunctions.cxx18
-rw-r--r--Tests/Tutorial/Step9/MathFunctions/MathFunctions.h1
-rw-r--r--Tests/Tutorial/Step9/MathFunctions/mysqrt.cxx41
-rw-r--r--Tests/Tutorial/Step9/MathFunctions/mysqrt.h6
-rw-r--r--Tests/Tutorial/Step9/TutorialConfig.h.in3
-rw-r--r--Tests/Tutorial/Step9/directions.txt166
-rw-r--r--Tests/Tutorial/Step9/tutorial.cxx33
-rw-r--r--Tests/UseSWIG/AlternateLibraryName/CMakeLists.txt35
-rw-r--r--Tests/UseSWIG/BasicConfiguration.cmake83
-rw-r--r--Tests/UseSWIG/BasicCsharp/CMakeLists.txt21
-rw-r--r--Tests/UseSWIG/BasicPerl/CMakeLists.txt14
-rw-r--r--Tests/UseSWIG/BasicPython/CMakeLists.txt13
-rw-r--r--Tests/UseSWIG/CMakeLists.txt137
-rw-r--r--Tests/UseSWIG/LegacyConfiguration.cmake68
-rw-r--r--Tests/UseSWIG/LegacyPerl/CMakeLists.txt14
-rw-r--r--Tests/UseSWIG/LegacyPython/CMakeLists.txt13
-rw-r--r--Tests/UseSWIG/ModuleName/CMakeLists.txt42
-rw-r--r--Tests/UseSWIG/ModuleName/example.i9
-rw-r--r--Tests/UseSWIG/ModuleName/runme.py52
-rw-r--r--Tests/UseSWIG/ModuleVersion2/CMakeLists.txt56
-rw-r--r--Tests/UseSWIG/MultipleModules/CMakeLists.txt68
-rw-r--r--Tests/UseSWIG/MultiplePython/CMakeLists.txt59
-rw-r--r--Tests/UseSWIG/SwigSrcFileExtension/CMakeLists.txt28
-rw-r--r--Tests/UseSWIG/SwigSrcFileExtension/my_add.i9
-rw-r--r--Tests/UseSWIG/SwigSrcFileExtension/my_sub.swg9
-rwxr-xr-xTests/UseSWIG/SwigSrcFileExtension/runme.py24
-rw-r--r--Tests/UseSWIG/UseTargetINCLUDE_DIRECTORIES/CMakeLists.txt45
-rw-r--r--Tests/UseSWIG/UseTargetINCLUDE_DIRECTORIES/example.i9
-rw-r--r--Tests/UseSWIG/example.cxx33
-rw-r--r--Tests/UseSWIG/example.h37
-rw-r--r--Tests/UseSWIG/example.i9
-rw-r--r--Tests/UseSWIG/runme.cs54
-rw-r--r--Tests/UseSWIG/runme.php458
-rw-r--r--Tests/UseSWIG/runme.pike53
-rw-r--r--Tests/UseSWIG/runme.pl56
-rw-r--r--Tests/UseSWIG/runme.py52
-rw-r--r--Tests/UseSWIG/runme.rb49
-rw-r--r--Tests/UseSWIG/runme.tcl49
-rw-r--r--Tests/UseSWIG/runme2.tcl69
-rw-r--r--Tests/VSNASM/bar.asm13
-rw-r--r--Tests/VSWinStorePhone/WinRT/Batman.cpp14
-rw-r--r--Tests/VSWinStorePhone/WinRT/Batman.h12
-rw-r--r--Tests/VSWinStorePhone/WinRT/CMakeLists.txt13
-rwxr-xr-xUtilities/Release/push.bash70
-rwxr-xr-xUtilities/Scripts/regenerate-lexers.bash52
-rwxr-xr-xUtilities/Scripts/regenerate-parsers.bash37
-rwxr-xr-xUtilities/Scripts/update-jsoncpp.bash33
-rwxr-xr-xUtilities/Scripts/update-zstd.bash36
-rw-r--r--Utilities/Sphinx/colors.py29
-rw-r--r--Utilities/cm_zstd.h14
-rw-r--r--Utilities/cmcurl/CMake/FindBrotli.cmake20
-rw-r--r--Utilities/cmcurl/CMake/cmake_uninstall.cmake.in26
-rw-r--r--Utilities/cmcurl/CMake/curl-config.cmake.in12
-rw-r--r--Utilities/cmcurl/include/curl/urlapi.h123
-rw-r--r--Utilities/cmcurl/lib/altsvc.c569
-rw-r--r--Utilities/cmcurl/lib/altsvc.h77
-rw-r--r--Utilities/cmcurl/lib/curl_ctype.c133
-rw-r--r--Utilities/cmcurl/lib/curl_ctype.h81
-rw-r--r--Utilities/cmcurl/lib/curl_get_line.c55
-rw-r--r--Utilities/cmcurl/lib/curl_get_line.h29
-rw-r--r--Utilities/cmcurl/lib/curl_path.c199
-rw-r--r--Utilities/cmcurl/lib/curl_path.h47
-rw-r--r--Utilities/cmcurl/lib/curl_range.c95
-rw-r--r--Utilities/cmcurl/lib/curl_range.h30
-rw-r--r--Utilities/cmcurl/lib/curl_sha256.h32
-rw-r--r--Utilities/cmcurl/lib/doh.c967
-rw-r--r--Utilities/cmcurl/lib/doh.h113
-rw-r--r--Utilities/cmcurl/lib/mime.c1904
-rw-r--r--Utilities/cmcurl/lib/mime.h164
-rw-r--r--Utilities/cmcurl/lib/psl.c111
-rw-r--r--Utilities/cmcurl/lib/psl.h47
-rw-r--r--Utilities/cmcurl/lib/setopt.c2777
-rw-r--r--Utilities/cmcurl/lib/setopt.h29
-rw-r--r--Utilities/cmcurl/lib/sha256.c267
-rw-r--r--Utilities/cmcurl/lib/ssh-libssh.c2740
-rw-r--r--Utilities/cmcurl/lib/urlapi-int.h37
-rw-r--r--Utilities/cmcurl/lib/urlapi.c1440
-rw-r--r--Utilities/cmcurl/lib/vtls/mesalink.c627
-rw-r--r--Utilities/cmcurl/lib/vtls/mesalink.h32
-rw-r--r--Utilities/cmcurl/lib/vtls/schannel_verify.c572
-rw-r--r--Utilities/cmcurl/lib/vtls/sectransp.c3264
-rw-r--r--Utilities/cmcurl/lib/vtls/sectransp.h32
-rw-r--r--Utilities/cmjsoncpp/include/json/allocator.h102
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_disk_acl_darwin.c559
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_disk_acl_freebsd.c702
-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_platform_acl.h49
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_platform_xattr.h41
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_filter_zstd.c292
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_version_details.c151
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_add_filter_zstd.c335
-rw-r--r--Utilities/cmliblzma/liblzma/api/lzma/lzma12.h420
-rw-r--r--Utilities/cmliblzma/liblzma/common/block_buffer_encoder.h24
-rw-r--r--Utilities/cmliblzma/liblzma/common/hardware_cputhreads.c22
-rw-r--r--Utilities/cmliblzma/liblzma/common/memcmplen.h175
-rw-r--r--Utilities/cmliblzma/liblzma/common/outqueue.c184
-rw-r--r--Utilities/cmliblzma/liblzma/common/outqueue.h156
-rw-r--r--Utilities/cmliblzma/liblzma/common/stream_encoder_mt.c1143
-rw-r--r--Utilities/cmlibuv/include/uv/aix.h32
-rw-r--r--Utilities/cmlibuv/include/uv/android-ifaddrs.h54
-rw-r--r--Utilities/cmlibuv/include/uv/bsd.h34
-rw-r--r--Utilities/cmlibuv/include/uv/darwin.h61
-rw-r--r--Utilities/cmlibuv/include/uv/errno.h443
-rw-r--r--Utilities/cmlibuv/include/uv/linux.h34
-rw-r--r--Utilities/cmlibuv/include/uv/os390.h33
-rw-r--r--Utilities/cmlibuv/include/uv/posix.h31
-rw-r--r--Utilities/cmlibuv/include/uv/stdint-msvc2008.h247
-rw-r--r--Utilities/cmlibuv/include/uv/sunos.h44
-rw-r--r--Utilities/cmlibuv/include/uv/threadpool.h37
-rw-r--r--Utilities/cmlibuv/include/uv/tree.h768
-rw-r--r--Utilities/cmlibuv/include/uv/unix.h497
-rw-r--r--Utilities/cmlibuv/include/uv/version.h43
-rw-r--r--Utilities/cmlibuv/include/uv/win.h696
-rw-r--r--Utilities/cmlibuv/src/idna.c291
-rw-r--r--Utilities/cmlibuv/src/idna.h31
-rw-r--r--Utilities/cmlibuv/src/strscpy.c17
-rw-r--r--Utilities/cmlibuv/src/strscpy.h18
-rw-r--r--Utilities/cmlibuv/src/timer.c181
-rw-r--r--Utilities/cmlibuv/src/unix/aix-common.c298
-rw-r--r--Utilities/cmlibuv/src/unix/bsd-proctitle.c93
-rw-r--r--Utilities/cmlibuv/src/unix/cmake-bootstrap.c140
-rw-r--r--Utilities/cmlibuv/src/unix/ibmi.c113
-rw-r--r--Utilities/cmlibuv/src/uv-data-getter-setters.c98
-rw-r--r--Utilities/cmzstd/CMakeLists.txt47
-rw-r--r--Utilities/cmzstd/LICENSE30
-rw-r--r--Utilities/cmzstd/README.md167
-rw-r--r--Utilities/cmzstd/lib/common/bitstream.h455
-rw-r--r--Utilities/cmzstd/lib/common/compiler.h140
-rw-r--r--Utilities/cmzstd/lib/common/cpu.h215
-rw-r--r--Utilities/cmzstd/lib/common/debug.c44
-rw-r--r--Utilities/cmzstd/lib/common/debug.h134
-rw-r--r--Utilities/cmzstd/lib/common/entropy_common.c236
-rw-r--r--Utilities/cmzstd/lib/common/error_private.c54
-rw-r--r--Utilities/cmzstd/lib/common/error_private.h76
-rw-r--r--Utilities/cmzstd/lib/common/fse.h708
-rw-r--r--Utilities/cmzstd/lib/common/fse_decompress.c309
-rw-r--r--Utilities/cmzstd/lib/common/huf.h358
-rw-r--r--Utilities/cmzstd/lib/common/mem.h380
-rw-r--r--Utilities/cmzstd/lib/common/pool.c340
-rw-r--r--Utilities/cmzstd/lib/common/pool.h84
-rw-r--r--Utilities/cmzstd/lib/common/threading.c75
-rw-r--r--Utilities/cmzstd/lib/common/threading.h123
-rw-r--r--Utilities/cmzstd/lib/common/xxhash.c876
-rw-r--r--Utilities/cmzstd/lib/common/xxhash.h305
-rw-r--r--Utilities/cmzstd/lib/common/zstd_common.c83
-rw-r--r--Utilities/cmzstd/lib/common/zstd_errors.h93
-rw-r--r--Utilities/cmzstd/lib/common/zstd_internal.h266
-rw-r--r--Utilities/cmzstd/lib/compress/fse_compress.c721
-rw-r--r--Utilities/cmzstd/lib/compress/hist.c203
-rw-r--r--Utilities/cmzstd/lib/compress/hist.h95
-rw-r--r--Utilities/cmzstd/lib/compress/huf_compress.c798
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_compress.c4290
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_compress_internal.h860
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_double_fast.c499
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_double_fast.h38
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_fast.c391
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_fast.h37
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_lazy.c1106
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_lazy.h67
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_ldm.c597
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_ldm.h105
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_opt.c1217
-rw-r--r--Utilities/cmzstd/lib/compress/zstd_opt.h56
-rw-r--r--Utilities/cmzstd/lib/compress/zstdmt_compress.c2107
-rw-r--r--Utilities/cmzstd/lib/compress/zstdmt_compress.h174
-rw-r--r--Utilities/cmzstd/lib/decompress/huf_decompress.c1232
-rw-r--r--Utilities/cmzstd/lib/decompress/zstd_ddict.c240
-rw-r--r--Utilities/cmzstd/lib/decompress/zstd_ddict.h44
-rw-r--r--Utilities/cmzstd/lib/decompress/zstd_decompress.c1672
-rw-r--r--Utilities/cmzstd/lib/decompress/zstd_decompress_block.c1307
-rw-r--r--Utilities/cmzstd/lib/decompress/zstd_decompress_block.h59
-rw-r--r--Utilities/cmzstd/lib/decompress/zstd_decompress_internal.h168
-rw-r--r--Utilities/cmzstd/lib/deprecated/zbuff.h213
-rw-r--r--Utilities/cmzstd/lib/deprecated/zbuff_common.c26
-rw-r--r--Utilities/cmzstd/lib/deprecated/zbuff_compress.c147
-rw-r--r--Utilities/cmzstd/lib/deprecated/zbuff_decompress.c75
-rw-r--r--Utilities/cmzstd/lib/dictBuilder/cover.c1081
-rw-r--r--Utilities/cmzstd/lib/dictBuilder/cover.h83
-rw-r--r--Utilities/cmzstd/lib/dictBuilder/divsufsort.c1913
-rw-r--r--Utilities/cmzstd/lib/dictBuilder/divsufsort.h67
-rw-r--r--Utilities/cmzstd/lib/dictBuilder/fastcover.c728
-rw-r--r--Utilities/cmzstd/lib/dictBuilder/zdict.c1111
-rw-r--r--Utilities/cmzstd/lib/dictBuilder/zdict.h267
-rw-r--r--Utilities/cmzstd/lib/zstd.h1766
-rw-r--r--packaging/cmake.spec3
3697 files changed, 168437 insertions, 2 deletions
diff --git a/Help/command/LINK_OPTIONS_LINKER.txt b/Help/command/LINK_OPTIONS_LINKER.txt
new file mode 100644
index 000000000..a72337515
--- /dev/null
+++ b/Help/command/LINK_OPTIONS_LINKER.txt
@@ -0,0 +1,22 @@
+To pass options to the linker tool, each compiler driver has is own syntax.
+The ``LINKER:`` prefix can be used to specify, in a portable way, options
+to pass to the linker tool. The ``LINKER:`` prefix is replaced by the required
+driver option and the rest of the option string defines linker arguments using
+``,`` as separator. These arguments will be formatted according to the
+:variable:`CMAKE_<LANG>_LINKER_WRAPPER_FLAG` and
+:variable:`CMAKE_<LANG>_LINKER_WRAPPER_FLAG_SEP` variables.
+
+For example, ``"LINKER:-z,defs"`` becomes ``-Xlinker -z -Xlinker defs`` for
+``Clang`` and ``-Wl,-z,defs`` for ``GNU GCC``.
+
+The ``LINKER:`` prefix can be specified as part of a ``SHELL:`` prefix
+expression.
+
+The ``LINKER:`` prefix supports, as alternate syntax, specification of
+arguments using ``SHELL:`` prefix and space as separator. Previous example
+becomes ``"LINKER:SHELL:-z defs"``.
+
+.. note::
+
+ Specifying ``SHELL:`` prefix elsewhere than at the beginning of the
+ ``LINKER:`` prefix is not supported.
diff --git a/Help/command/OPTIONS_SHELL.txt b/Help/command/OPTIONS_SHELL.txt
new file mode 100644
index 000000000..530c0126f
--- /dev/null
+++ b/Help/command/OPTIONS_SHELL.txt
@@ -0,0 +1,9 @@
+The final set of compile or link options used for a target is constructed by
+accumulating options from the current target and the usage requirements of
+it dependencies. The set of options is de-duplicated to avoid repetition.
+While beneficial for individual options, the de-duplication step can break
+up option groups. For example, ``-D A -D B`` becomes ``-D A B``. One may
+specify a group of options using shell-like quoting along with a ``SHELL:``
+prefix. The ``SHELL:`` prefix is dropped and the rest of the option string
+is parsed using the :command:`separate_arguments` ``UNIX_COMMAND`` mode.
+For example, ``"SHELL:-D A" "SHELL:-D B"`` becomes ``-D A -D B``.
diff --git a/Help/command/add_compile_definitions.rst b/Help/command/add_compile_definitions.rst
new file mode 100644
index 000000000..8225da783
--- /dev/null
+++ b/Help/command/add_compile_definitions.rst
@@ -0,0 +1,23 @@
+add_compile_definitions
+-----------------------
+
+Add preprocessor definitions to the compilation of source files.
+
+.. code-block:: cmake
+
+ add_compile_definitions(<definition> ...)
+
+Adds preprocessor definitions to the compiler command line for targets in the
+current directory and below (whether added before or after this command is
+invoked). See documentation of the :prop_dir:`directory <COMPILE_DEFINITIONS>`
+and :prop_tgt:`target <COMPILE_DEFINITIONS>` ``COMPILE_DEFINITIONS`` properties.
+
+Definitions are specified using the syntax ``VAR`` or ``VAR=value``.
+Function-style definitions are not supported. CMake will automatically
+escape the value correctly for the native build system (note that CMake
+language syntax may require escapes to specify some values).
+
+Arguments to ``add_compile_definitions`` may use "generator expressions" with
+the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
+manual for available expressions. See the :manual:`cmake-buildsystem(7)`
+manual for more on defining buildsystem properties.
diff --git a/Help/command/add_link_options.rst b/Help/command/add_link_options.rst
new file mode 100644
index 000000000..a83005b06
--- /dev/null
+++ b/Help/command/add_link_options.rst
@@ -0,0 +1,31 @@
+add_link_options
+----------------
+
+Add options to the link step for executable, shared library or module
+library targets in the current directory and below that are added after
+this command is invoked.
+
+.. code-block:: cmake
+
+ add_link_options(<option> ...)
+
+This command can be used to add any link options, but alternative commands
+exist to add libraries (:command:`target_link_libraries` or
+:command:`link_libraries`). See documentation of the
+:prop_dir:`directory <LINK_OPTIONS>` and
+:prop_tgt:`target <LINK_OPTIONS>` ``LINK_OPTIONS`` properties.
+
+.. note::
+
+ This command cannot be used to add options for static library targets,
+ since they do not use a linker. To add archiver or MSVC librarian flags,
+ see the :prop_tgt:`STATIC_LIBRARY_OPTIONS` target property.
+
+Arguments to ``add_link_options`` may use "generator expressions" with
+the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
+manual for available expressions. See the :manual:`cmake-buildsystem(7)`
+manual for more on defining buildsystem properties.
+
+.. include:: OPTIONS_SHELL.txt
+
+.. include:: LINK_OPTIONS_LINKER.txt
diff --git a/Help/command/include_guard.rst b/Help/command/include_guard.rst
new file mode 100644
index 000000000..877aa86d9
--- /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.
+
+.. code-block:: 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/target_link_directories.rst b/Help/command/target_link_directories.rst
new file mode 100644
index 000000000..76da94dc1
--- /dev/null
+++ b/Help/command/target_link_directories.rst
@@ -0,0 +1,55 @@
+target_link_directories
+-----------------------
+
+Add link directories to a target.
+
+.. code-block:: cmake
+
+ target_link_directories(<target> [BEFORE]
+ <INTERFACE|PUBLIC|PRIVATE> [items1...]
+ [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
+
+Specifies the paths in which the linker should search for libraries when
+linking a given target. Each item can be an absolute or relative path,
+with the latter being interpreted as relative to the current source
+directory. These items will be added to the link command.
+
+The named ``<target>`` must have been created by a command such as
+:command:`add_executable` or :command:`add_library` and must not be an
+:ref:`ALIAS target <Alias Targets>`.
+
+The ``INTERFACE``, ``PUBLIC`` and ``PRIVATE`` keywords are required to
+specify the scope of the items that follow them. ``PRIVATE`` and
+``PUBLIC`` items will populate the :prop_tgt:`LINK_DIRECTORIES` property
+of ``<target>``. ``PUBLIC`` and ``INTERFACE`` items will populate the
+:prop_tgt:`INTERFACE_LINK_DIRECTORIES` property of ``<target>``
+(:ref:`IMPORTED targets <Imported Targets>` only support ``INTERFACE`` items).
+Each item specifies a link directory and will be converted to an absolute
+path if necessary before adding it to the relevant property. Repeated
+calls for the same ``<target>`` append items in the order called.
+
+If ``BEFORE`` is specified, the content will be prepended to the relevant
+property instead of being appended.
+
+Arguments to ``target_link_directories`` may use "generator expressions"
+with the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
+manual for available expressions. See the :manual:`cmake-buildsystem(7)`
+manual for more on defining buildsystem properties.
+
+.. note::
+
+ This command is rarely necessary and should be avoided where there are
+ other choices. Prefer to pass full absolute paths to libraries where
+ possible, since this ensures the correct library will always be linked.
+ The :command:`find_library` command provides the full path, which can
+ generally be used directly in calls to :command:`target_link_libraries`.
+ Situations where a library search path may be needed include:
+
+ - Project generators like Xcode where the user can switch target
+ architecture at build time, but a full path to a library cannot
+ be used because it only provides one architecture (i.e. it is not
+ a universal binary).
+ - Libraries may themselves have other private library dependencies
+ that expect to be found via ``RPATH`` mechanisms, but some linkers
+ are not able to fully decode those paths (e.g. due to the presence
+ of things like ``$ORIGIN``).
diff --git a/Help/command/target_link_options.rst b/Help/command/target_link_options.rst
new file mode 100644
index 000000000..b5abbc476
--- /dev/null
+++ b/Help/command/target_link_options.rst
@@ -0,0 +1,48 @@
+target_link_options
+-------------------
+
+Add options to the link step for an executable, shared library or module
+library target.
+
+.. code-block:: cmake
+
+ target_link_options(<target> [BEFORE]
+ <INTERFACE|PUBLIC|PRIVATE> [items1...]
+ [<INTERFACE|PUBLIC|PRIVATE> [items2...] ...])
+
+The named ``<target>`` must have been created by a command such as
+:command:`add_executable` or :command:`add_library` and must not be an
+:ref:`ALIAS target <Alias Targets>`.
+
+This command can be used to add any link options, but alternative commands
+exist to add libraries (:command:`target_link_libraries` or
+:command:`link_libraries`). See documentation of the
+:prop_dir:`directory <LINK_OPTIONS>` and
+:prop_tgt:`target <LINK_OPTIONS>` ``LINK_OPTIONS`` properties.
+
+.. note::
+
+ This command cannot be used to add options for static library targets,
+ since they do not use a linker. To add archiver or MSVC librarian flags,
+ see the :prop_tgt:`STATIC_LIBRARY_OPTIONS` target property.
+
+If ``BEFORE`` is specified, the content will be prepended to the property
+instead of being appended.
+
+The ``INTERFACE``, ``PUBLIC`` and ``PRIVATE`` keywords are required to
+specify the scope of the following arguments. ``PRIVATE`` and ``PUBLIC``
+items will populate the :prop_tgt:`LINK_OPTIONS` property of
+``<target>``. ``PUBLIC`` and ``INTERFACE`` items will populate the
+:prop_tgt:`INTERFACE_LINK_OPTIONS` property of ``<target>``.
+(:ref:`IMPORTED targets <Imported Targets>` only support ``INTERFACE`` items.)
+The following arguments specify link options. Repeated calls for the same
+``<target>`` append items in the order called.
+
+Arguments to ``target_link_options`` may use "generator expressions"
+with the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
+manual for available expressions. See the :manual:`cmake-buildsystem(7)`
+manual for more on defining buildsystem properties.
+
+.. include:: OPTIONS_SHELL.txt
+
+.. include:: LINK_OPTIONS_LINKER.txt
diff --git a/Help/cpack_gen/archive.rst b/Help/cpack_gen/archive.rst
new file mode 100644
index 000000000..b288aaddc
--- /dev/null
+++ b/Help/cpack_gen/archive.rst
@@ -0,0 +1,35 @@
+CPack Archive Generator
+-----------------------
+
+Archive CPack generator that supports packaging of sources and binaries in
+different formats:
+
+ - 7Z - 7zip - (.7z)
+ - TBZ2 (.tar.bz2)
+ - TGZ (.tar.gz)
+ - TXZ (.tar.xz)
+ - TZ (.tar.Z)
+ - ZIP (.zip)
+
+Variables specific to CPack Archive generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. variable:: CPACK_ARCHIVE_FILE_NAME
+ CPACK_ARCHIVE_<component>_FILE_NAME
+
+ Package file name without extension which is added automatically depending
+ on the archive format.
+
+ * Mandatory : YES
+ * Default : ``<CPACK_PACKAGE_FILE_NAME>[-<component>].<extension>`` with
+ spaces replaced by '-'
+
+.. variable:: CPACK_ARCHIVE_COMPONENT_INSTALL
+
+ Enable component packaging for CPackArchive
+
+ * Mandatory : NO
+ * Default : OFF
+
+ If enabled (ON) multiple packages are generated. By default a single package
+ containing files of all components is generated.
diff --git a/Help/cpack_gen/bundle.rst b/Help/cpack_gen/bundle.rst
new file mode 100644
index 000000000..b16dbda03
--- /dev/null
+++ b/Help/cpack_gen/bundle.rst
@@ -0,0 +1,66 @@
+CPack Bundle Generator
+----------------------
+
+CPack Bundle generator (macOS) specific options
+
+Variables specific to CPack Bundle generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Installers built on macOS using the Bundle generator use the
+aforementioned DragNDrop (``CPACK_DMG_xxx``) variables, plus the following
+Bundle-specific parameters (``CPACK_BUNDLE_xxx``).
+
+.. variable:: CPACK_BUNDLE_NAME
+
+ The name of the generated bundle. This appears in the macOS Finder as the
+ bundle name. Required.
+
+.. variable:: CPACK_BUNDLE_PLIST
+
+ Path to an macOS Property List (``.plist``) file that will be used
+ for the generated bundle. This
+ assumes that the caller has generated or specified their own ``Info.plist``
+ file. Required.
+
+.. variable:: CPACK_BUNDLE_ICON
+
+ Path to an macOS icon file that will be used as the icon for the generated
+ bundle. This is the icon that appears in the macOS Finder for the bundle, and
+ in the macOS dock when the bundle is opened. Required.
+
+.. variable:: CPACK_BUNDLE_STARTUP_COMMAND
+
+ Path to a startup script. This is a path to an executable or script that
+ will be run whenever an end-user double-clicks the generated bundle in the
+ macOS Finder. Optional.
+
+.. variable:: CPACK_BUNDLE_APPLE_CERT_APP
+
+ The name of your Apple supplied code signing certificate for the application.
+ The name usually takes the form ``Developer ID Application: [Name]`` or
+ ``3rd Party Mac Developer Application: [Name]``. If this variable is not set
+ the application will not be signed.
+
+.. variable:: CPACK_BUNDLE_APPLE_ENTITLEMENTS
+
+ The name of the Property List (``.plist``) file that contains your Apple
+ entitlements for sandboxing your application. This file is required
+ for submission to the macOS App Store.
+
+.. variable:: CPACK_BUNDLE_APPLE_CODESIGN_FILES
+
+ A list of additional files that you wish to be signed. You do not need to
+ list the main application folder, or the main executable. You should
+ list any frameworks and plugins that are included in your app bundle.
+
+.. variable:: CPACK_BUNDLE_APPLE_CODESIGN_PARAMETER
+
+ Additional parameter that will passed to ``codesign``.
+ Default value: ``--deep -f``
+
+.. variable:: CPACK_COMMAND_CODESIGN
+
+ Path to the ``codesign(1)`` command used to sign applications with an
+ Apple cert. This variable can be used to override the automatically
+ detected command (or specify its location if the auto-detection fails
+ to find it).
diff --git a/Help/cpack_gen/cygwin.rst b/Help/cpack_gen/cygwin.rst
new file mode 100644
index 000000000..1c5f7af91
--- /dev/null
+++ b/Help/cpack_gen/cygwin.rst
@@ -0,0 +1,23 @@
+CPack Cygwin Generator
+----------------------
+
+Cygwin CPack generator (Cygwin).
+
+Variables specific to CPack Cygwin generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The
+following variable is specific to installers build on and/or for
+Cygwin:
+
+.. variable:: CPACK_CYGWIN_PATCH_NUMBER
+
+ The Cygwin patch number. FIXME: This documentation is incomplete.
+
+.. variable:: CPACK_CYGWIN_PATCH_FILE
+
+ The Cygwin patch file. FIXME: This documentation is incomplete.
+
+.. variable:: CPACK_CYGWIN_BUILD_SCRIPT
+
+ The Cygwin build script. FIXME: This documentation is incomplete.
diff --git a/Help/cpack_gen/deb.rst b/Help/cpack_gen/deb.rst
new file mode 100644
index 000000000..23f051530
--- /dev/null
+++ b/Help/cpack_gen/deb.rst
@@ -0,0 +1,557 @@
+CPack DEB Generator
+-------------------
+
+The built in (binary) CPack DEB generator (Unix only)
+
+Variables specific to CPack Debian (DEB) generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The CPack DEB generator may be used to create DEB package using :module:`CPack`.
+The CPack DEB generator is a :module:`CPack` generator thus it uses the
+``CPACK_XXX`` variables used by :module:`CPack`.
+
+The CPack DEB generator should work on any Linux host but it will produce
+better deb package when Debian specific tools ``dpkg-xxx`` are usable on
+the build system.
+
+The CPack DEB generator has specific features which are controlled by the
+specifics ``CPACK_DEBIAN_XXX`` variables.
+
+``CPACK_DEBIAN_<COMPONENT>_XXXX`` variables may be used in order to have
+**component** specific values. Note however that ``<COMPONENT>`` refers to
+the **grouping name** written in upper case. It may be either a component name
+or a component GROUP name.
+
+Here are some CPack DEB generator wiki resources that are here for historic
+reasons and are no longer maintained but may still prove useful:
+
+ - https://gitlab.kitware.com/cmake/community/wikis/doc/cpack/Configuration
+ - https://gitlab.kitware.com/cmake/community/wikis/doc/cpack/PackageGenerators#deb-unix-only
+
+List of CPack DEB generator specific variables:
+
+.. variable:: CPACK_DEB_COMPONENT_INSTALL
+
+ Enable component packaging for CPackDEB
+
+ * Mandatory : NO
+ * Default : OFF
+
+ If enabled (ON) multiple packages are generated. By default a single package
+ containing files of all components is generated.
+
+.. variable:: CPACK_DEBIAN_PACKAGE_NAME
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_NAME
+
+ Set Package control field (variable is automatically transformed to lower
+ case).
+
+ * Mandatory : YES
+ * Default :
+
+ - :variable:`CPACK_PACKAGE_NAME` for non-component based
+ installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_NAME` suffixed with -<COMPONENT>
+ for component-based installations.
+
+ See https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Source
+
+.. variable:: CPACK_DEBIAN_FILE_NAME
+ CPACK_DEBIAN_<COMPONENT>_FILE_NAME
+
+ Package file name.
+
+ * Mandatory : YES
+ * Default : ``<CPACK_PACKAGE_FILE_NAME>[-<component>].deb``
+
+ This may be set to ``DEB-DEFAULT`` to allow the CPack DEB generator to generate
+ package file name by itself in deb format::
+
+ <PackageName>_<VersionNumber>-<DebianRevisionNumber>_<DebianArchitecture>.deb
+
+ Alternatively provided package file name must end
+ with either ``.deb`` or ``.ipk`` suffix.
+
+ .. note::
+
+ Preferred setting of this variable is ``DEB-DEFAULT`` but for backward
+ compatibility with the CPack DEB generator in CMake prior to version 3.6 this
+ feature is disabled by default.
+
+ .. note::
+
+ By using non default filenames duplicate names may occur. Duplicate files
+ 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
+
+ * 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 : 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
+ :variable:`CPACK_DEBIAN_PACKAGE_VERSION`). One may change the default value
+ if the previous packaging was buggy and/or you want to put here a fancy Linux
+ distro specific numbering.
+
+.. variable:: CPACK_DEBIAN_PACKAGE_ARCHITECTURE
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_ARCHITECTURE
+
+ The Debian package architecture
+
+ * Mandatory : YES
+ * Default : Output of ``dpkg --print-architecture`` (or ``i386``
+ if ``dpkg`` is not found)
+
+.. variable:: CPACK_DEBIAN_PACKAGE_DEPENDS
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_DEPENDS
+
+ Sets the Debian dependencies of this package.
+
+ * Mandatory : NO
+ * Default :
+
+ - An empty string for non-component based installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_DEPENDS` for component-based
+ installations.
+
+ .. note::
+
+ If :variable:`CPACK_DEBIAN_PACKAGE_SHLIBDEPS` or
+ more specifically :variable:`CPACK_DEBIAN_<COMPONENT>_PACKAGE_SHLIBDEPS`
+ is set for this component, the discovered dependencies will be appended
+ to :variable:`CPACK_DEBIAN_<COMPONENT>_PACKAGE_DEPENDS` instead of
+ :variable:`CPACK_DEBIAN_PACKAGE_DEPENDS`. If
+ :variable:`CPACK_DEBIAN_<COMPONENT>_PACKAGE_DEPENDS` is an empty string,
+ only the automatically discovered dependencies will be set for this
+ component.
+
+ Example::
+
+ set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6 (>= 2.3.1-6), libc6 (< 2.4)")
+
+.. variable:: CPACK_DEBIAN_ENABLE_COMPONENT_DEPENDS
+
+ Sets inter component dependencies if listed with
+ :variable:`CPACK_COMPONENT_<compName>_DEPENDS` variables.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_DEBIAN_PACKAGE_MAINTAINER
+
+ The Debian package maintainer
+
+ * Mandatory : YES
+ * Default : ``CPACK_PACKAGE_CONTACT``
+
+.. variable:: CPACK_DEBIAN_PACKAGE_DESCRIPTION
+ CPACK_COMPONENT_<COMPONENT>_DESCRIPTION
+
+ The Debian package description
+
+ * Mandatory : YES
+ * Default :
+
+ - :variable:`CPACK_DEBIAN_PACKAGE_DESCRIPTION` if set or
+ - :variable:`CPACK_PACKAGE_DESCRIPTION_SUMMARY`
+
+
+.. variable:: CPACK_DEBIAN_PACKAGE_SECTION
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_SECTION
+
+ Set Section control field e.g. admin, devel, doc, ...
+
+ * Mandatory : YES
+ * Default : "devel"
+
+ See https://www.debian.org/doc/debian-policy/ch-archive.html#s-subsections
+
+.. variable:: CPACK_DEBIAN_ARCHIVE_TYPE
+
+ The archive format used for creating the Debian package.
+
+ * Mandatory : YES
+ * Default : "gnutar"
+
+ Possible value is:
+
+ - gnutar
+
+ .. note::
+
+ This variable previously defaulted to the ``paxr`` value, but ``dpkg``
+ has never supported that tar format. For backwards compatibility the
+ ``paxr`` value will be mapped to ``gnutar`` and a deprecation message
+ will be emitted.
+
+.. variable:: CPACK_DEBIAN_COMPRESSION_TYPE
+
+ The compression used for creating the Debian package.
+
+ * Mandatory : YES
+ * Default : "gzip"
+
+ Possible values are:
+
+ - lzma
+ - xz
+ - bzip2
+ - gzip
+
+.. variable:: CPACK_DEBIAN_PACKAGE_PRIORITY
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_PRIORITY
+
+ Set Priority control field e.g. required, important, standard, optional,
+ extra
+
+ * Mandatory : YES
+ * Default : "optional"
+
+ See https://www.debian.org/doc/debian-policy/ch-archive.html#s-priorities
+
+.. variable:: CPACK_DEBIAN_PACKAGE_HOMEPAGE
+
+ 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 : NO
+ * Default : :variable:`CMAKE_PROJECT_HOMEPAGE_URL`
+
+ .. note::
+
+ The content of this field is a simple URL without any surrounding
+ characters such as <>.
+
+.. variable:: CPACK_DEBIAN_PACKAGE_SHLIBDEPS
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_SHLIBDEPS
+
+ May be set to ON in order to use ``dpkg-shlibdeps`` to generate
+ better package dependency list.
+
+ * Mandatory : NO
+ * Default :
+
+ - :variable:`CPACK_DEBIAN_PACKAGE_SHLIBDEPS` if set or
+ - OFF
+
+ .. note::
+
+ You may need set :variable:`CMAKE_INSTALL_RPATH` to an appropriate value
+ if you use this feature, because if you don't ``dpkg-shlibdeps``
+ may fail to find your own shared libs.
+ See https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/RPATH-handling
+
+.. variable:: CPACK_DEBIAN_PACKAGE_DEBUG
+
+ May be set when invoking cpack in order to trace debug information
+ during the CPack DEB generator run.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_DEBIAN_PACKAGE_PREDEPENDS
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_PREDEPENDS
+
+ Sets the `Pre-Depends` field of the Debian package.
+ Like :variable:`Depends <CPACK_DEBIAN_PACKAGE_DEPENDS>`, except that it
+ also forces ``dpkg`` to complete installation of the packages named
+ before even starting the installation of the package which declares the
+ pre-dependency.
+
+ * Mandatory : NO
+ * Default :
+
+ - An empty string for non-component based installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_PREDEPENDS` for component-based
+ installations.
+
+ See http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
+
+.. variable:: CPACK_DEBIAN_PACKAGE_ENHANCES
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_ENHANCES
+
+ Sets the `Enhances` field of the Debian package.
+ Similar to :variable:`Suggests <CPACK_DEBIAN_PACKAGE_SUGGESTS>` but works
+ in the opposite direction: declares that a package can enhance the
+ functionality of another package.
+
+ * Mandatory : NO
+ * Default :
+
+ - An empty string for non-component based installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_ENHANCES` for component-based
+ installations.
+
+ See http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
+
+.. variable:: CPACK_DEBIAN_PACKAGE_BREAKS
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_BREAKS
+
+ Sets the `Breaks` field of the Debian package.
+ When a binary package (P) declares that it breaks other packages (B),
+ ``dpkg`` will not allow the package (P) which declares `Breaks` be
+ **unpacked** unless the packages that will be broken (B) are deconfigured
+ first.
+ As long as the package (P) is configured, the previously deconfigured
+ packages (B) cannot be reconfigured again.
+
+ * Mandatory : NO
+ * Default :
+
+ - An empty string for non-component based installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_BREAKS` for component-based
+ installations.
+
+ See https://www.debian.org/doc/debian-policy/ch-relationships.html#s-breaks
+
+.. variable:: CPACK_DEBIAN_PACKAGE_CONFLICTS
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_CONFLICTS
+
+ Sets the `Conflicts` field of the Debian package.
+ When one binary package declares a conflict with another using a `Conflicts`
+ field, ``dpkg`` will not allow them to be unpacked on the system at
+ the same time.
+
+ * Mandatory : NO
+ * Default :
+
+ - An empty string for non-component based installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_CONFLICTS` for component-based
+ installations.
+
+ See https://www.debian.org/doc/debian-policy/ch-relationships.html#s-conflicts
+
+ .. note::
+
+ This is a stronger restriction than
+ :variable:`Breaks <CPACK_DEBIAN_PACKAGE_BREAKS>`, which prevents the
+ broken package from being configured while the breaking package is in
+ the "Unpacked" state but allows both packages to be unpacked at the same
+ time.
+
+.. variable:: CPACK_DEBIAN_PACKAGE_PROVIDES
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_PROVIDES
+
+ Sets the `Provides` field of the Debian package.
+ A virtual package is one which appears in the `Provides` control field of
+ another package.
+
+ * Mandatory : NO
+ * Default :
+
+ - An empty string for non-component based installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_PROVIDES` for component-based
+ installations.
+
+ See https://www.debian.org/doc/debian-policy/ch-relationships.html#s-virtual
+
+.. variable:: CPACK_DEBIAN_PACKAGE_REPLACES
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_REPLACES
+
+ Sets the `Replaces` field of the Debian package.
+ Packages can declare in their control file that they should overwrite
+ files in certain other packages, or completely replace other packages.
+
+ * Mandatory : NO
+ * Default :
+
+ - An empty string for non-component based installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_REPLACES` for component-based
+ installations.
+
+ See http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
+
+.. variable:: CPACK_DEBIAN_PACKAGE_RECOMMENDS
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_RECOMMENDS
+
+ Sets the `Recommends` field of the Debian package.
+ Allows packages to declare a strong, but not absolute, dependency on other
+ packages.
+
+ * Mandatory : NO
+ * Default :
+
+ - An empty string for non-component based installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_RECOMMENDS` for component-based
+ installations.
+
+ See http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
+
+.. variable:: CPACK_DEBIAN_PACKAGE_SUGGESTS
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_SUGGESTS
+
+ Sets the `Suggests` field of the Debian package.
+ Allows packages to declare a suggested package install grouping.
+
+ * Mandatory : NO
+ * Default :
+
+ - An empty string for non-component based installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_SUGGESTS` for component-based
+ installations.
+
+ See http://www.debian.org/doc/debian-policy/ch-relationships.html#s-binarydeps
+
+.. variable:: CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS
+
+ * Mandatory : NO
+ * Default : OFF
+
+ Allows to generate shlibs control file automatically. Compatibility is defined by
+ :variable:`CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY` variable value.
+
+ .. note::
+
+ Libraries are only considered if they have both library name and version
+ set. This can be done by setting SOVERSION property with
+ :command:`set_target_properties` command.
+
+.. variable:: CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY
+
+ Compatibility policy for auto-generated shlibs control file.
+
+ * Mandatory : NO
+ * Default : "="
+
+ Defines compatibility policy for auto-generated shlibs control file.
+ Possible values: "=", ">="
+
+ See https://www.debian.org/doc/debian-policy/ch-sharedlibs.html#s-sharedlibs-shlibdeps
+
+.. variable:: CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_CONTROL_EXTRA
+
+ This variable allow advanced user to add custom script to the
+ control.tar.gz.
+ Typical usage is for conffiles, postinst, postrm, prerm.
+
+ * Mandatory : NO
+ * Default : -
+
+ Usage::
+
+ set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA
+ "${CMAKE_CURRENT_SOURCE_DIR}/prerm;${CMAKE_CURRENT_SOURCE_DIR}/postrm")
+
+ .. note::
+
+ The original permissions of the files will be used in the final
+ package unless the variable
+ :variable:`CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION` is set.
+ In particular, the scripts should have the proper executable
+ flag prior to the generation of the package.
+
+.. variable:: CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_CONTROL_STRICT_PERMISSION
+
+ This variable indicates if the Debian policy on control files should be
+ strictly followed.
+
+ * Mandatory : NO
+ * Default : FALSE
+
+ Usage::
+
+ set(CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION TRUE)
+
+ .. note::
+
+ This overrides the permissions on the original files, following the rules
+ set by Debian policy
+ https://www.debian.org/doc/debian-policy/ch-files.html#s-permissions-owners
+
+.. variable:: CPACK_DEBIAN_PACKAGE_SOURCE
+ CPACK_DEBIAN_<COMPONENT>_PACKAGE_SOURCE
+
+ Sets the ``Source`` field of the binary Debian package.
+ When the binary package name is not the same as the source package name
+ (in particular when several components/binaries are generated from one
+ source) the source from which the binary has been generated should be
+ indicated with the field ``Source``.
+
+ * Mandatory : NO
+ * Default :
+
+ - An empty string for non-component based installations
+ - :variable:`CPACK_DEBIAN_PACKAGE_SOURCE` for component-based
+ installations.
+
+ See https://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Source
+
+ .. note::
+
+ This value is not interpreted. It is possible to pass an optional
+ revision number of the referenced source package as well.
+
+Packaging of debug information
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Dbgsym packages contain debug symbols for debugging packaged binaries.
+
+Dbgsym packaging has its own set of variables:
+
+.. variable:: CPACK_DEBIAN_DEBUGINFO_PACKAGE
+ CPACK_DEBIAN_<component>_DEBUGINFO_PACKAGE
+
+ Enable generation of dbgsym .ddeb package(s).
+
+ * Mandatory : NO
+ * Default : OFF
+
+.. note::
+
+ Binaries must contain debug symbols before packaging so use either ``Debug``
+ or ``RelWithDebInfo`` for :variable:`CMAKE_BUILD_TYPE` variable value.
+
+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.
+
+Reproducible packages
+^^^^^^^^^^^^^^^^^^^^^
+
+The environment variable ``SOURCE_DATE_EPOCH`` may be set to a UNIX
+timestamp, defined as the number of seconds, excluding leap seconds,
+since 01 Jan 1970 00:00:00 UTC. If set, the CPack DEB generator will
+use its value for timestamps in the package.
diff --git a/Help/cpack_gen/dmg.rst b/Help/cpack_gen/dmg.rst
new file mode 100644
index 000000000..1e3788933
--- /dev/null
+++ b/Help/cpack_gen/dmg.rst
@@ -0,0 +1,101 @@
+CPack DragNDrop Generator
+-------------------------
+
+The DragNDrop CPack generator (macOS) creates a DMG image.
+
+Variables specific to CPack DragNDrop generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following variables are specific to the DragNDrop installers built
+on macOS:
+
+.. variable:: CPACK_DMG_VOLUME_NAME
+
+ The volume name of the generated disk image. Defaults to
+ CPACK_PACKAGE_FILE_NAME.
+
+.. variable:: CPACK_DMG_FORMAT
+
+ The disk image format. Common values are ``UDRO`` (UDIF read-only), ``UDZO`` (UDIF
+ zlib-compressed) or ``UDBZ`` (UDIF bzip2-compressed). Refer to ``hdiutil(1)`` for
+ more information on other available formats. Defaults to ``UDZO``.
+
+.. variable:: CPACK_DMG_DS_STORE
+
+ Path to a custom ``.DS_Store`` file. This ``.DS_Store`` file can be used to
+ specify the Finder window position/geometry and layout (such as hidden
+ toolbars, placement of the icons etc.). This file has to be generated by
+ the Finder (either manually or through AppleScript) using a normal folder
+ from which the ``.DS_Store`` file can then be extracted.
+
+.. variable:: CPACK_DMG_DS_STORE_SETUP_SCRIPT
+
+ Path to a custom AppleScript file. This AppleScript is used to generate
+ a ``.DS_Store`` file which specifies the Finder window position/geometry and
+ layout (such as hidden toolbars, placement of the icons etc.).
+ By specifying a custom AppleScript there is no need to use
+ ``CPACK_DMG_DS_STORE``, as the ``.DS_Store`` that is generated by the AppleScript
+ will be packaged.
+
+.. variable:: CPACK_DMG_BACKGROUND_IMAGE
+
+ Path to an image file to be used as the background. This file will be
+ copied to ``.background``/``background.<ext>``, where ``<ext>`` is the original image file
+ extension. The background image is installed into the image before
+ ``CPACK_DMG_DS_STORE_SETUP_SCRIPT`` is executed or ``CPACK_DMG_DS_STORE`` is
+ installed. By default no background image is set.
+
+.. variable:: CPACK_DMG_DISABLE_APPLICATIONS_SYMLINK
+
+ Default behaviour is to include a symlink to ``/Applications`` in the DMG.
+ Set this option to ``ON`` to avoid adding the symlink.
+
+.. variable:: CPACK_DMG_SLA_DIR
+
+ Directory where license and menu files for different languages are stored.
+ Setting this causes CPack to look for a ``<language>.menu.txt`` and
+ ``<language>.license.txt`` file for every language defined in
+ ``CPACK_DMG_SLA_LANGUAGES``. If both this variable and
+ ``CPACK_RESOURCE_FILE_LICENSE`` are set, CPack will only look for the menu
+ files and use the same license file for all languages.
+
+.. variable:: CPACK_DMG_SLA_LANGUAGES
+
+ Languages for which a license agreement is provided when mounting the
+ generated DMG. A menu file consists of 9 lines of text. The first line is
+ is the name of the language itself, uppercase, in English (e.g. German).
+ The other lines are translations of the following strings:
+
+ - Agree
+ - Disagree
+ - Print
+ - Save...
+ - You agree to the terms of the License Agreement when you click the
+ "Agree" button.
+ - Software License Agreement
+ - This text cannot be saved. The disk may be full or locked, or the file
+ may be locked.
+ - Unable to print. Make sure you have selected a printer.
+
+ For every language in this list, CPack will try to find files
+ ``<language>.menu.txt`` and ``<language>.license.txt`` in the directory
+ specified by the :variable:`CPACK_DMG_SLA_DIR` variable.
+
+.. variable:: CPACK_COMMAND_HDIUTIL
+
+ Path to the ``hdiutil(1)`` command used to operate on disk image files on
+ macOS. This variable can be used to override the automatically detected
+ command (or specify its location if the auto-detection fails to find it).
+
+.. variable:: CPACK_COMMAND_SETFILE
+
+ Path to the ``SetFile(1)`` command used to set extended attributes on files and
+ directories on macOS. This variable can be used to override the
+ automatically detected command (or specify its location if the
+ auto-detection fails to find it).
+
+.. variable:: CPACK_COMMAND_REZ
+
+ Path to the ``Rez(1)`` command used to compile resources on macOS. This
+ variable can be used to override the automatically detected command (or
+ specify its location if the auto-detection fails to find it).
diff --git a/Help/cpack_gen/external.rst b/Help/cpack_gen/external.rst
new file mode 100644
index 000000000..406f6be1a
--- /dev/null
+++ b/Help/cpack_gen/external.rst
@@ -0,0 +1,283 @@
+CPack External Generator
+------------------------
+
+CPack provides many generators to create packages for a variety of platforms
+and packaging systems. The intention is for CMake/CPack to be a complete
+end-to-end solution for building and packaging a software project. However, it
+may not always be possible to use CPack for the entire packaging process, due
+to either technical limitations or policies that require the use of certain
+tools. For this reason, CPack provides the "External" generator, which allows
+external packaging software to take advantage of some of the functionality
+provided by CPack, such as component installation and the dependency graph.
+
+Integration with External Packaging Tools
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The CPack External generator generates a ``.json`` file containing the
+CPack internal metadata, which gives external software information
+on how to package the software. External packaging software may itself
+invoke CPack, consume the generated metadata,
+install and package files as required.
+
+Alternatively CPack can invoke an external packaging software
+through an optional custom CMake script in
+:variable:`CPACK_EXTERNAL_PACKAGE_SCRIPT` instead.
+
+Staging of installation files may also optionally be
+taken care of by the generator when enabled through the
+:variable:`CPACK_EXTERNAL_ENABLE_STAGING` variable.
+
+JSON Format
+^^^^^^^^^^^
+
+The JSON metadata file contains a list of CPack components and component groups,
+the various options passed to :command:`cpack_add_component` and
+:command:`cpack_add_component_group`, the dependencies between the components
+and component groups, and various other options passed to CPack.
+
+The JSON's root object will always provide two fields:
+``formatVersionMajor`` and ``formatVersionMinor``, which are always integers
+that describe the output format of the generator. Backwards-compatible changes
+to the output format (for example, adding a new field that didn't exist before)
+cause the minor version to be incremented, and backwards-incompatible changes
+(for example, deleting a field or changing its meaning) cause the major version
+to be incremented and the minor version reset to 0. The format version is
+always of the format ``major.minor``. In other words, it always has exactly two
+parts, separated by a period.
+
+You can request one or more specific versions of the output format as described
+below with :variable:`CPACK_EXTERNAL_REQUESTED_VERSIONS`. The output format will
+have a major version that exactly matches the requested major version, and a
+minor version that is greater than or equal to the requested minor version. If
+no version is requested with :variable:`CPACK_EXTERNAL_REQUESTED_VERSIONS`, the
+latest known major version is used by default. Currently, the only supported
+format is 1.0, which is described below.
+
+Version 1.0
+***********
+
+In addition to the standard format fields, format version 1.0 provides the
+following fields in the root:
+
+``components``
+ The ``components`` field is an object with component names as the keys and
+ objects describing the components as the values. The component objects have
+ the following fields:
+
+ ``name``
+ The name of the component. This is always the same as the key in the
+ ``components`` object.
+
+ ``displayName``
+ The value of the ``DISPLAY_NAME`` field passed to
+ :command:`cpack_add_component`.
+
+ ``description``
+ The value of the ``DESCRIPTION`` field passed to
+ :command:`cpack_add_component`.
+
+ ``isHidden``
+ True if ``HIDDEN`` was passed to :command:`cpack_add_component`, false if
+ it was not.
+
+ ``isRequired``
+ True if ``REQUIRED`` was passed to :command:`cpack_add_component`, false if
+ it was not.
+
+ ``isDisabledByDefault``
+ True if ``DISABLED`` was passed to :command:`cpack_add_component`, false if
+ it was not.
+
+ ``group``
+ Only present if ``GROUP`` was passed to :command:`cpack_add_component`. If
+ so, this field is a string value containing the component's group.
+
+ ``dependencies``
+ An array of components the component depends on. This contains the values
+ in the ``DEPENDS`` argument passed to :command:`cpack_add_component`. If no
+ ``DEPENDS`` argument was passed, this is an empty list.
+
+ ``installationTypes``
+ An array of installation types the component is part of. This contains the
+ values in the ``INSTALL_TYPES`` argument passed to
+ :command:`cpack_add_component`. If no ``INSTALL_TYPES`` argument was
+ passed, this is an empty list.
+
+ ``isDownloaded``
+ True if ``DOWNLOADED`` was passed to :command:`cpack_add_component`, false
+ if it was not.
+
+ ``archiveFile``
+ The name of the archive file passed with the ``ARCHIVE_FILE`` argument to
+ :command:`cpack_add_component`. If no ``ARCHIVE_FILE`` argument was passed,
+ this is an empty string.
+
+``componentGroups``
+ The ``componentGroups`` field is an object with component group names as the
+ keys and objects describing the component groups as the values. The component
+ group objects have the following fields:
+
+ ``name``
+ The name of the component group. This is always the same as the key in the
+ ``componentGroups`` object.
+
+ ``displayName``
+ The value of the ``DISPLAY_NAME`` field passed to
+ :command:`cpack_add_component_group`.
+
+ ``description``
+ The value of the ``DESCRIPTION`` field passed to
+ :command:`cpack_add_component_group`.
+
+ ``parentGroup``
+ Only present if ``PARENT_GROUP`` was passed to
+ :command:`cpack_add_component_group`. If so, this field is a string value
+ containing the component group's parent group.
+
+ ``isExpandedByDefault``
+ True if ``EXPANDED`` was passed to :command:`cpack_add_component_group`,
+ false if it was not.
+
+ ``isBold``
+ True if ``BOLD_TITLE`` was passed to :command:`cpack_add_component_group`,
+ false if it was not.
+
+ ``components``
+ An array of names of components that are direct members of the group
+ (components that have this group as their ``GROUP``). Components of
+ subgroups are not included.
+
+ ``subgroups``
+ An array of names of component groups that are subgroups of the group
+ (groups that have this group as their ``PARENT_GROUP``).
+
+``installationTypes``
+ The ``installationTypes`` field is an object with installation type names as
+ the keys and objects describing the installation types as the values. The
+ installation type objects have the following fields:
+
+ ``name``
+ The name of the installation type. This is always the same as the key in
+ the ``installationTypes`` object.
+
+ ``displayName``
+ The value of the ``DISPLAY_NAME`` field passed to
+ :command:`cpack_add_install_type`.
+
+ ``index``
+ The integer index of the installation type in the list.
+
+``projects``
+ The ``projects`` field is an array of objects describing CMake projects which
+ comprise the CPack project. The values in this field are derived from
+ :variable:`CPACK_INSTALL_CMAKE_PROJECTS`. In most cases, this will be only a
+ single project. The project objects have the following fields:
+
+ ``projectName``
+ The project name passed to :variable:`CPACK_INSTALL_CMAKE_PROJECTS`.
+
+ ``component``
+ The name of the component or component set which comprises the project.
+
+ ``directory``
+ The build directory of the CMake project. This is the directory which
+ contains the ``cmake_install.cmake`` script.
+
+ ``subDirectory``
+ The subdirectory to install the project into inside the CPack package.
+
+``packageName``
+ The package name given in :variable:`CPACK_PACKAGE_NAME`. Only present if
+ this option is set.
+
+``packageVersion``
+ The package version given in :variable:`CPACK_PACKAGE_VERSION`. Only present
+ if this option is set.
+
+``packageDescriptionFile``
+ The package description file given in
+ :variable:`CPACK_PACKAGE_DESCRIPTION_FILE`. Only present if this option is
+ set.
+
+``packageDescriptionSummary``
+ The package description summary given in
+ :variable:`CPACK_PACKAGE_DESCRIPTION_SUMMARY`. Only present if this option is
+ set.
+
+``buildConfig``
+ The build configuration given to CPack with the ``-C`` option. Only present
+ if this option is set.
+
+``defaultDirectoryPermissions``
+ The default directory permissions given in
+ :variable:`CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS`. Only present if this
+ option is set.
+
+``setDestdir``
+ True if :variable:`CPACK_SET_DESTDIR` is true, false if it is not.
+
+``packagingInstallPrefix``
+ The install prefix given in :variable:`CPACK_PACKAGING_INSTALL_PREFIX`. Only
+ present if :variable:`CPACK_SET_DESTDIR` is true.
+
+``stripFiles``
+ True if :variable:`CPACK_STRIP_FILES` is true, false if it is not.
+
+``warnOnAbsoluteInstallDestination``
+ True if :variable:`CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION` is true, false
+ if it is not.
+
+``errorOnAbsoluteInstallDestination``
+ True if :variable:`CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION` is true,
+ false if it is not.
+
+Variables specific to CPack External generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. variable:: CPACK_EXTERNAL_REQUESTED_VERSIONS
+
+ This variable is used to request a specific version of the CPack External
+ generator. It is a list of ``major.minor`` values, separated by semicolons.
+
+ If this variable is set to a non-empty value, the CPack External generator
+ will iterate through each item in the list to search for a version that it
+ knows how to generate. Requested versions should be listed in order of
+ descending preference by the client software, as the first matching version
+ in the list will be generated.
+
+ The generator knows how to generate the version if it has a versioned
+ generator whose major version exactly matches the requested major version,
+ and whose minor version is greater than or equal to the requested minor
+ version. For example, if ``CPACK_EXTERNAL_REQUESTED_VERSIONS`` contains 1.0, and
+ the CPack External generator knows how to generate 1.1, it will generate 1.1.
+ If the generator doesn't know how to generate a version in the list, it skips
+ the version and looks at the next one. If it doesn't know how to generate any
+ of the requested versions, an error is thrown.
+
+ If this variable is not set, or is empty, the CPack External generator will
+ generate the highest major and minor version that it knows how to generate.
+
+ If an invalid version is encountered in ``CPACK_EXTERNAL_REQUESTED_VERSIONS`` (one
+ that doesn't match ``major.minor``, where ``major`` and ``minor`` are
+ integers), it is ignored.
+
+.. variable:: CPACK_EXTERNAL_ENABLE_STAGING
+
+ This variable can be set to true to enable optional installation
+ into a temporary staging area which can then be picked up
+ and packaged by an external packaging tool.
+ The top level directory used by CPack for the current packaging
+ task is contained in ``CPACK_TOPLEVEL_DIRECTORY``.
+ It is automatically cleaned up on each run before packaging is initiated
+ and can be used for custom temporary files required by
+ the external packaging tool.
+ It also contains the staging area ``CPACK_TEMPORARY_DIRECTORY``
+ into which CPack performs the installation when staging is enabled.
+
+.. variable:: CPACK_EXTERNAL_PACKAGE_SCRIPT
+
+ This variable can optionally specify the full path to
+ a CMake script file to be run as part of the CPack invocation.
+ It is invoked after (optional) staging took place and may
+ run an external packaging tool. The script has access to
+ the variables defined by the CPack config file.
diff --git a/Help/cpack_gen/freebsd.rst b/Help/cpack_gen/freebsd.rst
new file mode 100644
index 000000000..a8dd32050
--- /dev/null
+++ b/Help/cpack_gen/freebsd.rst
@@ -0,0 +1,138 @@
+CPack FreeBSD Generator
+-----------------------
+
+The built in (binary) CPack FreeBSD (pkg) generator (Unix only)
+
+Variables specific to CPack FreeBSD (pkg) generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The CPack FreeBSD generator 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`.
+
+The CPack FreeBSD generator 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
+:cpack_gen:`CPack DEB Generator`. It also tries to re-use RPM packaging
+information when Debian does not specify.
+
+The CPack FreeBSD generator should work on any host with libpkg installed. The
+packages it produces are specific to the host architecture and ABI.
+
+The CPack FreeBSD generator sets package-metadata through
+``CPACK_FREEBSD_XXX`` variables. The CPack FreeBSD generator, unlike the
+CPack Deb generator, 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:`CMAKE_PROJECT_HOMEPAGE_URL`, or if that is not set,
+ :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
diff --git a/Help/cpack_gen/ifw.rst b/Help/cpack_gen/ifw.rst
new file mode 100644
index 000000000..feccd3db0
--- /dev/null
+++ b/Help/cpack_gen/ifw.rst
@@ -0,0 +1,339 @@
+CPack IFW Generator
+-------------------
+
+See :module:`CPackIFW` for details on the CPackIFW module.
+
+.. _QtIFW: http://doc.qt.io/qtinstallerframework/index.html
+
+
+Overview
+^^^^^^^^
+
+CPack ``IFW`` generator helps you to create online and offline
+binary cross-platform installers with a graphical user interface.
+
+CPack IFW generator prepares project installation and generates configuration
+and meta information for QtIFW_ tools.
+
+The QtIFW_ provides a set of tools and utilities to create
+installers for the supported desktop Qt platforms: Linux, Microsoft Windows,
+and macOS.
+
+You should also install QtIFW_ to use CPack ``IFW`` generator.
+
+Hints
+^^^^^
+
+Generally, the CPack ``IFW`` generator automatically finds QtIFW_ tools,
+but if you don't use a default path for installation of the QtIFW_ tools,
+the path may be specified in either a CMake or an environment variable:
+
+.. variable:: CPACK_IFW_ROOT
+
+ An CMake variable which specifies the location of the QtIFW_ tool suite.
+
+ The variable will be cached in the ``CPackConfig.cmake`` file and used at
+ CPack runtime.
+
+.. variable:: QTIFWDIR
+
+ An environment variable which specifies the location of the QtIFW_ tool
+ suite.
+
+.. note::
+ The specified path should not contain "bin" at the end
+ (for example: "D:\\DevTools\\QtIFW2.0.5").
+
+The :variable:`CPACK_IFW_ROOT` variable has a higher priority and overrides
+the value of the :variable:`QTIFWDIR` variable.
+
+Internationalization
+^^^^^^^^^^^^^^^^^^^^
+
+Some variables and command arguments support internationalization via
+CMake script. This is an optional feature.
+
+Installers created by QtIFW_ tools have built-in support for
+internationalization and many phrases are localized to many languages,
+but this does not apply to the description of the your components and groups
+that will be distributed.
+
+Localization of the description of your components and groups is useful for
+users of your installers.
+
+A localized variable or argument can contain a single default value, and a
+set of pairs the name of the locale and the localized value.
+
+For example:
+
+.. code-block:: cmake
+
+ set(LOCALIZABLE_VARIABLE "Default value"
+ en "English value"
+ en_US "American value"
+ en_GB "Great Britain value"
+ )
+
+Variables
+^^^^^^^^^
+
+You can use the following variables to change behavior of CPack ``IFW``
+generator.
+
+Debug
+"""""
+
+.. variable:: CPACK_IFW_VERBOSE
+
+ Set to ``ON`` to enable addition debug output.
+ By default is ``OFF``.
+
+Package
+"""""""
+
+.. variable:: CPACK_IFW_PACKAGE_TITLE
+
+ Name of the installer as displayed on the title bar.
+ By default used :variable:`CPACK_PACKAGE_DESCRIPTION_SUMMARY`.
+
+.. variable:: CPACK_IFW_PACKAGE_PUBLISHER
+
+ Publisher of the software (as shown in the Windows Control Panel).
+ By default used :variable:`CPACK_PACKAGE_VENDOR`.
+
+.. variable:: CPACK_IFW_PRODUCT_URL
+
+ URL to a page that contains product information on your web site.
+
+.. variable:: CPACK_IFW_PACKAGE_ICON
+
+ Filename for a custom installer icon. The actual file is '.icns' (macOS),
+ '.ico' (Windows). No functionality on Unix.
+
+.. variable:: CPACK_IFW_PACKAGE_WINDOW_ICON
+
+ Filename for a custom window icon in PNG format for the Installer
+ application.
+
+.. variable:: CPACK_IFW_PACKAGE_LOGO
+
+ Filename for a logo is used as QWizard::LogoPixmap.
+
+.. variable:: CPACK_IFW_PACKAGE_WATERMARK
+
+ Filename for a watermark is used as QWizard::WatermarkPixmap.
+
+.. variable:: CPACK_IFW_PACKAGE_BANNER
+
+ Filename for a banner is used as QWizard::BannerPixmap.
+
+.. variable:: CPACK_IFW_PACKAGE_BACKGROUND
+
+ Filename for an image used as QWizard::BackgroundPixmap (only used by MacStyle).
+
+.. variable:: CPACK_IFW_PACKAGE_WIZARD_STYLE
+
+ Wizard style to be used ("Modern", "Mac", "Aero" or "Classic").
+
+.. variable:: CPACK_IFW_PACKAGE_STYLE_SHEET
+
+ Filename for a stylesheet.
+
+.. variable:: CPACK_IFW_PACKAGE_WIZARD_DEFAULT_WIDTH
+
+ Default width of the wizard in pixels. Setting a banner image will override this.
+
+.. variable:: CPACK_IFW_PACKAGE_WIZARD_DEFAULT_HEIGHT
+
+ Default height of the wizard in pixels. Setting a watermark image will override this.
+
+.. variable:: CPACK_IFW_PACKAGE_TITLE_COLOR
+
+ Color of the titles and subtitles (takes an HTML color code, such as "#88FF33").
+
+.. variable:: CPACK_IFW_PACKAGE_START_MENU_DIRECTORY
+
+ Name of the default program group for the product in the Windows Start menu.
+
+ By default used :variable:`CPACK_IFW_PACKAGE_NAME`.
+
+.. variable:: CPACK_IFW_TARGET_DIRECTORY
+
+ Default target directory for installation.
+ By default used
+ "@ApplicationsDir@/:variable:`CPACK_PACKAGE_INSTALL_DIRECTORY`"
+
+ You can use predefined variables.
+
+.. variable:: CPACK_IFW_ADMIN_TARGET_DIRECTORY
+
+ Default target directory for installation with administrator rights.
+
+ You can use predefined variables.
+
+.. variable:: CPACK_IFW_PACKAGE_GROUP
+
+ The group, which will be used to configure the root package
+
+.. variable:: CPACK_IFW_PACKAGE_NAME
+
+ The root package name, which will be used if configuration group is not
+ specified
+
+.. variable:: CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_NAME
+
+ Filename of the generated maintenance tool.
+ The platform-specific executable file extension is appended.
+
+ By default used QtIFW_ defaults (``maintenancetool``).
+
+.. variable:: CPACK_IFW_PACKAGE_REMOVE_TARGET_DIR
+
+ Set to ``OFF`` if the target directory should not be deleted when uninstalling.
+
+ Is ``ON`` by default
+
+.. variable:: CPACK_IFW_PACKAGE_MAINTENANCE_TOOL_INI_FILE
+
+ Filename for the configuration of the generated maintenance tool.
+
+ By default used QtIFW_ defaults (``maintenancetool.ini``).
+
+.. variable:: CPACK_IFW_PACKAGE_ALLOW_NON_ASCII_CHARACTERS
+
+ Set to ``ON`` if the installation path can contain non-ASCII characters.
+
+ Is ``ON`` for QtIFW_ less 2.0 tools.
+
+.. variable:: CPACK_IFW_PACKAGE_ALLOW_SPACE_IN_PATH
+
+ Set to ``OFF`` if the installation path cannot contain space characters.
+
+ Is ``ON`` for QtIFW_ less 2.0 tools.
+
+.. variable:: CPACK_IFW_PACKAGE_CONTROL_SCRIPT
+
+ Filename for a custom installer control script.
+
+.. variable:: CPACK_IFW_PACKAGE_RESOURCES
+
+ List of additional resources ('.qrc' files) to include in the installer
+ binary.
+
+ 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.
+
+ The default value of this variable is computed by CPack and contains
+ all repositories added with command :command:`cpack_ifw_add_repository`
+ or updated with command :command:`cpack_ifw_update_repository`.
+
+.. variable:: CPACK_IFW_DOWNLOAD_ALL
+
+ If this is ``ON`` all components will be downloaded.
+ By default is ``OFF`` or used value
+ from ``CPACK_DOWNLOAD_ALL`` if set
+
+Components
+""""""""""
+
+.. variable:: CPACK_IFW_RESOLVE_DUPLICATE_NAMES
+
+ Resolve duplicate names when installing components with groups.
+
+.. variable:: CPACK_IFW_PACKAGES_DIRECTORIES
+
+ 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
+"""""
+
+.. variable:: CPACK_IFW_FRAMEWORK_VERSION
+
+ The version of used QtIFW_ tools.
+
+.. variable:: CPACK_IFW_BINARYCREATOR_EXECUTABLE
+
+ The path to "binarycreator" command line client.
+
+ This variable is cached and may be configured if needed.
+
+.. variable:: CPACK_IFW_REPOGEN_EXECUTABLE
+
+ The path to "repogen" command line client.
+
+ This variable is cached and may be configured if needed.
+
+.. variable:: CPACK_IFW_INSTALLERBASE_EXECUTABLE
+
+ The path to "installerbase" installer executable base.
+
+ This variable is cached and may be configured if needed.
+
+.. variable:: CPACK_IFW_DEVTOOL_EXECUTABLE
+
+ The path to "devtool" command line client.
+
+ This variable is cached and may be configured if needed.
+
+
+Online installer
+^^^^^^^^^^^^^^^^
+
+By default CPack IFW generator makes offline installer. This means that all
+components will be packaged into a binary file.
+
+To make a component downloaded, you must set the ``DOWNLOADED`` option in
+:command:`cpack_add_component`.
+
+Then you would use the command :command:`cpack_configure_downloads`.
+If you set ``ALL`` option all components will be downloaded.
+
+You also can use command :command:`cpack_ifw_add_repository` and
+variable :variable:`CPACK_IFW_DOWNLOAD_ALL` for more specific configuration.
+
+CPack IFW generator creates "repository" dir in current binary dir. You
+would copy content of this dir to specified ``site`` (``url``).
+
+See Also
+^^^^^^^^
+
+Qt Installer Framework Manual:
+
+* Index page:
+ http://doc.qt.io/qtinstallerframework/index.html
+
+* Component Scripting:
+ http://doc.qt.io/qtinstallerframework/scripting.html
+
+* Predefined Variables:
+ http://doc.qt.io/qtinstallerframework/scripting.html#predefined-variables
+
+* Promoting Updates:
+ http://doc.qt.io/qtinstallerframework/ifw-updates.html
+
+Download Qt Installer Framework for you platform from Qt site:
+ http://download.qt.io/official_releases/qt-installer-framework
diff --git a/Help/cpack_gen/nsis.rst b/Help/cpack_gen/nsis.rst
new file mode 100644
index 000000000..cd2aea682
--- /dev/null
+++ b/Help/cpack_gen/nsis.rst
@@ -0,0 +1,130 @@
+CPack NSIS Generator
+--------------------
+
+CPack Nullsoft Scriptable Install System (NSIS) generator specific options
+
+Variables specific to CPack NSIS generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following variables are specific to the graphical installers built
+on Windows Nullsoft Scriptable Install System.
+
+.. variable:: CPACK_NSIS_INSTALL_ROOT
+
+ The default installation directory presented to the end user by the NSIS
+ installer is under this root dir. The full directory presented to the end
+ user is: ``${CPACK_NSIS_INSTALL_ROOT}/${CPACK_PACKAGE_INSTALL_DIRECTORY}``
+
+.. variable:: CPACK_NSIS_MUI_ICON
+
+ An icon filename. The name of a ``*.ico`` file used as the main icon for the
+ generated install program.
+
+.. variable:: CPACK_NSIS_MUI_UNIICON
+
+ An icon filename. The name of a ``*.ico`` file used as the main icon for the
+ generated uninstall program.
+
+.. variable:: CPACK_NSIS_INSTALLER_MUI_ICON_CODE
+
+ undocumented.
+
+.. variable:: CPACK_NSIS_MUI_WELCOMEFINISHPAGE_BITMAP
+
+ The filename of a bitmap to use as the NSIS ``MUI_WELCOMEFINISHPAGE_BITMAP``.
+
+.. variable:: CPACK_NSIS_MUI_UNWELCOMEFINISHPAGE_BITMAP
+
+ The filename of a bitmap to use as the NSIS ``MUI_UNWELCOMEFINISHPAGE_BITMAP``.
+
+.. variable:: CPACK_NSIS_EXTRA_PREINSTALL_COMMANDS
+
+ Extra NSIS commands that will be added to the beginning of the install
+ Section, before your install tree is available on the target system.
+
+.. variable:: CPACK_NSIS_EXTRA_INSTALL_COMMANDS
+
+ Extra NSIS commands that will be added to the end of the install Section,
+ after your install tree is available on the target system.
+
+.. variable:: CPACK_NSIS_EXTRA_UNINSTALL_COMMANDS
+
+ Extra NSIS commands that will be added to the uninstall Section, before
+ your install tree is removed from the target system.
+
+.. variable:: CPACK_NSIS_COMPRESSOR
+
+ The arguments that will be passed to the NSIS `SetCompressor` command.
+
+.. variable:: CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL
+
+ Ask about uninstalling previous versions first. If this is set to ``ON``,
+ then an installer will look for previous installed versions and if one is
+ found, ask the user whether to uninstall it before proceeding with the
+ install.
+
+.. variable:: CPACK_NSIS_MODIFY_PATH
+
+ Modify ``PATH`` toggle. If this is set to ``ON``, then an extra page will appear
+ in the installer that will allow the user to choose whether the program
+ directory should be added to the system ``PATH`` variable.
+
+.. variable:: CPACK_NSIS_DISPLAY_NAME
+
+ The display name string that appears in the Windows `Apps & features`
+ in `Control Panel`
+
+.. variable:: CPACK_NSIS_PACKAGE_NAME
+
+ The title displayed at the top of the installer.
+
+.. variable:: CPACK_NSIS_INSTALLED_ICON_NAME
+
+ A path to the executable that contains the installer icon.
+
+.. variable:: CPACK_NSIS_HELP_LINK
+
+ URL to a web site providing assistance in installing your application.
+
+.. variable:: CPACK_NSIS_URL_INFO_ABOUT
+
+ URL to a web site providing more information about your application.
+
+.. variable:: CPACK_NSIS_CONTACT
+
+ Contact information for questions and comments about the installation
+ process.
+
+.. variable:: CPACK_NSIS_<compName>_INSTALL_DIRECTORY
+
+ Custom install directory for the specified component ``<compName>`` instead
+ of ``$INSTDIR``.
+
+.. variable:: CPACK_NSIS_CREATE_ICONS_EXTRA
+
+ Additional NSIS commands for creating `Start Menu` shortcuts.
+
+.. variable:: CPACK_NSIS_DELETE_ICONS_EXTRA
+
+ Additional NSIS commands to uninstall `Start Menu` shortcuts.
+
+.. variable:: CPACK_NSIS_EXECUTABLES_DIRECTORY
+
+ Creating NSIS `Start Menu` links assumes that they are in ``bin`` unless this
+ variable is set. For example, you would set this to ``exec`` if your
+ executables are in an exec directory.
+
+.. variable:: CPACK_NSIS_MUI_FINISHPAGE_RUN
+
+ Specify an executable to add an option to run on the finish page of the
+ NSIS installer.
+
+.. variable:: CPACK_NSIS_MENU_LINKS
+
+ Specify links in ``[application]`` menu. This should contain a list of pair
+ ``link`` ``link name``. The link may be a URL or a path relative to
+ installation prefix. Like::
+
+ set(CPACK_NSIS_MENU_LINKS
+ "doc/cmake-@CMake_VERSION_MAJOR@.@CMake_VERSION_MINOR@/cmake.html"
+ "CMake Help" "https://cmake.org" "CMake Web Site")
diff --git a/Help/cpack_gen/nuget.rst b/Help/cpack_gen/nuget.rst
new file mode 100644
index 000000000..f8aa6266b
--- /dev/null
+++ b/Help/cpack_gen/nuget.rst
@@ -0,0 +1,189 @@
+CPack NuGet Generator
+---------------------
+
+When build a NuGet package there is no direct way to control an output
+filename due a lack of the corresponding CLI option of NuGet, so there
+is no ``CPACK_NUGET_PACKAGE_FILENAME`` variable. To form the output filename
+NuGet uses the package name and the version according to its built-in rules.
+
+Also, be aware that including a top level directory
+(``CPACK_INCLUDE_TOPLEVEL_DIRECTORY``) is ignored by this generator.
+
+
+Variables specific to CPack NuGet generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The CPack NuGet generator may be used to create NuGet packages using
+:module:`CPack`. The CPack NuGet generator is a :module:`CPack` generator thus
+it uses the ``CPACK_XXX`` variables used by :module:`CPack`.
+
+The CPack NuGet generator has specific features which are controlled by the
+specifics ``CPACK_NUGET_XXX`` variables. In the "one per group" mode
+(see :variable:`CPACK_COMPONENTS_GROUPING`), ``<compName>`` placeholder
+in the variables below would contain a group name (uppercased and turned into
+a "C" identifier).
+
+List of CPack NuGet generator specific variables:
+
+.. variable:: CPACK_NUGET_COMPONENT_INSTALL
+
+ Enable component packaging for CPack NuGet generator
+
+ * Mandatory : NO
+ * Default : OFF
+
+.. variable:: CPACK_NUGET_PACKAGE_NAME
+ CPACK_NUGET_<compName>_PACKAGE_NAME
+
+ The NUGET package name.
+
+ * Mandatory : YES
+ * Default : :variable:`CPACK_PACKAGE_NAME`
+
+.. variable:: CPACK_NUGET_PACKAGE_VERSION
+ CPACK_NUGET_<compName>_PACKAGE_VERSION
+
+ The NuGet package version.
+
+ * Mandatory : YES
+ * Default : :variable:`CPACK_PACKAGE_VERSION`
+
+.. variable:: CPACK_NUGET_PACKAGE_DESCRIPTION
+ CPACK_NUGET_<compName>_PACKAGE_DESCRIPTION
+
+ A long description of the package for UI display.
+
+ * Mandatory : YES
+ * Default :
+ - :variable:`CPACK_COMPONENT_<compName>_DESCRIPTION`,
+ - ``CPACK_COMPONENT_GROUP_<groupName>_DESCRIPTION``,
+ - :variable:`CPACK_PACKAGE_DESCRIPTION`
+
+.. variable:: CPACK_NUGET_PACKAGE_AUTHORS
+ CPACK_NUGET_<compName>_PACKAGE_AUTHORS
+
+ A comma-separated list of packages authors, matching the profile names
+ on nuget.org_. These are displayed in the NuGet Gallery on
+ nuget.org_ and are used to cross-reference packages by the same
+ authors.
+
+ * Mandatory : YES
+ * Default : :variable:`CPACK_PACKAGE_VENDOR`
+
+.. variable:: CPACK_NUGET_PACKAGE_TITLE
+ CPACK_NUGET_<compName>_PACKAGE_TITLE
+
+ A human-friendly title of the package, typically used in UI displays
+ as on nuget.org_ and the Package Manager in Visual Studio. If not
+ specified, the package ID is used.
+
+ * Mandatory : NO
+ * Default :
+ - :variable:`CPACK_COMPONENT_<compName>_DISPLAY_NAME`,
+ - ``CPACK_COMPONENT_GROUP_<groupName>_DISPLAY_NAME``
+
+.. variable:: CPACK_NUGET_PACKAGE_OWNERS
+ CPACK_NUGET_<compName>_PACKAGE_OWNERS
+
+ A comma-separated list of the package creators using profile names
+ on nuget.org_. This is often the same list as in authors,
+ and is ignored when uploading the package to nuget.org_.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_NUGET_PACKAGE_HOMEPAGE_URL
+ CPACK_NUGET_<compName>_PACKAGE_HOMEPAGE_URL
+
+ A URL for the package's home page, often shown in UI displays as well
+ as nuget.org_.
+
+ * Mandatory : NO
+ * Default : :variable:`CPACK_PACKAGE_HOMEPAGE_URL`
+
+.. variable:: CPACK_NUGET_PACKAGE_LICENSEURL
+ CPACK_NUGET_<compName>_PACKAGE_LICENSEURL
+
+ A URL for the package's license, often shown in UI displays as well
+ as nuget.org_.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_NUGET_PACKAGE_ICONURL
+ CPACK_NUGET_<compName>_PACKAGE_ICONURL
+
+ A URL for a 64x64 image with transparency background to use as the
+ icon for the package in UI display.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_NUGET_PACKAGE_DESCRIPTION_SUMMARY
+ CPACK_NUGET_<compName>_PACKAGE_DESCRIPTION_SUMMARY
+
+ A short description of the package for UI display. If omitted, a
+ truncated version of description is used.
+
+ * Mandatory : NO
+ * Default : :variable:`CPACK_PACKAGE_DESCRIPTION_SUMMARY`
+
+.. variable:: CPACK_NUGET_PACKAGE_RELEASE_NOTES
+ CPACK_NUGET_<compName>_PACKAGE_RELEASE_NOTES
+
+ A description of the changes made in this release of the package,
+ often used in UI like the Updates tab of the Visual Studio Package
+ Manager in place of the package description.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_NUGET_PACKAGE_COPYRIGHT
+ CPACK_NUGET_<compName>_PACKAGE_COPYRIGHT
+
+ Copyright details for the package.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_NUGET_PACKAGE_TAGS
+ CPACK_NUGET_<compName>_PACKAGE_TAGS
+
+ A space-delimited list of tags and keywords that describe the
+ package and aid discoverability of packages through search and
+ filtering.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_NUGET_PACKAGE_DEPENDENCIES
+ CPACK_NUGET_<compName>_PACKAGE_DEPENDENCIES
+
+ A list of package dependencies.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_NUGET_PACKAGE_DEPENDENCIES_<dependency>_VERSION
+ CPACK_NUGET_<compName>_PACKAGE_DEPENDENCIES_<dependency>_VERSION
+
+ A `version specification`_ for the particular dependency, where
+ ``<dependency>`` is an item of the dependency list (see above)
+ transformed with ``MAKE_C_IDENTIFIER`` function of :command:`string`
+ command.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_NUGET_PACKAGE_DEBUG
+
+ Enable debug messages while executing CPack NuGet generator.
+
+ * Mandatory : NO
+ * Default : OFF
+
+
+.. _nuget.org: http://nuget.org
+.. _version specification: https://docs.microsoft.com/en-us/nuget/reference/package-versioning#version-ranges-and-wildcards
+
+.. NuGet spec docs https://docs.microsoft.com/en-us/nuget/reference/nuspec
diff --git a/Help/cpack_gen/packagemaker.rst b/Help/cpack_gen/packagemaker.rst
new file mode 100644
index 000000000..e9464b749
--- /dev/null
+++ b/Help/cpack_gen/packagemaker.rst
@@ -0,0 +1,23 @@
+CPack PackageMaker Generator
+----------------------------
+
+PackageMaker CPack generator (macOS).
+
+Variables specific to CPack PackageMaker generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following variable is specific to installers built on Mac
+macOS using PackageMaker:
+
+.. variable:: CPACK_OSX_PACKAGE_VERSION
+
+ The version of macOS that the resulting PackageMaker archive should be
+ compatible with. Different versions of macOS support different
+ features. For example, CPack can only build component-based installers for
+ macOS 10.4 or newer, and can only build installers that download
+ component son-the-fly for macOS 10.5 or newer. If left blank, this value
+ will be set to the minimum version of macOS that supports the requested
+ features. Set this variable to some value (e.g., 10.4) only if you want to
+ guarantee that your installer will work on that version of macOS, and
+ don't mind missing extra features available in the installer shipping with
+ later versions of macOS.
diff --git a/Help/cpack_gen/productbuild.rst b/Help/cpack_gen/productbuild.rst
new file mode 100644
index 000000000..d22fcd48a
--- /dev/null
+++ b/Help/cpack_gen/productbuild.rst
@@ -0,0 +1,68 @@
+CPack productbuild Generator
+----------------------------
+
+productbuild CPack generator (macOS).
+
+Variables specific to CPack productbuild generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following variable is specific to installers built on Mac
+macOS using ProductBuild:
+
+.. variable:: CPACK_COMMAND_PRODUCTBUILD
+
+ Path to the ``productbuild(1)`` command used to generate a product archive for
+ the macOS Installer or Mac App Store. This variable can be used to override
+ the automatically detected command (or specify its location if the
+ auto-detection fails to find it).
+
+.. variable:: CPACK_PRODUCTBUILD_IDENTITY_NAME
+
+ Adds a digital signature to the resulting package.
+
+
+.. variable:: CPACK_PRODUCTBUILD_KEYCHAIN_PATH
+
+ Specify a specific keychain to search for the signing identity.
+
+
+.. variable:: CPACK_COMMAND_PKGBUILD
+
+ Path to the ``pkgbuild(1)`` command used to generate an macOS component package
+ on macOS. This variable can be used to override the automatically detected
+ command (or specify its location if the auto-detection fails to find it).
+
+
+.. variable:: CPACK_PKGBUILD_IDENTITY_NAME
+
+ Adds a digital signature to the resulting package.
+
+
+.. variable:: CPACK_PKGBUILD_KEYCHAIN_PATH
+
+ Specify a specific keychain to search for the signing identity.
+
+
+.. variable:: CPACK_PREFLIGHT_<COMP>_SCRIPT
+
+ Full path to a file that will be used as the ``preinstall`` script for the
+ named ``<COMP>`` component's package, where ``<COMP>`` is the uppercased
+ component name. No ``preinstall`` script is added if this variable is not
+ defined for a given component.
+
+
+.. variable:: CPACK_POSTFLIGHT_<COMP>_SCRIPT
+
+ Full path to a file that will be used as the ``postinstall`` script for the
+ named ``<COMP>`` component's package, where ``<COMP>`` is the uppercased
+ component name. No ``postinstall`` script is added if this variable is not
+ defined for a given component.
+
+
+.. variable:: CPACK_PRODUCTBUILD_RESOURCES_DIR
+
+ If specified the productbuild generator copies files from this directory
+ (including subdirectories) to the ``Resources`` directory. This is done
+ before the :variable:`CPACK_RESOURCE_FILE_WELCOME`,
+ :variable:`CPACK_RESOURCE_FILE_README`, and
+ :variable:`CPACK_RESOURCE_FILE_LICENSE` files are copied.
diff --git a/Help/cpack_gen/rpm.rst b/Help/cpack_gen/rpm.rst
new file mode 100644
index 000000000..2693c7b62
--- /dev/null
+++ b/Help/cpack_gen/rpm.rst
@@ -0,0 +1,955 @@
+CPack RPM Generator
+-------------------
+
+The built in (binary) CPack RPM generator (Unix only)
+
+Variables specific to CPack RPM generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The CPack RPM generator may be used to create RPM packages using :module:`CPack`.
+The CPack RPM generator is a :module:`CPack` generator thus it uses the
+``CPACK_XXX`` variables used by :module:`CPack`.
+
+The CPack RPM generator has specific features which are controlled by the specifics
+``CPACK_RPM_XXX`` variables.
+
+``CPACK_RPM_<COMPONENT>_XXXX`` variables may be used in order to have
+**component** specific values. Note however that ``<COMPONENT>`` refers to the
+**grouping name** written in upper case. It may be either a component name or
+a component GROUP name. Usually those variables correspond to RPM spec file
+entities. One may find information about spec files here
+http://www.rpm.org/wiki/Docs
+
+.. note::
+
+ `<COMPONENT>` part of variables is preferred to be in upper case (e.g. if
+ component is named ``foo`` then use ``CPACK_RPM_FOO_XXXX`` variable name format)
+ as is with other ``CPACK_<COMPONENT>_XXXX`` variables.
+ For the purposes of back compatibility (CMake/CPack version 3.5 and lower)
+ support for same cased component (e.g. ``fOo`` would be used as
+ ``CPACK_RPM_fOo_XXXX``) is still supported for variables defined in older
+ versions of CMake/CPack but is not guaranteed for variables that
+ will be added in the future. For the sake of back compatibility same cased
+ component variables also override upper cased versions where both are
+ present.
+
+Here are some CPack RPM generator wiki resources that are here for historic
+reasons and are no longer maintained but may still prove useful:
+
+ - https://gitlab.kitware.com/cmake/community/wikis/doc/cpack/Configuration
+ - https://gitlab.kitware.com/cmake/community/wikis/doc/cpack/PackageGenerators#rpm-unix-only
+
+List of CPack RPM generator specific variables:
+
+.. variable:: CPACK_RPM_COMPONENT_INSTALL
+
+ Enable component packaging for CPack RPM generator
+
+ * Mandatory : NO
+ * Default : OFF
+
+ If enabled (``ON``) multiple packages are generated. By default
+ a single package containing files of all components is generated.
+
+.. variable:: CPACK_RPM_PACKAGE_SUMMARY
+ CPACK_RPM_<component>_PACKAGE_SUMMARY
+
+ The RPM package summary.
+
+ * Mandatory : YES
+ * Default : :variable:`CPACK_PACKAGE_DESCRIPTION_SUMMARY`
+
+.. variable:: CPACK_RPM_PACKAGE_NAME
+ CPACK_RPM_<component>_PACKAGE_NAME
+
+ The RPM package name.
+
+ * Mandatory : YES
+ * Default : :variable:`CPACK_PACKAGE_NAME`
+
+.. variable:: CPACK_RPM_FILE_NAME
+ CPACK_RPM_<component>_FILE_NAME
+
+ Package file name.
+
+ * Mandatory : YES
+ * Default : ``<CPACK_PACKAGE_FILE_NAME>[-<component>].rpm`` with spaces
+ replaced by '-'
+
+ This may be set to ``RPM-DEFAULT`` to allow ``rpmbuild`` tool to generate package
+ file name by itself.
+ Alternatively provided package file name must end with ``.rpm`` suffix.
+
+ .. note::
+
+ By using user provided spec file, rpm macro extensions such as for
+ generating ``debuginfo`` packages or by simply using multiple components more
+ than one rpm file may be generated, either from a single spec file or from
+ multiple spec files (each component execution produces its own spec file).
+ In such cases duplicate file names may occur as a result of this variable
+ setting or spec file content structure. Duplicate files get overwritten
+ and it is up to the packager to set the variables in a manner that will
+ prevent such errors.
+
+.. variable:: CPACK_RPM_MAIN_COMPONENT
+
+ Main component that is packaged without component suffix.
+
+ * Mandatory : NO
+ * Default : -
+
+ This variable can be set to any component or group name so that component or
+ 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.
+
+ * Mandatory : YES
+ * Default : :variable:`CPACK_PACKAGE_VERSION`
+
+.. variable:: CPACK_RPM_PACKAGE_ARCHITECTURE
+ CPACK_RPM_<component>_PACKAGE_ARCHITECTURE
+
+ The RPM package architecture.
+
+ * Mandatory : YES
+ * Default : Native architecture output by ``uname -m``
+
+ This may be set to ``noarch`` if you know you are building a ``noarch`` package.
+
+.. variable:: CPACK_RPM_PACKAGE_RELEASE
+
+ The RPM package release.
+
+ * Mandatory : YES
+ * Default : 1
+
+ This is the numbering of the RPM package itself, i.e. the version of the
+ packaging and not the version of the content (see
+ :variable:`CPACK_RPM_PACKAGE_VERSION`). One may change the default value if
+ the previous packaging was buggy and/or you want to put here a fancy Linux
+ distro specific numbering.
+
+.. note::
+
+ This is the string that goes into the RPM ``Release:`` field. Some distros
+ (e.g. Fedora, CentOS) require ``1%{?dist}`` format and not just a number.
+ ``%{?dist}`` part can be added by setting :variable:`CPACK_RPM_PACKAGE_RELEASE_DIST`.
+
+.. variable:: CPACK_RPM_PACKAGE_RELEASE_DIST
+
+ The dist tag that is added RPM ``Release:`` field.
+
+ * Mandatory : NO
+ * Default : OFF
+
+ This is the reported ``%{dist}`` tag from the current distribution or empty
+ ``%{dist}`` if RPM macro is not set. If this variable is set then RPM
+ ``Release:`` field value is set to ``${CPACK_RPM_PACKAGE_RELEASE}%{?dist}``.
+
+.. variable:: CPACK_RPM_PACKAGE_LICENSE
+
+ The RPM package license policy.
+
+ * Mandatory : YES
+ * Default : "unknown"
+
+.. variable:: CPACK_RPM_PACKAGE_GROUP
+ CPACK_RPM_<component>_PACKAGE_GROUP
+
+ The RPM package group.
+
+ * Mandatory : YES
+ * Default : "unknown"
+
+.. variable:: CPACK_RPM_PACKAGE_VENDOR
+
+ The RPM package vendor.
+
+ * Mandatory : YES
+ * Default : CPACK_PACKAGE_VENDOR if set or "unknown"
+
+.. variable:: CPACK_RPM_PACKAGE_URL
+ CPACK_RPM_<component>_PACKAGE_URL
+
+ The projects URL.
+
+ * Mandatory : NO
+ * Default : :variable:`CMAKE_PROJECT_HOMEPAGE_URL`
+
+.. variable:: CPACK_RPM_PACKAGE_DESCRIPTION
+ CPACK_RPM_<component>_PACKAGE_DESCRIPTION
+
+ RPM package description.
+
+ * Mandatory : YES
+ * Default : :variable:`CPACK_COMPONENT_<compName>_DESCRIPTION` (component
+ based installers only) if set, :variable:`CPACK_PACKAGE_DESCRIPTION_FILE`
+ if set or "no package description available"
+
+.. variable:: CPACK_RPM_COMPRESSION_TYPE
+
+ RPM compression type.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to override RPM compression type to be used to build the
+ RPM. For example some Linux distribution now default to ``lzma`` or ``xz``
+ compression whereas older cannot use such RPM. Using this one can enforce
+ compression type to be used.
+
+ Possible values are:
+
+ - lzma
+ - xz
+ - bzip2
+ - gzip
+
+.. variable:: CPACK_RPM_PACKAGE_AUTOREQ
+ CPACK_RPM_<component>_PACKAGE_AUTOREQ
+
+ RPM spec autoreq field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to enable (``1``, ``yes``) or disable (``0``, ``no``) automatic
+ shared libraries dependency detection. Dependencies are added to requires list.
+
+ .. note::
+
+ By default automatic dependency detection is enabled by rpm generator.
+
+.. variable:: CPACK_RPM_PACKAGE_AUTOPROV
+ CPACK_RPM_<component>_PACKAGE_AUTOPROV
+
+ RPM spec autoprov field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to enable (``1``, ``yes``) or disable (``0``, ``no``)
+ automatic listing of shared libraries that are provided by the package.
+ Shared libraries are added to provides list.
+
+ .. note::
+
+ By default automatic provides detection is enabled by rpm generator.
+
+.. variable:: CPACK_RPM_PACKAGE_AUTOREQPROV
+ CPACK_RPM_<component>_PACKAGE_AUTOREQPROV
+
+ RPM spec autoreqprov field.
+
+ * Mandatory : NO
+ * Default : -
+
+ Variable enables/disables autoreq and autoprov at the same time.
+ See :variable:`CPACK_RPM_PACKAGE_AUTOREQ` and
+ :variable:`CPACK_RPM_PACKAGE_AUTOPROV` for more details.
+
+ .. note::
+
+ By default automatic detection feature is enabled by rpm.
+
+.. variable:: CPACK_RPM_PACKAGE_REQUIRES
+ CPACK_RPM_<component>_PACKAGE_REQUIRES
+
+ RPM spec requires field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set RPM dependencies (requires). Note that you must enclose
+ the complete requires string between quotes, for example::
+
+ set(CPACK_RPM_PACKAGE_REQUIRES "python >= 2.5.0, cmake >= 2.8")
+
+ The required package list of an RPM file could be printed with::
+
+ rpm -qp --requires file.rpm
+
+.. variable:: CPACK_RPM_PACKAGE_CONFLICTS
+ CPACK_RPM_<component>_PACKAGE_CONFLICTS
+
+ RPM spec conflicts field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set negative RPM dependencies (conflicts). Note that you must
+ enclose the complete requires string between quotes, for example::
+
+ set(CPACK_RPM_PACKAGE_CONFLICTS "libxml2")
+
+ The conflicting package list of an RPM file could be printed with::
+
+ rpm -qp --conflicts file.rpm
+
+.. variable:: CPACK_RPM_PACKAGE_REQUIRES_PRE
+ CPACK_RPM_<component>_PACKAGE_REQUIRES_PRE
+
+ RPM spec requires(pre) field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set RPM preinstall dependencies (requires(pre)). Note that
+ you must enclose the complete requires string between quotes, for example::
+
+ set(CPACK_RPM_PACKAGE_REQUIRES_PRE "shadow-utils, initscripts")
+
+.. variable:: CPACK_RPM_PACKAGE_REQUIRES_POST
+ CPACK_RPM_<component>_PACKAGE_REQUIRES_POST
+
+ RPM spec requires(post) field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set RPM postinstall dependencies (requires(post)). Note that
+ you must enclose the complete requires string between quotes, for example::
+
+ set(CPACK_RPM_PACKAGE_REQUIRES_POST "shadow-utils, initscripts")
+
+.. variable:: CPACK_RPM_PACKAGE_REQUIRES_POSTUN
+ CPACK_RPM_<component>_PACKAGE_REQUIRES_POSTUN
+
+ RPM spec requires(postun) field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set RPM postuninstall dependencies (requires(postun)). Note
+ that you must enclose the complete requires string between quotes, for
+ example::
+
+ set(CPACK_RPM_PACKAGE_REQUIRES_POSTUN "shadow-utils, initscripts")
+
+.. variable:: CPACK_RPM_PACKAGE_REQUIRES_PREUN
+ CPACK_RPM_<component>_PACKAGE_REQUIRES_PREUN
+
+ RPM spec requires(preun) field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set RPM preuninstall dependencies (requires(preun)). Note that
+ you must enclose the complete requires string between quotes, for example::
+
+ set(CPACK_RPM_PACKAGE_REQUIRES_PREUN "shadow-utils, initscripts")
+
+.. variable:: CPACK_RPM_PACKAGE_SUGGESTS
+ CPACK_RPM_<component>_PACKAGE_SUGGESTS
+
+ RPM spec suggest field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set weak RPM dependencies (suggests). Note that you must
+ enclose the complete requires string between quotes.
+
+.. variable:: CPACK_RPM_PACKAGE_PROVIDES
+ CPACK_RPM_<component>_PACKAGE_PROVIDES
+
+ RPM spec provides field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set RPM dependencies (provides). The provided package list
+ of an RPM file could be printed with::
+
+ rpm -qp --provides file.rpm
+
+.. variable:: CPACK_RPM_PACKAGE_OBSOLETES
+ CPACK_RPM_<component>_PACKAGE_OBSOLETES
+
+ RPM spec obsoletes field.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set RPM packages that are obsoleted by this one.
+
+.. variable:: CPACK_RPM_PACKAGE_RELOCATABLE
+
+ build a relocatable RPM.
+
+ * Mandatory : NO
+ * Default : CPACK_PACKAGE_RELOCATABLE
+
+ If this variable is set to TRUE or ON, the CPack RPM generator will try
+ to build a relocatable RPM package. A relocatable RPM may
+ be installed using::
+
+ rpm --prefix or --relocate
+
+ in order to install it at an alternate place see rpm(8). Note that
+ currently this may fail if :variable:`CPACK_SET_DESTDIR` is set to ``ON``. If
+ :variable:`CPACK_SET_DESTDIR` is set then you will get a warning message but
+ if there is file installed with absolute path you'll get unexpected behavior.
+
+.. variable:: CPACK_RPM_SPEC_INSTALL_POST
+
+ Deprecated - use :variable:`CPACK_RPM_SPEC_MORE_DEFINE` instead.
+
+ * Mandatory : NO
+ * Default : -
+ * Deprecated: YES
+
+ May be used to override the ``__spec_install_post`` section within the
+ generated spec file. This affects the install step during package creation,
+ not during package installation. For adding operations to be performed
+ during package installation, use
+ :variable:`CPACK_RPM_POST_INSTALL_SCRIPT_FILE` instead.
+
+.. variable:: CPACK_RPM_SPEC_MORE_DEFINE
+
+ RPM extended spec definitions lines.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to add any ``%define`` lines to the generated spec file. An
+ example of its use is to prevent stripping of executables (but note that
+ this may also disable other default post install processing)::
+
+ set(CPACK_RPM_SPEC_MORE_DEFINE "%define __spec_install_post /bin/true")
+
+.. variable:: CPACK_RPM_PACKAGE_DEBUG
+
+ Toggle CPack RPM generator debug output.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be set when invoking cpack in order to trace debug information
+ during CPack RPM run. For example you may launch CPack like this::
+
+ cpack -D CPACK_RPM_PACKAGE_DEBUG=1 -G RPM
+
+.. variable:: CPACK_RPM_USER_BINARY_SPECFILE
+ CPACK_RPM_<componentName>_USER_BINARY_SPECFILE
+
+ A user provided spec file.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be set by the user in order to specify a USER binary spec file
+ to be used by the CPack RPM generator instead of generating the file.
+ The specified file will be processed by configure_file( @ONLY).
+
+.. variable:: CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE
+
+ Spec file template.
+
+ * Mandatory : NO
+ * Default : -
+
+ If set CPack will generate a template for USER specified binary
+ spec file and stop with an error. For example launch CPack like this::
+
+ cpack -D CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE=1 -G RPM
+
+ The user may then use this file in order to hand-craft is own
+ binary spec file which may be used with
+ :variable:`CPACK_RPM_USER_BINARY_SPECFILE`.
+
+.. variable:: CPACK_RPM_PRE_INSTALL_SCRIPT_FILE
+ CPACK_RPM_PRE_UNINSTALL_SCRIPT_FILE
+
+ Path to file containing pre (un)install script.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to embed a pre (un)installation script in the spec file.
+ The referred script file (or both) will be read and directly
+ put after the ``%pre`` or ``%preun`` section
+ If :variable:`CPACK_RPM_COMPONENT_INSTALL` is set to ON the (un)install
+ script for each component can be overridden with
+ ``CPACK_RPM_<COMPONENT>_PRE_INSTALL_SCRIPT_FILE`` and
+ ``CPACK_RPM_<COMPONENT>_PRE_UNINSTALL_SCRIPT_FILE``.
+ One may verify which scriptlet has been included with::
+
+ rpm -qp --scripts package.rpm
+
+.. variable:: CPACK_RPM_POST_INSTALL_SCRIPT_FILE
+ CPACK_RPM_POST_UNINSTALL_SCRIPT_FILE
+
+ Path to file containing post (un)install script.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to embed a post (un)installation script in the spec file.
+ The referred script file (or both) will be read and directly
+ put after the ``%post`` or ``%postun`` section.
+ If :variable:`CPACK_RPM_COMPONENT_INSTALL` is set to ON the (un)install
+ script for each component can be overridden with
+ ``CPACK_RPM_<COMPONENT>_POST_INSTALL_SCRIPT_FILE`` and
+ ``CPACK_RPM_<COMPONENT>_POST_UNINSTALL_SCRIPT_FILE``.
+ One may verify which scriptlet has been included with::
+
+ rpm -qp --scripts package.rpm
+
+.. variable:: CPACK_RPM_USER_FILELIST
+ CPACK_RPM_<COMPONENT>_USER_FILELIST
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to explicitly specify ``%(<directive>)`` file line
+ in the spec file. Like ``%config(noreplace)`` or any other directive
+ that be found in the ``%files`` section. You can have multiple directives
+ per line, as in ``%attr(600,root,root) %config(noreplace)``. Since
+ the CPack RPM generator is generating the list of files (and directories) the
+ user specified files of the ``CPACK_RPM_<COMPONENT>_USER_FILELIST`` list will
+ be removed from the generated list. If referring to directories do
+ not add a trailing slash.
+
+.. variable:: CPACK_RPM_CHANGELOG_FILE
+
+ RPM changelog file.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to embed a changelog in the spec file.
+ The referred file will be read and directly put after the ``%changelog``
+ section.
+
+.. variable:: CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST
+
+ list of path to be excluded.
+
+ * Mandatory : NO
+ * 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 default value contains a
+ reasonable set of values if the variable is not defined by the user. If the
+ variable is defined by the user then the CPack RPM generator will NOT any of
+ the default path. If you want to add some path to the default list then you
+ can use :variable:`CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION` variable.
+
+.. variable:: CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION
+
+ additional list of path to be excluded.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to add more exclude path (directories or files) from the initial
+ default list of excluded paths. See
+ :variable:`CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST`.
+
+.. variable:: CPACK_RPM_RELOCATION_PATHS
+
+ Packages relocation paths list.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to specify more than one relocation path per relocatable RPM.
+ Variable contains a list of relocation paths that if relative are prefixed
+ by the value of :variable:`CPACK_RPM_<COMPONENT>_PACKAGE_PREFIX` or by the
+ value of :variable:`CPACK_PACKAGING_INSTALL_PREFIX` if the component version
+ is not provided.
+ Variable is not component based as its content can be used to set a different
+ path prefix for e.g. binary dir and documentation dir at the same time.
+ Only prefixes that are required by a certain component are added to that
+ component - component must contain at least one file/directory/symbolic link
+ with :variable:`CPACK_RPM_RELOCATION_PATHS` prefix for a certain relocation
+ path to be added. Package will not contain any relocation paths if there are
+ no files/directories/symbolic links on any of the provided prefix locations.
+ Packages that either do not contain any relocation paths or contain
+ files/directories/symbolic links that are outside relocation paths print
+ out an ``AUTHOR_WARNING`` that RPM will be partially relocatable.
+
+.. variable:: CPACK_RPM_<COMPONENT>_PACKAGE_PREFIX
+
+ Per component relocation path install prefix.
+
+ * Mandatory : NO
+ * Default : CPACK_PACKAGING_INSTALL_PREFIX
+
+ May be used to set per component :variable:`CPACK_PACKAGING_INSTALL_PREFIX`
+ for relocatable RPM packages.
+
+.. variable:: CPACK_RPM_NO_INSTALL_PREFIX_RELOCATION
+ CPACK_RPM_NO_<COMPONENT>_INSTALL_PREFIX_RELOCATION
+
+ Removal of default install prefix from relocation paths list.
+
+ * Mandatory : NO
+ * Default : CPACK_PACKAGING_INSTALL_PREFIX or CPACK_RPM_<COMPONENT>_PACKAGE_PREFIX
+ are treated as one of relocation paths
+
+ May be used to remove CPACK_PACKAGING_INSTALL_PREFIX and CPACK_RPM_<COMPONENT>_PACKAGE_PREFIX
+ from relocatable RPM prefix paths.
+
+.. variable:: CPACK_RPM_ADDITIONAL_MAN_DIRS
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set additional man dirs that could potentially be compressed
+ by brp-compress RPM macro. Variable content must be a list of regular
+ expressions that point to directories containing man files or to man files
+ directly. Note that in order to compress man pages a path must also be
+ present in brp-compress RPM script and that brp-compress script must be
+ added to RPM configuration by the operating system.
+
+ Regular expressions that are added by default were taken from brp-compress
+ RPM macro:
+
+ - /usr/man/man.*
+ - /usr/man/.*/man.*
+ - /usr/info.*
+ - /usr/share/man/man.*
+ - /usr/share/man/.*/man.*
+ - /usr/share/info.*
+ - /usr/kerberos/man.*
+ - /usr/X11R6/man/man.*
+ - /usr/lib/perl5/man/man.*
+ - /usr/share/doc/.*/man/man.*
+ - /usr/lib/.*/man/man.*
+
+.. variable:: CPACK_RPM_DEFAULT_USER
+ CPACK_RPM_<compName>_DEFAULT_USER
+
+ default user ownership of RPM content
+
+ * Mandatory : NO
+ * Default : root
+
+ Value should be user name and not UID.
+ Note that <compName> must be in upper-case.
+
+.. variable:: CPACK_RPM_DEFAULT_GROUP
+ CPACK_RPM_<compName>_DEFAULT_GROUP
+
+ default group ownership of RPM content
+
+ * Mandatory : NO
+ * Default : root
+
+ Value should be group name and not GID.
+ Note that <compName> must be in upper-case.
+
+.. variable:: CPACK_RPM_DEFAULT_FILE_PERMISSIONS
+ CPACK_RPM_<compName>_DEFAULT_FILE_PERMISSIONS
+
+ default permissions used for packaged files
+
+ * Mandatory : NO
+ * Default : - (system default)
+
+ Accepted values are lists with ``PERMISSIONS``. Valid permissions
+ are:
+
+ - OWNER_READ
+ - OWNER_WRITE
+ - OWNER_EXECUTE
+ - GROUP_READ
+ - GROUP_WRITE
+ - GROUP_EXECUTE
+ - WORLD_READ
+ - WORLD_WRITE
+ - WORLD_EXECUTE
+
+ Note that <compName> must be in upper-case.
+
+.. variable:: CPACK_RPM_DEFAULT_DIR_PERMISSIONS
+ CPACK_RPM_<compName>_DEFAULT_DIR_PERMISSIONS
+
+ default permissions used for packaged directories
+
+ * Mandatory : NO
+ * Default : - (system default)
+
+ Accepted values are lists with PERMISSIONS. Valid permissions
+ are the same as for :variable:`CPACK_RPM_DEFAULT_FILE_PERMISSIONS`.
+ Note that <compName> must be in upper-case.
+
+.. variable:: CPACK_RPM_INSTALL_WITH_EXEC
+
+ force execute permissions on programs and shared libraries
+
+ * Mandatory : NO
+ * Default : - (system default)
+
+ Force set owner, group and world execute permissions on programs and shared
+ libraries. This can be used for creating valid rpm packages on systems such
+ as Debian where shared libraries do not have execute permissions set.
+
+.. note::
+
+ Programs and shared libraries without execute permissions are ignored during
+ separation of debug symbols from the binary for debuginfo packages.
+
+Packaging of Symbolic Links
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The CPack RPM generator supports packaging of symbolic links::
+
+ execute_process(COMMAND ${CMAKE_COMMAND}
+ -E create_symlink <relative_path_location> <symlink_name>)
+ install(FILES ${CMAKE_CURRENT_BINARY_DIR}/<symlink_name>
+ DESTINATION <symlink_location> COMPONENT libraries)
+
+Symbolic links will be optimized (paths will be shortened if possible)
+before being added to the package or if multiple relocation paths are
+detected, a post install symlink relocation script will be generated.
+
+Symbolic links may point to locations that are not packaged by the same
+package (either a different component or even not packaged at all) but
+those locations will be treated as if they were a part of the package
+while determining if symlink should be either created or present in a
+post install script - depending on relocation paths.
+
+Symbolic links that point to locations outside packaging path produce a
+warning and are treated as non relocatable permanent symbolic links.
+
+Currently there are a few limitations though:
+
+* For component based packaging component interdependency is not checked
+ when processing symbolic links. Symbolic links pointing to content of
+ a different component are treated the same way as if pointing to location
+ that will not be packaged.
+
+* Symbolic links pointing to a location through one or more intermediate
+ symbolic links will not be handled differently - if the intermediate
+ symbolic link(s) is also on a relocatable path, relocating it during
+ package installation may cause initial symbolic link to point to an
+ invalid location.
+
+Packaging of debug information
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Debuginfo packages contain debug symbols and sources for debugging packaged
+binaries.
+
+Debuginfo RPM packaging has its own set of variables:
+
+.. variable:: CPACK_RPM_DEBUGINFO_PACKAGE
+ CPACK_RPM_<component>_DEBUGINFO_PACKAGE
+
+ Enable generation of debuginfo RPM package(s).
+
+ * Mandatory : NO
+ * Default : OFF
+
+.. note::
+
+ Binaries must contain debug symbols before packaging so use either ``Debug``
+ or ``RelWithDebInfo`` for :variable:`CMAKE_BUILD_TYPE` variable value.
+
+.. note::
+
+ Packages generated from packages without binary files, with binary files but
+ without execute permissions or without debug symbols will cause packaging
+ termination.
+
+.. variable:: CPACK_BUILD_SOURCE_DIRS
+
+ Provides locations of root directories of source files from which binaries
+ were built.
+
+ * Mandatory : YES if :variable:`CPACK_RPM_DEBUGINFO_PACKAGE` is set
+ * Default : -
+
+.. note::
+
+ For CMake project :variable:`CPACK_BUILD_SOURCE_DIRS` is set by default to
+ point to :variable:`CMAKE_SOURCE_DIR` and :variable:`CMAKE_BINARY_DIR` paths.
+
+.. note::
+
+ Sources with path prefixes that do not fall under any location provided with
+ :variable:`CPACK_BUILD_SOURCE_DIRS` will not be present in debuginfo package.
+
+.. variable:: CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX
+ CPACK_RPM_<component>_BUILD_SOURCE_DIRS_PREFIX
+
+ Prefix of location where sources will be placed during package installation.
+
+ * Mandatory : YES if :variable:`CPACK_RPM_DEBUGINFO_PACKAGE` is set
+ * Default : "/usr/src/debug/<CPACK_PACKAGE_FILE_NAME>" and
+ for component packaging "/usr/src/debug/<CPACK_PACKAGE_FILE_NAME>-<component>"
+
+.. note::
+
+ Each source path prefix is additionally suffixed by ``src_<index>`` where
+ index is index of the path used from :variable:`CPACK_BUILD_SOURCE_DIRS`
+ variable. This produces ``<CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX>/src_<index>``
+ replacement path.
+ Limitation is that replaced path part must be shorter or of equal
+ length than the length of its replacement. If that is not the case either
+ :variable:`CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX` variable has to be set to
+ a shorter path or source directories must be placed on a longer path.
+
+.. variable:: CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS
+
+ Directories containing sources that should be excluded from debuginfo packages.
+
+ * Mandatory : NO
+ * Default : "/usr /usr/src /usr/src/debug"
+
+ Listed paths are owned by other RPM packages and should therefore not be
+ deleted on debuginfo package uninstallation.
+
+.. variable:: CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS_ADDITION
+
+ Paths that should be appended to :variable:`CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS`
+ for exclusion.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE
+
+ Create a single debuginfo package even if components packaging is set.
+
+ * Mandatory : NO
+ * Default : OFF
+
+ When this variable is enabled it produces a single debuginfo package even if
+ component packaging is enabled.
+
+ When using this feature in combination with components packaging and there is
+ more than one component this variable requires :variable:`CPACK_RPM_MAIN_COMPONENT`
+ to be set.
+
+.. note::
+
+ If none of the :variable:`CPACK_RPM_<component>_DEBUGINFO_PACKAGE` variables
+ is set then :variable:`CPACK_RPM_DEBUGINFO_PACKAGE` is automatically set to
+ ``ON`` when :variable:`CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE` is set.
+
+.. variable:: CPACK_RPM_DEBUGINFO_FILE_NAME
+ CPACK_RPM_<component>_DEBUGINFO_FILE_NAME
+
+ Debuginfo package file name.
+
+ * Mandatory : NO
+ * Default : rpmbuild tool generated package file name
+
+ Alternatively provided debuginfo package file name must end with ``.rpm``
+ suffix and should differ from file names of other generated packages.
+
+ Variable may contain ``@cpack_component@`` placeholder which will be
+ replaced by component name if component packaging is enabled otherwise it
+ deletes the placeholder.
+
+ Setting the variable to ``RPM-DEFAULT`` may be used to explicitly set
+ filename generation to default.
+
+.. note::
+
+ :variable:`CPACK_RPM_FILE_NAME` also supports rpmbuild tool generated package
+ file name - disabled by default but can be enabled by setting the variable to
+ ``RPM-DEFAULT``.
+
+Packaging of sources (SRPM)
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+SRPM packaging is enabled by setting :variable:`CPACK_RPM_PACKAGE_SOURCES`
+variable while usually using :variable:`CPACK_INSTALLED_DIRECTORIES` variable
+to provide directory containing CMakeLists.txt and source files.
+
+For CMake projects SRPM package would be produced by executing::
+
+ cpack -G RPM --config ./CPackSourceConfig.cmake
+
+.. note::
+
+ Produced SRPM package is expected to be built with :manual:`cmake(1)` executable
+ and packaged with :manual:`cpack(1)` executable so CMakeLists.txt has to be
+ located in root source directory and must be able to generate binary rpm
+ packages by executing ``cpack -G`` command. The two executables as well as
+ rpmbuild must also be present when generating binary rpm packages from the
+ produced SRPM package.
+
+Once the SRPM package is generated it can be used to generate binary packages
+by creating a directory structure for rpm generation and executing rpmbuild
+tool::
+
+ mkdir -p build_dir/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
+ rpmbuild --define "_topdir <path_to_build_dir>" --rebuild <SRPM_file_name>
+
+Generated packages will be located in build_dir/RPMS directory or its sub
+directories.
+
+.. note::
+
+ SRPM package internally uses CPack/RPM generator to generate binary packages
+ so CMakeScripts.txt can decide during the SRPM to binary rpm generation step
+ what content the package(s) should have as well as how they should be packaged
+ (monolithic or components). CMake can decide this for e.g. by reading environment
+ variables set by the package manager before starting the process of generating
+ binary rpm packages. This way a single SRPM package can be used to produce
+ different binary rpm packages on different platforms depending on the platform's
+ packaging rules.
+
+Source RPM packaging has its own set of variables:
+
+.. variable:: CPACK_RPM_PACKAGE_SOURCES
+
+ Should the content be packaged as a source rpm (default is binary rpm).
+
+ * Mandatory : NO
+ * Default : OFF
+
+.. note::
+
+ For cmake projects :variable:`CPACK_RPM_PACKAGE_SOURCES` variable is set
+ to ``OFF`` in CPackConfig.cmake and ``ON`` in CPackSourceConfig.cmake
+ generated files.
+
+.. variable:: CPACK_RPM_SOURCE_PKG_BUILD_PARAMS
+
+ Additional command-line parameters provided to :manual:`cmake(1)` executable.
+
+ * Mandatory : NO
+ * Default : -
+
+.. variable:: CPACK_RPM_SOURCE_PKG_PACKAGING_INSTALL_PREFIX
+
+ Packaging install prefix that would be provided in :variable:`CPACK_PACKAGING_INSTALL_PREFIX`
+ variable for producing binary RPM packages.
+
+ * Mandatory : YES
+ * Default : "/"
+
+.. VARIABLE:: CPACK_RPM_BUILDREQUIRES
+
+ List of source rpm build dependencies.
+
+ * Mandatory : NO
+ * Default : -
+
+ May be used to set source RPM build dependencies (BuildRequires). Note that
+ you must enclose the complete build requirements string between quotes, for
+ example::
+
+ set(CPACK_RPM_BUILDREQUIRES "python >= 2.5.0, cmake >= 2.8")
diff --git a/Help/cpack_gen/wix.rst b/Help/cpack_gen/wix.rst
new file mode 100644
index 000000000..dde49438b
--- /dev/null
+++ b/Help/cpack_gen/wix.rst
@@ -0,0 +1,284 @@
+CPack WIX Generator
+-------------------
+
+CPack WIX generator specific options
+
+Variables specific to CPack WIX generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following variables are specific to the installers built on
+Windows using WiX.
+
+.. variable:: CPACK_WIX_UPGRADE_GUID
+
+ Upgrade GUID (``Product/@UpgradeCode``)
+
+ Will be automatically generated unless explicitly provided.
+
+ It should be explicitly set to a constant generated globally unique
+ identifier (GUID) to allow your installers to replace existing
+ installations that use the same GUID.
+
+ You may for example explicitly set this variable in your
+ CMakeLists.txt to the value that has been generated per default. You
+ should not use GUIDs that you did not generate yourself or which may
+ belong to other projects.
+
+ A GUID shall have the following fixed length syntax::
+
+ XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
+
+ (each X represents an uppercase hexadecimal digit)
+
+.. variable:: CPACK_WIX_PRODUCT_GUID
+
+ Product GUID (``Product/@Id``)
+
+ Will be automatically generated unless explicitly provided.
+
+ If explicitly provided this will set the Product Id of your installer.
+
+ The installer will abort if it detects a pre-existing installation that
+ uses the same GUID.
+
+ The GUID shall use the syntax described for CPACK_WIX_UPGRADE_GUID.
+
+.. variable:: CPACK_WIX_LICENSE_RTF
+
+ RTF License File
+
+ If CPACK_RESOURCE_FILE_LICENSE has an .rtf extension it is used as-is.
+
+ If CPACK_RESOURCE_FILE_LICENSE has an .txt extension it is implicitly
+ converted to RTF by the WIX Generator.
+ The expected encoding of the .txt file is UTF-8.
+
+ With CPACK_WIX_LICENSE_RTF you can override the license file used by the
+ WIX Generator in case CPACK_RESOURCE_FILE_LICENSE is in an unsupported
+ format or the .txt -> .rtf conversion does not work as expected.
+
+.. variable:: CPACK_WIX_PRODUCT_ICON
+
+ The Icon shown next to the program name in Add/Remove programs.
+
+ If set, this icon is used in place of the default icon.
+
+.. variable:: CPACK_WIX_UI_REF
+
+ This variable allows you to override the Id of the ``<UIRef>`` element
+ in the WiX template.
+
+ The default is ``WixUI_InstallDir`` in case no CPack components have
+ been defined and ``WixUI_FeatureTree`` otherwise.
+
+.. variable:: CPACK_WIX_UI_BANNER
+
+ The bitmap will appear at the top of all installer pages other than the
+ welcome and completion dialogs.
+
+ If set, this image will replace the default banner image.
+
+ This image must be 493 by 58 pixels.
+
+.. variable:: CPACK_WIX_UI_DIALOG
+
+ Background bitmap used on the welcome and completion dialogs.
+
+ If this variable is set, the installer will replace the default dialog
+ image.
+
+ This image must be 493 by 312 pixels.
+
+.. variable:: CPACK_WIX_PROGRAM_MENU_FOLDER
+
+ Start menu folder name for launcher.
+
+ If this variable is not set, it will be initialized with CPACK_PACKAGE_NAME
+
+.. variable:: CPACK_WIX_CULTURES
+
+ Language(s) of the installer
+
+ Languages are compiled into the WixUI extension library. To use them,
+ simply provide the name of the culture. If you specify more than one
+ culture identifier in a comma or semicolon delimited list, the first one
+ that is found will be used. You can find a list of supported languages at:
+ http://wix.sourceforge.net/manual-wix3/WixUI_localization.htm
+
+.. variable:: CPACK_WIX_TEMPLATE
+
+ Template file for WiX generation
+
+ If this variable is set, the specified template will be used to generate
+ the WiX wxs file. This should be used if further customization of the
+ output is required.
+
+ If this variable is not set, the default MSI template included with CMake
+ will be used.
+
+.. variable:: CPACK_WIX_PATCH_FILE
+
+ Optional list of XML files with fragments to be inserted into
+ generated WiX sources
+
+ This optional variable can be used to specify an XML file that the
+ WIX generator will use to inject fragments into its generated
+ source files.
+
+ Patch files understood by the CPack WIX generator
+ roughly follow this RELAX NG compact schema:
+
+ .. code-block:: none
+
+ start = CPackWiXPatch
+
+ CPackWiXPatch = element CPackWiXPatch { CPackWiXFragment* }
+
+ CPackWiXFragment = element CPackWiXFragment
+ {
+ attribute Id { string },
+ fragmentContent*
+ }
+
+ fragmentContent = element * - CPackWiXFragment
+ {
+ (attribute * { text } | text | fragmentContent)*
+ }
+
+ Currently fragments can be injected into most
+ Component, File, Directory and Feature elements.
+
+ The following additional special Ids can be used:
+
+ * ``#PRODUCT`` for the ``<Product>`` element.
+ * ``#PRODUCTFEATURE`` for the root ``<Feature>`` element.
+
+ The following example illustrates how this works.
+
+ Given that the WIX generator creates the following XML element:
+
+ .. code-block:: xml
+
+ <Component Id="CM_CP_applications.bin.my_libapp.exe" Guid="*"/>
+
+ The following XML patch file may be used to inject an Environment element
+ into it:
+
+ .. code-block:: xml
+
+ <CPackWiXPatch>
+ <CPackWiXFragment Id="CM_CP_applications.bin.my_libapp.exe">
+ <Environment Id="MyEnvironment" Action="set"
+ Name="MyVariableName" Value="MyVariableValue"/>
+ </CPackWiXFragment>
+ </CPackWiXPatch>
+
+.. variable:: CPACK_WIX_EXTRA_SOURCES
+
+ Extra WiX source files
+
+ This variable provides an optional list of extra WiX source files (.wxs)
+ that should be compiled and linked. The full path to source files is
+ required.
+
+.. variable:: CPACK_WIX_EXTRA_OBJECTS
+
+ Extra WiX object files or libraries
+
+ This variable provides an optional list of extra WiX object (.wixobj)
+ and/or WiX library (.wixlib) files. The full path to objects and libraries
+ is required.
+
+.. variable:: CPACK_WIX_EXTENSIONS
+
+ This variable provides a list of additional extensions for the WiX
+ tools light and candle.
+
+.. variable:: CPACK_WIX_<TOOL>_EXTENSIONS
+
+ This is the tool specific version of CPACK_WIX_EXTENSIONS.
+ ``<TOOL>`` can be either LIGHT or CANDLE.
+
+.. variable:: CPACK_WIX_<TOOL>_EXTRA_FLAGS
+
+ This list variable allows you to pass additional
+ flags to the WiX tool ``<TOOL>``.
+
+ Use it at your own risk.
+ Future versions of CPack may generate flags which may be in conflict
+ with your own flags.
+
+ ``<TOOL>`` can be either LIGHT or CANDLE.
+
+.. variable:: CPACK_WIX_CMAKE_PACKAGE_REGISTRY
+
+ If this variable is set the generated installer will create
+ an entry in the windows registry key
+ ``HKEY_LOCAL_MACHINE\Software\Kitware\CMake\Packages\<PackageName>``
+ The value for ``<PackageName>`` is provided by this variable.
+
+ Assuming you also install a CMake configuration file this will
+ allow other CMake projects to find your package with
+ the :command:`find_package` command.
+
+.. variable:: CPACK_WIX_PROPERTY_<PROPERTY>
+
+ This variable can be used to provide a value for
+ the Windows Installer property ``<PROPERTY>``
+
+ The following list contains some example properties that can be used to
+ customize information under
+ "Programs and Features" (also known as "Add or Remove Programs")
+
+ * ARPCOMMENTS - Comments
+ * ARPHELPLINK - Help and support information URL
+ * ARPURLINFOABOUT - General information URL
+ * ARPURLUPDATEINFO - Update information URL
+ * ARPHELPTELEPHONE - Help and support telephone number
+ * ARPSIZE - Size (in kilobytes) of the application
+
+.. variable:: CPACK_WIX_ROOT_FEATURE_TITLE
+
+ Sets the name of the root install feature in the WIX installer. Same as
+ CPACK_COMPONENT_<compName>_DISPLAY_NAME for components.
+
+.. variable:: CPACK_WIX_ROOT_FEATURE_DESCRIPTION
+
+ Sets the description of the root install feature in the WIX installer. Same as
+ CPACK_COMPONENT_<compName>_DESCRIPTION for components.
+
+.. variable:: CPACK_WIX_SKIP_PROGRAM_FOLDER
+
+ If this variable is set to true, the default install location
+ of the generated package will be CPACK_PACKAGE_INSTALL_DIRECTORY directly.
+ The install location will not be located relatively below
+ ProgramFiles or ProgramFiles64.
+
+ .. note::
+ Installers created with this feature do not take differences
+ between the system on which the installer is created
+ and the system on which the installer might be used into account.
+
+ It is therefore possible that the installer e.g. might try to install
+ onto a drive that is unavailable or unintended or a path that does not
+ follow the localization or convention of the system on which the
+ installation is performed.
+
+.. variable:: CPACK_WIX_ROOT_FOLDER_ID
+
+ This variable allows specification of a custom root folder ID.
+ The generator specific ``<64>`` token can be used for
+ folder IDs that come in 32-bit and 64-bit variants.
+ In 32-bit builds the token will expand empty while in 64-bit builds
+ it will expand to ``64``.
+
+ When unset generated installers will default installing to
+ ``ProgramFiles<64>Folder``.
+
+.. variable:: CPACK_WIX_ROOT
+
+ This variable can optionally be set to the root directory
+ of a custom WiX Toolset installation.
+
+ When unspecified CPack will try to locate a WiX Toolset
+ installation via the ``WIX`` environment variable instead.
diff --git a/Help/dev/documentation.rst b/Help/dev/documentation.rst
new file mode 100644
index 000000000..c302790aa
--- /dev/null
+++ b/Help/dev/documentation.rst
@@ -0,0 +1,530 @@
+CMake Documentation Guide
+*************************
+
+The following is a guide to the CMake documentation source for developers.
+See documentation on `CMake Development`_ for more information.
+
+.. _`CMake Development`: README.rst
+
+Help
+====
+
+The ``Help`` directory contains CMake help manual source files.
+They are written using the `reStructuredText`_ markup syntax and
+processed by `Sphinx`_ to generate the CMake help manuals.
+
+.. _`reStructuredText`: http://docutils.sourceforge.net/docs/ref/rst/introduction.html
+.. _`Sphinx`: http://sphinx-doc.org
+
+Markup Constructs
+-----------------
+
+In addition to using Sphinx to generate the CMake help manuals, we
+also use a C++-implemented document processor to print documents for
+the ``--help-*`` command-line help options. It supports a subset of
+reStructuredText markup. When authoring or modifying documents,
+please verify that the command-line help looks good in addition to the
+Sphinx-generated html and man pages.
+
+The command-line help processor supports the following constructs
+defined by reStructuredText, Sphinx, and a CMake extension to Sphinx.
+
+..
+ Note: This list must be kept consistent with the cmRST implementation.
+
+CMake Domain directives
+ Directives defined in the `CMake Domain`_ for defining CMake
+ documentation objects are printed in command-line help output as
+ if the lines were normal paragraph text with interpretation.
+
+CMake Domain interpreted text roles
+ Interpreted text roles defined in the `CMake Domain`_ for
+ cross-referencing CMake documentation objects are replaced by their
+ link text in command-line help output. Other roles are printed
+ literally and not processed.
+
+``code-block`` directive
+ Add a literal code block without interpretation. The command-line
+ help processor prints the block content without the leading directive
+ line and with common indentation replaced by one space.
+
+``include`` directive
+ Include another document source file. The command-line help
+ processor prints the included document inline with the referencing
+ document.
+
+literal block after ``::``
+ A paragraph ending in ``::`` followed by a blank line treats
+ the following indented block as literal text without interpretation.
+ The command-line help processor prints the ``::`` literally and
+ prints the block content with common indentation replaced by one
+ space.
+
+``note`` directive
+ Call out a side note. The command-line help processor prints the
+ block content as if the lines were normal paragraph text with
+ interpretation.
+
+``parsed-literal`` directive
+ Add a literal block with markup interpretation. The command-line
+ help processor prints the block content without the leading
+ directive line and with common indentation replaced by one space.
+
+``productionlist`` directive
+ Render context-free grammar productions. The command-line help
+ processor prints the block content as if the lines were normal
+ paragraph text with interpretation.
+
+``replace`` directive
+ Define a ``|substitution|`` replacement.
+ The command-line help processor requires a substitution replacement
+ to be defined before it is referenced.
+
+``|substitution|`` reference
+ Reference a substitution replacement previously defined by
+ the ``replace`` directive. The command-line help processor
+ performs the substitution and replaces all newlines in the
+ replacement text with spaces.
+
+``toctree`` directive
+ Include other document sources in the Table-of-Contents
+ document tree. The command-line help processor prints
+ the referenced documents inline as part of the referencing
+ document.
+
+Inline markup constructs not listed above are printed literally in the
+command-line help output. We prefer to use inline markup constructs that
+look correct in source form, so avoid use of \\-escapes in favor of inline
+literals when possible.
+
+Explicit markup blocks not matching directives listed above are removed from
+command-line help output. Do not use them, except for plain ``..`` comments
+that are removed by Sphinx too.
+
+Note that nested indentation of blocks is not recognized by the
+command-line help processor. Therefore:
+
+* Explicit markup blocks are recognized only when not indented
+ inside other blocks.
+
+* Literal blocks after paragraphs ending in ``::`` but not
+ at the top indentation level may consume all indented lines
+ following them.
+
+Try to avoid these cases in practice.
+
+CMake Domain
+------------
+
+CMake adds a `Sphinx Domain`_ called ``cmake``, also called the
+"CMake Domain". It defines several "object" types for CMake
+documentation:
+
+``command``
+ A CMake language command.
+
+``generator``
+ A CMake native build system generator.
+ See the `cmake(1)`_ command-line tool's ``-G`` option.
+
+``manual``
+ A CMake manual page, like the `cmake(1)`_ manual.
+
+``module``
+ A CMake module.
+ See the `cmake-modules(7)`_ manual
+ and the `include()`_ command.
+
+``policy``
+ A CMake policy.
+ See the `cmake-policies(7)`_ manual
+ and the `cmake_policy()`_ command.
+
+``prop_cache, prop_dir, prop_gbl, prop_sf, prop_inst, prop_test, prop_tgt``
+ A CMake cache, directory, global, source file, installed file, test,
+ or target property, respectively. See the `cmake-properties(7)`_
+ manual and the `set_property()`_ command.
+
+``variable``
+ A CMake language variable.
+ See the `cmake-variables(7)`_ manual
+ and the `set()`_ command.
+
+Documentation objects in the CMake Domain come from two sources.
+First, the CMake extension to Sphinx transforms every document named
+with the form ``Help/<type>/<file-name>.rst`` to a domain object with
+type ``<type>``. The object name is extracted from the document title,
+which is expected to be of the form::
+
+ <object-name>
+ -------------
+
+and to appear at or near the top of the ``.rst`` file before any other
+lines starting in a letter, digit, or ``<``. If no such title appears
+literally in the ``.rst`` file, the object name is the ``<file-name>``.
+If a title does appear, it is expected that ``<file-name>`` is equal
+to ``<object-name>`` with any ``<`` and ``>`` characters removed.
+
+Second, the CMake Domain provides directives to define objects inside
+other documents:
+
+.. code-block:: rst
+
+ .. command:: <command-name>
+
+ This indented block documents <command-name>.
+
+ .. variable:: <variable-name>
+
+ This indented block documents <variable-name>.
+
+Object types for which no directive is available must be defined using
+the first approach above.
+
+.. _`Sphinx Domain`: http://sphinx-doc.org/domains.html
+.. _`cmake(1)`: https://cmake.org/cmake/help/latest/manual/cmake.1.html
+.. _`cmake-modules(7)`: https://cmake.org/cmake/help/latest/manual/cmake-modules.7.html
+.. _`cmake-policies(7)`: https://cmake.org/cmake/help/latest/manual/cmake-policies.7.html
+.. _`cmake-properties(7)`: https://cmake.org/cmake/help/latest/manual/cmake-properties.7.html
+.. _`cmake-variables(7)`: https://cmake.org/cmake/help/latest/manual/cmake-variables.7.html
+.. _`cmake_policy()`: https://cmake.org/cmake/help/latest/command/cmake_policy.html
+.. _`include()`: https://cmake.org/cmake/help/latest/command/include.html
+.. _`set()`: https://cmake.org/cmake/help/latest/command/set.html
+.. _`set_property()`: https://cmake.org/cmake/help/latest/command/set_property.html
+
+Cross-References
+----------------
+
+Sphinx uses reStructuredText interpreted text roles to provide
+cross-reference syntax. The `CMake Domain`_ provides for each
+domain object type a role of the same name to cross-reference it.
+CMake Domain roles are inline markup of the forms::
+
+ :type:`name`
+ :type:`text <name>`
+
+where ``type`` is the domain object type and ``name`` is the
+domain object name. In the first form the link text will be
+``name`` (or ``name()`` if the type is ``command``) and in
+the second form the link text will be the explicit ``text``.
+For example, the code:
+
+.. code-block:: rst
+
+ * The :command:`list` command.
+ * The :command:`list(APPEND)` sub-command.
+ * The :command:`list() command <list>`.
+ * The :command:`list(APPEND) sub-command <list>`.
+ * The :variable:`CMAKE_VERSION` variable.
+ * The :prop_tgt:`OUTPUT_NAME_<CONFIG>` target property.
+
+produces:
+
+* The `list()`_ command.
+* The `list(APPEND)`_ sub-command.
+* The `list() command`_.
+* The `list(APPEND) sub-command`_.
+* The `CMAKE_VERSION`_ variable.
+* The `OUTPUT_NAME_<CONFIG>`_ target property.
+
+Note that CMake Domain roles differ from Sphinx and reStructuredText
+convention in that the form ``a<b>``, without a space preceding ``<``,
+is interpreted as a name instead of link text with an explicit target.
+This is necessary because we use ``<placeholders>`` frequently in
+object names like ``OUTPUT_NAME_<CONFIG>``. The form ``a <b>``,
+with a space preceding ``<``, is still interpreted as a link text
+with an explicit target.
+
+.. _`list()`: https://cmake.org/cmake/help/latest/command/list.html
+.. _`list(APPEND)`: https://cmake.org/cmake/help/latest/command/list.html
+.. _`list(APPEND) sub-command`: https://cmake.org/cmake/help/latest/command/list.html
+.. _`list() command`: https://cmake.org/cmake/help/latest/command/list.html
+.. _`CMAKE_VERSION`: https://cmake.org/cmake/help/latest/variable/CMAKE_VERSION.html
+.. _`OUTPUT_NAME_<CONFIG>`: https://cmake.org/cmake/help/latest/prop_tgt/OUTPUT_NAME_CONFIG.html
+
+Style
+-----
+
+Style: Section Headers
+^^^^^^^^^^^^^^^^^^^^^^
+
+When marking section titles, make the section decoration line as long as
+the title text. Use only a line below the title, not above. For
+example:
+
+.. code-block:: rst
+
+ Title Text
+ ----------
+
+Capitalize the first letter of each non-minor word in the title.
+
+The section header underline character hierarchy is
+
+* ``#``: Manual group (part) in the master document
+* ``*``: Manual (chapter) title
+* ``=``: Section within a manual
+* ``-``: Subsection or `CMake Domain`_ object document title
+* ``^``: Subsubsection or `CMake Domain`_ object document section
+* ``"``: Paragraph or `CMake Domain`_ object document subsection
+
+Style: Whitespace
+^^^^^^^^^^^^^^^^^
+
+Use two spaces for indentation. Use two spaces between sentences in
+prose.
+
+Style: Line Length
+^^^^^^^^^^^^^^^^^^
+
+Prefer to restrict the width of lines to 75-80 columns. This is not a
+hard restriction, but writing new paragraphs wrapped at 75 columns
+allows space for adding minor content without significant re-wrapping of
+content.
+
+Style: Prose
+^^^^^^^^^^^^
+
+Use American English spellings in prose.
+
+Style: Starting Literal Blocks
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Prefer to mark the start of literal blocks with ``::`` at the end of
+the preceding paragraph. In cases where the following block gets
+a ``code-block`` marker, put a single ``:`` at the end of the preceding
+paragraph.
+
+Style: CMake Command Signatures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Command signatures should be marked up as plain literal blocks, not as
+cmake ``code-blocks``.
+
+Signatures are separated from preceding content by a section header.
+That is, use:
+
+.. code-block:: rst
+
+ ... preceding paragraph.
+
+ Normal Libraries
+ ^^^^^^^^^^^^^^^^
+
+ ::
+
+ add_library(<lib> ...)
+
+ This signature is used for ...
+
+Signatures of commands should wrap optional parts with square brackets,
+and should mark list of optional arguments with an ellipsis (``...``).
+Elements of the signature which are specified by the user should be
+specified with angle brackets, and may be referred to in prose using
+``inline-literal`` syntax.
+
+Style: Boolean Constants
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Use "``OFF``" and "``ON``" for boolean values which can be modified by
+the user, such as ``POSITION_INDEPENDENT_CODE``. Such properties
+may be "enabled" and "disabled". Use "``True``" and "``False``" for
+inherent values which can't be modified after being set, such as the
+``IMPORTED`` property of a build target.
+
+Style: Inline Literals
+^^^^^^^^^^^^^^^^^^^^^^
+
+Mark up references to keywords in signatures, file names, and other
+technical terms with ``inline-literal`` syntax, for example:
+
+.. code-block:: rst
+
+ If ``WIN32`` is used with :command:`add_executable`, the
+ :prop_tgt:`WIN32_EXECUTABLE` target property is enabled. That command
+ creates the file ``<name>.exe`` on Windows.
+
+Style: Cross-References
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Mark up linkable references as links, including repeats.
+An alternative, which is used by wikipedia
+(`<http://en.wikipedia.org/wiki/WP:REPEATLINK>`_),
+is to link to a reference only once per article. That style is not used
+in CMake documentation.
+
+Style: Referencing CMake Concepts
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+If referring to a concept which corresponds to a property, and that
+concept is described in a high-level manual, prefer to link to the
+manual section instead of the property. For example:
+
+.. code-block:: rst
+
+ This command creates an :ref:`Imported Target <Imported Targets>`.
+
+instead of:
+
+.. code-block:: rst
+
+ This command creates an :prop_tgt:`IMPORTED` target.
+
+The latter should be used only when referring specifically to the
+property.
+
+References to manual sections are not automatically created by creating
+a section, but code such as:
+
+.. code-block:: rst
+
+ .. _`Imported Targets`:
+
+creates a suitable anchor. Use an anchor name which matches the name
+of the corresponding section. Refer to the anchor using a
+cross-reference with specified text.
+
+Imported Targets need the ``IMPORTED`` term marked up with care in
+particular because the term may refer to a command keyword, a target
+property, or a concept.
+
+Where a property, command or variable is related conceptually to others,
+by for example, being related to the buildsystem description, generator
+expressions or Qt, each relevant property, command or variable should
+link to the primary manual, which provides high-level information. Only
+particular information relating to the command should be in the
+documentation of the command.
+
+Style: Referencing CMake Domain Objects
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+When referring to `CMake Domain`_ objects such as properties, variables,
+commands etc, prefer to link to the target object and follow that with
+the type of object it is. For example:
+
+.. code-block:: rst
+
+ Set the :prop_tgt:`AUTOMOC` target property to ``ON``.
+
+Instead of
+
+.. code-block:: rst
+
+ Set the target property :prop_tgt:`AUTOMOC` to ``ON``.
+
+The ``policy`` directive is an exception, and the type us usually
+referred to before the link:
+
+.. code-block:: rst
+
+ If policy :policy:`CMP0022` is set to ``NEW`` the behavior is ...
+
+However, markup self-references with ``inline-literal`` syntax.
+For example, within the ``add_executable`` command documentation, use
+
+.. code-block:: rst
+
+ ``add_executable``
+
+not
+
+.. code-block:: rst
+
+ :command:`add_executable`
+
+which is used elsewhere.
+
+Modules
+=======
+
+The ``Modules`` directory contains CMake-language ``.cmake`` module files.
+
+Module Documentation
+--------------------
+
+To document CMake module ``Modules/<module-name>.cmake``, modify
+``Help/manual/cmake-modules.7.rst`` to reference the module in the
+``toctree`` directive, in sorted order, as::
+
+ /module/<module-name>
+
+Then add the module document file ``Help/module/<module-name>.rst``
+containing just the line::
+
+ .. cmake-module:: ../../Modules/<module-name>.cmake
+
+The ``cmake-module`` directive will scan the module file to extract
+reStructuredText markup from comment blocks that start in ``.rst:``.
+At the top of ``Modules/<module-name>.cmake``, begin with the following
+license notice:
+
+::
+
+ # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ # file Copyright.txt or https://cmake.org/licensing for details.
+
+After this notice, add a *BLANK* line. Then, add documentation using
+a `Bracket Comment`_ of the form:
+
+::
+
+ #[=======================================================================[.rst:
+ <module-name>
+ -------------
+
+ <reStructuredText documentation of module>
+ #]=======================================================================]
+
+Any number of ``=`` may be used in the opening and closing brackets
+as long as they match. Content on the line containing the closing
+bracket is excluded if and only if the line starts in ``#``.
+
+Additional such ``.rst:`` comments may appear anywhere in the module file.
+All such comments must start with ``#`` in the first column.
+
+For example, a ``Findxxx.cmake`` module may contain:
+
+::
+
+ # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ # file Copyright.txt or https://cmake.org/licensing for details.
+
+ #[=======================================================================[.rst:
+ FindXxx
+ -------
+
+ This is a cool module.
+ This module does really cool stuff.
+ It can do even more than you think.
+
+ It even needs two paragraphs to tell you about it.
+ And it defines the following variables:
+
+ ``VAR_COOL``
+ this is great isn't it?
+ ``VAR_REALLY_COOL``
+ cool right?
+ #]=======================================================================]
+
+ <code>
+
+ #[=======================================================================[.rst:
+ .. command:: xxx_do_something
+
+ This command does something for Xxx::
+
+ xxx_do_something(some arguments)
+ #]=======================================================================]
+ macro(xxx_do_something)
+ <code>
+ endmacro()
+
+Test the documentation formatting by running
+``cmake --help-module <module-name>``, and also by enabling the
+``SPHINX_HTML`` and ``SPHINX_MAN`` options to build the documentation.
+Edit the comments until generated documentation looks satisfactory. To
+have a .cmake file in this directory NOT show up in the modules
+documentation, simply leave out the ``Help/module/<module-name>.rst``
+file and the ``Help/manual/cmake-modules.7.rst`` toctree entry.
+
+.. _`Bracket Comment`: https://cmake.org/cmake/help/latest/manual/cmake-language.7.html#bracket-comment
diff --git a/Help/envvar/ASM_DIALECT.rst b/Help/envvar/ASM_DIALECT.rst
new file mode 100644
index 000000000..a06e3cba2
--- /dev/null
+++ b/Help/envvar/ASM_DIALECT.rst
@@ -0,0 +1,14 @@
+ASM<DIALECT>
+------------
+
+.. include:: ENV_VAR.txt
+
+Preferred executable for compiling a specific dialect of assembly language
+files. ``ASM<DIALECT>`` can be ``ASM``, ``ASM_NASM`` (Netwide Assembler),
+``ASM_MASM`` (Microsoft Assembler) or ``ASM-ATT`` (Assembler AT&T).
+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..3c3b02a76
--- /dev/null
+++ b/Help/envvar/ASM_DIALECTFLAGS.rst
@@ -0,0 +1,13 @@
+ASM<DIALECT>FLAGS
+-----------------
+
+.. include:: ENV_VAR.txt
+
+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 ``CMAKE_ASM<DIALECT>_FLAGS <CMAKE_<LANG>_FLAGS>``. For any configuration
+run (including the first), the environment variable will be ignored, if the
+``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..ef120593e
--- /dev/null
+++ b/Help/envvar/CC.rst
@@ -0,0 +1,11 @@
+CC
+--
+
+.. include:: ENV_VAR.txt
+
+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..fda9ccc48
--- /dev/null
+++ b/Help/envvar/CFLAGS.rst
@@ -0,0 +1,11 @@
+CFLAGS
+------
+
+.. include:: ENV_VAR.txt
+
+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_BUILD_PARALLEL_LEVEL.rst b/Help/envvar/CMAKE_BUILD_PARALLEL_LEVEL.rst
new file mode 100644
index 000000000..199ca3e4b
--- /dev/null
+++ b/Help/envvar/CMAKE_BUILD_PARALLEL_LEVEL.rst
@@ -0,0 +1,11 @@
+CMAKE_BUILD_PARALLEL_LEVEL
+--------------------------
+
+.. include:: ENV_VAR.txt
+
+Specifies the maximum number of concurrent processes to use when building
+using the ``cmake --build`` command line
+:ref:`Build Tool Mode <Build Tool Mode>`.
+
+If this variable is defined empty the native build tool's default number is
+used.
diff --git a/Help/envvar/CMAKE_CONFIG_TYPE.rst b/Help/envvar/CMAKE_CONFIG_TYPE.rst
new file mode 100644
index 000000000..168593d50
--- /dev/null
+++ b/Help/envvar/CMAKE_CONFIG_TYPE.rst
@@ -0,0 +1,7 @@
+CMAKE_CONFIG_TYPE
+-----------------
+
+.. include:: ENV_VAR.txt
+
+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_GENERATOR.rst b/Help/envvar/CMAKE_GENERATOR.rst
new file mode 100644
index 000000000..f2d055f10
--- /dev/null
+++ b/Help/envvar/CMAKE_GENERATOR.rst
@@ -0,0 +1,16 @@
+CMAKE_GENERATOR
+---------------
+
+.. include:: ENV_VAR.txt
+
+Specifies the CMake default generator to use when no generator is supplied
+with ``-G``. If the provided value doesn't name a generator known by CMake,
+the internal default is used. Either way the resulting generator selection
+is stored in the :variable:`CMAKE_GENERATOR` variable.
+
+Some generators may be additionally configured using the environment
+variables:
+
+* :envvar:`CMAKE_GENERATOR_PLATFORM`
+* :envvar:`CMAKE_GENERATOR_TOOLSET`
+* :envvar:`CMAKE_GENERATOR_INSTANCE`
diff --git a/Help/envvar/CMAKE_GENERATOR_INSTANCE.rst b/Help/envvar/CMAKE_GENERATOR_INSTANCE.rst
new file mode 100644
index 000000000..1654fa1db
--- /dev/null
+++ b/Help/envvar/CMAKE_GENERATOR_INSTANCE.rst
@@ -0,0 +1,7 @@
+CMAKE_GENERATOR_INSTANCE
+------------------------
+
+.. include:: ENV_VAR.txt
+
+Default value for :variable:`CMAKE_GENERATOR_INSTANCE` if no Cache entry is
+present. This value is only applied if :envvar:`CMAKE_GENERATOR` is set.
diff --git a/Help/envvar/CMAKE_GENERATOR_PLATFORM.rst b/Help/envvar/CMAKE_GENERATOR_PLATFORM.rst
new file mode 100644
index 000000000..917b30b14
--- /dev/null
+++ b/Help/envvar/CMAKE_GENERATOR_PLATFORM.rst
@@ -0,0 +1,8 @@
+CMAKE_GENERATOR_PLATFORM
+------------------------
+
+.. include:: ENV_VAR.txt
+
+Default value for :variable:`CMAKE_GENERATOR_PLATFORM` if no Cache entry
+is present and no value is specified by :manual:`cmake(1)` ``-A`` option.
+This value is only applied if :envvar:`CMAKE_GENERATOR` is set.
diff --git a/Help/envvar/CMAKE_GENERATOR_TOOLSET.rst b/Help/envvar/CMAKE_GENERATOR_TOOLSET.rst
new file mode 100644
index 000000000..7ac3856a1
--- /dev/null
+++ b/Help/envvar/CMAKE_GENERATOR_TOOLSET.rst
@@ -0,0 +1,8 @@
+CMAKE_GENERATOR_TOOLSET
+-----------------------
+
+.. include:: ENV_VAR.txt
+
+Default value for :variable:`CMAKE_GENERATOR_TOOLSET` if no Cache entry
+is present and no value is specified by :manual:`cmake(1)` ``-T`` option.
+This value is only applied if :envvar:`CMAKE_GENERATOR` is set.
diff --git a/Help/envvar/CMAKE_MSVCIDE_RUN_PATH.rst b/Help/envvar/CMAKE_MSVCIDE_RUN_PATH.rst
new file mode 100644
index 000000000..77ead4d55
--- /dev/null
+++ b/Help/envvar/CMAKE_MSVCIDE_RUN_PATH.rst
@@ -0,0 +1,10 @@
+CMAKE_MSVCIDE_RUN_PATH
+----------------------
+
+.. include:: ENV_VAR.txt
+
+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_NO_VERBOSE.rst b/Help/envvar/CMAKE_NO_VERBOSE.rst
new file mode 100644
index 000000000..149efbd6f
--- /dev/null
+++ b/Help/envvar/CMAKE_NO_VERBOSE.rst
@@ -0,0 +1,8 @@
+CMAKE_NO_VERBOSE
+----------------
+
+Disables verbose output from CMake when :envvar:`VERBOSE` environment variable
+is set.
+
+Only your build tool of choice will still print verbose output when you start
+to actually build your project.
diff --git a/Help/envvar/CMAKE_OSX_ARCHITECTURES.rst b/Help/envvar/CMAKE_OSX_ARCHITECTURES.rst
new file mode 100644
index 000000000..ef7d5470b
--- /dev/null
+++ b/Help/envvar/CMAKE_OSX_ARCHITECTURES.rst
@@ -0,0 +1,10 @@
+CMAKE_OSX_ARCHITECTURES
+-----------------------
+
+.. include:: ENV_VAR.txt
+
+Target specific architectures for macOS.
+
+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..404bb5930
--- /dev/null
+++ b/Help/envvar/CSFLAGS.rst
@@ -0,0 +1,11 @@
+CSFLAGS
+-------
+
+.. include:: ENV_VAR.txt
+
+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..e1991b2df
--- /dev/null
+++ b/Help/envvar/CTEST_INTERACTIVE_DEBUG_MODE.rst
@@ -0,0 +1,7 @@
+CTEST_INTERACTIVE_DEBUG_MODE
+----------------------------
+
+.. include:: ENV_VAR.txt
+
+Environment variable that will exist and be set to ``1`` when a test executed
+by :manual:`ctest(1)` 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..d8b42624f
--- /dev/null
+++ b/Help/envvar/CTEST_OUTPUT_ON_FAILURE.rst
@@ -0,0 +1,9 @@
+CTEST_OUTPUT_ON_FAILURE
+-----------------------
+
+.. include:: ENV_VAR.txt
+
+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..fd4936e37
--- /dev/null
+++ b/Help/envvar/CTEST_PARALLEL_LEVEL.rst
@@ -0,0 +1,7 @@
+CTEST_PARALLEL_LEVEL
+--------------------
+
+.. include:: ENV_VAR.txt
+
+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_PROGRESS_OUTPUT.rst b/Help/envvar/CTEST_PROGRESS_OUTPUT.rst
new file mode 100644
index 000000000..b36a6b8c2
--- /dev/null
+++ b/Help/envvar/CTEST_PROGRESS_OUTPUT.rst
@@ -0,0 +1,16 @@
+CTEST_PROGRESS_OUTPUT
+---------------------
+
+.. include:: ENV_VAR.txt
+
+Boolean environment variable that affects how :manual:`ctest <ctest(1)>`
+command output reports overall progress. When set to ``1``, ``TRUE``, ``ON`` or anything
+else that evaluates to boolean true, progress is reported by repeatedly
+updating the same line. This greatly reduces the overall verbosity, but is
+only supported when output is sent directly to a terminal. If the environment
+variable is not set or has a value that evaluates to false, output is reported
+normally with each test having its own start and end lines logged to the
+output.
+
+The ``--progress`` option to :manual:`ctest <ctest(1)>` overrides this
+environment variable if both are given.
diff --git a/Help/envvar/CTEST_USE_LAUNCHERS_DEFAULT.rst b/Help/envvar/CTEST_USE_LAUNCHERS_DEFAULT.rst
new file mode 100644
index 000000000..79dbb79f3
--- /dev/null
+++ b/Help/envvar/CTEST_USE_LAUNCHERS_DEFAULT.rst
@@ -0,0 +1,6 @@
+CTEST_USE_LAUNCHERS_DEFAULT
+---------------------------
+
+.. include:: ENV_VAR.txt
+
+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..10c0f9dd7
--- /dev/null
+++ b/Help/envvar/CUDACXX.rst
@@ -0,0 +1,11 @@
+CUDACXX
+-------
+
+.. include:: ENV_VAR.txt
+
+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..4456d6bf8
--- /dev/null
+++ b/Help/envvar/CUDAFLAGS.rst
@@ -0,0 +1,11 @@
+CUDAFLAGS
+---------
+
+.. include:: ENV_VAR.txt
+
+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..b9f65bd1e
--- /dev/null
+++ b/Help/envvar/CUDAHOSTCXX.rst
@@ -0,0 +1,15 @@
+CUDAHOSTCXX
+-----------
+
+.. include:: ENV_VAR.txt
+
+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.
+
+This environment variable is primarily meant for use with projects that
+enable ``CUDA`` as a first-class language. The :module:`FindCUDA`
+module will also use it to initialize its ``CUDA_HOST_COMPILER`` setting.
diff --git a/Help/envvar/CXX.rst b/Help/envvar/CXX.rst
new file mode 100644
index 000000000..d6553501a
--- /dev/null
+++ b/Help/envvar/CXX.rst
@@ -0,0 +1,11 @@
+CXX
+---
+
+.. include:: ENV_VAR.txt
+
+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..d7296dca0
--- /dev/null
+++ b/Help/envvar/CXXFLAGS.rst
@@ -0,0 +1,11 @@
+CXXFLAGS
+--------
+
+.. include:: ENV_VAR.txt
+
+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..6a52d6494
--- /dev/null
+++ b/Help/envvar/DASHBOARD_TEST_FROM_CTEST.rst
@@ -0,0 +1,8 @@
+DASHBOARD_TEST_FROM_CTEST
+-------------------------
+
+.. include:: ENV_VAR.txt
+
+Environment variable that will exist when a test executed by :manual:`ctest(1)`
+is run in non-interactive mode. The value will be equal to
+:variable:`CMAKE_VERSION`.
diff --git a/Help/envvar/DESTDIR.rst b/Help/envvar/DESTDIR.rst
new file mode 100644
index 000000000..d2144ae7c
--- /dev/null
+++ b/Help/envvar/DESTDIR.rst
@@ -0,0 +1,21 @@
+DESTDIR
+-------
+
+.. include:: ENV_VAR.txt
+
+On UNIX one can use the ``DESTDIR`` mechanism in order to relocate the
+whole installation. ``DESTDIR`` means DESTination DIRectory. It is
+commonly used by makefile users in order to install software at
+non-default location. It is usually invoked like this:
+
+::
+
+ make DESTDIR=/home/john install
+
+which will install the concerned software using the installation
+prefix, e.g. ``/usr/local`` prepended with the ``DESTDIR`` value which
+finally gives ``/home/john/usr/local``.
+
+WARNING: ``DESTDIR`` may not be used on Windows because installation
+prefix usually contains a drive letter like in ``C:/Program Files``
+which cannot be prepended with some other prefix.
diff --git a/Help/envvar/ENV_VAR.txt b/Help/envvar/ENV_VAR.txt
new file mode 100644
index 000000000..e1e70cd99
--- /dev/null
+++ b/Help/envvar/ENV_VAR.txt
@@ -0,0 +1,3 @@
+This is a CMake :ref:`Environment Variable <CMake Language
+Environment Variables>`. Its initial value is taken from
+the calling process environment.
diff --git a/Help/envvar/FC.rst b/Help/envvar/FC.rst
new file mode 100644
index 000000000..d6cabbc90
--- /dev/null
+++ b/Help/envvar/FC.rst
@@ -0,0 +1,12 @@
+FC
+--
+
+.. include:: ENV_VAR.txt
+
+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..02d3c3461
--- /dev/null
+++ b/Help/envvar/FFLAGS.rst
@@ -0,0 +1,11 @@
+FFLAGS
+------
+
+.. include:: ENV_VAR.txt
+
+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..816d6ef77
--- /dev/null
+++ b/Help/envvar/LDFLAGS.rst
@@ -0,0 +1,12 @@
+LDFLAGS
+-------
+
+.. include:: ENV_VAR.txt
+
+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..662bd03ec
--- /dev/null
+++ b/Help/envvar/MACOSX_DEPLOYMENT_TARGET.rst
@@ -0,0 +1,10 @@
+MACOSX_DEPLOYMENT_TARGET
+------------------------
+
+.. include:: ENV_VAR.txt
+
+Specify the minimum version of macOS 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/PackageName_ROOT.rst b/Help/envvar/PackageName_ROOT.rst
new file mode 100644
index 000000000..82b0a069e
--- /dev/null
+++ b/Help/envvar/PackageName_ROOT.rst
@@ -0,0 +1,17 @@
+<PackageName>_ROOT
+------------------
+
+.. include:: ENV_VAR.txt
+
+Calls to :command:`find_package(<PackageName>)` will search in prefixes
+specified by the ``<PackageName>_ROOT`` environment variable, where
+``<PackageName>`` is the name given to the :command:`find_package` call
+and ``_ROOT`` is literal. For example, ``find_package(Foo)`` will search
+prefixes specified in the ``Foo_ROOT`` environment variable (if set).
+See policy :policy:`CMP0074`.
+
+This variable may hold a single prefix or a list of prefixes separated
+by ``:`` on UNIX or ``;`` on Windows (the same as the ``PATH`` environment
+variable convention on those platforms).
+
+See also the :variable:`<PackageName>_ROOT` CMake variable.
diff --git a/Help/envvar/RC.rst b/Help/envvar/RC.rst
new file mode 100644
index 000000000..557520e8f
--- /dev/null
+++ b/Help/envvar/RC.rst
@@ -0,0 +1,11 @@
+RC
+--
+
+.. include:: ENV_VAR.txt
+
+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..45419fed1
--- /dev/null
+++ b/Help/envvar/RCFLAGS.rst
@@ -0,0 +1,11 @@
+RCFLAGS
+-------
+
+.. include:: ENV_VAR.txt
+
+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/envvar/SWIFTC.rst b/Help/envvar/SWIFTC.rst
new file mode 100644
index 000000000..b12e51df9
--- /dev/null
+++ b/Help/envvar/SWIFTC.rst
@@ -0,0 +1,11 @@
+SWIFTC
+------
+
+.. include:: ENV_VAR.txt
+
+Preferred executable for compiling ``Swift`` language files. Will only be used by
+CMake on the first configuration to determine ``Swift`` compiler, after which the
+value for ``SWIFTC`` is stored in the cache as
+:variable:`CMAKE_Swift_COMPILER <CMAKE_<LANG>_COMPILER>`. For any configuration run
+(including the first), the environment variable will be ignored if the
+:variable:`CMAKE_Swift_COMPILER <CMAKE_<LANG>_COMPILER>` variable is defined.
diff --git a/Help/envvar/VERBOSE.rst b/Help/envvar/VERBOSE.rst
new file mode 100644
index 000000000..2d775a5be
--- /dev/null
+++ b/Help/envvar/VERBOSE.rst
@@ -0,0 +1,10 @@
+VERBOSE
+-------
+
+Activates verbose output from CMake and your build tools of choice when
+you start to actually build your project.
+
+Note that any given value is ignored. It's just checked for existence.
+
+See also :ref:`Build Tool Mode <Build Tool Mode>` and
+:envvar:`CMAKE_NO_VERBOSE` environment variable
diff --git a/Help/generator/Visual Studio 16 2019.rst b/Help/generator/Visual Studio 16 2019.rst
new file mode 100644
index 000000000..4aec7f73c
--- /dev/null
+++ b/Help/generator/Visual Studio 16 2019.rst
@@ -0,0 +1,54 @@
+Visual Studio 16 2019
+---------------------
+
+Generates Visual Studio 16 (VS 2019) project files.
+
+Project Types
+^^^^^^^^^^^^^
+
+Only Visual C++ and C# projects may be generated. Other types of
+projects (JavaScript, Powershell, Python, etc.) are not supported.
+
+Instance Selection
+^^^^^^^^^^^^^^^^^^
+
+VS 2019 supports multiple installations on the same machine.
+The :variable:`CMAKE_GENERATOR_INSTANCE` variable may be set as a
+cache entry containing the absolute path to a Visual Studio instance.
+If the value is not specified explicitly by the user or a toolchain file,
+CMake queries the Visual Studio Installer to locate VS instances, chooses
+one, and sets the variable as a cache entry to hold the value persistently.
+
+When CMake first chooses an instance, if the ``VS160COMNTOOLS`` environment
+variable is set and points to the ``Common7/Tools`` directory within
+one of the instances, that instance will be used. Otherwise, if more
+than one instance is installed we do not define which one is chosen
+by default.
+
+Platform Selection
+^^^^^^^^^^^^^^^^^^
+
+The default target platform name (architecture) is that of the host
+and is provided in the :variable:`CMAKE_VS_PLATFORM_NAME_DEFAULT` variable.
+
+The :variable:`CMAKE_GENERATOR_PLATFORM` variable may be set, perhaps
+via the :manual:`cmake(1)` ``-A`` option, to specify a target platform
+name (architecture). For example:
+
+* ``cmake -G "Visual Studio 16 2019" -A Win32``
+* ``cmake -G "Visual Studio 16 2019" -A x64``
+* ``cmake -G "Visual Studio 16 2019" -A ARM``
+* ``cmake -G "Visual Studio 16 2019" -A ARM64``
+
+Toolset Selection
+^^^^^^^^^^^^^^^^^
+
+The ``v142`` toolset that comes with Visual Studio 16 2019 is selected by
+default. The :variable:`CMAKE_GENERATOR_TOOLSET` option may be set, perhaps
+via the :manual:`cmake(1)` ``-T`` option, to specify another toolset.
+
+.. |VS_TOOLSET_HOST_ARCH_DEFAULT| replace::
+ By default this generator uses the 64-bit variant on x64 hosts and
+ the 32-bit variant otherwise.
+
+.. include:: VS_TOOLSET_HOST_ARCH.txt
diff --git a/Help/manual/cmake-env-variables.7.rst b/Help/manual/cmake-env-variables.7.rst
new file mode 100644
index 000000000..96ceb945a
--- /dev/null
+++ b/Help/manual/cmake-env-variables.7.rst
@@ -0,0 +1,73 @@
+.. cmake-manual-description: CMake Environment Variables Reference
+
+cmake-env-variables(7)
+**********************
+
+.. only:: html
+
+ .. contents::
+
+This page lists environment variables that have special
+meaning to CMake.
+
+For general information on environment variables, see the
+:ref:`Environment Variables <CMake Language Environment Variables>`
+section in the cmake-language manual.
+
+
+Environment Variables that Control the Build
+============================================
+
+.. toctree::
+ :maxdepth: 1
+
+ /envvar/CMAKE_BUILD_PARALLEL_LEVEL
+ /envvar/CMAKE_CONFIG_TYPE
+ /envvar/CMAKE_GENERATOR
+ /envvar/CMAKE_GENERATOR_INSTANCE
+ /envvar/CMAKE_GENERATOR_PLATFORM
+ /envvar/CMAKE_GENERATOR_TOOLSET
+ /envvar/CMAKE_MSVCIDE_RUN_PATH
+ /envvar/CMAKE_NO_VERBOSE
+ /envvar/CMAKE_OSX_ARCHITECTURES
+ /envvar/DESTDIR
+ /envvar/LDFLAGS
+ /envvar/MACOSX_DEPLOYMENT_TARGET
+ /envvar/PackageName_ROOT
+ /envvar/VERBOSE
+
+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
+ /envvar/SWIFTC
+
+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_PROGRESS_OUTPUT
+ /envvar/CTEST_USE_LAUNCHERS_DEFAULT
+ /envvar/DASHBOARD_TEST_FROM_CTEST
diff --git a/Help/manual/cmake-file-api.7.rst b/Help/manual/cmake-file-api.7.rst
new file mode 100644
index 000000000..04b6ed259
--- /dev/null
+++ b/Help/manual/cmake-file-api.7.rst
@@ -0,0 +1,1113 @@
+.. cmake-manual-description: CMake File-Based API
+
+cmake-file-api(7)
+*****************
+
+.. only:: html
+
+ .. contents::
+
+Introduction
+============
+
+CMake provides a file-based API that clients may use to get semantic
+information about the buildsystems CMake generates. Clients may use
+the API by writing query files to a specific location in a build tree
+to request zero or more `Object Kinds`_. When CMake generates the
+buildsystem in that build tree it will read the query files and write
+reply files for the client to read.
+
+The file-based API uses a ``<build>/.cmake/api/`` directory at the top
+of a build tree. The API is versioned to support changes to the layout
+of files within the API directory. API file layout versioning is
+orthogonal to the versioning of `Object Kinds`_ used in replies.
+This version of CMake supports only one API version, `API v1`_.
+
+API v1
+======
+
+API v1 is housed in the ``<build>/.cmake/api/v1/`` directory.
+It has the following subdirectories:
+
+``query/``
+ Holds query files written by clients.
+ These may be `v1 Shared Stateless Query Files`_,
+ `v1 Client Stateless Query Files`_, or `v1 Client Stateful Query Files`_.
+
+``reply/``
+ Holds reply files written by CMake whenever it runs to generate a build
+ system. These are indexed by a `v1 Reply Index File`_ file that may
+ reference additional `v1 Reply Files`_. CMake owns all reply files.
+ Clients must never remove them.
+
+ Clients may look for and read a reply index file at any time.
+ Clients may optionally create the ``reply/`` directory at any time
+ and monitor it for the appearance of a new reply index file.
+
+v1 Shared Stateless Query Files
+-------------------------------
+
+Shared stateless query files allow clients to share requests for
+major versions of the `Object Kinds`_ and get all requested versions
+recognized by the CMake that runs.
+
+Clients may create shared requests by creating empty files in the
+``v1/query/`` directory. The form is::
+
+ <build>/.cmake/api/v1/query/<kind>-v<major>
+
+where ``<kind>`` is one of the `Object Kinds`_, ``-v`` is literal,
+and ``<major>`` is the major version number.
+
+Files of this form are stateless shared queries not owned by any specific
+client. Once created they should not be removed without external client
+coordination or human intervention.
+
+v1 Client Stateless Query Files
+-------------------------------
+
+Client stateless query files allow clients to create owned requests for
+major versions of the `Object Kinds`_ and get all requested versions
+recognized by the CMake that runs.
+
+Clients may create owned requests by creating empty files in
+client-specific query subdirectories. The form is::
+
+ <build>/.cmake/api/v1/query/client-<client>/<kind>-v<major>
+
+where ``client-`` is literal, ``<client>`` is a string uniquely
+identifying the client, ``<kind>`` is one of the `Object Kinds`_,
+``-v`` is literal, and ``<major>`` is the major version number.
+Each client must choose a unique ``<client>`` identifier via its
+own means.
+
+Files of this form are stateless queries owned by the client ``<client>``.
+The owning client may remove them at any time.
+
+v1 Client Stateful Query Files
+------------------------------
+
+Stateful query files allow clients to request a list of versions of
+each of the `Object Kinds`_ and get only the most recent version
+recognized by the CMake that runs.
+
+Clients may create owned stateful queries by creating ``query.json``
+files in client-specific query subdirectories. The form is::
+
+ <build>/.cmake/api/v1/query/client-<client>/query.json
+
+where ``client-`` is literal, ``<client>`` is a string uniquely
+identifying the client, and ``query.json`` is literal. Each client
+must choose a unique ``<client>`` identifier via its own means.
+
+``query.json`` files are stateful queries owned by the client ``<client>``.
+The owning client may update or remove them at any time. When a
+given client installation is updated it may then update the stateful
+query it writes to build trees to request newer object versions.
+This can be used to avoid asking CMake to generate multiple object
+versions unnecessarily.
+
+A ``query.json`` file must contain a JSON object:
+
+.. code-block:: json
+
+ {
+ "requests": [
+ { "kind": "<kind>" , "version": 1 },
+ { "kind": "<kind>" , "version": { "major": 1, "minor": 2 } },
+ { "kind": "<kind>" , "version": [2, 1] },
+ { "kind": "<kind>" , "version": [2, { "major": 1, "minor": 2 }] },
+ { "kind": "<kind>" , "version": 1, "client": {} },
+ { "kind": "..." }
+ ],
+ "client": {}
+ }
+
+The members are:
+
+``requests``
+ A JSON array containing zero or more requests. Each request is
+ a JSON object with members:
+
+ ``kind``
+ Specifies one of the `Object Kinds`_ to be included in the reply.
+
+ ``version``
+ Indicates the version(s) of the object kind that the client
+ understands. Versions have major and minor components following
+ semantic version conventions. The value must be
+
+ * a JSON integer specifying a (non-negative) major version number, or
+ * a JSON object containing ``major`` and (optionally) ``minor``
+ members specifying non-negative integer version components, or
+ * a JSON array whose elements are each one of the above.
+
+ ``client``
+ Optional member reserved for use by the client. This value is
+ preserved in the reply written for the client in the
+ `v1 Reply Index File`_ but is otherwise ignored. Clients may use
+ this to pass custom information with a request through to its reply.
+
+ For each requested object kind CMake will choose the *first* version
+ that it recognizes for that kind among those listed in the request.
+ The response will use the selected *major* version with the highest
+ *minor* version known to the running CMake for that major version.
+ Therefore clients should list all supported major versions in
+ preferred order along with the minimal minor version required
+ for each major version.
+
+``client``
+ Optional member reserved for use by the client. This value is
+ preserved in the reply written for the client in the
+ `v1 Reply Index File`_ but is otherwise ignored. Clients may use
+ this to pass custom information with a query through to its reply.
+
+Other ``query.json`` top-level members are reserved for future use.
+If present they are ignored for forward compatibility.
+
+v1 Reply Index File
+-------------------
+
+CMake writes an ``index-*.json`` file to the ``v1/reply/`` directory
+whenever it runs to generate a build system. Clients must read the
+reply index file first and may read other `v1 Reply Files`_ only by
+following references. The form of the reply index file name is::
+
+ <build>/.cmake/api/v1/reply/index-<unspecified>.json
+
+where ``index-`` is literal and ``<unspecified>`` is an unspecified
+name selected by CMake. Whenever a new index file is generated it
+is given a new name and any old one is deleted. During the short
+time between these steps there may be multiple index files present;
+the one with the largest name in lexicographic order is the current
+index file.
+
+The reply index file contains a JSON object:
+
+.. code-block:: json
+
+ {
+ "cmake": {
+ "version": {
+ "major": 3, "minor": 14, "patch": 0, "suffix": "",
+ "string": "3.14.0", "isDirty": false
+ },
+ "paths": {
+ "cmake": "/prefix/bin/cmake",
+ "ctest": "/prefix/bin/ctest",
+ "cpack": "/prefix/bin/cpack",
+ "root": "/prefix/share/cmake-3.14"
+ },
+ "generator": {
+ "name": "Unix Makefiles"
+ }
+ },
+ "objects": [
+ { "kind": "<kind>",
+ "version": { "major": 1, "minor": 0 },
+ "jsonFile": "<file>" },
+ { "...": "..." }
+ ],
+ "reply": {
+ "<kind>-v<major>": { "kind": "<kind>",
+ "version": { "major": 1, "minor": 0 },
+ "jsonFile": "<file>" },
+ "<unknown>": { "error": "unknown query file" },
+ "...": {},
+ "client-<client>": {
+ "<kind>-v<major>": { "kind": "<kind>",
+ "version": { "major": 1, "minor": 0 },
+ "jsonFile": "<file>" },
+ "<unknown>": { "error": "unknown query file" },
+ "...": {},
+ "query.json": {
+ "requests": [ {}, {}, {} ],
+ "responses": [
+ { "kind": "<kind>",
+ "version": { "major": 1, "minor": 0 },
+ "jsonFile": "<file>" },
+ { "error": "unknown query file" },
+ { "...": {} }
+ ],
+ "client": {}
+ }
+ }
+ }
+ }
+
+The members are:
+
+``cmake``
+ A JSON object containing information about the instance of CMake that
+ generated the reply. It contains members:
+
+ ``version``
+ A JSON object specifying the version of CMake with members:
+
+ ``major``, ``minor``, ``patch``
+ Integer values specifying the major, minor, and patch version components.
+ ``suffix``
+ A string specifying the version suffix, if any, e.g. ``g0abc3``.
+ ``string``
+ A string specifying the full version in the format
+ ``<major>.<minor>.<patch>[-<suffix>]``.
+ ``isDirty``
+ A boolean indicating whether the version was built from a version
+ controlled source tree with local modifications.
+
+ ``paths``
+ A JSON object specifying paths to things that come with CMake.
+ It has members for ``cmake``, ``ctest``, and ``cpack`` whose values
+ are JSON strings specifying the absolute path to each tool,
+ represented with forward slashes. It also has a ``root`` member for
+ the absolute path to the directory containing CMake resources like the
+ ``Modules/`` directory (see :variable:`CMAKE_ROOT`).
+
+ ``generator``
+ A JSON object describing the CMake generator used for the build.
+ It has members:
+
+ ``name``
+ A string specifying the name of the generator.
+ ``platform``
+ If the generator supports :variable:`CMAKE_GENERATOR_PLATFORM`,
+ this is a string specifying the generator platform name.
+
+``objects``
+ A JSON array listing all versions of all `Object Kinds`_ generated
+ as part of the reply. Each array entry is a
+ `v1 Reply File Reference`_.
+
+``reply``
+ A JSON object mirroring the content of the ``query/`` directory
+ that CMake loaded to produce the reply. The members are of the form
+
+ ``<kind>-v<major>``
+ A member of this form appears for each of the
+ `v1 Shared Stateless Query Files`_ that CMake recognized as a
+ request for object kind ``<kind>`` with major version ``<major>``.
+ The value is a `v1 Reply File Reference`_ to the corresponding
+ reply file for that object kind and version.
+
+ ``<unknown>``
+ A member of this form appears for each of the
+ `v1 Shared Stateless Query Files`_ that CMake did not recognize.
+ The value is a JSON object with a single ``error`` member
+ containing a string with an error message indicating that the
+ query file is unknown.
+
+ ``client-<client>``
+ A member of this form appears for each client-owned directory
+ holding `v1 Client Stateless Query Files`_.
+ The value is a JSON object mirroring the content of the
+ ``query/client-<client>/`` directory. The members are of the form:
+
+ ``<kind>-v<major>``
+ A member of this form appears for each of the
+ `v1 Client Stateless Query Files`_ that CMake recognized as a
+ request for object kind ``<kind>`` with major version ``<major>``.
+ The value is a `v1 Reply File Reference`_ to the corresponding
+ reply file for that object kind and version.
+
+ ``<unknown>``
+ A member of this form appears for each of the
+ `v1 Client Stateless Query Files`_ that CMake did not recognize.
+ The value is a JSON object with a single ``error`` member
+ containing a string with an error message indicating that the
+ query file is unknown.
+
+ ``query.json``
+ This member appears for clients using
+ `v1 Client Stateful Query Files`_.
+ If the ``query.json`` file failed to read or parse as a JSON object,
+ this member is a JSON object with a single ``error`` member
+ containing a string with an error message. Otherwise, this member
+ is a JSON object mirroring the content of the ``query.json`` file.
+ The members are:
+
+ ``client``
+ A copy of the ``query.json`` file ``client`` member, if it exists.
+
+ ``requests``
+ A copy of the ``query.json`` file ``requests`` member, if it exists.
+
+ ``responses``
+ If the ``query.json`` file ``requests`` member is missing or invalid,
+ this member is a JSON object with a single ``error`` member
+ containing a string with an error message. Otherwise, this member
+ contains a JSON array with a response for each entry of the
+ ``requests`` array, in the same order. Each response is
+
+ * a JSON object with a single ``error`` member containing a string
+ with an error message, or
+ * a `v1 Reply File Reference`_ to the corresponding reply file for
+ the requested object kind and selected version.
+
+After reading the reply index file, clients may read the other
+`v1 Reply Files`_ it references.
+
+v1 Reply File Reference
+^^^^^^^^^^^^^^^^^^^^^^^
+
+The reply index file represents each reference to another reply file
+using a JSON object with members:
+
+``kind``
+ A string specifying one of the `Object Kinds`_.
+``version``
+ A JSON object with members ``major`` and ``minor`` specifying
+ integer version components of the object kind.
+``jsonFile``
+ A JSON string specifying a path relative to the reply index file
+ to another JSON file containing the object.
+
+v1 Reply Files
+--------------
+
+Reply files containing specific `Object Kinds`_ are written by CMake.
+The names of these files are unspecified and must not be interpreted
+by clients. Clients must first read the `v1 Reply Index File`_ and
+and follow references to the names of the desired response objects.
+
+Reply files (including the index file) will never be replaced by
+files of the same name but different content. This allows a client
+to read the files concurrently with a running CMake that may generate
+a new reply. However, after generating a new reply CMake will attempt
+to remove reply files from previous runs that it did not just write.
+If a client attempts to read a reply file referenced by the index but
+finds the file missing, that means a concurrent CMake has generated
+a new reply. The client may simply start again by reading the new
+reply index file.
+
+.. _`file-api object kinds`:
+
+Object Kinds
+============
+
+The CMake file-based API reports semantic information about the build
+system using the following kinds of JSON objects. Each kind of object
+is versioned independently using semantic versioning with major and
+minor components. Every kind of object has the form:
+
+.. code-block:: json
+
+ {
+ "kind": "<kind>",
+ "version": { "major": 1, "minor": 0 },
+ "...": {}
+ }
+
+The ``kind`` member is a string specifying the object kind name.
+The ``version`` member is a JSON object with ``major`` and ``minor``
+members specifying integer components of the object kind's version.
+Additional top-level members are specific to each object kind.
+
+Object Kind "codemodel"
+-----------------------
+
+The ``codemodel`` object kind describes the build system structure as
+modeled by CMake.
+
+There is only one ``codemodel`` object major version, version 2.
+Version 1 does not exist to avoid confusion with that from
+:manual:`cmake-server(7)` mode.
+
+"codemodel" version 2
+^^^^^^^^^^^^^^^^^^^^^
+
+``codemodel`` object version 2 is a JSON object:
+
+.. code-block:: json
+
+ {
+ "kind": "codemodel",
+ "version": { "major": 2, "minor": 0 },
+ "paths": {
+ "source": "/path/to/top-level-source-dir",
+ "build": "/path/to/top-level-build-dir"
+ },
+ "configurations": [
+ {
+ "name": "Debug",
+ "directories": [
+ {
+ "source": ".",
+ "build": ".",
+ "childIndexes": [ 1 ],
+ "projectIndex": 0,
+ "targetIndexes": [ 0 ],
+ "hasInstallRule": true,
+ "minimumCMakeVersion": {
+ "string": "3.14"
+ }
+ },
+ {
+ "source": "sub",
+ "build": "sub",
+ "parentIndex": 0,
+ "projectIndex": 0,
+ "targetIndexes": [ 1 ],
+ "minimumCMakeVersion": {
+ "string": "3.14"
+ }
+ }
+ ],
+ "projects": [
+ {
+ "name": "MyProject",
+ "directoryIndexes": [ 0, 1 ],
+ "targetIndexes": [ 0, 1 ]
+ }
+ ],
+ "targets": [
+ {
+ "name": "MyExecutable",
+ "directoryIndex": 0,
+ "projectIndex": 0,
+ "jsonFile": "<file>"
+ },
+ {
+ "name": "MyLibrary",
+ "directoryIndex": 1,
+ "projectIndex": 0,
+ "jsonFile": "<file>"
+ }
+ ]
+ }
+ ]
+ }
+
+The members specific to ``codemodel`` objects are:
+
+``paths``
+ A JSON object containing members:
+
+ ``source``
+ A string specifying the absolute path to the top-level source directory,
+ represented with forward slashes.
+
+ ``build``
+ A string specifying the absolute path to the top-level build directory,
+ represented with forward slashes.
+
+``configurations``
+ A JSON array of entries corresponding to available build configurations.
+ On single-configuration generators there is one entry for the value
+ of the :variable:`CMAKE_BUILD_TYPE` variable. For multi-configuration
+ generators there is an entry for each configuration listed in the
+ :variable:`CMAKE_CONFIGURATION_TYPES` variable.
+ Each entry is a JSON object containing members:
+
+ ``name``
+ A string specifying the name of the configuration, e.g. ``Debug``.
+
+ ``directories``
+ A JSON array of entries each corresponding to a build system directory
+ whose source directory contains a ``CMakeLists.txt`` file. The first
+ entry corresponds to the top-level directory. Each entry is a
+ JSON object containing members:
+
+ ``source``
+ A string specifying the path to the source directory, represented
+ with forward slashes. If the directory is inside the top-level
+ source directory then the path is specified relative to that
+ directory (with ``.`` for the top-level source directory itself).
+ Otherwise the path is absolute.
+
+ ``build``
+ A string specifying the path to the build directory, represented
+ with forward slashes. If the directory is inside the top-level
+ build directory then the path is specified relative to that
+ directory (with ``.`` for the top-level build directory itself).
+ Otherwise the path is absolute.
+
+ ``parentIndex``
+ Optional member that is present when the directory is not top-level.
+ The value is an unsigned integer 0-based index of another entry in
+ the main ``directories`` array that corresponds to the parent
+ directory that added this directory as a subdirectory.
+
+ ``childIndexes``
+ Optional member that is present when the directory has subdirectories.
+ The value is a JSON array of entries corresponding to child directories
+ created by the :command:`add_subdirectory` or :command:`subdirs`
+ command. Each entry is an unsigned integer 0-based index of another
+ entry in the main ``directories`` array.
+
+ ``projectIndex``
+ An unsigned integer 0-based index into the main ``projects`` array
+ indicating the build system project to which the this directory belongs.
+
+ ``targetIndexes``
+ Optional member that is present when the directory itself has targets,
+ excluding those belonging to subdirectories. The value is a JSON
+ array of entries corresponding to the targets. Each entry is an
+ unsigned integer 0-based index into the main ``targets`` array.
+
+ ``minimumCMakeVersion``
+ Optional member present when a minimum required version of CMake is
+ known for the directory. This is the ``<min>`` version given to the
+ most local call to the :command:`cmake_minimum_required(VERSION)`
+ command in the directory itself or one of its ancestors.
+ The value is a JSON object with one member:
+
+ ``string``
+ A string specifying the minimum required version in the format::
+
+ <major>.<minor>[.<patch>[.<tweak>]][<suffix>]
+
+ Each component is an unsigned integer and the suffix may be an
+ arbitrary string.
+
+ ``hasInstallRule``
+ Optional member that is present with boolean value ``true`` when
+ the directory or one of its subdirectories contains any
+ :command:`install` rules, i.e. whether a ``make install``
+ or equivalent rule is available.
+
+ ``projects``
+ A JSON array of entries corresponding to the top-level project
+ and sub-projects defined in the build system. Each (sub-)project
+ corresponds to a source directory whose ``CMakeLists.txt`` file
+ calls the :command:`project` command with a project name different
+ from its parent directory. The first entry corresponds to the
+ top-level project.
+
+ Each entry is a JSON object containing members:
+
+ ``name``
+ A string specifying the name given to the :command:`project` command.
+
+ ``parentIndex``
+ Optional member that is present when the project is not top-level.
+ The value is an unsigned integer 0-based index of another entry in
+ the main ``projects`` array that corresponds to the parent project
+ that added this project as a sub-project.
+
+ ``childIndexes``
+ Optional member that is present when the project has sub-projects.
+ The value is a JSON array of entries corresponding to the sub-projects.
+ Each entry is an unsigned integer 0-based index of another
+ entry in the main ``projects`` array.
+
+ ``directoryIndexes``
+ A JSON array of entries corresponding to build system directories
+ that are part of the project. The first entry corresponds to the
+ top-level directory of the project. Each entry is an unsigned
+ integer 0-based index into the main ``directories`` array.
+
+ ``targetIndexes``
+ Optional member that is present when the project itself has targets,
+ excluding those belonging to sub-projects. The value is a JSON
+ array of entries corresponding to the targets. Each entry is an
+ unsigned integer 0-based index into the main ``targets`` array.
+
+ ``targets``
+ A JSON array of entries corresponding to the build system targets.
+ Such targets are created by calls to :command:`add_executable`,
+ :command:`add_library`, and :command:`add_custom_target`, excluding
+ imported targets and interface libraries (which do not generate any
+ build rules). Each entry is a JSON object containing members:
+
+ ``name``
+ A string specifying the target name.
+
+ ``id``
+ A string uniquely identifying the target. This matches the ``id``
+ field in the file referenced by ``jsonFile``.
+
+ ``directoryIndex``
+ An unsigned integer 0-based index into the main ``directories`` array
+ indicating the build system directory in which the target is defined.
+
+ ``projectIndex``
+ An unsigned integer 0-based index into the main ``projects`` array
+ indicating the build system project in which the target is defined.
+
+ ``jsonFile``
+ A JSON string specifying a path relative to the codemodel file
+ to another JSON file containing a
+ `"codemodel" version 2 "target" object`_.
+
+"codemodel" version 2 "target" object
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+A codemodel "target" object is referenced by a `"codemodel" version 2`_
+object's ``targets`` array. Each "target" object is a JSON object
+with members:
+
+``name``
+ A string specifying the logical name of the target.
+
+``id``
+ A string uniquely identifying the target. The format is unspecified
+ and should not be interpreted by clients.
+
+``type``
+ A string specifying the type of the target. The value is one of
+ ``EXECUTABLE``, ``STATIC_LIBRARY``, ``SHARED_LIBRARY``,
+ ``MODULE_LIBRARY``, ``OBJECT_LIBRARY``, or ``UTILITY``.
+
+``backtrace``
+ Optional member that is present when a CMake language backtrace to
+ the command in the source code that created the target is available.
+ The value is an unsigned integer 0-based index into the
+ ``backtraceGraph`` member's ``nodes`` array.
+
+``folder``
+ Optional member that is present when the :prop_tgt:`FOLDER` target
+ property is set. The value is a JSON object with one member:
+
+ ``name``
+ A string specifying the name of the target folder.
+
+``paths``
+ A JSON object containing members:
+
+ ``source``
+ A string specifying the path to the target's source directory,
+ represented with forward slashes. If the directory is inside the
+ top-level source directory then the path is specified relative to
+ that directory (with ``.`` for the top-level source directory itself).
+ Otherwise the path is absolute.
+
+ ``build``
+ A string specifying the path to the target's build directory,
+ represented with forward slashes. If the directory is inside the
+ top-level build directory then the path is specified relative to
+ that directory (with ``.`` for the top-level build directory itself).
+ Otherwise the path is absolute.
+
+``nameOnDisk``
+ Optional member that is present for executable and library targets
+ that are linked or archived into a single primary artifact.
+ The value is a string specifying the file name of that artifact on disk.
+
+``artifacts``
+ Optional member that is present for executable and library targets
+ that produce artifacts on disk meant for consumption by dependents.
+ The value is a JSON array of entries corresponding to the artifacts.
+ Each entry is a JSON object containing one member:
+
+ ``path``
+ A string specifying the path to the file on disk, represented with
+ forward slashes. If the file is inside the top-level build directory
+ then the path is specified relative to that directory.
+ Otherwise the path is absolute.
+
+``isGeneratorProvided``
+ Optional member that is present with boolean value ``true`` if the
+ target is provided by CMake's build system generator rather than by
+ a command in the source code.
+
+``install``
+ Optional member that is present when the target has an :command:`install`
+ rule. The value is a JSON object with members:
+
+ ``prefix``
+ A JSON object specifying the installation prefix. It has one member:
+
+ ``path``
+ A string specifying the value of :variable:`CMAKE_INSTALL_PREFIX`.
+
+ ``destinations``
+ A JSON array of entries specifying an install destination path.
+ Each entry is a JSON object with members:
+
+ ``path``
+ A string specifying the install destination path. The path may
+ be absolute or relative to the install prefix.
+
+ ``backtrace``
+ Optional member that is present when a CMake language backtrace to
+ the :command:`install` command invocation that specified this
+ destination is available. The value is an unsigned integer 0-based
+ index into the ``backtraceGraph`` member's ``nodes`` array.
+
+``link``
+ Optional member that is present for executables and shared library
+ targets that link into a runtime binary. The value is a JSON object
+ with members describing the link step:
+
+ ``language``
+ A string specifying the language (e.g. ``C``, ``CXX``, ``Fortran``)
+ of the toolchain is used to invoke the linker.
+
+ ``commandFragments``
+ Optional member that is present when fragments of the link command
+ line invocation are available. The value is a JSON array of entries
+ specifying ordered fragments. Each entry is a JSON object with members:
+
+ ``fragment``
+ A string specifying a fragment of the link command line invocation.
+ The value is encoded in the build system's native shell format.
+
+ ``role``
+ A string specifying the role of the fragment's content:
+
+ * ``flags``: link flags.
+ * ``libraries``: link library file paths or flags.
+ * ``libraryPath``: library search path flags.
+ * ``frameworkPath``: macOS framework search path flags.
+
+ ``lto``
+ Optional member that is present with boolean value ``true``
+ when link-time optimization (a.k.a. interprocedural optimization
+ or link-time code generation) is enabled.
+
+ ``sysroot``
+ Optional member that is present when the :variable:`CMAKE_SYSROOT_LINK`
+ or :variable:`CMAKE_SYSROOT` variable is defined. The value is a
+ JSON object with one member:
+
+ ``path``
+ A string specifying the absolute path to the sysroot, represented
+ with forward slashes.
+
+``archive``
+ Optional member that is present for static library targets. The value
+ is a JSON object with members describing the archive step:
+
+ ``commandFragments``
+ Optional member that is present when fragments of the archiver command
+ line invocation are available. The value is a JSON array of entries
+ specifying the fragments. Each entry is a JSON object with members:
+
+ ``fragment``
+ A string specifying a fragment of the archiver command line invocation.
+ The value is encoded in the build system's native shell format.
+
+ ``role``
+ A string specifying the role of the fragment's content:
+
+ * ``flags``: archiver flags.
+
+ ``lto``
+ Optional member that is present with boolean value ``true``
+ when link-time optimization (a.k.a. interprocedural optimization
+ or link-time code generation) is enabled.
+
+``dependencies``
+ Optional member that is present when the target depends on other targets.
+ The value is a JSON array of entries corresponding to the dependencies.
+ Each entry is a JSON object with members:
+
+ ``id``
+ A string uniquely identifying the target on which this target depends.
+ This matches the main ``id`` member of the other target.
+
+ ``backtrace``
+ Optional member that is present when a CMake language backtrace to
+ the :command:`add_dependencies`, :command:`target_link_libraries`,
+ or other command invocation that created this dependency is
+ available. The value is an unsigned integer 0-based index into
+ the ``backtraceGraph`` member's ``nodes`` array.
+
+``sources``
+ A JSON array of entries corresponding to the target's source files.
+ Each entry is a JSON object with members:
+
+ ``path``
+ A string specifying the path to the source file on disk, represented
+ with forward slashes. If the file is inside the top-level source
+ directory then the path is specified relative to that directory.
+ Otherwise the path is absolute.
+
+ ``compileGroupIndex``
+ Optional member that is present when the source is compiled.
+ The value is an unsigned integer 0-based index into the
+ ``compileGroups`` array.
+
+ ``sourceGroupIndex``
+ Optional member that is present when the source is part of a source
+ group either via the :command:`source_group` command or by default.
+ The value is an unsigned integer 0-based index into the
+ ``sourceGroups`` array.
+
+ ``isGenerated``
+ Optional member that is present with boolean value ``true`` if
+ the source is :prop_sf:`GENERATED`.
+
+ ``backtrace``
+ Optional member that is present when a CMake language backtrace to
+ the :command:`target_sources`, :command:`add_executable`,
+ :command:`add_library`, :command:`add_custom_target`, or other
+ command invocation that added this source to the target is
+ available. The value is an unsigned integer 0-based index into
+ the ``backtraceGraph`` member's ``nodes`` array.
+
+``sourceGroups``
+ Optional member that is present when sources are grouped together by
+ the :command:`source_group` command or by default. The value is a
+ JSON array of entries corresponding to the groups. Each entry is
+ a JSON object with members:
+
+ ``name``
+ A string specifying the name of the source group.
+
+ ``sourceIndexes``
+ A JSON array listing the sources belonging to the group.
+ Each entry is an unsigned integer 0-based index into the
+ main ``sources`` array for the target.
+
+``compileGroups``
+ Optional member that is present when the target has sources that compile.
+ The value is a JSON array of entries corresponding to groups of sources
+ that all compile with the same settings. Each entry is a JSON object
+ with members:
+
+ ``sourceIndexes``
+ A JSON array listing the sources belonging to the group.
+ Each entry is an unsigned integer 0-based index into the
+ main ``sources`` array for the target.
+
+ ``language``
+ A string specifying the language (e.g. ``C``, ``CXX``, ``Fortran``)
+ of the toolchain is used to compile the source file.
+
+ ``compileCommandFragments``
+ Optional member that is present when fragments of the compiler command
+ line invocation are available. The value is a JSON array of entries
+ specifying ordered fragments. Each entry is a JSON object with
+ one member:
+
+ ``fragment``
+ A string specifying a fragment of the compile command line invocation.
+ The value is encoded in the build system's native shell format.
+
+ ``includes``
+ Optional member that is present when there are include directories.
+ The value is a JSON array with an entry for each directory. Each
+ entry is a JSON object with members:
+
+ ``path``
+ A string specifying the path to the include directory,
+ represented with forward slashes.
+
+ ``isSystem``
+ Optional member that is present with boolean value ``true`` if
+ the include directory is marked as a system include directory.
+
+ ``backtrace``
+ Optional member that is present when a CMake language backtrace to
+ the :command:`target_include_directories` or other command invocation
+ that added this include directory is available. The value is
+ an unsigned integer 0-based index into the ``backtraceGraph``
+ member's ``nodes`` array.
+
+ ``defines``
+ Optional member that is present when there are preprocessor definitions.
+ The value is a JSON array with an entry for each definition. Each
+ entry is a JSON object with members:
+
+ ``define``
+ A string specifying the preprocessor definition in the format
+ ``<name>[=<value>]``, e.g. ``DEF`` or ``DEF=1``.
+
+ ``backtrace``
+ Optional member that is present when a CMake language backtrace to
+ the :command:`target_compile_definitions` or other command invocation
+ that added this preprocessor definition is available. The value is
+ an unsigned integer 0-based index into the ``backtraceGraph``
+ member's ``nodes`` array.
+
+ ``sysroot``
+ Optional member that is present when the
+ :variable:`CMAKE_SYSROOT_COMPILE` or :variable:`CMAKE_SYSROOT`
+ variable is defined. The value is a JSON object with one member:
+
+ ``path``
+ A string specifying the absolute path to the sysroot, represented
+ with forward slashes.
+
+``backtraceGraph``
+ A JSON object describing the graph of backtraces whose nodes are
+ referenced from ``backtrace`` members elsewhere. The members are:
+
+ ``nodes``
+ A JSON array listing nodes in the backtrace graph. Each entry
+ is a JSON object with members:
+
+ ``file``
+ An unsigned integer 0-based index into the backtrace ``files`` array.
+
+ ``line``
+ An optional member present when the node represents a line within
+ the file. The value is an unsigned integer 1-based line number.
+
+ ``command``
+ An optional member present when the node represents a command
+ invocation within the file. The value is an unsigned integer
+ 0-based index into the backtrace ``commands`` array.
+
+ ``parent``
+ An optional member present when the node is not the bottom of
+ the call stack. The value is an unsigned integer 0-based index
+ of another entry in the backtrace ``nodes`` array.
+
+ ``commands``
+ A JSON array listing command names referenced by backtrace nodes.
+ Each entry is a string specifying a command name.
+
+ ``files``
+ A JSON array listing CMake language files referenced by backtrace nodes.
+ Each entry is a string specifying the path to a file, represented
+ with forward slashes. If the file is inside the top-level source
+ directory then the path is specified relative to that directory.
+ Otherwise the path is absolute.
+
+Object Kind "cache"
+-------------------
+
+The ``cache`` object kind lists cache entries. These are the
+:ref:`CMake Language Variables` stored in the persistent cache
+(``CMakeCache.txt``) for the build tree.
+
+There is only one ``cache`` object major version, version 2.
+Version 1 does not exist to avoid confusion with that from
+:manual:`cmake-server(7)` mode.
+
+"cache" version 2
+^^^^^^^^^^^^^^^^^
+
+``cache`` object version 2 is a JSON object:
+
+.. code-block:: json
+
+ {
+ "kind": "cache",
+ "version": { "major": 2, "minor": 0 },
+ "entries": [
+ {
+ "name": "BUILD_SHARED_LIBS",
+ "value": "ON",
+ "type": "BOOL",
+ "properties": [
+ {
+ "name": "HELPSTRING",
+ "value": "Build shared libraries"
+ }
+ ]
+ },
+ {
+ "name": "CMAKE_GENERATOR",
+ "value": "Unix Makefiles",
+ "type": "INTERNAL",
+ "properties": [
+ {
+ "name": "HELPSTRING",
+ "value": "Name of generator."
+ }
+ ]
+ }
+ ]
+ }
+
+The members specific to ``cache`` objects are:
+
+``entries``
+ A JSON array whose entries are each a JSON object specifying a
+ cache entry. The members of each entry are:
+
+ ``name``
+ A string specifying the name of the entry.
+
+ ``value``
+ A string specifying the value of the entry.
+
+ ``type``
+ A string specifying the type of the entry used by
+ :manual:`cmake-gui(1)` to choose a widget for editing.
+
+ ``properties``
+ A JSON array of entries specifying associated
+ :ref:`cache entry properties <Cache Entry Properties>`.
+ Each entry is a JSON object containing members:
+
+ ``name``
+ A string specifying the name of the cache entry property.
+
+ ``value``
+ A string specifying the value of the cache entry property.
+
+Object Kind "cmakeFiles"
+------------------------
+
+The ``cmakeFiles`` object kind lists files used by CMake while
+configuring and generating the build system. These include the
+``CMakeLists.txt`` files as well as included ``.cmake`` files.
+
+There is only one ``cmakeFiles`` object major version, version 1.
+
+"cmakeFiles" version 1
+^^^^^^^^^^^^^^^^^^^^^^
+
+``cmakeFiles`` object version 1 is a JSON object:
+
+.. code-block:: json
+
+ {
+ "kind": "cmakeFiles",
+ "version": { "major": 1, "minor": 0 },
+ "paths": {
+ "build": "/path/to/top-level-build-dir",
+ "source": "/path/to/top-level-source-dir"
+ },
+ "inputs": [
+ {
+ "path": "CMakeLists.txt"
+ },
+ {
+ "isGenerated": true,
+ "path": "/path/to/top-level-build-dir/.../CMakeSystem.cmake"
+ },
+ {
+ "isExternal": true,
+ "path": "/path/to/external/third-party/module.cmake"
+ },
+ {
+ "isCMake": true,
+ "isExternal": true,
+ "path": "/path/to/cmake/Modules/CMakeGenericSystem.cmake"
+ }
+ ]
+ }
+
+The members specific to ``cmakeFiles`` objects are:
+
+``paths``
+ A JSON object containing members:
+
+ ``source``
+ A string specifying the absolute path to the top-level source directory,
+ represented with forward slashes.
+
+ ``build``
+ A string specifying the absolute path to the top-level build directory,
+ represented with forward slashes.
+
+``inputs``
+ A JSON array whose entries are each a JSON object specifying an input
+ file used by CMake when configuring and generating the build system.
+ The members of each entry are:
+
+ ``path``
+ A string specifying the path to an input file to CMake, represented
+ with forward slashes. If the file is inside the top-level source
+ directory then the path is specified relative to that directory.
+ Otherwise the path is absolute.
+
+ ``isGenerated``
+ Optional member that is present with boolean value ``true``
+ if the path specifies a file that is under the top-level
+ build directory and the build is out-of-source.
+ This member is not available on in-source builds.
+
+ ``isExternal``
+ Optional member that is present with boolean value ``true``
+ if the path specifies a file that is not under the top-level
+ source or build directories.
+
+ ``isCMake``
+ Optional member that is present with boolean value ``true``
+ if the path specifies a file in the CMake installation.
diff --git a/Help/manual/cpack-generators.7.rst b/Help/manual/cpack-generators.7.rst
new file mode 100644
index 000000000..ade9149c1
--- /dev/null
+++ b/Help/manual/cpack-generators.7.rst
@@ -0,0 +1,29 @@
+.. cmake-manual-description: CPack Generator Reference
+
+cpack-generators(7)
+*******************
+
+.. only:: html
+
+ .. contents::
+
+Generators
+==========
+
+.. toctree::
+ :maxdepth: 1
+
+ /cpack_gen/archive
+ /cpack_gen/bundle
+ /cpack_gen/cygwin
+ /cpack_gen/deb
+ /cpack_gen/dmg
+ /cpack_gen/external
+ /cpack_gen/freebsd
+ /cpack_gen/ifw
+ /cpack_gen/nsis
+ /cpack_gen/nuget
+ /cpack_gen/packagemaker
+ /cpack_gen/productbuild
+ /cpack_gen/rpm
+ /cpack_gen/wix
diff --git a/Help/module/CPackFreeBSD.rst b/Help/module/CPackFreeBSD.rst
new file mode 100644
index 000000000..69701b8e9
--- /dev/null
+++ b/Help/module/CPackFreeBSD.rst
@@ -0,0 +1,4 @@
+CPackFreeBSD
+------------
+
+The documentation for the CPack FreeBSD generator has moved here: :cpack_gen:`CPack FreeBSD Generator`
diff --git a/Help/module/CPackNuGet.rst b/Help/module/CPackNuGet.rst
new file mode 100644
index 000000000..4f39b3a7e
--- /dev/null
+++ b/Help/module/CPackNuGet.rst
@@ -0,0 +1,4 @@
+CPackNuGet
+----------
+
+The documentation for the CPack NuGet generator has moved here: :cpack_gen:`CPack NuGet Generator`
diff --git a/Help/module/CheckFortranSourceRuns.rst b/Help/module/CheckFortranSourceRuns.rst
new file mode 100644
index 000000000..a1bff7063
--- /dev/null
+++ b/Help/module/CheckFortranSourceRuns.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/CheckFortranSourceRuns.cmake
diff --git a/Help/module/CheckPIESupported.rst b/Help/module/CheckPIESupported.rst
new file mode 100644
index 000000000..02e7b4316
--- /dev/null
+++ b/Help/module/CheckPIESupported.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/CheckPIESupported.cmake
diff --git a/Help/module/FetchContent.rst b/Help/module/FetchContent.rst
new file mode 100644
index 000000000..c130a6dcb
--- /dev/null
+++ b/Help/module/FetchContent.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FetchContent.cmake
diff --git a/Help/module/FindEnvModules.rst b/Help/module/FindEnvModules.rst
new file mode 100644
index 000000000..72c120f22
--- /dev/null
+++ b/Help/module/FindEnvModules.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindEnvModules.cmake
diff --git a/Help/module/FindFontconfig.rst b/Help/module/FindFontconfig.rst
new file mode 100644
index 000000000..449fe09d0
--- /dev/null
+++ b/Help/module/FindFontconfig.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindFontconfig.cmake
diff --git a/Help/module/FindIconv.rst b/Help/module/FindIconv.rst
new file mode 100644
index 000000000..c1f3ed080
--- /dev/null
+++ b/Help/module/FindIconv.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindIconv.cmake
diff --git a/Help/module/FindLibinput.rst b/Help/module/FindLibinput.rst
new file mode 100644
index 000000000..a8ca0b024
--- /dev/null
+++ b/Help/module/FindLibinput.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindLibinput.cmake
diff --git a/Help/module/FindODBC.rst b/Help/module/FindODBC.rst
new file mode 100644
index 000000000..8558334df
--- /dev/null
+++ b/Help/module/FindODBC.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindODBC.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/module/FindPython.rst b/Help/module/FindPython.rst
new file mode 100644
index 000000000..057a350c0
--- /dev/null
+++ b/Help/module/FindPython.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindPython.cmake
diff --git a/Help/module/FindPython2.rst b/Help/module/FindPython2.rst
new file mode 100644
index 000000000..1696bedc1
--- /dev/null
+++ b/Help/module/FindPython2.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindPython2.cmake
diff --git a/Help/module/FindPython3.rst b/Help/module/FindPython3.rst
new file mode 100644
index 000000000..e530ab85c
--- /dev/null
+++ b/Help/module/FindPython3.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindPython3.cmake
diff --git a/Help/module/FindSQLite3.rst b/Help/module/FindSQLite3.rst
new file mode 100644
index 000000000..d1910e5a6
--- /dev/null
+++ b/Help/module/FindSQLite3.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindSQLite3.cmake
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..855ecf0e9
--- /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/policy/CMP0072.rst b/Help/policy/CMP0072.rst
new file mode 100644
index 000000000..3abbad790
--- /dev/null
+++ b/Help/policy/CMP0072.rst
@@ -0,0 +1,26 @@
+CMP0072
+-------
+
+:module:`FindOpenGL` prefers GLVND by default when available.
+
+The :module:`FindOpenGL` module provides an ``OpenGL::GL`` target and an
+``OPENGL_LIBRARIES`` variable for projects to use for legacy GL interfaces.
+When both a legacy GL library (e.g. ``libGL.so``) and GLVND libraries
+for OpenGL and GLX (e.g. ``libOpenGL.so`` and ``libGLX.so``) are available,
+the module must choose between them. It documents an ``OpenGL_GL_PREFERENCE``
+variable that can be used to specify an explicit preference. When no such
+preference is set, the module must choose a default preference.
+
+CMake 3.11 and above prefer to choose GLVND libraries. This policy provides
+compatibility with projects that expect the legacy GL library to be used.
+
+The ``OLD`` behavior for this policy is to set ``OpenGL_GL_PREFERENCE`` to
+``LEGACY``. The ``NEW`` behavior for this policy is to set
+``OpenGL_GL_PREFERENCE`` to ``GLVND``.
+
+This policy was introduced in CMake version 3.11. 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/CMP0073.rst b/Help/policy/CMP0073.rst
new file mode 100644
index 000000000..9bfa0e905
--- /dev/null
+++ b/Help/policy/CMP0073.rst
@@ -0,0 +1,25 @@
+CMP0073
+-------
+
+Do not produce legacy ``_LIB_DEPENDS`` cache entries.
+
+Ancient CMake versions once used ``<tgt>_LIB_DEPENDS`` cache entries to
+propagate library link dependencies. This has long been done by other
+means, leaving the :command:`export_library_dependencies` command as the
+only user of these values. That command has long been disallowed by
+policy :policy:`CMP0033`, but the ``<tgt>_LIB_DEPENDS`` cache entries
+were left for compatibility with possible non-standard uses by projects.
+
+CMake 3.12 and above now prefer to not produce these cache entries
+at all. This policy provides compatibility with projects that have
+not been updated to avoid using them.
+
+The ``OLD`` behavior for this policy is to set ``<tgt>_LIB_DEPENDS`` cache
+entries. The ``NEW`` behavior for this policy is to not set them.
+
+This policy was introduced in CMake version 3.12. Use the
+:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly.
+Unlike most policies, CMake version |release| does *not* warn
+when this policy is not set and simply uses ``OLD`` behavior.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/policy/CMP0074.rst b/Help/policy/CMP0074.rst
new file mode 100644
index 000000000..896936b21
--- /dev/null
+++ b/Help/policy/CMP0074.rst
@@ -0,0 +1,23 @@
+CMP0074
+-------
+
+:command:`find_package` uses ``<PackageName>_ROOT`` variables.
+
+In CMake 3.12 and above the :command:`find_package(<PackageName>)` command now
+searches prefixes specified by the :variable:`<PackageName>_ROOT` CMake
+variable and the :envvar:`<PackageName>_ROOT` environment variable.
+Package roots are maintained as a stack so nested calls to all ``find_*``
+commands inside find modules also search the roots as prefixes. This policy
+provides compatibility with projects that have not been updated to avoid using
+``<PackageName>_ROOT`` variables for other purposes.
+
+The ``OLD`` behavior for this policy is to ignore ``<PackageName>_ROOT``
+variables. The ``NEW`` behavior for this policy is to use
+``<PackageName>_ROOT`` variables.
+
+This policy was introduced in CMake version 3.12. 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/CMP0075.rst b/Help/policy/CMP0075.rst
new file mode 100644
index 000000000..aa5c3f76f
--- /dev/null
+++ b/Help/policy/CMP0075.rst
@@ -0,0 +1,26 @@
+CMP0075
+-------
+
+Include file check macros honor ``CMAKE_REQUIRED_LIBRARIES``.
+
+In CMake 3.12 and above, the
+
+* ``check_include_file`` macro in the :module:`CheckIncludeFile` module, the
+* ``check_include_file_cxx`` macro in the
+ :module:`CheckIncludeFileCXX` module, and the
+* ``check_include_files`` macro in the :module:`CheckIncludeFiles` module
+
+now prefer to link the check executable to the libraries listed in the
+``CMAKE_REQUIRED_LIBRARIES`` variable. This policy provides compatibility
+with projects that have not been updated to expect this behavior.
+
+The ``OLD`` behavior for this policy is to ignore ``CMAKE_REQUIRED_LIBRARIES``
+in the include file check macros. The ``NEW`` behavior of this policy is to
+honor ``CMAKE_REQUIRED_LIBRARIES`` in the include file check macros.
+
+This policy was introduced in CMake version 3.12. 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/CMP0076.rst b/Help/policy/CMP0076.rst
new file mode 100644
index 000000000..dd25f80c6
--- /dev/null
+++ b/Help/policy/CMP0076.rst
@@ -0,0 +1,26 @@
+CMP0076
+-------
+
+The :command:`target_sources` command converts relative paths to absolute.
+
+In CMake 3.13 and above, the :command:`target_sources` command now converts
+relative source file paths to absolute paths in the following cases:
+
+* Source files are added to the target's :prop_tgt:`INTERFACE_SOURCES`
+ property.
+* The target's :prop_tgt:`SOURCE_DIR` property differs from
+ :variable:`CMAKE_CURRENT_SOURCE_DIR`.
+
+A path that begins with a generator expression is always left unmodified.
+
+This policy provides compatibility with projects that have not been updated
+to expect this behavior. The ``OLD`` behavior for this policy is to leave
+all relative source file paths unmodified. The ``NEW`` behavior of this
+policy is to convert relative paths to absolute according to above rules.
+
+This policy was introduced in CMake version 3.13. 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/CMP0077.rst b/Help/policy/CMP0077.rst
new file mode 100644
index 000000000..44797b648
--- /dev/null
+++ b/Help/policy/CMP0077.rst
@@ -0,0 +1,52 @@
+CMP0077
+-------
+
+:command:`option` honors normal variables.
+
+The :command:`option` command is typically used to create a cache entry
+to allow users to set the option. However, there are cases in which a
+normal (non-cached) variable of the same name as the option may be
+defined by the project prior to calling the :command:`option` command.
+For example, a project that embeds another project as a subdirectory
+may want to hard-code options of the subproject to build the way it needs.
+
+For historical reasons in CMake 3.12 and below the :command:`option`
+command *removes* a normal (non-cached) variable of the same name when:
+
+* a cache entry of the specified name does not exist at all, or
+* a cache entry of the specified name exists but has not been given
+ a type (e.g. via ``-D<name>=ON`` on the command line).
+
+In both of these cases (typically on the first run in a new build tree),
+the :command:`option` command gives the cache entry type ``BOOL`` and
+removes any normal (non-cached) variable of the same name. In the
+remaining case that the cache entry of the specified name already
+exists and has a type (typically on later runs in a build tree), the
+:command:`option` command changes nothing and any normal variable of
+the same name remains set.
+
+In CMake 3.13 and above the :command:`option` command prefers to
+do nothing when a normal variable of the given name already exists.
+It does not create or update a cache entry or remove the normal variable.
+The new behavior is consistent between the first and later runs in a
+build tree. This policy provides compatibility with projects that have
+not been updated to expect the new behavior.
+
+When the :command:`option` command sees a normal variable of the given
+name:
+
+* The ``OLD`` behavior for this policy is to proceed even when a normal
+ variable of the same name exists. If the cache entry does not already
+ exist and have a type then it is created and/or given a type and the
+ normal variable is removed.
+
+* The ``NEW`` behavior for this policy is to do nothing when a normal
+ variable of the same name exists. The normal variable is not removed.
+ The cache entry is not created or updated and is ignored if it exists.
+
+This policy was introduced in CMake version 3.13. 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/CMP0078.rst b/Help/policy/CMP0078.rst
new file mode 100644
index 000000000..2e97934f4
--- /dev/null
+++ b/Help/policy/CMP0078.rst
@@ -0,0 +1,24 @@
+CMP0078
+-------
+
+:module:`UseSWIG` generates standard target names.
+
+Starting with CMake 3.13, :module:`UseSWIG` generates now standard target
+names. This policy provides compatibility with projects that expect the legacy
+behavior.
+
+The ``OLD`` behavior for this policy relies on
+``UseSWIG_TARGET_NAME_PREFERENCE`` variable that can be used to specify an
+explicit preference. The value may be one of:
+
+* ``LEGACY``: legacy strategy is applied. Variable
+ ``SWIG_MODULE_<name>_REAL_NAME`` must be used to get real target name.
+ This is the default if not specified.
+* ``STANDARD``: target name matches specified name.
+
+This policy was introduced in CMake version 3.13. 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/CMP0079.rst b/Help/policy/CMP0079.rst
new file mode 100644
index 000000000..0244d6ca6
--- /dev/null
+++ b/Help/policy/CMP0079.rst
@@ -0,0 +1,40 @@
+CMP0079
+-------
+
+:command:`target_link_libraries` allows use with targets in other directories.
+
+Prior to CMake 3.13 the :command:`target_link_libraries` command did not
+accept targets not created in the calling directory as its first argument
+for calls that update the :prop_tgt:`LINK_LIBRARIES` of the target itself.
+It did accidentally accept targets from other directories on calls that
+only update the :prop_tgt:`INTERFACE_LINK_LIBRARIES`, but would simply
+add entries to the property as if the call were made in the original
+directory. Thus link interface libraries specified this way were always
+looked up by generators in the scope of the original target rather than
+in the scope that called :command:`target_link_libraries`.
+
+CMake 3.13 now allows the :command:`target_link_libraries` command to
+be called from any directory to add link dependencies and link interface
+libraries to targets created in other directories. The entries are added
+to :prop_tgt:`LINK_LIBRARIES` and :prop_tgt:`INTERFACE_LINK_LIBRARIES`
+using a special (internal) suffix to tell the generators to look up the
+names in the calling scope rather than the scope that created the target.
+
+This policy provides compatibility with projects that already use
+:command:`target_link_libraries` with the ``INTERFACE`` keyword
+on a target in another directory to add :prop_tgt:`INTERFACE_LINK_LIBRARIES`
+entries to be looked up in the target's directory. Such projects should
+be updated to be aware of the new scoping rules in that case.
+
+The ``OLD`` behavior of this policy is to disallow
+:command:`target_link_libraries` calls naming targets from another directory
+except in the previously accidentally allowed case of using the ``INTERFACE``
+keyword only. The ``NEW`` behavior of this policy is to allow all such
+calls but use the new scoping rules.
+
+This policy was introduced in CMake version 3.13. 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/CMP0080.rst b/Help/policy/CMP0080.rst
new file mode 100644
index 000000000..5ce9591da
--- /dev/null
+++ b/Help/policy/CMP0080.rst
@@ -0,0 +1,25 @@
+CMP0080
+-------
+
+:module:`BundleUtilities` cannot be included at configure time.
+
+The macros provided by :module:`BundleUtilities` are intended to be invoked
+at install time rather than at configure time, because they depend on the
+listed targets already existing at the time they are invoked. If they are
+invoked at configure time, the targets haven't been built yet, and the
+commands will fail.
+
+This policy restricts the inclusion of :module:`BundleUtilities` to
+``cmake -P`` style scripts and install rules. Specifically, it looks for the
+presence of :variable:`CMAKE_GENERATOR` and throws a fatal error if it exists.
+
+The ``OLD`` behavior of this policy is to allow :module:`BundleUtilities` to
+be included at configure time. The ``NEW`` behavior of this policy is to
+disallow such inclusion.
+
+This policy was introduced in CMake version 3.13. 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/CMP0081.rst b/Help/policy/CMP0081.rst
new file mode 100644
index 000000000..d3b2872c4
--- /dev/null
+++ b/Help/policy/CMP0081.rst
@@ -0,0 +1,22 @@
+CMP0081
+-------
+
+Relative paths not allowed in :prop_tgt:`LINK_DIRECTORIES` target property.
+
+CMake 3.12 and lower allowed the :prop_dir:`LINK_DIRECTORIES` directory
+property to contain relative paths. The base path for such relative
+entries is not well defined. CMake 3.13 and later will issue a
+``FATAL_ERROR`` if the :prop_tgt:`LINK_DIRECTORIES` target property
+(which is initialized by the :prop_dir:`LINK_DIRECTORIES` directory property)
+contains a relative path.
+
+The ``OLD`` behavior for this policy is not to warn about relative paths
+in the :prop_tgt:`LINK_DIRECTORIES` target property. The ``NEW`` behavior for
+this policy is to issue a ``FATAL_ERROR`` if :prop_tgt:`LINK_DIRECTORIES`
+contains a relative path.
+
+This policy was introduced in CMake version 3.13. 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/CMP0082.rst b/Help/policy/CMP0082.rst
new file mode 100644
index 000000000..d887616be
--- /dev/null
+++ b/Help/policy/CMP0082.rst
@@ -0,0 +1,26 @@
+CMP0082
+-------
+
+Install rules from :command:`add_subdirectory` calls are interleaved with
+those in caller.
+
+CMake 3.13 and lower ran the install rules from :command:`add_subdirectory`
+after all other install rules, even if :command:`add_subdirectory` was called
+before the other install rules. CMake 3.14 and above prefer to interleave
+these :command:`add_subdirectory` install rules with the others so that
+they are run in the order they are declared. This policy provides
+compatibility for projects that have not been updated to expect the
+new behavior.
+
+The ``OLD`` behavior for this policy is to run the install rules from
+:command:`add_subdirectory` after the other install rules. The ``NEW``
+behavior for this policy is to run all install rules in the order they are
+declared.
+
+This policy was introduced in CMake version 3.14. Unlike most policies,
+CMake version |release| does *not* warn by default when this policy
+is not set and simply uses ``OLD`` behavior. See documentation of the
+:variable:`CMAKE_POLICY_WARNING_CMP0082 <CMAKE_POLICY_WARNING_CMP<NNNN>>`
+variable to control the warning.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/policy/CMP0083.rst b/Help/policy/CMP0083.rst
new file mode 100644
index 000000000..e0b09cff5
--- /dev/null
+++ b/Help/policy/CMP0083.rst
@@ -0,0 +1,69 @@
+CMP0083
+-------
+
+To control generation of Position Independent Executable (``PIE``) or not, some
+flags are required at link time.
+
+CMake 3.13 and lower did not add these link flags when
+:prop_tgt:`POSITION_INDEPENDENT_CODE` is set.
+
+The ``OLD`` behavior for this policy is to not manage ``PIE`` link flags. The
+``NEW`` behavior is to add link flags if :prop_tgt:`POSITION_INDEPENDENT_CODE`
+is set:
+
+* Set to ``TRUE``: flags to produce a position independent executable are
+ passed to the linker step. For example ``-pie`` for ``GCC``.
+* Set to ``FALSE``: flags not to produce a position independent executable are
+ passed to the linker step. For example ``-no-pie`` for ``GCC``.
+* Not set: no flags are passed to the linker step.
+
+Since a given linker may not support ``PIE`` flags in all environments in
+which it is used, it is the project's responsibility to use the
+:module:`CheckPIESupported` module to check for support to ensure that the
+:prop_tgt:`POSITION_INDEPENDENT_CODE` target property for executables will be
+honored at link time.
+
+This policy was introduced in CMake version 3.14. Use the
+:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly.
+Unlike most policies, CMake version |release| does not warn when this policy is
+not set and simply uses ``OLD`` behavior.
+
+.. Note::
+
+ Android platform has a special handling of ``PIE`` so it is not required
+ to use the :module:`CheckPIESupported` module to ensure flags are passed to
+ the linker.
+
+.. include:: DEPRECATED.txt
+
+Examples
+^^^^^^^^
+
+Behave like CMake 3.13 and do not apply any ``PIE`` flags at link stage.
+
+.. code-block:: cmake
+
+ cmake_minimum_required(VERSION 3.13)
+ project(foo)
+
+ # ...
+
+ add_executable(foo ...)
+ set_property(TARGET foo PROPERTY POSITION_INDEPENDENT_CODE TRUE)
+
+Use the :module:`CheckPIESupported` module to detect whether ``PIE`` is
+supported by the current linker and environment. Apply ``PIE`` flags only
+if the linker supports them.
+
+.. code-block:: cmake
+
+ cmake_minimum_required(VERSION 3.14) # CMP0083 NEW
+ project(foo)
+
+ include(CheckPIESupported)
+ check_pie_supported()
+
+ # ...
+
+ add_executable(foo ...)
+ set_property(TARGET foo PROPERTY POSITION_INDEPENDENT_CODE TRUE)
diff --git a/Help/policy/CMP0084.rst b/Help/policy/CMP0084.rst
new file mode 100644
index 000000000..713d295f8
--- /dev/null
+++ b/Help/policy/CMP0084.rst
@@ -0,0 +1,26 @@
+CMP0084
+-------
+
+The :module:`FindQt` module does not exist for :command:`find_package`.
+
+The existence of :module:`FindQt` means that for Qt upstream to provide
+package config files that can be found by ``find_package(Qt)``, the consuming
+project has to explicitly specify ``find_package(Qt CONFIG)``. Removing this
+module gives Qt a path forward for exporting its own config files which can
+easily be found by consuming projects.
+
+This policy pretends that CMake's internal :module:`FindQt` module does not
+exist for :command:`find_package`. If a project really wants to use Qt 3 or 4,
+it can call ``find_package(Qt[34])``, ``include(FindQt)``, or add
+:module:`FindQt` to their :variable:`CMAKE_MODULE_PATH`.
+
+The ``OLD`` behavior of this policy is for :module:`FindQt` to exist for
+:command:`find_package`. The ``NEW`` behavior is to pretend that it doesn't
+exist for :command:`find_package`.
+
+This policy was introduced in CMake version 3.14. 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/CMP0085.rst b/Help/policy/CMP0085.rst
new file mode 100644
index 000000000..d9ec9a207
--- /dev/null
+++ b/Help/policy/CMP0085.rst
@@ -0,0 +1,21 @@
+CMP0085
+-------
+
+``$<IN_LIST:...>`` handles empty list items.
+
+In CMake 3.13 and lower, the ``$<IN_LIST:...>`` generator expression always
+returned ``0`` if the first argument was empty, even if the list contained an
+empty item. This behavior is inconsistent with the ``IN_LIST`` behavior of
+:command:`if`, which this generator expression is meant to emulate. CMake 3.14
+and later handles this case correctly.
+
+The ``OLD`` behavior of this policy is for ``$<IN_LIST:...>`` to always return
+``0`` if the first argument is empty. The ``NEW`` behavior is to return ``1``
+if the first argument is empty and the list contains an empty item.
+
+This policy was introduced in CMake version 3.14. 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/CMP0086.rst b/Help/policy/CMP0086.rst
new file mode 100644
index 000000000..4a9e8b80a
--- /dev/null
+++ b/Help/policy/CMP0086.rst
@@ -0,0 +1,20 @@
+CMP0086
+-------
+
+:module:`UseSWIG` honors ``SWIG_MODULE_NAME`` via ``-module`` flag.
+
+Starting with CMake 3.14, :module:`UseSWIG` passes option
+``-module <module_name>`` to ``SWIG`` compiler if the file property
+``SWIG_MODULE_NAME`` is specified. This policy provides compatibility with
+projects that expect the legacy behavior.
+
+The ``OLD`` behavior for this policy is to never pass ``-module`` option.
+The ``NEW`` behavior is to pass ``-module`` option to ``SWIG`` compiler if
+``SWIG_MODULE_NAME`` is specified.
+
+This policy was introduced in CMake version 3.14. 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/CMP0087.rst b/Help/policy/CMP0087.rst
new file mode 100644
index 000000000..4c45b99e4
--- /dev/null
+++ b/Help/policy/CMP0087.rst
@@ -0,0 +1,29 @@
+CMP0087
+-------
+
+:command:`install(CODE)` and :command:`install(SCRIPT)` support generator
+expressions.
+
+In CMake 3.13 and earlier, :command:`install(CODE)` and
+:command:`install(SCRIPT)` did not evaluate generator expressions. CMake 3.14
+and later will evaluate generator expressions for :command:`install(CODE)` and
+:command:`install(SCRIPT)`.
+
+The ``OLD`` behavior of this policy is for :command:`install(CODE)` and
+:command:`install(SCRIPT)` to not evaluate generator expressions. The ``NEW``
+behavior is to evaluate generator expressions for :command:`install(CODE)` and
+:command:`install(SCRIPT)`.
+
+Note that it is the value of this policy setting at the end of the directory
+scope that is important, not its setting at the time of the call to
+:command:`install(CODE)` or :command:`install(SCRIPT)`. This has implications
+for calling these commands from places that have their own policy scope but not
+their own directory scope (e.g. from files brought in via :command:`include()`
+rather than :command:`add_subdirectory()`).
+
+This policy was introduced in CMake version 3.14. 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/CMP0088.rst b/Help/policy/CMP0088.rst
new file mode 100644
index 000000000..82c04ef7b
--- /dev/null
+++ b/Help/policy/CMP0088.rst
@@ -0,0 +1,29 @@
+CMP0088
+-------
+
+:module:`FindBISON` runs bison in :variable:`CMAKE_CURRENT_BINARY_DIR`
+when executing.
+
+The module provides a ``BISON_TARGET`` macro which generates BISON output.
+In CMake 3.13 and below the macro would generate a custom command that runs
+``bison`` in the source directory. CMake 3.14 and later prefer to run it
+in the build directory and use :variable:`CMAKE_CURRENT_BINARY_DIR` as the
+``WORKING_DIRECTORY`` of its :command:`add_custom_command` invocation.
+This ensures that any implicitly generated file is written to the build
+tree rather than the source.
+
+This policy provides compatibility for projects that have not been updated
+to expect the new behavior.
+
+The ``OLD`` behavior for this policy is for ``BISON_TARGET`` to use
+the current source directory for the ``WORKING_DIRECTORY`` and where
+to generate implicit files. The ``NEW`` behavior of this policy is to
+use the current binary directory for the ``WORKING_DIRECTORY`` and where
+to generate implicit files.
+
+This policy was introduced in CMake version 3.14. Use the
+:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly.
+Unlike most policies, CMake version |release| does *not* warn
+when this policy is not set and simply uses ``OLD`` behavior.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/policy/CMP0089.rst b/Help/policy/CMP0089.rst
new file mode 100644
index 000000000..029de5534
--- /dev/null
+++ b/Help/policy/CMP0089.rst
@@ -0,0 +1,30 @@
+CMP0089
+-------
+
+Compiler id for IBM Clang-based XL compilers is now ``XLClang``.
+
+CMake 3.15 and above recognize that IBM's Clang-based XL compilers
+that define ``__ibmxl__`` are a new front-end distinct from ``xlc``
+with a different command line and set of capabilities.
+CMake now prefers to present this to projects by setting the
+:variable:`CMAKE_<LANG>_COMPILER_ID` variable to ``XLClang`` instead
+of ``XL``. However, existing projects may assume the compiler id for
+Clang-based XL is just ``XL`` as it was in CMake versions prior to 3.15.
+Therefore this policy determines for Clang-based XL compilers which
+compiler id to report in the :variable:`CMAKE_<LANG>_COMPILER_ID`
+variable after language ``<LANG>`` is enabled by the :command:`project`
+or :command:`enable_language` command. The policy must be set prior
+to the invocation of either command.
+
+The ``OLD`` behavior for this policy is to use compiler id ``XL``. The
+``NEW`` behavior for this policy is to use compiler id ``XLClang``.
+
+This policy was introduced in CMake version 3.15. Use the
+:command:`cmake_policy` command to set this policy to ``OLD`` or ``NEW`` explicitly.
+Unlike most policies, CMake version |release| does *not* warn
+by default when this policy is not set and simply uses ``OLD`` behavior.
+See documentation of the
+:variable:`CMAKE_POLICY_WARNING_CMP0089 <CMAKE_POLICY_WARNING_CMP<NNNN>>`
+variable to control the warning.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/policy/CMP0090.rst b/Help/policy/CMP0090.rst
new file mode 100644
index 000000000..720c17c2a
--- /dev/null
+++ b/Help/policy/CMP0090.rst
@@ -0,0 +1,27 @@
+CMP0090
+-------
+
+:command:`export(PACKAGE)` does not populate package registry by default.
+
+In CMake 3.14 and below the :command:`export(PACKAGE)` command populated the
+user package registry by default and users needed to set the
+:variable:`CMAKE_EXPORT_NO_PACKAGE_REGISTRY` to disable it, e.g. in automated
+build and packaging environments. Since the user package registry is stored
+outside the build tree, this side effect should not be enabled by default.
+Therefore CMake 3.15 and above prefer that :command:`export(PACKAGE)` does
+nothing unless an explicit :variable:`CMAKE_EXPORT_PACKAGE_REGISTRY` variable
+is set to enable it. This policy provides compatibility with projects that
+have not been updated.
+
+The ``OLD`` behavior for this policy is for :command:`export(PACKAGE)` command
+to populate the user package registry unless
+:variable:`CMAKE_EXPORT_NO_PACKAGE_REGISTRY` is enabled.
+The ``NEW`` behavior is for :command:`export(PACKAGE)` command to do nothing
+unless the :variable:`CMAKE_EXPORT_PACKAGE_REGISTRY` is enabled.
+
+This policy was introduced in CMake version 3.15. Use the
+:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly.
+Unlike most policies, CMake version |release| does *not* warn
+when this policy is not set and simply uses ``OLD`` behavior.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/policy/CMP0091.rst b/Help/policy/CMP0091.rst
new file mode 100644
index 000000000..1a5878a1f
--- /dev/null
+++ b/Help/policy/CMP0091.rst
@@ -0,0 +1,49 @@
+CMP0091
+-------
+
+MSVC runtime library flags are selected by an abstraction.
+
+Compilers targeting the MSVC ABI have flags to select the MSVC runtime library.
+Runtime library selection typically varies with build configuration because
+there is a separate runtime library for Debug builds.
+
+In CMake 3.14 and below, MSVC runtime library selection flags are added to
+the default :variable:`CMAKE_<LANG>_FLAGS_<CONFIG>` cache entries by CMake
+automatically. This allows users to edit their cache entries to adjust the
+flags. However, the presence of such default flags is problematic for
+projects that want to choose a different runtime library programmatically.
+In particular, it requires string editing of the
+:variable:`CMAKE_<LANG>_FLAGS_<CONFIG>` variables with knowledge of the
+CMake builtin defaults so they can be replaced.
+
+CMake 3.15 and above prefer to leave the MSVC runtime library selection flags
+out of the default :variable:`CMAKE_<LANG>_FLAGS_<CONFIG>` values and instead
+offer a first-class abstraction. The :variable:`CMAKE_MSVC_RUNTIME_LIBRARY`
+variable and :prop_tgt:`MSVC_RUNTIME_LIBRARY` target property may be set to
+select the MSVC runtime library. If they are not set then CMake uses the
+default value ``MultiThreaded$<$<CONFIG:Debug>:Debug>DLL`` which is
+equivalent to the original flags.
+
+This policy provides compatibility with projects that have not been updated
+to be aware of the abstraction. The policy setting takes effect as of the
+first :command:`project` or :command:`enable_language` command that enables
+a language whose compiler targets the MSVC ABI.
+
+.. note::
+
+ Once the policy has taken effect at the top of a project, that choice
+ must be used throughout the tree. In projects that have nested projects
+ in subdirectories, be sure to convert everything together.
+
+The ``OLD`` behavior for this policy is to place MSVC runtime library
+flags in the default :variable:`CMAKE_<LANG>_FLAGS_<CONFIG>` cache
+entries and ignore the :variable:`CMAKE_MSVC_RUNTIME_LIBRARY` abstraction.
+The ``NEW`` behavior for this policy is to *not* place MSVC runtime
+library flags in the default cache entries and use the abstraction instead.
+
+This policy was introduced in CMake version 3.15. Use the
+:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly.
+Unlike many policies, CMake version |release| does *not* warn
+when this policy is not set and simply uses ``OLD`` behavior.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/policy/CMP0092.rst b/Help/policy/CMP0092.rst
new file mode 100644
index 000000000..8d3a288ae
--- /dev/null
+++ b/Help/policy/CMP0092.rst
@@ -0,0 +1,38 @@
+CMP0092
+-------
+
+MSVC warning flags are not in :variable:`CMAKE_<LANG>_FLAGS` by default.
+
+When using MSVC-like compilers in CMake 3.14 and below, warning flags
+like ``/W3`` are added to :variable:`CMAKE_<LANG>_FLAGS` by default.
+This is problematic for projects that want to choose a different warning
+level programmatically. In particular, it requires string editing of the
+:variable:`CMAKE_<LANG>_FLAGS` variables with knowledge of the
+CMake builtin defaults so they can be replaced.
+
+CMake 3.15 and above prefer to leave out warning flags from the value of
+:variable:`CMAKE_<LANG>_FLAGS` by default.
+
+This policy provides compatibility with projects that have not been updated
+to expect the lack of warning flags. The policy setting takes effect as of
+the first :command:`project` or :command:`enable_language` command that
+initializes :variable:`CMAKE_<LANG>_FLAGS` for a given lanuage ``<LANG>``.
+
+.. note::
+
+ Once the policy has taken effect at the top of a project for a given
+ language, that choice must be used throughout the tree for that language.
+ In projects that have nested projects in subdirectories, be sure to
+ convert everything together.
+
+The ``OLD`` behavior for this policy is to place MSVC warning flags in the
+default :variable:`CMAKE_<LANG>_FLAGS` cache entries. The ``NEW`` behavior
+for this policy is to *not* place MSVC warning flags in the default cache
+entries.
+
+This policy was introduced in CMake version 3.15. Use the
+:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly.
+Unlike many policies, CMake version |release| does *not* warn
+when this policy is not set and simply uses ``OLD`` behavior.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/policy/CMP0093.rst b/Help/policy/CMP0093.rst
new file mode 100644
index 000000000..0ffc493de
--- /dev/null
+++ b/Help/policy/CMP0093.rst
@@ -0,0 +1,24 @@
+CMP0093
+-------
+
+:module:`FindBoost` reports ``Boost_VERSION`` in ``x.y.z`` format.
+
+In CMake 3.14 and below the module would report the Boost version
+number as specified in the preprocessor definition ``BOOST_VERSION`` in
+the ``boost/version.hpp`` file. In CMake 3.15 and later it is preferred
+that the reported version number matches the ``x.y.z`` format reported
+by the CMake package shipped with Boost ``1.70.0`` and later. The macro
+value is still reported in the ``Boost_VERSION_MACRO`` variable.
+
+The ``OLD`` behavior for this policy is for :module:`FindBoost` to report
+``Boost_VERSION`` as specified in the preprocessor definition
+``BOOST_VERSION`` in ``boost/version.hpp``. The ``NEW`` behavior for this
+policy is for :module:`FindBoost` to report ``Boost_VERSION`` in
+``x.y.z`` format.
+
+This policy was introduced in CMake version 3.15. Use the
+:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly.
+Unlike many policies, CMake version |release| does *not* warn
+when this policy is not set and simply uses the ``OLD`` behavior.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/policy/CMP0094.rst b/Help/policy/CMP0094.rst
new file mode 100644
index 000000000..836f30f09
--- /dev/null
+++ b/Help/policy/CMP0094.rst
@@ -0,0 +1,22 @@
+CMP0094
+-------
+
+Modules :module:`FindPython3`, :module:`FindPython2` and :module:`FindPython`
+use ``LOCATION`` for lookup strategy.
+
+Starting with CMake 3.15, Modules :module:`FindPython3`, :module:`FindPython2`
+and :module:`FindPython` set value ``LOCATION`` for, respectively, variables
+``Python3_FIND_STRATEGY``, ``Python2_FIND_STRATEGY`` and
+``Python_FIND_STRATEGY``. This policy provides compatibility with projects that
+expect the legacy behavior.
+
+The ``OLD`` behavior for this policy set value ``VERSION`` for variables
+``Python3_FIND_STRATEGY``, ``Python2_FIND_STRATEGY`` and
+``Python_FIND_STRATEGY``.
+
+This policy was introduced in CMake version 3.15. Use the
+:command:`cmake_policy` command to set it to ``OLD`` or ``NEW`` explicitly.
+Unlike many policies, CMake version |release| does *not* warn
+when this policy is not set and simply uses the ``OLD`` behavior.
+
+.. include:: DEPRECATED.txt
diff --git a/Help/prop_dir/ADDITIONAL_CLEAN_FILES.rst b/Help/prop_dir/ADDITIONAL_CLEAN_FILES.rst
new file mode 100644
index 000000000..051d22a81
--- /dev/null
+++ b/Help/prop_dir/ADDITIONAL_CLEAN_FILES.rst
@@ -0,0 +1,21 @@
+ADDITIONAL_CLEAN_FILES
+----------------------
+
+A :ref:`;-list <CMake Language Lists>` of files or directories that will be
+removed as a part of the global ``clean`` target. It is useful for
+specifying generated files or directories that are used by multiple targets
+or by CMake itself, or that are generated in ways which cannot be captured as
+outputs or byproducts of custom commands.
+
+If an additional clean file is specific to a single target only, then the
+:prop_tgt:`ADDITIONAL_CLEAN_FILES` target property would usually be a better
+choice than this directory property.
+
+Relative paths are allowed and are interpreted relative to the
+current binary directory.
+
+Contents of ``ADDITIONAL_CLEAN_FILES`` may use
+:manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+This property only works for the :generator:`Ninja` and the Makefile
+generators. It is ignored by other generators.
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/LINK_OPTIONS.rst b/Help/prop_dir/LINK_OPTIONS.rst
new file mode 100644
index 000000000..54ac6ddaa
--- /dev/null
+++ b/Help/prop_dir/LINK_OPTIONS.rst
@@ -0,0 +1,17 @@
+LINK_OPTIONS
+------------
+
+List of options to use for the link step of shared library, module
+and executable targets.
+
+This property holds a :ref:`semicolon-separated list <CMake Language Lists>` of options
+given so far to the :command:`add_link_options` command.
+
+This property is used to initialize the :prop_tgt:`LINK_OPTIONS` target
+property when a target is created, which is used by the generators to set
+the options for the compiler.
+
+Contents of ``LINK_OPTIONS`` may use "generator expressions" with the
+syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)` manual
+for available expressions. See the :manual:`cmake-buildsystem(7)` manual
+for more on defining buildsystem properties.
diff --git a/Help/prop_dir/TESTS.rst b/Help/prop_dir/TESTS.rst
new file mode 100644
index 000000000..1c9f6e5c6
--- /dev/null
+++ b/Help/prop_dir/TESTS.rst
@@ -0,0 +1,8 @@
+TESTS
+-----
+
+List of tests.
+
+This read-only property holds a
+:ref:`semicolon-separated list <CMake Language Lists>` of tests
+defined so far, in the current directory, by the :command:`add_test` command.
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_gbl/CMAKE_ROLE.rst b/Help/prop_gbl/CMAKE_ROLE.rst
new file mode 100644
index 000000000..27512fada
--- /dev/null
+++ b/Help/prop_gbl/CMAKE_ROLE.rst
@@ -0,0 +1,20 @@
+CMAKE_ROLE
+----------
+
+Tells what mode the current running script is in. Could be one of several
+values:
+
+``PROJECT``
+ Running in project mode (processing a ``CMakeLists.txt`` file).
+
+``SCRIPT``
+ Running in ``-P`` script mode.
+
+``FIND_PACKAGE``
+ Running in ``--find-package`` mode.
+
+``CTEST``
+ Running in CTest script mode.
+
+``CPACK``
+ Running in CPack.
diff --git a/Help/prop_gbl/ECLIPSE_EXTRA_CPROJECT_CONTENTS.rst b/Help/prop_gbl/ECLIPSE_EXTRA_CPROJECT_CONTENTS.rst
new file mode 100644
index 000000000..50c41a923
--- /dev/null
+++ b/Help/prop_gbl/ECLIPSE_EXTRA_CPROJECT_CONTENTS.rst
@@ -0,0 +1,12 @@
+ECLIPSE_EXTRA_CPROJECT_CONTENTS
+-------------------------------
+
+Additional contents to be inserted into the generated Eclipse cproject file.
+
+The cproject file defines the CDT specific information. Some third party IDE's
+are based on Eclipse with the addition of other information specific to that IDE.
+Through this property, it is possible to add this additional contents to
+the generated project.
+It is expected to contain valid XML.
+
+Also see the :prop_gbl:`ECLIPSE_EXTRA_NATURES` property.
diff --git a/Help/prop_sf/COMPILE_OPTIONS.rst b/Help/prop_sf/COMPILE_OPTIONS.rst
new file mode 100644
index 000000000..7e48271d0
--- /dev/null
+++ b/Help/prop_sf/COMPILE_OPTIONS.rst
@@ -0,0 +1,21 @@
+COMPILE_OPTIONS
+---------------
+
+List of additional options to pass to the compiler.
+
+This property holds a :ref:`semicolon-separated list <CMake Language Lists>` of options
+and will be added to the list of compile flags when this
+source file builds. Use :prop_sf:`COMPILE_DEFINITIONS` to pass
+additional preprocessor definitions and :prop_sf:`INCLUDE_DIRECTORIES` to pass
+additional include directories.
+
+Contents of ``COMPILE_OPTIONS`` may use "generator expressions" with the
+syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)` manual
+for available expressions. However, :generator:`Xcode`
+does not support per-config per-source settings, so expressions
+that depend on the build configuration are not allowed with that
+generator.
+
+.. note::
+
+ This property should be preferred over the :prop_sf:`COMPILE_FLAGS` property.
diff --git a/Help/prop_sf/INCLUDE_DIRECTORIES.rst b/Help/prop_sf/INCLUDE_DIRECTORIES.rst
new file mode 100644
index 000000000..23de70e16
--- /dev/null
+++ b/Help/prop_sf/INCLUDE_DIRECTORIES.rst
@@ -0,0 +1,18 @@
+INCLUDE_DIRECTORIES
+-------------------
+
+List of preprocessor include file search directories.
+
+This property holds a :ref:`semicolon-separated list <CMake Language Lists>` of paths
+and will be added to the list of include directories when this
+source file builds. These directories will take precedence over directories
+defined at target level except for :generator:`Xcode` generator due to technical
+limitations.
+
+Relative paths should not be added to this property directly.
+
+Contents of ``INCLUDE_DIRECTORIES`` may use "generator expressions" with
+the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)` manual
+for available expressions. However, :generator:`Xcode` does not support
+per-config per-source settings, so expressions that depend on the build
+configuration are not allowed with that generator.
diff --git a/Help/prop_sf/Swift_DEPENDENCIES_FILE.rst b/Help/prop_sf/Swift_DEPENDENCIES_FILE.rst
new file mode 100644
index 000000000..faac2df7b
--- /dev/null
+++ b/Help/prop_sf/Swift_DEPENDENCIES_FILE.rst
@@ -0,0 +1,5 @@
+Swift_DEPENDENCIES_FILE
+-----------------------
+
+This property sets the path for the Swift dependency file (swiftdeps) for the
+source. If one is not specified, it will default to ``<OBJECT>.swiftdeps``.
diff --git a/Help/prop_sf/Swift_DIAGNOSTICS_FILE.rst b/Help/prop_sf/Swift_DIAGNOSTICS_FILE.rst
new file mode 100644
index 000000000..5bf5d59cd
--- /dev/null
+++ b/Help/prop_sf/Swift_DIAGNOSTICS_FILE.rst
@@ -0,0 +1,4 @@
+Swift_DIAGNOSTICS_FILE
+----------------------
+
+This property controls where the Swift diagnostics are serialized.
diff --git a/Help/prop_sf/VS_SHADER_DISABLE_OPTIMIZATIONS.rst b/Help/prop_sf/VS_SHADER_DISABLE_OPTIMIZATIONS.rst
new file mode 100644
index 000000000..446dd26d9
--- /dev/null
+++ b/Help/prop_sf/VS_SHADER_DISABLE_OPTIMIZATIONS.rst
@@ -0,0 +1,6 @@
+VS_SHADER_DISABLE_OPTIMIZATIONS
+-------------------------------
+
+Disable compiler optimizations for an ``.hlsl`` source file. This adds the
+``-Od`` flag to the command line for the FxCompiler tool. Specify the value
+``true`` for this property to disable compiler optimizations.
diff --git a/Help/prop_sf/VS_SHADER_ENABLE_DEBUG.rst b/Help/prop_sf/VS_SHADER_ENABLE_DEBUG.rst
new file mode 100644
index 000000000..c0e60a3e3
--- /dev/null
+++ b/Help/prop_sf/VS_SHADER_ENABLE_DEBUG.rst
@@ -0,0 +1,6 @@
+VS_SHADER_ENABLE_DEBUG
+----------------------
+
+Enable debugging information for an ``.hlsl`` source file. This adds the
+``-Zi`` flag to the command line for the FxCompiler tool. Specify the value
+``true`` to generate debugging information for the compiled shader.
diff --git a/Help/prop_sf/VS_SHADER_OBJECT_FILE_NAME.rst b/Help/prop_sf/VS_SHADER_OBJECT_FILE_NAME.rst
new file mode 100644
index 000000000..093bcc666
--- /dev/null
+++ b/Help/prop_sf/VS_SHADER_OBJECT_FILE_NAME.rst
@@ -0,0 +1,6 @@
+VS_SHADER_OBJECT_FILE_NAME
+--------------------------
+
+Specifies a file name for the compiled shader object file for an ``.hlsl``
+source file. This adds the ``-Fo`` flag to the command line for the FxCompiler
+tool.
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/PROCESSOR_AFFINITY.rst b/Help/prop_test/PROCESSOR_AFFINITY.rst
new file mode 100644
index 000000000..38ec17947
--- /dev/null
+++ b/Help/prop_test/PROCESSOR_AFFINITY.rst
@@ -0,0 +1,11 @@
+PROCESSOR_AFFINITY
+------------------
+
+Set to a true value to ask CTest to launch the test process with CPU affinity
+for a fixed set of processors. If enabled and supported for the current
+platform, CTest will choose a set of processors to place in the CPU affinity
+mask when launching the test process. The number of processors in the set is
+determined by the :prop_test:`PROCESSORS` test property or the number of
+processors available to CTest, whichever is smaller. The set of processors
+chosen will be disjoint from the processors assigned to other concurrently
+running tests that also have the ``PROCESSOR_AFFINITY`` property enabled.
diff --git a/Help/prop_tgt/ADDITIONAL_CLEAN_FILES.rst b/Help/prop_tgt/ADDITIONAL_CLEAN_FILES.rst
new file mode 100644
index 000000000..3b9d965f8
--- /dev/null
+++ b/Help/prop_tgt/ADDITIONAL_CLEAN_FILES.rst
@@ -0,0 +1,23 @@
+ADDITIONAL_CLEAN_FILES
+----------------------
+
+A :ref:`;-list <CMake Language Lists>` of files or directories that will be
+removed as a part of the global ``clean`` target. It can be used to specify
+files and directories that are generated as part of building the target or
+that are directly associated with the target in some way (e.g. created as a
+result of running the target).
+
+For custom targets, if such files can be captured as outputs or byproducts
+instead, then that should be preferred over adding them to this property.
+If an additional clean file is used by multiple targets or isn't
+target-specific, then the :prop_dir:`ADDITIONAL_CLEAN_FILES` directory
+property may be the more appropriate property to use.
+
+Relative paths are allowed and are interpreted relative to the
+current binary directory.
+
+Contents of ``ADDITIONAL_CLEAN_FILES`` may use
+:manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+This property only works for the :generator:`Ninja` and the Makefile
+generators. It is ignored by other generators.
diff --git a/Help/prop_tgt/AUTOGEN_ORIGIN_DEPENDS.rst b/Help/prop_tgt/AUTOGEN_ORIGIN_DEPENDS.rst
new file mode 100644
index 000000000..022bab502
--- /dev/null
+++ b/Help/prop_tgt/AUTOGEN_ORIGIN_DEPENDS.rst
@@ -0,0 +1,38 @@
+AUTOGEN_ORIGIN_DEPENDS
+----------------------
+
+Switch for forwarding origin target dependencies to the corresponding
+``_autogen`` target.
+
+Targets which have their :prop_tgt:`AUTOMOC` or :prop_tgt:`AUTOUIC` property
+``ON`` have a corresponding ``_autogen`` target which generates
+``moc`` and ``uic`` files. As this ``_autogen`` target is created at
+generate-time, it is not possible to define dependencies of it using
+e.g. :command:`add_dependencies`. Instead the
+:prop_tgt:`AUTOGEN_ORIGIN_DEPENDS` target property decides whether the origin
+target dependencies should be forwarded to the ``_autogen`` target or not.
+
+By default :prop_tgt:`AUTOGEN_ORIGIN_DEPENDS` is initialized from
+:variable:`CMAKE_AUTOGEN_ORIGIN_DEPENDS` which is ``ON`` by default.
+
+In total the dependencies of the ``_autogen`` target are composed from
+
+- forwarded origin target dependencies
+ (enabled by default via :prop_tgt:`AUTOGEN_ORIGIN_DEPENDS`)
+- additional user defined dependencies from :prop_tgt:`AUTOGEN_TARGET_DEPENDS`
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
+
+Note
+^^^^
+
+Disabling :prop_tgt:`AUTOGEN_ORIGIN_DEPENDS` is useful to avoid building of
+origin target dependencies when building the ``_autogen`` target only.
+This is especially interesting when a
+:variable:`global autogen target <CMAKE_GLOBAL_AUTOGEN_TARGET>` is enabled.
+
+When the ``_autogen`` target doesn't require all the origin target's
+dependencies, and :prop_tgt:`AUTOGEN_ORIGIN_DEPENDS` is disabled, it might be
+necessary to extend :prop_tgt:`AUTOGEN_TARGET_DEPENDS` to add missing
+dependencies.
diff --git a/Help/prop_tgt/AUTOGEN_PARALLEL.rst b/Help/prop_tgt/AUTOGEN_PARALLEL.rst
new file mode 100644
index 000000000..07fbc5a5e
--- /dev/null
+++ b/Help/prop_tgt/AUTOGEN_PARALLEL.rst
@@ -0,0 +1,21 @@
+AUTOGEN_PARALLEL
+----------------
+
+Number of parallel ``moc`` or ``uic`` processes to start when using
+:prop_tgt:`AUTOMOC` and :prop_tgt:`AUTOUIC`.
+
+The custom `<origin>_autogen` target starts a number of threads of which
+each one parses a source file and on demand starts a ``moc`` or ``uic``
+process. :prop_tgt:`AUTOGEN_PARALLEL` controls how many parallel threads
+(and therefore ``moc`` or ``uic`` processes) are started.
+
+- An empty (or unset) value or the string ``AUTO`` sets the number of
+ threads/processes to the number of physical CPUs on the host system.
+- A positive non zero integer value sets the exact thread/process count.
+- Otherwise a single thread/process is started.
+
+By default :prop_tgt:`AUTOGEN_PARALLEL` is initialized from
+:variable:`CMAKE_AUTOGEN_PARALLEL`.
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
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_EXECUTABLE.rst b/Help/prop_tgt/AUTOMOC_EXECUTABLE.rst
new file mode 100644
index 000000000..6b66ce81f
--- /dev/null
+++ b/Help/prop_tgt/AUTOMOC_EXECUTABLE.rst
@@ -0,0 +1,15 @@
+AUTOMOC_EXECUTABLE
+------------------
+
+:prop_tgt:`AUTOMOC_EXECUTABLE` is file path pointing to the ``moc``
+executable to use for :prop_tgt:`AUTOMOC` enabled files. Setting
+this property will make CMake skip the automatic detection of the
+``moc`` binary as well as the sanity-tests normally run to ensure
+that the binary is available and working as expected.
+
+Usually this property does not need to be set. Only consider this
+property if auto-detection of ``moc`` can not work -- e.g. because
+you are building the ``moc`` binary as part of your project.
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
diff --git a/Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst b/Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst
new file mode 100644
index 000000000..5329bbac9
--- /dev/null
+++ b/Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst
@@ -0,0 +1,32 @@
+AUTOMOC_MACRO_NAMES
+-------------------
+
+A :ref:`semicolon-separated 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 ``Q_OBJECT`` macro is hidden inside another 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_EXECUTABLE.rst b/Help/prop_tgt/AUTORCC_EXECUTABLE.rst
new file mode 100644
index 000000000..ca0fbd75b
--- /dev/null
+++ b/Help/prop_tgt/AUTORCC_EXECUTABLE.rst
@@ -0,0 +1,15 @@
+AUTORCC_EXECUTABLE
+------------------
+
+:prop_tgt:`AUTORCC_EXECUTABLE` is file path pointing to the ``rcc``
+executable to use for :prop_tgt:`AUTORCC` enabled files. Setting
+this property will make CMake skip the automatic detection of the
+``rcc`` binary as well as the sanity-tests normally run to ensure
+that the binary is available and working as expected.
+
+Usually this property does not need to be set. Only consider this
+property if auto-detection of ``rcc`` can not work -- e.g. because
+you are building the ``rcc`` binary as part of your project.
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
diff --git a/Help/prop_tgt/AUTOUIC_EXECUTABLE.rst b/Help/prop_tgt/AUTOUIC_EXECUTABLE.rst
new file mode 100644
index 000000000..03bd55499
--- /dev/null
+++ b/Help/prop_tgt/AUTOUIC_EXECUTABLE.rst
@@ -0,0 +1,15 @@
+AUTOUIC_EXECUTABLE
+------------------
+
+:prop_tgt:`AUTOUIC_EXECUTABLE` is file path pointing to the ``uic``
+executable to use for :prop_tgt:`AUTOUIC` enabled files. Setting
+this property will make CMake skip the automatic detection of the
+``uic`` binary as well as the sanity-tests normally run to ensure
+that the binary is available and working as expected.
+
+Usually this property does not need to be set. Only consider this
+property if auto-detection of ``uic`` can not work -- e.g. because
+you are building the ``uic`` binary as part of your project.
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
diff --git a/Help/prop_tgt/BUILD_RPATH_USE_ORIGIN.rst b/Help/prop_tgt/BUILD_RPATH_USE_ORIGIN.rst
new file mode 100644
index 000000000..337879780
--- /dev/null
+++ b/Help/prop_tgt/BUILD_RPATH_USE_ORIGIN.rst
@@ -0,0 +1,24 @@
+BUILD_RPATH_USE_ORIGIN
+----------------------
+
+Whether to use relative paths for the build ``RPATH``.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_BUILD_RPATH_USE_ORIGIN`.
+
+On platforms that support runtime paths (``RPATH``) with the
+``$ORIGIN`` token, setting this property to ``TRUE`` enables relative
+paths in the build ``RPATH`` for executables and shared libraries that
+point to shared libraries in the same build tree.
+
+Normally the build ``RPATH`` of a binary contains absolute paths
+to the directory of each shared library it links to. The ``RPATH``
+entries for directories contained within the build tree can be made
+relative to enable relocatable builds and to help achieve reproducible
+builds by omitting the build directory from the build environment.
+
+This property has no effect on platforms that do not support the
+``$ORIGIN`` token in ``RPATH``, or when the :variable:`CMAKE_SKIP_RPATH`
+variable is set. The runtime path set through the
+:prop_tgt:`BUILD_RPATH` target property is also unaffected by this
+property.
diff --git a/Help/prop_tgt/COMMON_LANGUAGE_RUNTIME.rst b/Help/prop_tgt/COMMON_LANGUAGE_RUNTIME.rst
new file mode 100644
index 000000000..052ac6df0
--- /dev/null
+++ b/Help/prop_tgt/COMMON_LANGUAGE_RUNTIME.rst
@@ -0,0 +1,22 @@
+COMMON_LANGUAGE_RUNTIME
+-----------------------
+
+By setting this target property, the target is configured to build with
+``C++/CLI`` support.
+
+The Visual Studio generator defines the ``clr`` parameter depending on
+the value of ``COMMON_LANGUAGE_RUNTIME``:
+
+* property not set: native C++ (i.e. default)
+* property set but empty: mixed unmanaged/managed C++
+* property set to any non empty value: managed C++
+
+Supported values: ``""``, ``"pure"``, ``"safe"``
+
+This property is only evaluated :ref:`Visual Studio Generators` for
+VS 2010 and above.
+
+To be able to build managed C++ targets with VS 2017 and above the component
+``C++/CLI support`` must be installed, which may not be done by default.
+
+See also :prop_tgt:`IMPORTED_COMMON_LANGUAGE_RUNTIME`
diff --git a/Help/prop_tgt/DEPLOYMENT_ADDITIONAL_FILES.rst b/Help/prop_tgt/DEPLOYMENT_ADDITIONAL_FILES.rst
new file mode 100644
index 000000000..5e9c19158
--- /dev/null
+++ b/Help/prop_tgt/DEPLOYMENT_ADDITIONAL_FILES.rst
@@ -0,0 +1,18 @@
+DEPLOYMENT_ADDITIONAL_FILES
+---------------------------
+
+Set the WinCE project ``AdditionalFiles`` in ``DeploymentTool`` in ``.vcproj``
+files generated by the :generator:`Visual Studio 9 2008` generator.
+This is useful when you want to debug on remote WinCE device.
+Specify additional files that will be copied to the device.
+For example:
+
+.. code-block:: cmake
+
+ set_property(TARGET ${TARGET} PROPERTY
+ DEPLOYMENT_ADDITIONAL_FILES "english.lng|local_folder|remote_folder|0"
+ "german.lng|local_folder|remote_folder|0")
+
+produces::
+
+ <DeploymentTool AdditionalFiles="english.lng|local_folder|remote_folder|0;german.lng|local_folder|remote_folder|0" ... />
diff --git a/Help/prop_tgt/DOTNET_TARGET_FRAMEWORK_VERSION.rst b/Help/prop_tgt/DOTNET_TARGET_FRAMEWORK_VERSION.rst
new file mode 100644
index 000000000..c100326b9
--- /dev/null
+++ b/Help/prop_tgt/DOTNET_TARGET_FRAMEWORK_VERSION.rst
@@ -0,0 +1,13 @@
+DOTNET_TARGET_FRAMEWORK_VERSION
+-------------------------------
+
+Specify the .NET target framework version.
+
+Used to specify the .NET target framework version for C++/CLI. For
+example: ``v4.5``.
+
+This property is only evaluated for :ref:`Visual Studio Generators`
+VS 2010 and above.
+
+Can be initialized for all targets using the variable
+:variable:`CMAKE_DOTNET_TARGET_FRAMEWORK_VERSION`.
diff --git a/Help/prop_tgt/EXPORT_PROPERTIES.rst b/Help/prop_tgt/EXPORT_PROPERTIES.rst
new file mode 100644
index 000000000..bcf47a624
--- /dev/null
+++ b/Help/prop_tgt/EXPORT_PROPERTIES.rst
@@ -0,0 +1,14 @@
+EXPORT_PROPERTIES
+-----------------
+
+List additional properties to export for a target.
+
+This property contains a list of property names that should be exported by
+the :command:`install(EXPORT)` and :command:`export` commands. By default
+only a limited number of properties are exported. This property can be used
+to additionally export other properties as well.
+
+Properties starting with ``INTERFACE_`` or ``IMPORTED_`` are not allowed as
+they are reserved for internal CMake use.
+
+Properties containing generator expressions are also not allowed.
diff --git a/Help/prop_tgt/GHS_INTEGRITY_APP.rst b/Help/prop_tgt/GHS_INTEGRITY_APP.rst
new file mode 100644
index 000000000..b6697817a
--- /dev/null
+++ b/Help/prop_tgt/GHS_INTEGRITY_APP.rst
@@ -0,0 +1,10 @@
+GHS_INTEGRITY_APP
+-----------------
+
+``ON`` / ``OFF`` boolean to determine if an executable target should
+be treated as an `Integrity Application`.
+
+If no value is set and if a ``.int`` file is added as a source file to the
+executable target it will be treated as an `Integrity Application`.
+
+Supported on :generator:`Green Hills MULTI`.
diff --git a/Help/prop_tgt/GHS_NO_SOURCE_GROUP_FILE.rst b/Help/prop_tgt/GHS_NO_SOURCE_GROUP_FILE.rst
new file mode 100644
index 000000000..11ce0b223
--- /dev/null
+++ b/Help/prop_tgt/GHS_NO_SOURCE_GROUP_FILE.rst
@@ -0,0 +1,13 @@
+GHS_NO_SOURCE_GROUP_FILE
+------------------------
+
+``ON`` / ``OFF`` boolean to control if the project file for a target should
+be one single file or multiple files.
+
+The default behavior or when the property is ``OFF`` is to generate a project
+file for the target and then a sub-project file for each source group.
+
+When this property is ``ON`` or if :variable:`CMAKE_GHS_NO_SOURCE_GROUP_FILE`
+is ``ON`` then only a single project file is generated for the target.
+
+Supported on :generator:`Green Hills MULTI`.
diff --git a/Help/prop_tgt/IMPORTED_COMMON_LANGUAGE_RUNTIME.rst b/Help/prop_tgt/IMPORTED_COMMON_LANGUAGE_RUNTIME.rst
new file mode 100644
index 000000000..99e3bc45e
--- /dev/null
+++ b/Help/prop_tgt/IMPORTED_COMMON_LANGUAGE_RUNTIME.rst
@@ -0,0 +1,8 @@
+IMPORTED_COMMON_LANGUAGE_RUNTIME
+--------------------------------
+
+Property to define if the target uses ``C++/CLI``.
+
+Ignored for non-imported targets.
+
+See also the :prop_tgt:`COMMON_LANGUAGE_RUNTIME` target property.
diff --git a/Help/prop_tgt/IMPORTED_GLOBAL.rst b/Help/prop_tgt/IMPORTED_GLOBAL.rst
new file mode 100644
index 000000000..1feca049d
--- /dev/null
+++ b/Help/prop_tgt/IMPORTED_GLOBAL.rst
@@ -0,0 +1,22 @@
+IMPORTED_GLOBAL
+---------------
+
+Indication of whether an :ref:`IMPORTED target <Imported Targets>` is
+globally visible.
+
+The boolean value of this property is True for targets created with the
+``IMPORTED`` ``GLOBAL`` options to :command:`add_executable()` or
+:command:`add_library()`. It is always False for targets built within the
+project.
+
+For targets created with the ``IMPORTED`` option to
+:command:`add_executable()` or :command:`add_library()` but without the
+additional option ``GLOBAL`` this is False, too. However, setting this
+property for such a locally ``IMPORTED`` target to True promotes that
+target to global scope. This promotion can only be done in the same
+directory where that ``IMPORTED`` target was created in the first place.
+
+Once an imported target has been made global, it cannot be changed back to
+non-global. Therefore, if a project sets this property, it may only
+provide a value of True. CMake will issue an error if the project tries to
+set the property to a non-True value, even if the value was already False.
diff --git a/Help/prop_tgt/INTERFACE_LINK_DEPENDS.rst b/Help/prop_tgt/INTERFACE_LINK_DEPENDS.rst
new file mode 100644
index 000000000..790554d9f
--- /dev/null
+++ b/Help/prop_tgt/INTERFACE_LINK_DEPENDS.rst
@@ -0,0 +1,32 @@
+INTERFACE_LINK_DEPENDS
+----------------------
+
+Additional public interface files on which a target binary depends for linking.
+
+This property is supported only by :generator:`Ninja` and
+:ref:`Makefile Generators`.
+It is intended to specify dependencies on "linker scripts" for
+custom Makefile link rules.
+
+When target dependencies are specified using :command:`target_link_libraries`,
+CMake will read this property from all target dependencies to determine the
+build properties of the consumer.
+
+Contents of ``INTERFACE_LINK_DEPENDS`` may use "generator expressions"
+with the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
+manual for available expressions. See the :manual:`cmake-buildsystem(7)`
+-manual for more on defining buildsystem properties.
+
+Link dependency files usage requirements commonly differ between the build-tree
+and the install-tree. The ``BUILD_INTERFACE`` and ``INSTALL_INTERFACE``
+generator expressions can be used to describe separate usage requirements
+based on the usage location. Relative paths are allowed within the
+``INSTALL_INTERFACE`` expression and are interpreted relative to the
+installation prefix. For example:
+
+.. code-block:: cmake
+
+ set_property(TARGET mylib PROPERTY INTERFACE_LINK_DEPENDS
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/mylinkscript>
+ $<INSTALL_INTERFACE:mylinkscript> # <prefix>/mylinkscript
+ )
diff --git a/Help/prop_tgt/INTERFACE_LINK_DIRECTORIES.rst b/Help/prop_tgt/INTERFACE_LINK_DIRECTORIES.rst
new file mode 100644
index 000000000..56a4ec0ec
--- /dev/null
+++ b/Help/prop_tgt/INTERFACE_LINK_DIRECTORIES.rst
@@ -0,0 +1,9 @@
+INTERFACE_LINK_DIRECTORIES
+--------------------------
+
+.. |property_name| replace:: link directories
+.. |command_name| replace:: :command:`target_link_directories`
+.. |PROPERTY_INTERFACE_NAME| replace:: ``INTERFACE_LINK_DIRECTORIES``
+.. |PROPERTY_LINK| replace:: :prop_tgt:`LINK_DIRECTORIES`
+.. |PROPERTY_GENEX| replace:: ``$<TARGET_PROPERTY:foo,INTERFACE_LINK_DIRECTORIES>``
+.. include:: INTERFACE_BUILD_PROPERTY.txt
diff --git a/Help/prop_tgt/INTERFACE_LINK_OPTIONS.rst b/Help/prop_tgt/INTERFACE_LINK_OPTIONS.rst
new file mode 100644
index 000000000..c293b986d
--- /dev/null
+++ b/Help/prop_tgt/INTERFACE_LINK_OPTIONS.rst
@@ -0,0 +1,9 @@
+INTERFACE_LINK_OPTIONS
+----------------------
+
+.. |property_name| replace:: link options
+.. |command_name| replace:: :command:`target_link_options`
+.. |PROPERTY_INTERFACE_NAME| replace:: ``INTERFACE_LINK_OPTIONS``
+.. |PROPERTY_LINK| replace:: :prop_tgt:`LINK_OPTIONS`
+.. |PROPERTY_GENEX| replace:: ``$<TARGET_PROPERTY:foo,INTERFACE_LINK_OPTIONS>``
+.. include:: INTERFACE_BUILD_PROPERTY.txt
diff --git a/Help/prop_tgt/LANG_CPPCHECK.rst b/Help/prop_tgt/LANG_CPPCHECK.rst
new file mode 100644
index 000000000..60785d062
--- /dev/null
+++ b/Help/prop_tgt/LANG_CPPCHECK.rst
@@ -0,0 +1,15 @@
+<LANG>_CPPCHECK
+---------------
+
+This property is supported only when ``<LANG>`` is ``C`` or ``CXX``.
+
+Specify a :ref:`semicolon-separated 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. If the command-line specifies the
+exit code options to ``cppcheck`` then the build will fail if the
+tool returns non-zero.
+
+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/LINK_DIRECTORIES.rst b/Help/prop_tgt/LINK_DIRECTORIES.rst
new file mode 100644
index 000000000..c2905b37d
--- /dev/null
+++ b/Help/prop_tgt/LINK_DIRECTORIES.rst
@@ -0,0 +1,18 @@
+LINK_DIRECTORIES
+----------------
+
+List of directories to use for the link step of shared library, module
+and executable targets.
+
+This property holds a :ref:`semicolon-separated list <CMake Language Lists>` of directories
+specified so far for its target. Use the :command:`target_link_directories`
+command to append more search directories.
+
+This property is initialized by the :prop_dir:`LINK_DIRECTORIES` directory
+property when a target is created, and is used by the generators to set
+the search directories for the linker.
+
+Contents of ``LINK_DIRECTORIES`` may use "generator expressions" with the
+syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)` manual
+for available expressions. See the :manual:`cmake-buildsystem(7)` manual
+for more on defining buildsystem properties.
diff --git a/Help/prop_tgt/LINK_LIBRARIES_INDIRECTION.txt b/Help/prop_tgt/LINK_LIBRARIES_INDIRECTION.txt
new file mode 100644
index 000000000..1fdb6ad0e
--- /dev/null
+++ b/Help/prop_tgt/LINK_LIBRARIES_INDIRECTION.txt
@@ -0,0 +1,10 @@
+.. note::
+ A call to :command:`target_link_libraries(<target> ...)` may update this
+ property on ``<target>``. If ``<target>`` was not created in the same
+ directory as the call then :command:`target_link_libraries` will add a
+ suffix of the form ``::@<directory-id>`` to each entry, where the
+ ``::@`` is a separator and the ``<directory-id>`` is unspecified.
+ This tells the generators that the named libraries must be looked up in
+ the scope of the caller rather than in the scope in which the
+ ``<target>`` was created. Valid directory ids are stripped on export
+ by the :command:`install(EXPORT)` and :command:`export` commands.
diff --git a/Help/prop_tgt/LINK_OPTIONS.rst b/Help/prop_tgt/LINK_OPTIONS.rst
new file mode 100644
index 000000000..2a05ea75a
--- /dev/null
+++ b/Help/prop_tgt/LINK_OPTIONS.rst
@@ -0,0 +1,24 @@
+LINK_OPTIONS
+------------
+
+List of options to use for the link step of shared library, module
+and executable targets. Targets that are static libraries need to use
+the :prop_tgt:`STATIC_LIBRARY_OPTIONS` target property.
+
+
+This property holds a :ref:`semicolon-separated list <CMake Language Lists>` of options
+specified so far for its target. Use the :command:`target_link_options`
+command to append more options.
+
+This property is initialized by the :prop_dir:`LINK_OPTIONS` directory
+property when a target is created, and is used by the generators to set
+the options for the compiler.
+
+Contents of ``LINK_OPTIONS`` may use "generator expressions" with the
+syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)` manual
+for available expressions. See the :manual:`cmake-buildsystem(7)` manual
+for more on defining buildsystem properties.
+
+.. note::
+
+ This property must be used in preference to :prop_tgt:`LINK_FLAGS` property.
diff --git a/Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt b/Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt
new file mode 100644
index 000000000..6c6134197
--- /dev/null
+++ b/Help/prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt
@@ -0,0 +1,20 @@
+``MultiThreaded``
+ Compile with ``-MT`` or equivalent flag(s) to use a multi-threaded
+ statically-linked runtime library.
+``MultiThreadedDLL``
+ Compile with ``-MD`` or equivalent flag(s) to use a multi-threaded
+ dynamically-linked runtime library.
+``MultiThreadedDebug``
+ Compile with ``-MTd`` or equivalent flag(s) to use a multi-threaded
+ statically-linked runtime library.
+``MultiThreadedDebugDLL``
+ Compile with ``-MDd`` or equivalent flag(s) to use a multi-threaded
+ dynamically-linked runtime library.
+
+The value is ignored on non-MSVC compilers but an unsupported value will
+be rejected as an error when using a compiler targeting the MSVC ABI.
+
+The value may also be the empty string (``""``) in which case no runtime
+library selection flag will be added explicitly by CMake. Note that with
+:ref:`Visual Studio Generators` the native build system may choose to
+add its own default runtime library selection flag.
diff --git a/Help/prop_tgt/MSVC_RUNTIME_LIBRARY.rst b/Help/prop_tgt/MSVC_RUNTIME_LIBRARY.rst
new file mode 100644
index 000000000..73792def1
--- /dev/null
+++ b/Help/prop_tgt/MSVC_RUNTIME_LIBRARY.rst
@@ -0,0 +1,29 @@
+MSVC_RUNTIME_LIBRARY
+--------------------
+
+Select the MSVC runtime library for use by compilers targeting the MSVC ABI.
+
+The allowed values are:
+
+.. include:: MSVC_RUNTIME_LIBRARY-VALUES.txt
+
+Use :manual:`generator expressions <cmake-generator-expressions(7)>` to
+support per-configuration specification. For example, the code:
+
+.. code-block:: cmake
+
+ add_executable(foo foo.c)
+ set_property(TARGET foo PROPERTY
+ MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
+
+selects for the target ``foo`` a multi-threaded statically-linked runtime
+library with or without debug information depending on the configuration.
+
+If this property is not set then CMake uses the default value
+``MultiThreaded$<$<CONFIG:Debug>:Debug>DLL`` to select a MSVC runtime library.
+
+.. note::
+
+ This property has effect only when policy :policy:`CMP0091` is set to ``NEW``
+ prior to the first :command:`project` or :command:`enable_language` command
+ that enables a language using a compiler targeting the MSVC ABI.
diff --git a/Help/prop_tgt/STATIC_LIBRARY_OPTIONS.rst b/Help/prop_tgt/STATIC_LIBRARY_OPTIONS.rst
new file mode 100644
index 000000000..d05fda4aa
--- /dev/null
+++ b/Help/prop_tgt/STATIC_LIBRARY_OPTIONS.rst
@@ -0,0 +1,20 @@
+STATIC_LIBRARY_OPTIONS
+----------------------
+
+Archiver (or MSVC librarian) flags for a static library target.
+Targets that are shared libraries, modules, or executables need to use
+the :prop_tgt:`LINK_OPTIONS` target property.
+
+This property holds a :ref:`semicolon-separated list <CMake Language Lists>` of options
+specified so far for its target. Use :command:`set_target_properties` or
+:command:`set_property` commands to set its content.
+
+Contents of ``STATIC_LIBRARY_OPTIONS`` may use "generator expressions" with the
+syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)` manual
+for available expressions. See the :manual:`cmake-buildsystem(7)` manual
+for more on defining buildsystem properties.
+
+.. note::
+
+ This property must be used in preference to :prop_tgt:`STATIC_LIBRARY_FLAGS`
+ property.
diff --git a/Help/prop_tgt/Swift_DEPENDENCIES_FILE.rst b/Help/prop_tgt/Swift_DEPENDENCIES_FILE.rst
new file mode 100644
index 000000000..46c9a1d9b
--- /dev/null
+++ b/Help/prop_tgt/Swift_DEPENDENCIES_FILE.rst
@@ -0,0 +1,5 @@
+Swift_DEPENDENCIES_FILE
+-----------------------
+
+This property sets the path for the Swift dependency file (swiftdep) for the
+target. If one is not specified, it will default to ``<TARGET>.swiftdeps``.
diff --git a/Help/prop_tgt/Swift_MODULE_DIRECTORY.rst b/Help/prop_tgt/Swift_MODULE_DIRECTORY.rst
new file mode 100644
index 000000000..d40425166
--- /dev/null
+++ b/Help/prop_tgt/Swift_MODULE_DIRECTORY.rst
@@ -0,0 +1,10 @@
+Swift_MODULE_DIRECTORY
+----------------------
+
+Specify output directory for Swift modules provided by the target.
+
+If the target contains Swift source files, this specifies the directory in which
+the modules will be placed. When this property is not set, the modules will be
+placed in the build directory corresponding to the target's source directory.
+If the variable :variable:`CMAKE_Swift_MODULE_DIRECTORY` is set when a target is
+created its value is used to initialise this property.
diff --git a/Help/prop_tgt/Swift_MODULE_NAME.rst b/Help/prop_tgt/Swift_MODULE_NAME.rst
new file mode 100644
index 000000000..28660203e
--- /dev/null
+++ b/Help/prop_tgt/Swift_MODULE_NAME.rst
@@ -0,0 +1,5 @@
+Swift_MODULE_NAME
+-----------------
+
+This property specifies the name of the Swift module. It is defaulted to the
+name of the target.
diff --git a/Help/prop_tgt/VS_DEBUGGER_COMMAND.rst b/Help/prop_tgt/VS_DEBUGGER_COMMAND.rst
new file mode 100644
index 000000000..ba5fd0aeb
--- /dev/null
+++ b/Help/prop_tgt/VS_DEBUGGER_COMMAND.rst
@@ -0,0 +1,11 @@
+VS_DEBUGGER_COMMAND
+-------------------
+
+Sets the local debugger command for Visual Studio C++ targets.
+The property value may use
+:manual:`generator expressions <cmake-generator-expressions(7)>`.
+This is defined in ``<LocalDebuggerCommand>`` in the Visual Studio
+project file.
+
+This property only works for Visual Studio 2010 and above;
+it is ignored on other generators.
diff --git a/Help/prop_tgt/VS_DEBUGGER_COMMAND_ARGUMENTS.rst b/Help/prop_tgt/VS_DEBUGGER_COMMAND_ARGUMENTS.rst
new file mode 100644
index 000000000..06ef5d5fc
--- /dev/null
+++ b/Help/prop_tgt/VS_DEBUGGER_COMMAND_ARGUMENTS.rst
@@ -0,0 +1,11 @@
+VS_DEBUGGER_COMMAND_ARGUMENTS
+-----------------------------
+
+Sets the local debugger command line arguments for Visual Studio C++ targets.
+The property value may use
+:manual:`generator expressions <cmake-generator-expressions(7)>`.
+This is defined in ``<LocalDebuggerCommandArguments>`` in the Visual Studio
+project file.
+
+This property only works for Visual Studio 2010 and above;
+it is ignored on other generators.
diff --git a/Help/prop_tgt/VS_DEBUGGER_ENVIRONMENT.rst b/Help/prop_tgt/VS_DEBUGGER_ENVIRONMENT.rst
new file mode 100644
index 000000000..f55ac7bee
--- /dev/null
+++ b/Help/prop_tgt/VS_DEBUGGER_ENVIRONMENT.rst
@@ -0,0 +1,11 @@
+VS_DEBUGGER_ENVIRONMENT
+-----------------------
+
+Sets the local debugger environment for Visual Studio C++ targets.
+The property value may use
+:manual:`generator expressions <cmake-generator-expressions(7)>`.
+This is defined in ``<LocalDebuggerEnvironment>`` in the Visual Studio
+project file.
+
+This property only works for Visual Studio 2010 and above;
+it is ignored on other generators.
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/prop_tgt/VS_JUST_MY_CODE_DEBUGGING.rst b/Help/prop_tgt/VS_JUST_MY_CODE_DEBUGGING.rst
new file mode 100644
index 000000000..42fb8ad86
--- /dev/null
+++ b/Help/prop_tgt/VS_JUST_MY_CODE_DEBUGGING.rst
@@ -0,0 +1,10 @@
+VS_JUST_MY_CODE_DEBUGGING
+-------------------------
+
+Enable Just My Code with Visual Studio debugger.
+
+Supported on :ref:`Visual Studio Generators` for VS 2010 and higher,
+:ref:`Makefile Generators` and the :generator:`Ninja` generators.
+
+This property is initialized by the :variable:`CMAKE_VS_JUST_MY_CODE_DEBUGGING`
+variable if it is set when a target is created.
diff --git a/Help/prop_tgt/VS_NO_SOLUTION_DEPLOY.rst b/Help/prop_tgt/VS_NO_SOLUTION_DEPLOY.rst
new file mode 100644
index 000000000..ffcbde572
--- /dev/null
+++ b/Help/prop_tgt/VS_NO_SOLUTION_DEPLOY.rst
@@ -0,0 +1,46 @@
+VS_NO_SOLUTION_DEPLOY
+---------------------
+
+Specify that the target should not be marked for deployment to a Windows CE
+or Windows Phone device in the generated Visual Studio solution.
+
+Be default, all EXE and shared library (DLL) targets are marked to deploy to
+the target device in the generated Visual Studio solution.
+
+Generator expressions are supported.
+
+There are reasons one might want to exclude a target / generated project from
+deployment:
+
+- The library or executable may not be necessary in the primary deploy/debug
+ scenario, and excluding from deployment saves time in the
+ develop/download/debug cycle.
+- There may be insufficient space on the target device to accommodate all of
+ the build products.
+- Visual Studio 2013 requires a target device IP address be entered for each
+ target marked for deployment. For large numbers of targets, this can be
+ tedious.
+ NOTE: Visual Studio *will* deploy all project dependencies of a project
+ tagged for deployment to the IP address configured for that project even
+ if those dependencies are not tagged for deployment.
+
+
+Example 1
+^^^^^^^^^
+
+This shows setting the variable for the target foo.
+
+.. code-block:: cmake
+
+ add_library(foo SHARED foo.cpp)
+ set_property(TARGET foo PROPERTY VS_NO_SOLUTION_DEPLOY ON)
+
+Example 2
+^^^^^^^^^
+
+This shows setting the variable for the Release configuration only.
+
+.. code-block:: cmake
+
+ add_library(foo SHARED foo.cpp)
+ set_property(TARGET foo PROPERTY VS_NO_SOLUTION_DEPLOY "$<CONFIG:Release>")
diff --git a/Help/prop_tgt/VS_PACKAGE_REFERENCES.rst b/Help/prop_tgt/VS_PACKAGE_REFERENCES.rst
new file mode 100644
index 000000000..5a0465bcc
--- /dev/null
+++ b/Help/prop_tgt/VS_PACKAGE_REFERENCES.rst
@@ -0,0 +1,13 @@
+VS_PACKAGE_REFERENCES
+---------------------
+
+Visual Studio package references for nuget.
+
+Adds one or more semicolon-delimited package references to a generated
+Visual Studio project. The version of the package will be
+underscore delimited. For example, ``boost_1.7.0;nunit_3.12.*``.
+
+.. code-block:: cmake
+
+ set_property(TARGET ${TARGET_NAME} PROPERTY
+ VS_PACKAGE_REFERENCES "boost_1.7.0")
diff --git a/Help/prop_tgt/VS_PROJECT_IMPORT.rst b/Help/prop_tgt/VS_PROJECT_IMPORT.rst
new file mode 100644
index 000000000..569c8ea74
--- /dev/null
+++ b/Help/prop_tgt/VS_PROJECT_IMPORT.rst
@@ -0,0 +1,8 @@
+VS_PROJECT_IMPORT
+-----------------
+
+Visual Studio managed project imports
+
+Adds to a generated Visual Studio project one or more semicolon-delimited paths
+to .props files needed when building projects from some NuGet packages.
+For example, ``my_packages_path/MyPackage.1.0.0/build/MyPackage.props``.
diff --git a/Help/prop_tgt/XCODE_GENERATE_SCHEME.rst b/Help/prop_tgt/XCODE_GENERATE_SCHEME.rst
new file mode 100644
index 000000000..0adb5dbea
--- /dev/null
+++ b/Help/prop_tgt/XCODE_GENERATE_SCHEME.rst
@@ -0,0 +1,39 @@
+XCODE_GENERATE_SCHEME
+---------------------
+
+If enabled, the :generator:`Xcode` generator will generate schema files. These
+are useful to invoke analyze, archive, build-for-testing and test
+actions from the command line.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_GENERATE_SCHEME` if it is set when a target
+is created.
+
+The following target properties overwrite the default of the
+corresponding settings on the "Diagnostic" tab for each schema file.
+Each of those is initialized by the respective ``CMAKE_`` variable
+at target creation time.
+
+- :prop_tgt:`XCODE_SCHEME_ADDRESS_SANITIZER`
+- :prop_tgt:`XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN`
+- :prop_tgt:`XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER`
+- :prop_tgt:`XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS`
+- :prop_tgt:`XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE`
+- :prop_tgt:`XCODE_SCHEME_GUARD_MALLOC`
+- :prop_tgt:`XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP`
+- :prop_tgt:`XCODE_SCHEME_MALLOC_GUARD_EDGES`
+- :prop_tgt:`XCODE_SCHEME_MALLOC_SCRIBBLE`
+- :prop_tgt:`XCODE_SCHEME_MALLOC_STACK`
+- :prop_tgt:`XCODE_SCHEME_THREAD_SANITIZER`
+- :prop_tgt:`XCODE_SCHEME_THREAD_SANITIZER_STOP`
+- :prop_tgt:`XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER`
+- :prop_tgt:`XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP`
+- :prop_tgt:`XCODE_SCHEME_ZOMBIE_OBJECTS`
+
+The following target properties will be applied on the
+"Info" and "Arguments" tab:
+
+- :prop_tgt:`XCODE_SCHEME_ARGUMENTS`
+- :prop_tgt:`XCODE_SCHEME_DEBUG_AS_ROOT`
+- :prop_tgt:`XCODE_SCHEME_ENVIRONMENT`
+- :prop_tgt:`XCODE_SCHEME_EXECUTABLE`
diff --git a/Help/prop_tgt/XCODE_SCHEME_ADDRESS_SANITIZER.rst b/Help/prop_tgt/XCODE_SCHEME_ADDRESS_SANITIZER.rst
new file mode 100644
index 000000000..cc9bac2e6
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_ADDRESS_SANITIZER.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_ADDRESS_SANITIZER
+------------------------------
+
+Whether to enable ``Address Sanitizer`` in the Diagnostics
+section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN.rst b/Help/prop_tgt/XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN.rst
new file mode 100644
index 000000000..37a043a1a
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN
+-----------------------------------------------
+
+Whether to enable ``Detect use of stack after return``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN`
+if it is set when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_ARGUMENTS.rst b/Help/prop_tgt/XCODE_SCHEME_ARGUMENTS.rst
new file mode 100644
index 000000000..1f228e34c
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_ARGUMENTS.rst
@@ -0,0 +1,10 @@
+XCODE_SCHEME_ARGUMENTS
+----------------------
+
+Specify command line arguments that should be added to the Arguments
+section of the generated Xcode scheme.
+
+If set to a list of arguments those will be added to the scheme.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_DEBUG_AS_ROOT.rst b/Help/prop_tgt/XCODE_SCHEME_DEBUG_AS_ROOT.rst
new file mode 100644
index 000000000..5407e807b
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_DEBUG_AS_ROOT.rst
@@ -0,0 +1,7 @@
+XCODE_SCHEME_DEBUG_AS_ROOT
+--------------------------
+
+Whether to debug the target as 'root'.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER.rst b/Help/prop_tgt/XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER.rst
new file mode 100644
index 000000000..1a6fcfd2e
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER
+----------------------------------------
+
+Whether to disable the ``Main Thread Checker``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER`
+if it is set when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS.rst b/Help/prop_tgt/XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS.rst
new file mode 100644
index 000000000..922402290
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS
+----------------------------------
+
+Whether to enable ``Dynamic Library Loads``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE.rst b/Help/prop_tgt/XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE.rst
new file mode 100644
index 000000000..203c80329
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE
+-------------------------------------
+
+Whether to enable ``Dynamic Linker API usage``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_ENVIRONMENT.rst b/Help/prop_tgt/XCODE_SCHEME_ENVIRONMENT.rst
new file mode 100644
index 000000000..c6d875e88
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_ENVIRONMENT.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_ENVIRONMENT
+------------------------
+
+Specify environment variables that should be added to the Arguments
+section of the generated Xcode scheme.
+
+If set to a list of environment variables and values of the form
+``MYVAR=value`` those environment variables will be added to the
+scheme.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_EXECUTABLE.rst b/Help/prop_tgt/XCODE_SCHEME_EXECUTABLE.rst
new file mode 100644
index 000000000..104841b7c
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_EXECUTABLE.rst
@@ -0,0 +1,9 @@
+XCODE_SCHEME_EXECUTABLE
+-----------------------
+
+Specify path to executable in the Info section of the generated
+Xcode scheme. If not set the schema generator will select the
+current target if it is actually executable.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_GUARD_MALLOC.rst b/Help/prop_tgt/XCODE_SCHEME_GUARD_MALLOC.rst
new file mode 100644
index 000000000..c4e83da2f
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_GUARD_MALLOC.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_GUARD_MALLOC
+------------------------------
+
+Whether to enable ``Guard Malloc``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_GUARD_MALLOC` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP.rst b/Help/prop_tgt/XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP.rst
new file mode 100644
index 000000000..73992c3c3
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP.rst
@@ -0,0 +1,13 @@
+XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP
+-------------------------------------
+
+Whether to enable the ``Main Thread Checker`` option
+``Pause on issues``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_MALLOC_GUARD_EDGES.rst b/Help/prop_tgt/XCODE_SCHEME_MALLOC_GUARD_EDGES.rst
new file mode 100644
index 000000000..ca761c05b
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_MALLOC_GUARD_EDGES.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_MALLOC_GUARD_EDGES
+-------------------------------
+
+Whether to enable ``Malloc Guard Edges``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_MALLOC_GUARD_EDGES` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_MALLOC_SCRIBBLE.rst b/Help/prop_tgt/XCODE_SCHEME_MALLOC_SCRIBBLE.rst
new file mode 100644
index 000000000..c5ddb950f
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_MALLOC_SCRIBBLE.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_MALLOC_SCRIBBLE
+------------------------------
+
+Whether to enable ``Malloc Scribble``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_MALLOC_SCRIBBLE` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_MALLOC_STACK.rst b/Help/prop_tgt/XCODE_SCHEME_MALLOC_STACK.rst
new file mode 100644
index 000000000..170f33d90
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_MALLOC_STACK.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_MALLOC_STACK
+-------------------------
+
+Whether to enable ``Malloc Stack`` in the Diagnostics
+section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_MALLOC_STACK` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_THREAD_SANITIZER.rst b/Help/prop_tgt/XCODE_SCHEME_THREAD_SANITIZER.rst
new file mode 100644
index 000000000..bb70141f3
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_THREAD_SANITIZER.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_THREAD_SANITIZER
+-----------------------------
+
+Whether to enable ``Thread Sanitizer`` in the Diagnostics
+section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_THREAD_SANITIZER` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_THREAD_SANITIZER_STOP.rst b/Help/prop_tgt/XCODE_SCHEME_THREAD_SANITIZER_STOP.rst
new file mode 100644
index 000000000..5deadb16e
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_THREAD_SANITIZER_STOP.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_THREAD_SANITIZER_STOP
+----------------------------------
+
+Whether to enable ``Thread Sanitizer - Pause on issues``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_THREAD_SANITIZER_STOP` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER.rst b/Help/prop_tgt/XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER.rst
new file mode 100644
index 000000000..0cd823dec
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER
+------------------------------------------
+
+Whether to enable ``Undefined Behavior Sanitizer``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER`
+if it is set when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP.rst b/Help/prop_tgt/XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP.rst
new file mode 100644
index 000000000..d1a9bca2c
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP.rst
@@ -0,0 +1,13 @@
+XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP
+-----------------------------------------------
+
+Whether to enable ``Undefined Behavior Sanitizer`` option
+``Pause on issues``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP`
+if it is set when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/prop_tgt/XCODE_SCHEME_ZOMBIE_OBJECTS.rst b/Help/prop_tgt/XCODE_SCHEME_ZOMBIE_OBJECTS.rst
new file mode 100644
index 000000000..6e70e8be9
--- /dev/null
+++ b/Help/prop_tgt/XCODE_SCHEME_ZOMBIE_OBJECTS.rst
@@ -0,0 +1,12 @@
+XCODE_SCHEME_ZOMBIE_OBJECTS
+------------------------------
+
+Whether to enable ``Zombie Objects``
+in the Diagnostics section of the generated Xcode scheme.
+
+This property is initialized by the value of the variable
+:variable:`CMAKE_XCODE_SCHEME_ZOMBIE_OBJECTS` if it is set
+when a target is created.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/release/3.10.rst b/Help/release/3.10.rst
new file mode 100644
index 000000000..03eda362d
--- /dev/null
+++ b/Help/release/3.10.rst
@@ -0,0 +1,282 @@
+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. Note that a breaking change was made in CMake 3.10.3 to address
+ an ambiguity of the ``TIMEOUT`` keyword (see :ref:`Release Notes 3.10.3`).
+
+* 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
+-----
+
+* A :cpack_gen:`CPack FreeBSD Generator` was added for FreeBSD ``pkg(8)``.
+
+* The :cpack_gen:`CPack DEB Generator` 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 :cpack_gen:`CPack DEB Generator` learned to set package release
+ version in ``Version`` info property.
+ See the :variable:`CPACK_DEBIAN_PACKAGE_RELEASE` variable.
+
+* The :cpack_gen:`CPack DEB Generator` 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 :cpack_gen:`CPack IFW Generator` gained new
+ :variable:`CPACK_IFW_PACKAGE_FILE_EXTENSION` variable to customize
+ target binary format.
+
+* The :cpack_gen:`CPack IFW Generator` 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.
+
+* The :cpack_gen:`CPack RPM Generator` and :cpack_gen:`CPack DEB Generator`
+ learned to set the 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.
+
+Updates
+=======
+
+Changes made since CMake 3.10.0 include the following.
+
+3.10.1
+------
+
+* The :manual:`cmake-server(7)` ``codemodel`` response ``crossReferences``
+ field added by 3.10.0 has been dropped due to excessive memory usage.
+ Another approach will be needed to provide backtrace information.
+
+.. _`Release Notes 3.10.3`:
+
+3.10.3
+------
+
+* CMake 3.10.1 added a ``TIMEOUT`` option to :command:`gtest_discover_tests`
+ from the :module:`GoogleTest` module. That keyword clashed with the
+ ``TIMEOUT`` test property, which is one of the common properties that
+ would be set with the command's ``PROPERTIES`` keyword, usually leading
+ to legal but unintended behavior. The keyword was changed to
+ ``DISCOVERY_TIMEOUT`` in CMake 3.10.3 to address this problem. The
+ ambiguous behavior of the :command:`gtest_discover_tests` command's
+ ``TIMEOUT`` keyword in 3.10.1 and 3.10.2 has not been preserved.
diff --git a/Help/release/3.11.rst b/Help/release/3.11.rst
new file mode 100644
index 000000000..a80657d2d
--- /dev/null
+++ b/Help/release/3.11.rst
@@ -0,0 +1,307 @@
+CMake 3.11 Release Notes
+************************
+
+.. only:: html
+
+ .. contents::
+
+Changes made since CMake 3.10 include the following.
+
+New Features
+============
+
+Platforms
+---------
+
+* TI C/C++ compilers are now supported by the :generator:`Ninja` generator.
+
+Generators
+----------
+
+* The :generator:`CodeBlocks` extra generator learned to check a
+ :variable:`CMAKE_CODEBLOCKS_COMPILER_ID` variable for a custom
+ compiler identification value to place in the project file.
+
+* The :ref:`Makefile Generators` and the :generator:`Ninja` generator learned
+ to add compiler launcher tools along with the compiler for the ``Fortran``
+ language (``C``, ``CXX``, and ``CUDA`` were supported previously).
+ See the :variable:`CMAKE_<LANG>_COMPILER_LAUNCHER` variable and
+ :prop_tgt:`<LANG>_COMPILER_LAUNCHER` target property for details.
+
+* :ref:`Visual Studio Generators` learned to support the ``COMPILE_LANGUAGE``
+ :manual:`generator expression <cmake-generator-expressions(7)>` in
+ target-wide :prop_tgt:`COMPILE_DEFINITIONS`,
+ :prop_tgt:`INCLUDE_DIRECTORIES`, :prop_tgt:`COMPILE_OPTIONS`, and
+ :command:`file(GENERATE)`. See generator expression documentation
+ for caveats.
+
+* The :generator:`Xcode` generator learned to support the ``COMPILE_LANGUAGE``
+ :manual:`generator expression <cmake-generator-expressions(7)>` in
+ target-wide :prop_tgt:`COMPILE_DEFINITIONS` and
+ :prop_tgt:`INCLUDE_DIRECTORIES`. It previously supported only
+ :prop_tgt:`COMPILE_OPTIONS` and :command:`file(GENERATE)`.
+ See generator expression documentation for caveats.
+
+Commands
+--------
+
+* :command:`add_library` and :command:`add_executable` commands can now be
+ called without any sources and will not complain as long as sources are
+ added later via the :command:`target_sources` command.
+
+* The :command:`file(DOWNLOAD)` and :command:`file(UPLOAD)` commands
+ gained ``NETRC`` and ``NETRC_FILE`` options to specify use of a
+ ``.netrc`` file.
+
+* The :command:`target_compile_definitions` command learned to set the
+ :prop_tgt:`INTERFACE_COMPILE_DEFINITIONS` property on
+ :ref:`Imported Targets`.
+
+* The :command:`target_compile_features` command learned to set the
+ :prop_tgt:`INTERFACE_COMPILE_FEATURES` property on :ref:`Imported Targets`.
+
+* The :command:`target_compile_options` command learned to set the
+ :prop_tgt:`INTERFACE_COMPILE_OPTIONS` property on :ref:`Imported Targets`.
+
+* The :command:`target_include_directories` command learned to set the
+ :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` property on
+ :ref:`Imported Targets`.
+
+* The :command:`target_sources` command learned to set the
+ :prop_tgt:`INTERFACE_SOURCES` property on :ref:`Imported Targets`.
+
+* The :command:`target_link_libraries` command learned to set the
+ :prop_tgt:`INTERFACE_LINK_LIBRARIES` property on :ref:`Imported Targets`.
+
+Variables
+---------
+
+* A :variable:`CMAKE_GENERATOR_INSTANCE` variable was introduced
+ to hold the selected instance of the generator's corresponding
+ native tools if multiple are available. This is used by the
+ :generator:`Visual Studio 15 2017` generator to hold the
+ selected instance of Visual Studio persistently.
+
+* A :variable:`CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS` variable was added
+ to enable setting of default permissions for directories created implicitly
+ during installation of files by :command:`install` and
+ :command:`file(INSTALL)`, e.g. during ``make install``.
+
+* A :variable:`CMAKE_JOB_POOLS` variable was added specify a value to use for
+ the :prop_gbl:`JOB_POOLS` property. This enables control over build
+ parallelism with command line configuration parameters when using the Ninja
+ generator.
+
+* The :variable:`CMAKE_NETRC` and :variable:`CMAKE_NETRC_FILE` variables
+ were added to specify use of a ``.netrc`` file by the
+ :command:`file(DOWNLOAD)` and :command:`file(UPLOAD)` commands and
+ the :module:`ExternalProject` module.
+
+* A :variable:`CMAKE_CUDA_SEPARABLE_COMPILATION` variable was added to
+ initialize the :prop_tgt:`CUDA_SEPARABLE_COMPILATION` target property
+ on targets when they are created.
+
+Properties
+----------
+
+* The :prop_sf:`COMPILE_DEFINITIONS` source file property learned to support
+ :manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+* A :prop_sf:`COMPILE_OPTIONS` source file property was added to manage list
+ of options to pass to the compiler.
+
+* An :prop_tgt:`IMPORTED_GLOBAL` target property was added to indicate
+ whether an :ref:`IMPORTED target <Imported Targets>` is globally visible.
+ It is automatically set to a true value for targets created with the
+ ``GLOBAL`` option to :command:`add_library` or :command:`add_executable`.
+ Additionally, project code may now *promote* a local imported target
+ to be globally visible by setting this property to ``TRUE``.
+
+* An :prop_sf:`INCLUDE_DIRECTORIES` source file property was added to specify
+ list of preprocessor include file search directories.
+
+* Source file properties :prop_sf:`VS_SHADER_DISABLE_OPTIMIZATIONS` and
+ :prop_sf:`VS_SHADER_ENABLE_DEBUG` have been added to specify more
+ details of ``.hlsl`` sources with :ref:`Visual Studio Generators`.
+
+Modules
+-------
+
+* The :module:`CheckIncludeFiles` module :command:`CHECK_INCLUDE_FILES`
+ command gained a ``LANGUAGE`` option to specify whether to check using the
+ ``C`` or ``CXX`` compiler.
+
+* The :module:`CMakePackageConfigHelpers` module
+ :command:`write_basic_package_version_file` command learned a new
+ ``SameMinorVersion`` mode for the ``COMPATIBILITY`` argument.
+
+* The :module:`ExternalProject` module learned to substitute ``<DOWNLOAD_DIR>``
+ in comments, commands, working directory and byproducts.
+
+* The :module:`ExternalProject` module gained ``NETRC`` and ``NETRC_FILE``
+ options to specify use of a ``.netrc`` file.
+
+* A new :module:`FetchContent` module was added which supports populating
+ content at configure time using any of the download/update methods
+ supported by :command:`ExternalProject_Add`. This allows the content
+ to be used immediately during the configure stage, such as with
+ :command:`add_subdirectory`, etc. Hierarchical project structures are
+ well supported, allowing parent projects to override the content details
+ of child projects and ensuring content is not populated multiple times
+ throughout the whole project tree.
+
+* The :module:`FindBLAS` and :module:`FindLAPACK` modules learned to support
+ `FLAME`_ ``blis`` and ``libflame``.
+
+* The :module:`FindDoxygen` module :command:`doxygen_add_docs` function
+ now supports a new ``DOXYGEN_VERBATIM_VARS`` list variable. Any
+ ``DOXYGEN_...`` variable contained in that list will bypass the automatic
+ quoting logic, leaving its contents untouched when transferring them to the
+ output ``Doxyfile``.
+
+* A :module:`FindIconv` module was added to locate iconv support.
+
+* The :module:`GenerateExportHeader` module ``GENERATE_EXPORT_HEADER`` command
+ gained an ``INCLUDE_GUARD_NAME`` option to change the name of the include
+ guard symbol written to the generated export header.
+ Additionally, it now adds a comment after the closing ``#endif`` on the
+ generated export header's include guard.
+
+* The :module:`UseJava` module ``add_jar`` command gained a
+ ``GENERATE_NATIVE_HEADERS`` option to generate native header files
+ using ``javac -h`` for ``javac`` 1.8 or above. This supersedes
+ ``create_javah``, which no longer works with JDK 1.10 and above due
+ to removal of the ``javah`` tool by `JEP 313`_.
+
+.. _`FLAME`: https://github.com/flame
+.. _`JEP 313`: http://openjdk.java.net/jeps/313
+
+Autogen
+-------
+
+* When using :prop_tgt:`AUTOMOC` or :prop_tgt:`AUTOUIC`, CMake now starts
+ multiple parallel ``moc`` or ``uic`` processes to reduce the build time.
+ A new :variable:`CMAKE_AUTOGEN_PARALLEL` variable and
+ :prop_tgt:`AUTOGEN_PARALLEL` target property may be set to specify the
+ number of parallel ``moc`` or ``uic`` processes to start. The default
+ is derived from the number of CPUs on the host.
+
+CTest
+-----
+
+* The :command:`ctest_start` command no longer sets
+ :variable:`CTEST_RUN_CURRENT_SCRIPT` due to issues with scoping if it is
+ called from inside a function. Instead, it sets an internal variable in
+ CTest. However, setting :variable:`CTEST_RUN_CURRENT_SCRIPT` to 0 at the
+ global scope still prevents the script from being re-run at the end.
+
+CPack
+-----
+
+* :manual:`cpack(1)` gained ``--trace`` and ``--trace-expand`` options.
+
+* The :cpack_gen:`CPack IFW Generator` gained new
+ :variable:`CPACK_IFW_PACKAGE_REMOVE_TARGET_DIR` variable to control
+ if the target directory should not be deleted when uninstalling.
+
+* The :cpack_gen:`CPack RPM Generator` learned to enable enforcing of execute
+ privileges on programs and shared libraries.
+ See :variable:`CPACK_RPM_INSTALL_WITH_EXEC` variable.
+
+* A :variable:`CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS` variable was added
+ which serves the same purpose during packaging (e.g. ``make package``) as the
+ :variable:`CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS` variable serves during
+ installation (e.g. ``make install``).
+
+Other
+-----
+
+* :ref:`Alias Targets` may now alias :ref:`Imported Targets` that are
+ created with the ``GLOBAL`` option to :command:`add_library`.
+
+* :ref:`Interface Libraries` may now have custom properties set on them if
+ they start with either an underscore (``_``) or a lowercase ASCII character.
+ The original intention was to only allow properties which made sense for
+ ``INTERFACE`` libraries, but it also blocked usage of custom properties.
+
+* The :manual:`cmake(1)` ``--open <dir>`` command-line option was added
+ to open generated IDE projects like Visual Studio solutions or Xcode
+ projects.
+
+Deprecated and Removed Features
+===============================
+
+* An explicit deprecation diagnostic was added for policies ``CMP0037``
+ through ``CMP0054`` (``CMP0036`` and below were already deprecated).
+ The :manual:`cmake-policies(7)` manual explains that the OLD behaviors
+ of all policies are deprecated and that projects should port to the
+ NEW behaviors.
+
+* The ``KDevelop3`` generator has been removed.
+
+Other Changes
+=============
+
+* Policy :policy:`CMP0037` no longer reserves target names associated
+ with optional features, such as ``test`` and ``package``, unless
+ the corresponding feature is enabled.
+
+* The :module:`FindOpenGL` module now prefers GLVND libraries if available.
+ See policy :policy:`CMP0072`.
+
+* The minimum deployment target set in the
+ :variable:`CMAKE_OSX_DEPLOYMENT_TARGET` variable used to be only
+ applied for macOS regardless of the selected SDK. It is now properly
+ set for the target platform selected by :variable:`CMAKE_OSX_SYSROOT`.
+ For example, if the sysroot variable specifies an iOS SDK then the
+ value in ``CMAKE_OSX_DEPLOYMENT_TARGET`` is interpreted as minimum
+ iOS version.
+
+* The :generator:`Xcode` generator behavior of generating one project
+ file per :command:`project()` command may now be controlled with the
+ :variable:`CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY` variable.
+ This could be useful to speed up the CMake generation step for
+ large projects and to work-around a bug in the ``ZERO_CHECK`` logic.
+
+* Since the ``CMakeCache.txt`` format does not support newlines in values,
+ values containing newlines are now truncated before writing to the file.
+ In addition, a warning comment is written to the cache file, and a warning
+ message is displayed to the user on the console.
+
+Updates
+=======
+
+Changes made since CMake 3.11.0 include the following.
+
+3.11.1
+------
+
+* The :module:`CheckIncludeFile` module ``check_include_file`` macro,
+ :module:`CheckIncludeFileCXX` module ``check_include_file_cxx`` macro,
+ and :module:`CheckIncludeFiles` module ``check_include_files`` macro
+ were taught to honor the ``CMAKE_REQUIRED_LIBRARIES`` variable in
+ CMake 3.11.0. This has been reverted due to changing behavior of
+ checks for existing projects. It may be restored in the future
+ with a policy for compatibility.
+
+3.11.2
+------
+
+* Calling :command:`add_library` to create an alias of an imported
+ target that is not globally visible now causes an error again as
+ it did prior to 3.11.0. This diagnostic was accidentally dropped
+ from CMake 3.11.0 and 3.11.1 by the change to allow globally visible
+ imported targets to be aliased.
+
+* The :module:`FindQt4` module ``qt4_wrap_cpp``, ``qt4_wrap_ui`` and
+ ``qt4_add_resources`` macros now set :prop_sf:`SKIP_AUTOMOC` and
+ :prop_sf:`SKIP_AUTOUIC` on their generated files. These files never
+ need to be processed by moc or uic, and we must say so explicitly to
+ account for policy :policy:`CMP0071`.
+
+3.11.3
+------
+
+* CMake 3.11.0 introduced support for resolving symbolic links on
+ Windows in code paths that typically do so on UNIX. This has been
+ reverted due to breakage on ``subst`` drives.
diff --git a/Help/release/3.12.rst b/Help/release/3.12.rst
new file mode 100644
index 000000000..481027ec7
--- /dev/null
+++ b/Help/release/3.12.rst
@@ -0,0 +1,305 @@
+CMake 3.12 Release Notes
+************************
+
+.. only:: html
+
+ .. contents::
+
+Changes made since CMake 3.11 include the following.
+
+New Features
+============
+
+Generators
+----------
+
+* The :ref:`Visual Studio Generators` for VS 2017 learned to support a
+ ``version=14.##`` option in the :variable:`CMAKE_GENERATOR_TOOLSET`
+ value (e.g. via the :manual:`cmake(1)` ``-T`` option) to specify a
+ toolset version number.
+
+Command-Line
+------------
+
+* The :manual:`cmake(1)` :ref:`Build Tool Mode` (``cmake --build``) gained
+ ``--parallel [<jobs>]`` and ``-j [<jobs>]`` options to specify a parallel
+ build level. They map to corresponding options of the native build tool.
+
+Commands
+--------
+
+* The :command:`add_compile_definitions` command was added to set preprocessor
+ definitions at directory level. This supersedes :command:`add_definitions`.
+
+* The :command:`cmake_minimum_required` and :command:`cmake_policy(VERSION)`
+ commands now accept a version range using the form ``<min>[...<max>]``.
+ The ``<min>`` version is required but policies are set based on the
+ older of the running CMake version and the version specified by
+ ``<max>``. This allows projects to specify a range of versions
+ for which they have been updated and avoid explicit policy settings.
+
+* The :command:`file(GLOB)` and :command:`file(GLOB_RECURSE)` commands
+ learned a new flag ``CONFIGURE_DEPENDS`` which enables expression of
+ build system dependency on globbed directory's contents.
+
+* The :command:`file(TOUCH)` and :command:`file(TOUCH_NOCREATE)` commands
+ were added to expose ``TOUCH`` functionality without having to use
+ CMake's command-line tool mode with :command:`execute_process`.
+
+* The :command:`find_package` command now searches prefixes specified by
+ the :variable:`<PackageName>_ROOT` CMake variable and the
+ :envvar:`<PackageName>_ROOT` environment variable. Package roots are
+ maintained as a stack so nested calls to all ``find_*`` commands inside
+ find modules also search the roots as prefixes.
+ See policy :policy:`CMP0074`.
+
+* The :command:`install` command learned an optional ``NAMELINK_COMPONENT``
+ parameter, which allows you to change the component for a shared library's
+ namelink. If none is specified, the value of ``COMPONENT`` is used by
+ default.
+
+* The :command:`list` command learned a ``JOIN`` sub-command
+ to concatenate list's elements separated by a glue string.
+
+* The :command:`list` command learned a ``SUBLIST`` sub-command
+ to get a sublist of the list.
+
+* The :command:`list` command learned a ``TRANSFORM`` sub-command
+ to apply various string transformation to list's elements.
+
+* The :command:`project` command learned an optional ``HOMEPAGE_URL``
+ parameter which has the effect of setting variables like
+ :variable:`PROJECT_HOMEPAGE_URL`, :variable:`<PROJECT-NAME>_HOMEPAGE_URL`
+ and :variable:`CMAKE_PROJECT_HOMEPAGE_URL`.
+
+* The :command:`string` command learned a ``JOIN`` sub-command
+ to concatenate input strings separated by a glue string.
+
+* :command:`target_compile_options` and :command:`add_compile_options`
+ commands gained a ``SHELL:`` prefix to specify a group of related
+ options using shell-like quoting.
+
+* The :command:`target_link_libraries` command now supports
+ :ref:`Object Libraries`. Linking to an object library uses its object
+ files in direct dependents and also propagates usage requirements.
+
+Variables
+---------
+
+* The :variable:`CMAKE_FOLDER` variable was added to initialize the
+ :prop_tgt:`FOLDER` property on all targets.
+
+* The :variable:`CMAKE_DOTNET_TARGET_FRAMEWORK_VERSION` variable
+ was defined to initialize all
+ :prop_tgt:`DOTNET_TARGET_FRAMEWORK_VERSION` target properties.
+
+* ``CMAKE_PROJECT_VERSION*`` variables have been introduced:
+
+ - :variable:`CMAKE_PROJECT_VERSION`
+ - :variable:`CMAKE_PROJECT_VERSION_MAJOR`
+ - :variable:`CMAKE_PROJECT_VERSION_MINOR`
+ - :variable:`CMAKE_PROJECT_VERSION_PATCH`
+ - :variable:`CMAKE_PROJECT_VERSION_TWEAK`
+
+* The :variable:`CMAKE_SUPPRESS_REGENERATION` variable was extended to
+ support the :generator:`Ninja` and :ref:`Makefile Generators`.
+ It is also now documented.
+
+* ``CMAKE_VS_SDK_*_DIRECTORIES`` variables were defined to tell
+ :ref:`Visual Studio Generators` for VS 2010 and above how to populate
+ fields in ``.vcxproj`` files that specify SDK directories. The
+ variables are:
+
+ - :variable:`CMAKE_VS_SDK_EXCLUDE_DIRECTORIES`
+ - :variable:`CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES`
+ - :variable:`CMAKE_VS_SDK_INCLUDE_DIRECTORIES`
+ - :variable:`CMAKE_VS_SDK_LIBRARY_DIRECTORIES`
+ - :variable:`CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES`
+ - :variable:`CMAKE_VS_SDK_REFERENCE_DIRECTORIES`
+ - :variable:`CMAKE_VS_SDK_SOURCE_DIRECTORIES`
+
+* A :variable:`MSVC_TOOLSET_VERSION` variable was added to provide the
+ MSVC toolset version associated with the current MSVC compiler version
+ in :variable:`MSVC_VERSION`.
+
+Properties
+----------
+
+* The :prop_tgt:`COMMON_LANGUAGE_RUNTIME` target property was introduced
+ to configure the use of managed C++ for :ref:`Visual Studio Generators`
+ for VS 2010 and above.
+ A corresponding :prop_tgt:`IMPORTED_COMMON_LANGUAGE_RUNTIME` target
+ property was added to support ``C++/CLI`` for imported targets.
+
+* The :prop_tgt:`DOTNET_TARGET_FRAMEWORK_VERSION` target property
+ was introduced as replacement for
+ :prop_tgt:`VS_DOTNET_TARGET_FRAMEWORK_VERSION`, which is considered
+ deprecated now.
+
+* An :prop_tgt:`EXPORT_PROPERTIES` target property was added to specify a
+ custom list of target properties to include in targets exported by the
+ :command:`install(EXPORT)` and :command:`export` commands.
+
+* The :prop_tgt:`PDB_OUTPUT_DIRECTORY` property learned to support
+ :manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+* A :prop_dir:`TESTS` directory property was added to hold the list of
+ tests defined by the :command:`add_test` command.
+
+* A :prop_tgt:`VS_DEBUGGER_COMMAND` target property was created to set the
+ debugging command line with :ref:`Visual Studio Generators` for VS 2010
+ and above.
+
+* HLSL source file properties :prop_sf:`VS_SHADER_DISABLE_OPTIMIZATIONS`
+ and :prop_sf:`VS_SHADER_ENABLE_DEBUG` gained support for generator
+ expressions.
+
+* HLSL source file property :prop_sf:`VS_SHADER_OBJECT_FILE_NAME` has been
+ added to the :ref:`Visual Studio Generators` for VS 2010 and above.
+ The property specifies the file name of the compiled shader object.
+
+Modules
+-------
+
+* The :module:`FindALSA` module now provides imported targets.
+
+* The :module:`FindCURL` module now provides imported targets.
+
+* The :module:`FindJPEG` module now provides imported targets.
+
+* The :module:`FindLibXml2` module now provides imported targets.
+
+* The :module:`FindMatlab` module now supports the Matlab Runtime
+ Compiler (MCR) for compiling and linking matlab extensions.
+
+* A :module:`FindODBC` module was added to find an Open Database Connectivity
+ (ODBC) library.
+
+* The :module:`FindPkgConfig` module has learned to export the found
+ libraries with full path for direct consumption with the
+ :command:`target_link_libraries` command.
+
+* New :module:`FindPython3` and :module:`FindPython2` modules, as well as
+ a new :module:`FindPython` module, have been added to provide a new way
+ to locate python environments.
+
+* The :module:`UseSWIG` module gained a whole refresh and is now more
+ consistent with standard CMake commands to generate libraries and is
+ fully configurable through properties.
+
+* The :module:`UseSWIG` module learned to manage multiple behaviors through
+ ``UseSWIG_MODULE_VERSION`` variable to ensure legacy support as well as more
+ robust handling of ``SWIG`` advanced features (like ``%template``).
+
+* The :module:`UseSWIG` module learned to support CSHARP variant
+ wrapper files.
+
+* The :module:`WriteCompilerDetectionHeader` module gained a ``BARE_FEATURES``
+ option to add a compatibility define for the exact keyword of a new language
+ feature.
+
+Generator Expressions
+---------------------
+
+* A new ``$<GENEX_EVAL:...>`` and ``$<TARGET_GENEX_EVAL:target,...>``
+ :manual:`generator expression <cmake-generator-expressions(7)>`
+ has been added to enable consumption of generator expressions whose
+ evaluation results itself in generator expressions.
+
+* A new ``$<IN_LIST:...>``
+ :manual:`generator expression <cmake-generator-expressions(7)>`
+ has been added.
+
+* A new ``$<TARGET_EXISTS:...>``
+ :manual:`generator expression <cmake-generator-expressions(7)>`
+ has been added.
+
+* A new ``$<TARGET_NAME_IF_EXISTS:...>``
+ :manual:`generator expression <cmake-generator-expressions(7)>`
+ has been added.
+
+CTest
+-----
+
+* The :command:`ctest_start` command has been reworked so that you can simply
+ call ``ctest_start(APPEND)`` and it will read all the needed information from
+ the TAG file. The argument parsing has also been relaxed so that the order of
+ the arguments is less significant.
+
+* A :prop_test:`PROCESSOR_AFFINITY` test property was added to request
+ that CTest run a test with CPU affinity for a set of processors
+ disjoint from other concurrently running tests with the property set.
+
+CPack
+-----
+
+* The :module:`CPack` module now uses variables
+ :variable:`CMAKE_PROJECT_VERSION_MAJOR`,
+ :variable:`CMAKE_PROJECT_VERSION_MINOR` and
+ :variable:`CMAKE_PROJECT_VERSION_PATCH`
+ to initialize corresponding CPack variables.
+
+* A :cpack_gen:`CPack NuGet Generator` was was added with basic
+ support for `NuGet`_.
+
+.. _NuGet: https://docs.microsoft.com/en-us/nuget/what-is-nuget
+
+Other
+-----
+
+* The :manual:`Compile Features <cmake-compile-features(7)>` functionality
+ is now aware of C++ 20. No specific features are yet enumerated besides
+ the ``cxx_std_20`` meta-feature.
+
+* The :manual:`Compile Features <cmake-compile-features(7)>` functionality
+ is now aware of the availability of C features in MSVC since VS 2010.
+
+* The :manual:`Compile Features <cmake-compile-features(7)>` functionality
+ is now aware of C language standards supported by Texas Instruments C
+ compilers.
+
+Deprecated and Removed Features
+===============================
+
+* The :generator:`Visual Studio 8 2005` generator has been removed.
+
+* CMake no longer produces ``<tgt>_LIB_DEPENDS`` cache entries
+ for library targets. See policy :policy:`CMP0073`.
+
+Other Changes
+=============
+
+* Include flags for directories marked as ``SYSTEM`` are now moved after
+ non-system directories. The ``-isystem`` flag does this automatically,
+ so moving them explicitly to the end makes the behavior consistent on
+ compilers that do not have any ``-isystem`` flag.
+
+* Fortran dependency scanning now supports dependencies implied by
+ `Fortran Submodules`_.
+
+* The existence and functionality of the file
+ ``${CMAKE_BINARY_DIR}/cmake_install.cmake`` has now been documented in the
+ :command:`install` documentation so that external packaging software can take
+ advantage of CPack-style component installs.
+
+* The :module:`CheckIncludeFile` module ``check_include_file`` macro
+ learned to honor the ``CMAKE_REQUIRED_LIBRARIES`` variable.
+ See policy :policy:`CMP0075`.
+
+* The :module:`CheckIncludeFileCXX` module ``check_include_file_cxx`` macro
+ learned to honor the ``CMAKE_REQUIRED_LIBRARIES`` variable.
+ See policy :policy:`CMP0075`.
+
+* The :module:`CheckIncludeFiles` module ``check_include_files`` macro
+ learned to honor the ``CMAKE_REQUIRED_LIBRARIES`` variable.
+ See policy :policy:`CMP0075`.
+
+* The :manual:`cmake(1)` ``-E copy_directory`` tool now fails when the
+ source directory does not exist. Previously it succeeded by creating
+ an empty destination directory.
+
+* The :module:`UseSWIG` module :command:`swig_add_library` command
+ (and legacy ``swig_add_module`` command) now set the prefix of
+ Java modules to ``""`` for MINGW, MSYS, and CYGWIN environments.
+
+.. _`Fortran Submodules`: http://fortranwiki.org/fortran/show/Submodules
diff --git a/Help/release/3.13.rst b/Help/release/3.13.rst
new file mode 100644
index 000000000..a8dd0baf7
--- /dev/null
+++ b/Help/release/3.13.rst
@@ -0,0 +1,289 @@
+CMake 3.13 Release Notes
+************************
+
+.. only:: html
+
+ .. contents::
+
+Changes made since CMake 3.12 include the following.
+
+New Features
+============
+
+Generators
+----------
+
+* The :ref:`Visual Studio Generators` for VS 2010 and above learned to
+ support the :prop_tgt:`INTERPROCEDURAL_OPTIMIZATION` target property
+ and supporting :module:`CheckIPOSupported` module.
+
+* The :generator:`Xcode` generator learned to configure more Xcode Scheme
+ fields. See the :variable:`CMAKE_XCODE_GENERATE_SCHEME` variable.
+
+* The :generator:`Green Hills MULTI` generator has been updated:
+
+ - Added support for architecture selection through
+ :variable:`CMAKE_GENERATOR_PLATFORM`:
+ e.g. ``arm``, ``ppc``, and ``86``.
+
+ - Added support for toolset selection through
+ :variable:`CMAKE_GENERATOR_TOOLSET`,
+ e.g. ``comp_201205``, ``comp_201510``, ``comp_201722_beta``.
+
+ - Added support for platform selection through ``GHS_TARGET_PLATFORM``,
+ e.g. ``integrity``, ``linux``, ``standalone``, etc.
+
+ - No longer checks that ``arm`` based compilers are installed but ensures
+ that the correct ``gbuild.exe`` exists.
+
+ - No longer hard-codes ARM files, BSP, toolset, or OS locations.
+
+Command-Line
+------------
+
+* The :manual:`cmake(1)` command gained the ``-S <source_dir>``
+ command line option to specify the location of the source directory.
+ This option can be used independently of ``-B``.
+
+* The :manual:`cmake(1)` command gained the ``-B <build_dir>``
+ command line option to specify the location of the build directory.
+ This option can be used independently of ``-S``.
+
+* The :manual:`cmake(1)` ``-E create_symlink`` command can now be used
+ on Windows.
+
+Commands
+--------
+
+* The :command:`add_custom_command` and :command:`add_custom_target` commands
+ learned to support generator expressions in ``WORKING_DIRECTORY`` options.
+
+* The :command:`add_link_options` command was created to add link
+ options in the current directory.
+
+* The :command:`install(TARGETS)` command learned to install targets
+ created outside the current directory.
+
+* The :command:`link_directories` command gained options to control
+ insertion position.
+
+* The :command:`list(SORT)` command gained options to control the
+ comparison operation used to order the entries.
+
+* The :command:`math` command gained options for hexadecimal.
+
+* The :command:`target_link_directories` command was created to
+ specify link directories for targets and their dependents.
+
+* The :command:`target_link_options` command was created to
+ specify link options for targets and their dependents.
+
+* The :command:`target_link_libraries` command may now be called
+ to modify targets created outside the current directory.
+ See policy :policy:`CMP0079`.
+
+Variables
+---------
+
+* A :variable:`CMAKE_AUTOGEN_VERBOSE` variable was added to optionally
+ increase the verbosity of :prop_tgt:`AUTOMOC`, :prop_tgt:`AUTOUIC`
+ and :prop_tgt:`AUTORCC` from within CMake project code.
+
+* A :variable:`CMAKE_VS_GLOBALS` variable was added to initialize
+ :prop_tgt:`VS_GLOBAL_<variable>` target properties on targets as
+ they are created.
+
+Properties
+----------
+
+* The :prop_tgt:`DEPLOYMENT_ADDITIONAL_FILES` target property was
+ added to tell the :generator:`Visual Studio 9 2008` generator
+ to specify additional files for deployment to WinCE devices
+ for remote debugging.
+
+* The :prop_tgt:`INTERFACE_LINK_DEPENDS` target property was created
+ to specify transitive link dependencies on files.
+
+* The :prop_tgt:`LINK_DEPENDS` target property learned to support
+ :manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+* :prop_tgt:`LINK_DIRECTORIES` and :prop_tgt:`INTERFACE_LINK_DIRECTORIES`
+ target properties were added to collect link directories for a target
+ and its dependents. Use the :command:`target_link_directories` command
+ to set them.
+
+* :prop_tgt:`LINK_OPTIONS` and :prop_tgt:`INTERFACE_LINK_OPTIONS` target
+ properties were added to collect link options for a target and its
+ dependents. Use the :command:`target_link_options` command to set them.
+
+* A :prop_dir:`LINK_OPTIONS` directory property was added to collect
+ link options for targets created under the current directory.
+ Use the :command:`add_link_options` command to set it.
+
+* A :prop_tgt:`STATIC_LIBRARY_OPTIONS` target property was created
+ to specify archiver options to use when creating static libraries.
+
+* A :prop_tgt:`VS_DEBUGGER_COMMAND_ARGUMENTS` target property was created to
+ set the debugging command line arguments with
+ :ref:`Visual Studio Generators` for VS 2010 and above.
+
+* A :prop_tgt:`VS_DEBUGGER_ENVIRONMENT` target property was created to
+ set the debugging environment with
+ :ref:`Visual Studio Generators` for VS 2010 and above.
+
+* The :prop_tgt:`VS_DEBUGGER_COMMAND` and
+ :prop_tgt:`VS_DEBUGGER_WORKING_DIRECTORY` target properties
+ now support generator expressions.
+
+Modules
+-------
+
+* The :module:`FindBoost` module gained a ``Boost_ARCHITECTURE`` option
+ to specify a Boost architecture-specific library filename fragment.
+
+* The :module:`FindCURL` module learned to find debug and release variants
+ separately.
+
+* The :module:`FindMatlab` module gained new components ``ENGINE_LIBRARY`` and
+ ``DATAARRAY_LIBRARY`` to request finding the Matlab C++ Engine and DataArray
+ libraries respectively.
+
+* The :module:`FindMatlab` module now explicitly exports mexFunction in Visual
+ Studio.
+
+* The :module:`FindMatlab` module gained a new ``MCC_COMPILER``
+ component to request finding the Matlab Compiler add-on.
+
+* The :module:`FindPkgConfig` module gained an option to create imported
+ targets in global scope.
+
+* The :module:`FindPkgConfig` module gained support for ``<`` and ``>``
+ operators for version checks in addition to the already supported
+ operators ``>=``, ``<=``, and ``=``.
+
+* Modules :module:`FindPython3`, :module:`FindPython2` and :module:`FindPython`
+ gain capability to control order of resource lookup on macOS (Framework) and
+ Windows (Registry).
+
+* The :module:`FindSubversion` module ``Subversion_WC_INFO`` command
+ gained an ``IGNORE_SVN_FAILURE`` option to suppress failures,
+ e.g. when the source tree is not under Subversion control.
+
+* The :module:`UseSWIG` module learned to manage target property
+ :prop_tgt:`INCLUDE_DIRECTORIES` for ``SWIG`` compilation.
+
+CTest
+-----
+
+* :manual:`ctest(1)` gained a ``--progress`` option to enable a live
+ test progress summary when output goes to a terminal.
+
+CPack
+-----
+
+* The :cpack_gen:`CPack DEB Generator` learned to split debug symbols into
+ a corresponding .ddeb package when ``CPACK_DEBIAN_DEBUGINFO_PACKAGE`` is
+ set.
+
+* The :cpack_gen:`CPack DEB Generator` learned to honor the ``SOURCE_DATE_EPOCH``
+ environment variable when packaging files. This is useful for generating
+ reproducible packages.
+
+* CPack gained a new :cpack_gen:`CPack External Generator` which is used to
+ export the CPack metadata in a format that other software can understand. The
+ intention of this generator is to allow external packaging software to take
+ advantage of CPack's features when it may not be possible to use CPack for
+ the entire packaging process.
+
+Deprecated and Removed Features
+===============================
+
+* An explicit deprecation diagnostic was added for policies ``CMP0055``
+ through ``CMP0063`` (``CMP0054`` and below were already deprecated).
+ The :manual:`cmake-policies(7)` manual explains that the OLD behaviors
+ of all policies are deprecated and that projects should port to the
+ NEW behaviors.
+
+Other Changes
+=============
+
+* The precompiled binaries provided on ``cmake.org`` now include
+ qthelp-format documentation.
+
+* The :command:`option` command now honors an existing normal variable
+ of the same name and does nothing instead of possibly creating a cache
+ entry (or setting its type) and removing the normal variable.
+ See policy :policy:`CMP0077`.
+
+* The :ref:`Makefile Generators` learned to remove custom command and
+ custom target byproducts during ``make clean``.
+
+* The :command:`target_sources` command now interprets relative source file
+ paths as relative to the current source directory. This simplifies
+ incrementally building up a target's sources from subdirectories. The
+ :policy:`CMP0076` policy was added to provide backward compatibility with
+ the old behavior where required.
+
+* The :module:`BundleUtilities` module may no longer be included at configure
+ time. This was always a bug anyway. See policy :policy:`CMP0080`.
+
+* The :module:`UseSWIG` module has changed strategy for target naming.
+ See policy :policy:`CMP0078`.
+
+* The :prop_tgt:`LINK_DIRECTORIES` target property now expects absolute paths.
+ See policy :policy:`CMP0081`.
+
+* The CPack generators have been moved into their own separate section
+ in the documentation, rather than having the documentation in their
+ internal implementation modules.
+ These internal implementation modules are also no longer available
+ to scripts that may have been incorrectly including them, because
+ they should never have been available in the first place.
+
+Updates
+=======
+
+Changes made since CMake 3.13.0 include the following.
+
+3.13.2
+------
+
+* CMake 3.13.0 included a change to pass compiler implicit include
+ directories to the ``moc`` tool for :prop_tgt:`AUTOMOC`. This has
+ been reverted due to regressing existing builds and will need
+ further investigation before being re-introduced in a later release.
+
+3.13.3
+------
+
+* The :generator:`Visual Studio 15 2017` generator has been fixed to work
+ when VS 2019 is installed.
+
+* CMake now checks that at least one of the source or binary directory
+ is specified when running CMake and issues an error if both are missing.
+ This has always been a documented requirement, but the implementation
+ previously accidentally accepted cases in which neither are specified
+ so long as some other argument is given, and silently used the current
+ working directory as the source and build tree.
+
+3.13.4
+------
+
+* The error added by 3.13.3 in cases that neither a source or binary
+ directory is specified has been downgraded to a warning. While this
+ was never intended, documented, nor supported behavior, some projects
+ relied on it. The error has been downgraded to a warning for the
+ remainder of the 3.13.x release series to allow a transition period,
+ but it may become a fatal error again in a later release. Scripts
+ relying on the old behavior can be trivially fixed by specifying
+ the path to the source tree (even if just ``.``) explicitly and
+ continue to work with all versions of CMake.
+
+3.13.5
+------
+
+* In CMake 3.13.0 through 3.13.4, calling :command:`target_link_libraries`
+ to add ``PRIVATE`` dependencies to a static library created in another
+ directory (under policy :policy:`CMP0079` ``NEW`` behavior) would
+ incorrectly propagate usage requirements of those dependencies to
+ dependents that link the static library. This has been fixed.
diff --git a/Help/release/3.14.rst b/Help/release/3.14.rst
new file mode 100644
index 000000000..8a9738c84
--- /dev/null
+++ b/Help/release/3.14.rst
@@ -0,0 +1,438 @@
+CMake 3.14 Release Notes
+************************
+
+.. only:: html
+
+ .. contents::
+
+Changes made since CMake 3.13 include the following.
+
+New Features
+============
+
+Generators
+----------
+
+* The :generator:`Visual Studio 16 2019` generator was added. This is
+ experimental and based on "Visual Studio 2019 Preview 4" because this
+ version of VS has not been released.
+
+ The VS 2019 generator differs from generators for earlier versions
+ in that it does not provide variants that specify the target platform
+ in the generator name. Instead :variable:`CMAKE_GENERATOR_PLATFORM`
+ must be used, e.g. through the ``-A`` command-line option. Furthermore,
+ the default target platform (architecture) is now based on the *host*
+ platform. The VS host toolset selection is now based on the host
+ architecture as well.
+
+* The :generator:`Green Hills MULTI` generator has been updated:
+
+ * Now supports :ref:`Object Libraries`.
+
+ * Now warns on unsupported project types such as shared libraries.
+
+ * Now generates a top-level ``<PROJECT-NAME>.top.gpj`` for each directory
+ calling the :command:`project` command. The top-level project file
+ ``default.gpj`` is no longer created.
+
+ * Now honors target renaming and destination output control properties
+ such as :prop_tgt:`RUNTIME_OUTPUT_DIRECTORY` and :prop_tgt:`OUTPUT_NAME`.
+ This also fixes support for installation rules generated by
+ :command:`install`.
+
+ * Now honors source file properties :prop_sf:`INCLUDE_DIRECTORIES`,
+ :prop_sf:`COMPILE_DEFINITIONS`, and :prop_sf:`COMPILE_OPTIONS`.
+
+ * Now supports Dynamic Download Integrity Applications which did not include
+ Integrate Files via :prop_tgt:`GHS_INTEGRITY_APP` and setting a target
+ link flag of ``-dynamic``.
+
+ * The contents of project files now sorts sources groups and files by name.
+ Set the :prop_tgt:`GHS_NO_SOURCE_GROUP_FILE` target property to ``ON`` to
+ generate a single project file for the target instead of a project file for
+ each source group. Set the :variable:`CMAKE_GHS_NO_SOURCE_GROUP_FILE`
+ variable to enable this for all targets.
+
+File-Based API
+--------------
+
+* A file-based api for clients to get semantic buildsystem information
+ has been added. See the :manual:`cmake-file-api(7)` manual.
+ This is intended to replace the :manual:`cmake-server(7)` mode for IDEs.
+
+Platforms
+---------
+
+* CMake now supports :ref:`Cross Compiling for iOS, tvOS, or watchOS`
+ using simple toolchain files.
+
+Command-Line
+------------
+
+* The :manual:`cmake(1)` :ref:`Build Tool Mode <Build Tool Mode>`
+ (``cmake --build``) gained ``--verbose`` and ``-v`` options to
+ specify verbose build output. Some generators such as Xcode don't
+ support this option currently.
+
+* The :manual:`cmake(1)` ``-E compare_files`` command learned a new
+ ``--ignore-eol`` option to specify that end-of-line differences
+ (e.g. LF vs CRLF) should be ignored when comparing files.
+
+* The :manual:`cmake-gui(1)` dialog gained new ``-S`` and ``-B`` arguments to
+ explicitly specify source and build directories.
+
+Commands
+--------
+
+* The :command:`file` command learned a new sub-command, ``CREATE_LINK``,
+ which can be used to create hard or symbolic links.
+
+* The :command:`file` command learned a new sub-command, ``READ_SYMLINK``,
+ which can be used to determine the path that a symlink points to.
+
+* The :command:`file` command gained a ``SIZE`` mode to get the size
+ of a file on disk.
+
+* The :command:`find_package` command learned to optionally resolve
+ symbolic links in the paths to package configuration files.
+ See the :variable:`CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS` variable.
+
+* The :command:`get_filename_component` command gained new
+ ``LAST_EXT`` and ``NAME_WLE`` variants to work with the
+ extension after the last ``.`` in the name.
+
+* The :command:`if` command gained support for checking if cache variables
+ are defined with the ``DEFINED CACHE{VAR}`` syntax.
+
+* The :command:`install(CODE)` and :command:`install(SCRIPT)` commands
+ learned to support generator expressions. See policy :policy:`CMP0087`.
+
+* The :command:`install(TARGETS)` command learned how to install to an
+ appropriate default directory for a given target type, based on
+ variables from the :module:`GNUInstallDirs` module and built-in defaults,
+ in lieu of a ``DESTINATION`` argument.
+
+* The :command:`install(FILES)` and :command:`install(DIRECTORY)` commands
+ learned a new set of parameters for installing files as a file type,
+ setting the destination based on the appropriate variables from
+ :module:`GNUInstallDirs` and built-in defaults, in lieu of a
+ ``DESTINATION`` argument.
+
+* The :command:`list` operations ``REMOVE_ITEM``, ``REMOVE_DUPLICATES``,
+ ``SORT``, ``REVERSE``, and ``FILTER`` all now accept a non-existent variable
+ as the list since these operations on empty lists is also the empty list.
+
+* The :command:`list` operation ``REMOVE_AT`` now indicates that the given
+ indices are invalid for a non-existent variable or empty list.
+
+* The :command:`try_compile` and :command:`try_run` commands gained a new
+ ``LINK_OPTIONS`` option.
+
+Variables
+---------
+
+* A :variable:`CMAKE_BUILD_RPATH_USE_ORIGIN` variable and corresponding
+ :prop_tgt:`BUILD_RPATH_USE_ORIGIN` target property were added to
+ enable use of relative runtime paths (RPATHs). This helps achieving
+ relocatable and reproducible builds that are invariant of the build
+ directory.
+
+* A :variable:`CMAKE_VS_PLATFORM_NAME_DEFAULT` variable was added for
+ :ref:`Visual Studio Generators` to report their default platform used
+ when :variable:`CMAKE_GENERATOR_PLATFORM` is not set explicitly.
+
+Properties
+----------
+
+* A :prop_gbl:`CMAKE_ROLE` global property was added to allow scripts to
+ determine whether they're running in project mode, script mode,
+ find-package mode, CTest, or CPack.
+
+* The :prop_tgt:`CUDA_RESOLVE_DEVICE_SYMBOLS` target property is now supported
+ on shared library, module library, and executable targets. Previously it was
+ only honored on static libraries.
+
+* The :prop_tgt:`EXCLUDE_FROM_ALL` target property was created to override
+ the setting of its directory. A target will now be built as part of "all"
+ if its :prop_tgt:`EXCLUDE_FROM_ALL` property is set to ``OFF``, even if its
+ containing directory is marked as :prop_dir:`EXCLUDE_FROM_ALL`.
+
+* :prop_tgt:`INTERFACE_POSITION_INDEPENDENT_CODE` target property gains the
+ support of :manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+Modules
+-------
+
+* The family of modules to check capabilities (like
+ :module:`CheckCSourceCompiles`) gain capability to manage ``LINK_OPTIONS``.
+
+* A :module:`CheckFortranSourceRuns` module was added to provide a
+ :command:`check_fortran_source_runs` command to check if a Fortran
+ source snippet compiles and runs.
+
+* The :module:`CMakePackageConfigHelpers` module's
+ :command:`write_basic_package_version_file` command gained a new
+ ``ARCH_INDEPENDENT`` option for supporting architecture-independent
+ packages.
+
+* The :module:`ExternalProject` module :command:`ExternalProject_Add` command
+ gained ``LOG_DIR`` and ``LOG_MERGED_STDOUTERR`` options to control logging.
+
+* The :module:`ExternalProject` module :command:`ExternalProject_Add` command
+ gained ``LOG_PATCH`` to optionally log the patch step.
+
+* The :module:`ExternalProject` module :command:`ExternalProject_Add` command
+ learned to apply ``SOURCE_SUBDIR`` when ``BUILD_IN_SOURCE`` is also used.
+ The ``BUILD_COMMAND`` is run in the given ``SOURCE_SUBDIR`` of the
+ ``SOURCE_DIR``.
+
+* The :module:`FetchContent` module gained a new
+ :command:`FetchContent_MakeAvailable` command. It accepts a list of
+ dependency names, which it then iterates over, populating and adding
+ each one to the main build using the canonical pattern. This
+ significantly reduces the amount of boilerplate needed in a project.
+
+* The :module:`FindBISON` module's ``BISON_TARGET`` command now runs ``bison``
+ with :variable:`CMAKE_CURRENT_BINARY_DIR` as the working directory.
+ See policy :policy:`CMP0088`.
+
+* The :module:`FindCURL` module gained support for requesting
+ protocols as package components.
+
+* The :module:`FindFontconfig` module was added to find `fontconfig`_.
+
+* The :module:`FindGDAL` module now provides imported targets.
+
+* The :module:`FindGIF` module now provides imported targets.
+
+* The :module:`FindGit` module now provides an imported target for the
+ Git executable.
+
+* The :module:`FindIce` module learned to find ``slice2confluence``
+ and ``slice2matlab``.
+
+* The :module:`FindLibinput` module was added to find `libinput`_.
+
+* The :module:`FindLibLZMA` module now provides imported targets.
+
+* The :module:`FindMatlab` module gained new options ``R2017b`` and
+ ``R2018a`` to specify the MEX API version to use; these options
+ mirror the new options to the ``mex`` command in MATLAB R2018a.
+ The option ``MX_LIBRARY`` is no longer needed.
+
+* The :module:`FindPostgreSQL` module now provides imported targets.
+
+* The :module:`FindPython`, :module:`FindPython2`, and :module:`FindPython3`
+ modules gained support for ``NumPy`` component.
+
+* The :module:`FindPython2`, :module:`FindPython3`, and :module:`FindPython`
+ modules now support running in script mode by skipping the creation of
+ imported targets and helper functions.
+
+* The :module:`FindSQLite3` module was added to find the SQLite v3.x library.
+
+* The :module:`FindX11` had the following variables renamed in order to match
+ their library names rather than header names. The old variables are provided
+ for compatibility:
+
+ - ``X11_Xxf86misc_INCLUDE_PATH`` instead of ``X11_xf86misc_INCLUDE_PATH``
+ - ``X11_Xxf86misc_LIB`` instead of ``X11_xf86misc_LIB``
+ - ``X11_Xxf86misc_FOUND`` instead of ``X11_xf86misc_FOUND``
+ - ``X11_Xxf86vm_INCLUDE_PATH`` instead of ``X11_xf86vmode_INCLUDE_PATH``
+ - ``X11_Xxf86vm_LIB`` instead of ``X11_xf86vmode_LIB``
+ - ``X11_Xxf86vm_FOUND`` instead of ``X11_xf86vmode_FOUND``
+ - ``X11_xkbfile_INCLUDE_PATH`` instead of ``X11_Xkbfile_INCLUDE_PATH``
+ - ``X11_xkbfile_LIB`` instead of ``X11_Xkbfile_LIB``
+ - ``X11_xkbfile_FOUND`` instead of ``X11_Xkbfile_FOUND``
+ - ``X11_Xtst_INCLUDE_PATH`` instead of ``X11_XTest_INCLUDE_PATH``
+ - ``X11_Xtst_LIB`` instead of ``X11_XTest_LIB``
+ - ``X11_Xtst_FOUND`` instead of ``X11_XTest_FOUND``
+ - ``X11_Xss_INCLUDE_PATH`` instead of ``X11_Xscreensaver_INCLUDE_PATH``
+ - ``X11_Xss_LIB`` instead of ``X11_Xscreensaver_LIB``
+ - ``X11_Xss_FOUND`` instead of ``X11_Xscreensaver_FOUND``
+
+ The following variables are deprecated completely since they were
+ essentially duplicates:
+
+ - ``X11_Xinput_INCLUDE_PATH`` (use ``X11_Xi_INCLUDE_PATH``)
+ - ``X11_Xinput_LIB`` (use ``X11_Xi_LIB``)
+ - ``X11_Xinput_FOUND`` (use ``X11_Xi_FOUND``)
+
+* The :module:`FindX11` now provides ``X11_Xext_INCLUDE_PATH``.
+
+* The :module:`FindX11` now provides imported targets.
+
+* The :module:`UseSWIG` module learned to pass ``-module <module_name>`` to
+ the ``SWIG`` compiler if the file property ``SWIG_MODULE_NAME`` is defined.
+ See policy :policy:`CMP0086`.
+
+* The :module:`UseSWIG` module gained an option to specify
+ ``SWIG`` source file extensions.
+
+.. _`fontconfig`: https://www.freedesktop.org/wiki/Software/fontconfig/
+.. _`libinput`: https://www.freedesktop.org/wiki/Software/libinput/
+
+Generator Expressions
+---------------------
+
+* The ``$<Fortran_COMPILER_ID:...>`` and ``$<Fortran_COMPILER_VERSION:...>``
+ :manual:`generator expressions <cmake-generator-expressions(7)>` were added.
+
+* The ``$<IN_LIST:...>`` generator expression now correctly handles an
+ empty argument. See :policy:`CMP0085` for details.
+
+Autogen
+-------
+
+* The :prop_tgt:`AUTOMOC_EXECUTABLE`, :prop_tgt:`AUTORCC_EXECUTABLE`, and
+ :prop_tgt:`AUTOUIC_EXECUTABLE` target properties were added. They all
+ take a path to an executable and force automoc/autorcc/autouic to use
+ this executable.
+
+ Setting these will also prevent the configure time testing for these
+ executables. This is mainly useful when you build these tools yourself.
+
+* The new variables :variable:`CMAKE_GLOBAL_AUTOGEN_TARGET`,
+ :variable:`CMAKE_GLOBAL_AUTOGEN_TARGET_NAME`,
+ :variable:`CMAKE_GLOBAL_AUTORCC_TARGET` and
+ :variable:`CMAKE_GLOBAL_AUTORCC_TARGET_NAME` control the generation
+ of global ``autogen`` and ``autorcc`` targets.
+
+* A new :variable:`CMAKE_AUTOGEN_ORIGIN_DEPENDS` variable and
+ :prop_tgt:`AUTOGEN_ORIGIN_DEPENDS` target property may be set to enable or
+ disable forwarding of the origin target dependencies to the corresponding
+ ``_autogen`` target.
+
+CTest
+-----
+
+* :manual:`ctest(1)` gained a ``--show-only=json-v1`` option to show the
+ list of tests in a machine-readable JSON format.
+ See the :ref:`Show as JSON Object Model` section of the manual.
+
+* The :command:`ctest_submit` command learned a new ``Done`` part that can be used
+ to inform CDash that a build is complete and that no more parts will be uploaded.
+
+* CTest learned to accept the dashboard server submission URL from a single
+ variable. See the ``SubmitURL`` setting in :manual:`ctest(1)`,
+ the :variable:`CTEST_SUBMIT_URL` variable, and the ``SUBMIT_URL``
+ argument of the :command:`ctest_submit` command.
+
+Deprecated and Removed Features
+===============================
+
+* An explicit deprecation diagnostic was added for policies ``CMP0064``
+ and ``CMP0065`` (``CMP0063`` and below were already deprecated).
+ The :manual:`cmake-policies(7)` manual explains that the OLD behaviors
+ of all policies are deprecated and that projects should port to the
+ NEW behaviors.
+
+* The :generator:`Xcode` generator deprecated support for Xcode
+ versions prior to Xcode 5. Support for those will be dropped in a
+ future version of CMake.
+
+* The :module:`FindQt` module is no longer used by the :command:`find_package`
+ command as a find module. This allows the Qt Project upstream to optionally
+ provide its own ``QtConfig.cmake`` package configuration file and have
+ applications use it via ``find_package(Qt)`` rather than
+ ``find_package(Qt CONFIG)``. See policy :policy:`CMP0084`.
+
+* Support for running CMake on Windows XP and Windows Vista has been dropped.
+ The precompiled Windows binaries provided on ``cmake.org`` now require
+ Windows 7 or higher.
+
+* CTest no longer supports submissions via ``ftp``, ``scp``, ``cp``, and
+ ``xmlrpc``. CDash is the only maintained testing dashboard for CTest,
+ and it only supports submissions over ``http`` and ``https``.
+
+Other Changes
+=============
+
+* Object library linking has been fixed to propagate private link libraries
+ of object libraries to consuming targets.
+
+* Install rules under :command:`add_subdirectory` now interleave with those in
+ the calling directory. See policy :policy:`CMP0082` for details.
+
+* CMake now imposes a maximum recursion limit to prevent a stack overflow on
+ scripts that recurse infinitely. The limit can be adjusted at runtime with
+ :variable:`CMAKE_MAXIMUM_RECURSION_DEPTH`.
+
+* When using cppcheck via the :variable:`CMAKE_<LANG>_CPPCHECK` variable
+ or :prop_tgt:`<LANG>_CPPCHECK` property, the build will now fail if
+ ``cppcheck`` returns non-zero as configured by its command-line options.
+
+* Required link options to manage Position Independent Executable are now
+ added when :prop_tgt:`POSITION_INDEPENDENT_CODE` is set. The project is
+ responsible for using the :module:`CheckPIESupported` module to check for
+ ``PIE`` support to ensure that the :prop_tgt:`POSITION_INDEPENDENT_CODE`
+ target property will be honored at link time for executables. This behavior
+ is controlled by policy :policy:`CMP0083`.
+
+* :ref:`Visual Studio Generators` for VS 2010 and above learned
+ to support the ``VS_DEBUGGER_*`` properties on targets created
+ via :command:`add_custom_target`.
+
+* The :module:`CPack` module no longer defaults to the ``paxr`` value in the
+ :variable:`CPACK_DEBIAN_ARCHIVE_TYPE` variable, because ``dpkg`` has
+ never supported the PAX tar format. The ``paxr`` value will be mapped
+ to ``gnutar`` and a deprecation message emitted.
+
+* CMake no longer issues a warning if a target listed in an
+ :command:`install(TARGETS)` command has its :prop_tgt:`EXCLUDE_FROM_ALL`
+ property set to true.
+
+Updates
+=======
+
+Changes made since CMake 3.14.0 include the following.
+
+3.14.1
+------
+
+* The :module:`FindFontconfig` module added by 3.14.0 accidentally
+ used uppercase ``FONTCONFIG_*`` variable names that do not match
+ our conventions. 3.14.1 revises the module to use ``Fontconfig_*``
+ variable names. This is incompatible with 3.14.0 but since the
+ module is new in the 3.14 series usage should not yet be widespread.
+
+3.14.3
+------
+
+* The :variable:`CMAKE_VS_PLATFORM_NAME_DEFAULT` variable was added
+ to help toolchain files work with the :generator:`Visual Studio 16 2019`
+ generator where the default platform now depends on the host platform.
+
+3.14.4
+------
+
+* In CMake 3.14.0 through 3.14.3, calling :command:`target_link_libraries`
+ to add ``PRIVATE`` dependencies to a static library created in another
+ directory (under policy :policy:`CMP0079` ``NEW`` behavior) would
+ incorrectly propagate usage requirements of those dependencies to
+ dependents that link the static library. This has been fixed.
+ The bug also existed in 3.13.0 through 3.13.4 and is fixed in 3.13.5.
+
+3.14.5
+------
+
+* Entries of the ``CPATH`` environment variable are no longer excluded
+ from explicit use via :command:`include_directories` and
+ :command:`target_include_directories` as they were in CMake 3.14.0
+ through 3.14.4.
+
+3.14.6
+------
+
+* In CMake 3.14.0 through 3.14.5, the :module:`FindBISON` module
+ policy :policy:`CMP0088` ``NEW`` behavior accidentally interpreted
+ a relative path to the ``.y`` input as relative to the build tree
+ directory instead of the source tree directory. This has been fixed.
+
+3.14.7
+------
+
+* In CMake 3.14.0 through 3.14.6, the :prop_dir:`EXCLUDE_FROM_ALL`
+ directory property was regressed from pre-3.14 behavior and caused
+ targets within the directory to be excluded even from its own "all".
+ This has been fixed.
diff --git a/Help/release/3.15.rst b/Help/release/3.15.rst
new file mode 100644
index 000000000..957e6e958
--- /dev/null
+++ b/Help/release/3.15.rst
@@ -0,0 +1,387 @@
+CMake 3.15 Release Notes
+************************
+
+.. only:: html
+
+ .. contents::
+
+Changes made since CMake 3.14 include the following.
+
+New Features
+============
+
+Generators
+----------
+
+* The :generator:`Xcode` generator now supports per-target schemes.
+ See the :variable:`CMAKE_XCODE_GENERATE_SCHEME` variable and
+ :prop_tgt:`XCODE_GENERATE_SCHEME` target property.
+
+* The :generator:`Green Hills MULTI` generator has been updated:
+
+ * It now supports the :command:`add_custom_command` and
+ :command:`add_custom_target` commands.
+
+ * It is now available on Linux.
+
+Languages
+---------
+
+* Preliminary support for the ``Swift`` language was added to the
+ :generator:`Ninja` generator:
+
+ * Use the :envvar:`SWIFTC` environment variable to specify a compiler.
+
+ * The :prop_tgt:`Swift_DEPENDENCIES_FILE` target property and
+ :prop_sf:`Swift_DEPENDENCIES_FILE` source file property were added
+ to customize dependency files.
+
+ * The :prop_tgt:`Swift_MODULE_NAME` target property was added to
+ customize the Swift module name.
+
+ * The :prop_sf:`Swift_DIAGNOSTICS_FILE` source property was added to
+ indicate where to write the serialised Swift diagnostics.
+
+ The Swift support is experimental, not considered stable, and may change
+ in future releases of CMake.
+
+Compilers
+---------
+
+* The ``Clang`` compiler variant on Windows that targets the MSVC ABI
+ but has a GNU-like command line is now supported.
+
+* Support for the Clang-based ARM compiler was added with compiler id
+ ``ARMClang``.
+
+* Support was added for the IAR compiler architectures Renesas RX,
+ RL78, RH850 and Texas Instruments MSP430.
+
+* Support was added for the IAR compilers built for Linux (IAR BuildLx).
+
+Command-Line
+------------
+
+* The :envvar:`CMAKE_GENERATOR` environment variable was added
+ to specify a default generator to use when :manual:`cmake(1)` is
+ run without a ``-G`` option. Additionally, environment variables
+ :envvar:`CMAKE_GENERATOR_PLATFORM`, :envvar:`CMAKE_GENERATOR_TOOLSET`,
+ and :envvar:`CMAKE_GENERATOR_INSTANCE` were created to configure
+ the generator.
+
+* The :manual:`cmake(1)` ``--build`` tool ``--target`` parameter gained support
+ for multiple targets, e.g. ``cmake --build . --target Library1 Library2``.
+ It now also has a short form ``-t`` alias, e.g.
+ ``cmake --build . -t Library1 Library2``.
+
+* The :manual:`cmake(1)` command gained a new ``--install`` option.
+ This may be used after building a project to run installation without
+ using the generated build system or the native build tool.
+
+* The :manual:`cmake(1)` command learned a new CLI option ``--loglevel``.
+
+* The :manual:`cmake(1)` ``-E remove_directory`` command-line tool learned
+ to support removing multiple directories.
+
+* The :manual:`cmake(1)` ``-E tar`` tool has been improved:
+
+ * It now continues adding files to an archive even if some of the files
+ are not readable. This behavior is more consistent with the
+ classic ``tar`` tool.
+
+ * It now parses all flags, and if an invalid flag was provided, a
+ warning is issued.
+
+ * It now displays an error if no action flag was specified, along with a
+ list of possible actions: ``t`` (list), ``c`` (create) or ``x`` (extract).
+
+ * It now supports extracting (``-x``) or listing (``-t``) only specific
+ files or directories.
+
+ * It now supports Zstandard compression with a ``--zstd`` option.
+ Zstandard was designed to give a compression ratio comparable to that
+ of the DEFLATE (zip) algorithm, but faster, especially for decompression.
+
+Commands
+--------
+
+* The :command:`add_custom_command` and :command:`add_custom_target` commands
+ gained a new ``JOB_POOL`` option that works with the :generator:`Ninja`
+ generator to set the pool variable on the build statement.
+
+* The :command:`add_library` command ``ALIAS`` option learned to support
+ import libraries of the ``UNKNOWN`` type.
+
+* The :command:`cmake_parse_arguments` command gained an additional
+ ``<prefix>_KEYWORDS_MISSING_VALUES`` output variable to report
+ keyword arguments that were given by the caller with no values.
+
+* The :command:`execute_process` command gained a ``COMMAND_ECHO`` option
+ and supporting :variable:`CMAKE_EXECUTE_PROCESS_COMMAND_ECHO` variable
+ to enable echoing of the command-line string before execution.
+
+* The :command:`file(INSTALL)` command learned a new argument,
+ ``FOLLOW_SYMLINK_CHAIN``, which can be used to recursively resolve and
+ install symlinks.
+
+* :command:`list` learned new sub-commands:
+ ``PREPEND``, ``POP_FRONT`` and ``POP_BACK``.
+
+* The :command:`message` command learned new types:
+ ``NOTICE``, ``VERBOSE``, ``DEBUG`` and ``TRACE``.
+
+* The :command:`string` learned a new sub-command ``REPEAT``.
+
+Variables
+---------
+
+* The :variable:`CMAKE_CROSSCOMPILING_EMULATOR` variable and corresponding
+ :prop_tgt:`CROSSCOMPILING_EMULATOR` target property learned to support
+ arguments to the emulator.
+
+* The :variable:`CMAKE_FIND_PACKAGE_PREFER_CONFIG` variable was added to tell
+ :command:`find_package` calls to look for a package configuration
+ file first even if a find module is available.
+
+* The :variable:`CMAKE_FRAMEWORK` variable was added to initialize the
+ :prop_tgt:`FRAMEWORK` property on all targets.
+
+* The :variable:`CMAKE_VS_JUST_MY_CODE_DEBUGGING` variable and
+ :prop_tgt:`VS_JUST_MY_CODE_DEBUGGING` target property were added to
+ enable the Just My Code feature of the Visual Studio Debugger when
+ compiling with MSVC cl 19.05 and higher.
+
+* The :variable:`CMAKE_MSVC_RUNTIME_LIBRARY` variable and
+ :prop_tgt:`MSVC_RUNTIME_LIBRARY` target property were introduced to
+ select the runtime library used by compilers targeting the MSVC ABI.
+ See policy :policy:`CMP0091`.
+
+* The :variable:`CMAKE_PROJECT_INCLUDE` and
+ :variable:`CMAKE_PROJECT_INCLUDE_BEFORE` variables were added to allow
+ injection of custom code at the sites of :command:`project` calls
+ without knowing the project name a priori.
+
+Properties
+----------
+
+* The :prop_tgt:`ADDITIONAL_CLEAN_FILES` target property and
+ :prop_dir:`ADDITIONAL_CLEAN_FILES` directory property were added.
+ They allow to register additional files that should be removed during
+ the clean stage.
+
+* The :prop_tgt:`PUBLIC_HEADER` and :prop_tgt:`PRIVATE_HEADER` properties
+ may now be set on :ref:`Interface Libraries`. The headers specified by those
+ properties can be installed using the :command:`install(TARGETS)` command by
+ passing the ``PUBLIC_HEADER`` and ``PRIVATE_HEADER`` arguments respectively.
+
+* The :prop_tgt:`VS_PACKAGE_REFERENCES` target property was added to
+ tell :ref:`Visual Studio Generators` to add references to ``nuget``
+ packages.
+
+* The :prop_tgt:`VS_PROJECT_IMPORT` target property was added to allow
+ managed Visual Studio project files to import external ``.props`` files.
+
+* The :prop_tgt:`VS_NO_SOLUTION_DEPLOY` target property was added to
+ tell :ref:`Visual Studio Generators` whether to deploy an artifact
+ to the WinCE or Windows Phone target device.
+
+Modules
+-------
+
+* The :module:`FindBoost` module was reworked to expose a more consistent
+ user experience between its "Config" and "Module" modes and with other
+ find modules in general.
+
+ * A new imported target ``Boost::headers`` is now defined (same
+ as ``Boost::boost``).
+
+ * New output variables ``Boost_VERSION_MACRO``,
+ ``Boost_VERSION_MAJOR``, ``Boost_VERSION_MINOR``,
+ ``Boost_VERSION_PATCH``, and ``Boost_VERSION_COUNT``
+ were added.
+
+ * The ``QUIET`` argument passed to :command:`find_package` is no
+ longer ignored in config mode. Note that the CMake package shipped with
+ Boost ``1.70.0`` ignores the ``QUIET`` argument passed to
+ :command:`find_package`. This is fixed in the next Boost release.
+
+ * The input switch ``Boost_DETAILED_FAILURE_MSG`` was removed.
+
+ * ``Boost_VERSION`` now reports the version in ``x.y.z``
+ format in module mode. See policy :policy:`CMP0093`.
+
+* The :module:`FindCups` module now provides imported targets.
+
+* The :module:`FindEnvModules` module was added to use Lua- and TCL-based
+ environment modules in :ref:`CTest Scripts <CTest Script>`.
+
+* The :module:`FindGLEW` module now provides an interface more consistent
+ with what upstream GLEW provides in its own CMake package files.
+
+* The :module:`FindPkgConfig` now populates :prop_tgt:`INTERFACE_LINK_OPTIONS`
+ property of imported targets with other (non-library) linker flags.
+
+* The :module:`FindPostgreSQL` module learned to find debug and release
+ variants separately.
+
+* Modules :module:`FindPython3`, :module:`FindPython2` and :module:`FindPython`
+ gained additional lookup strategies and controls, and a new default.
+ See policy :policy:`CMP0094`.
+
+* Modules :module:`FindPython`, :module:`FindPython2` and :module:`FindPython3`
+ gain a new target (respectively ``Python::Module``, ``Python2::Module``
+ and ``Python3::Module``) which can be used to develop Python modules.
+
+* Modules :module:`FindPython3`, :module:`FindPython2` and :module:`FindPython`
+ gain capability to control how virtual environments are handled.
+
+* The :module:`UseSWIG` module learned to manage alternate library names
+ by passing ``-interface <library_name>`` for ``python`` language or
+ ``-dllimport <library_name>`` for ``CSharp`` language to the ``SWIG``
+ compiler.
+
+Generator Expressions
+---------------------
+
+* The :manual:`generator expressions <cmake-generator-expressions(7)>`
+ ``C_COMPILER_ID``, ``CXX_COMPILER_ID``, ``CUDA_COMPILER_ID``,
+ ``Fortran_COMPILER_ID``, ``COMPILE_LANGUAGE``, ``COMPILE_LANG_AND_ID``, and
+ ``PLATFORM_ID`` learned to support matching one value from a comma-separated
+ list.
+
+* The ``$<CUDA_COMPILER_ID:...>`` and ``$<CUDA_COMPILER_VERSION:...>``
+ :manual:`generator expressions <cmake-generator-expressions(7)>` were added.
+
+* The ``$<COMPILE_LANG_AND_ID:...>`` generator expression was introduced to
+ allow specification of compile options for target files based on the
+ :variable:`CMAKE_<LANG>_COMPILER_ID` and :prop_sf:`LANGUAGE` of
+ each source file.
+
+* A ``$<FILTER:list,INCLUDE|EXCLUDE,regex>``
+ :manual:`generator expression <cmake-generator-expressions(7)>`
+ has been added.
+
+* A ``$<REMOVE_DUPLICATES:list>``
+ :manual:`generator expression <cmake-generator-expressions(7)>`
+ has been added.
+
+* The ``$<SHELL_PATH:...>`` :manual:`generator expression
+ <cmake-generator-expressions(7)>` gained support for a list of paths.
+
+* New ``$<TARGET_FILE*>`` :manual:`generator expressions
+ <cmake-generator-expressions(7)>` were added to retrieve the prefix, base
+ name, and suffix of the file names of various artifacts:
+
+ * ``$<TARGET_FILE_PREFIX:...>``
+ * ``$<TARGET_FILE_BASE_NAME:...>``
+ * ``$<TARGET_FILE_SUFFIX:...>``
+ * ``$<TARGET_LINKER_FILE_PREFIX:...>``
+ * ``$<TARGET_LINKER_FILE_BASE_NAME:...>``
+ * ``$<TARGET_LINKER_FILE_SUFFIX:...>``
+ * ``$<TARGET_PDB_FILE_BASE_NAME:...>``
+
+* The ``$<TARGET_OBJECTS:...>`` :manual:`generator expression
+ <cmake-generator-expressions(7)>` is now supported on ``SHARED``,
+ ``STATIC``, ``MODULE`` libraries and executables.
+
+CTest
+-----
+
+* The :command:`ctest_submit` command learned a new option: ``BUILD_ID``.
+ This can be used to store the ID assigned to this build by CDash to a
+ variable.
+
+* The :command:`ctest_update` command learned to honor a new variable:
+ :variable:`CTEST_UPDATE_VERSION_OVERRIDE`. This can be used to specify
+ the current version of your source tree rather than using the update
+ command to discover the current version that is checked out.
+
+CPack
+-----
+
+* The :cpack_gen:`CPack IFW Generator` gained a new
+ :variable:`CPACK_IFW_PACKAGE_STYLE_SHEET` variable to customize the
+ installer stylesheet.
+
+Deprecated and Removed Features
+===============================
+
+* The :manual:`cmake-server(7)` mode has been deprecated and will be
+ removed from a future version of CMake. Please port clients to use
+ the :manual:`cmake-file-api(7)` instead.
+
+* The :prop_dir:`ADDITIONAL_MAKE_CLEAN_FILES` directory property is now
+ deprecated. Use the :prop_dir:`ADDITIONAL_CLEAN_FILES` directory property
+ instead.
+
+* The variable :variable:`CMAKE_AUTOMOC_RELAXED_MODE` is considered
+ deprecated. Support still exists but will be removed in future versions.
+
+* The :command:`export(PACKAGE)` command now does nothing unless
+ enabled via :variable:`CMAKE_EXPORT_PACKAGE_REGISTRY`.
+ See policy :policy:`CMP0090`.
+
+* The :generator:`Xcode` generator now requires at least Xcode 5.
+
+* An explicit deprecation diagnostic was added for policy ``CMP0066``
+ (``CMP0065`` and below were already deprecated).
+ The :manual:`cmake-policies(7)` manual explains that the OLD behaviors
+ of all policies are deprecated and that projects should port to the
+ NEW behaviors.
+
+Other Changes
+=============
+
+* CMake learned how to compile C++14 with the IBM AIX XL compiler
+ and the SunPro compiler and to compile C++20 with the AppleClang compiler.
+
+* With MSVC-like compilers the value of :variable:`CMAKE_<LANG>_FLAGS`
+ no longer contains warning flags like ``/W3`` by default.
+ See policy :policy:`CMP0092`.
+
+* IBM Clang-based XL compilers that define ``__ibmxl__`` now use the
+ compiler id ``XLClang`` instead of ``XL``. See policy :policy:`CMP0089`.
+
+* The :command:`file(REMOVE)` and :command:`file(REMOVE_RECURSE)` commands
+ were changed to ignore empty arguments with a warning instead of treating
+ them as a relative path and removing the contents of the current directory.
+
+Updates
+=======
+
+Changes made since CMake 3.15.0 include the following.
+
+3.15.1
+------
+
+* In CMake 3.15.0 support for the GNU-like ``Clang`` compiler targeting the
+ MSVC ABI implemented :variable:`CMAKE_CXX_STANDARD` values 98 and 11 using
+ the corresponding ``-std=`` flags. However, these modes do not work with
+ the MSVC standard library. Therefore CMake 3.15.1 passes C++14 standard
+ flags even for C++98 and C++11. This is consistent with MSVC itself which
+ always runs in a mode aware of C++14.
+
+* Preliminary Swift support added in 3.15.0 has been updated.
+
+3.15.2
+------
+
+* In CMake 3.15.0 and 3.15.1 the :variable:`CMAKE_FIND_PACKAGE_PREFER_CONFIG`
+ variable caused the :command:`find_package` command to fail on a missing
+ package even without the ``REQUIRED`` option. This has been fixed.
+
+3.15.3
+------
+
+* ``CrayPrgEnv`` compiler wrapper support has been updated for the 19.06
+ release of the Cray Programming Environment for which the default linking
+ mode on XC Cray systems is now dynamic instead of static.
+
+3.15.4
+------
+
+* In CMake 3.15.0 through 3.15.3, the :prop_dir:`EXCLUDE_FROM_ALL`
+ directory property was regressed from pre-3.14 behavior and caused
+ targets within the directory to be excluded even from its own "all".
+ This has been fixed.
+ The bug also existed in 3.14.0 through 3.14.6 and is fixed in 3.14.7.
diff --git a/Help/variable/CACHE.rst b/Help/variable/CACHE.rst
new file mode 100644
index 000000000..2cef27efa
--- /dev/null
+++ b/Help/variable/CACHE.rst
@@ -0,0 +1,18 @@
+CACHE
+-----
+
+Operator to read cache variables.
+
+Use the syntax ``$CACHE{VAR}`` to read cache entry ``VAR``.
+See the :ref:`cmake-language(7) variables <CMake Language Variables>`
+documentation for more complete documentation of the interaction of
+normal variables and cache entries.
+
+When evaluating :ref:`Variable References` of the form ``${VAR}``,
+CMake first searches for a normal variable with that name, and if not
+found CMake will search for a cache entry with that name.
+The ``$CACHE{VAR}`` syntax can be used to do direct cache lookup and
+ignore any existing normal variable.
+
+See the :command:`set` and :command:`unset` commands to see how to
+write or remove cache variables.
diff --git a/Help/variable/CMAKE_AUTOGEN_ORIGIN_DEPENDS.rst b/Help/variable/CMAKE_AUTOGEN_ORIGIN_DEPENDS.rst
new file mode 100644
index 000000000..1398e7856
--- /dev/null
+++ b/Help/variable/CMAKE_AUTOGEN_ORIGIN_DEPENDS.rst
@@ -0,0 +1,11 @@
+CMAKE_AUTOGEN_ORIGIN_DEPENDS
+----------------------------
+
+Switch for forwarding origin target dependencies to the corresponding
+``_autogen`` targets.
+
+This variable is used to initialize the :prop_tgt:`AUTOGEN_ORIGIN_DEPENDS`
+property on all the targets. See that target property for additional
+information.
+
+By default :variable:`CMAKE_AUTOGEN_ORIGIN_DEPENDS` is ``ON``.
diff --git a/Help/variable/CMAKE_AUTOGEN_PARALLEL.rst b/Help/variable/CMAKE_AUTOGEN_PARALLEL.rst
new file mode 100644
index 000000000..dd9499af3
--- /dev/null
+++ b/Help/variable/CMAKE_AUTOGEN_PARALLEL.rst
@@ -0,0 +1,10 @@
+CMAKE_AUTOGEN_PARALLEL
+----------------------
+
+Number of parallel ``moc`` or ``uic`` processes to start when using
+:prop_tgt:`AUTOMOC` and :prop_tgt:`AUTOUIC`.
+
+This variable is used to initialize the :prop_tgt:`AUTOGEN_PARALLEL` property
+on all the targets. See that target property for additional information.
+
+By default :variable:`CMAKE_AUTOGEN_PARALLEL` is unset.
diff --git a/Help/variable/CMAKE_AUTOGEN_VERBOSE.rst b/Help/variable/CMAKE_AUTOGEN_VERBOSE.rst
new file mode 100644
index 000000000..bad9cf2b3
--- /dev/null
+++ b/Help/variable/CMAKE_AUTOGEN_VERBOSE.rst
@@ -0,0 +1,13 @@
+CMAKE_AUTOGEN_VERBOSE
+---------------------
+
+Sets the verbosity of :prop_tgt:`AUTOMOC`, :prop_tgt:`AUTOUIC` and
+:prop_tgt:`AUTORCC`. A positive integer value or a true boolean value
+lets the ``AUTO*`` generators output additional processing information.
+
+Setting :variable:`CMAKE_AUTOGEN_VERBOSE` has the same effect
+as setting the ``VERBOSE`` environment variable during
+generation (e.g. by calling ``make VERBOSE=1``).
+The extra verbosity is limited to the ``AUTO*`` generators though.
+
+By default :variable:`CMAKE_AUTOGEN_VERBOSE` is unset.
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..ba1b9d27a
--- /dev/null
+++ b/Help/variable/CMAKE_AUTOMOC_MACRO_NAMES.rst
@@ -0,0 +1,20 @@
+CMAKE_AUTOMOC_MACRO_NAMES
+----------------------------
+
+:ref:`Semicolon-separated 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_BUILD_RPATH_USE_ORIGIN.rst b/Help/variable/CMAKE_BUILD_RPATH_USE_ORIGIN.rst
new file mode 100644
index 000000000..e34ede6ad
--- /dev/null
+++ b/Help/variable/CMAKE_BUILD_RPATH_USE_ORIGIN.rst
@@ -0,0 +1,7 @@
+CMAKE_BUILD_RPATH_USE_ORIGIN
+----------------------------
+
+Whether to use relative paths for the build ``RPATH``.
+
+This is used to initialize the :prop_tgt:`BUILD_RPATH_USE_ORIGIN` target
+property for all targets, see that property for more details.
diff --git a/Help/variable/CMAKE_CODEBLOCKS_COMPILER_ID.rst b/Help/variable/CMAKE_CODEBLOCKS_COMPILER_ID.rst
new file mode 100644
index 000000000..ad2709dc3
--- /dev/null
+++ b/Help/variable/CMAKE_CODEBLOCKS_COMPILER_ID.rst
@@ -0,0 +1,13 @@
+CMAKE_CODEBLOCKS_COMPILER_ID
+----------------------------
+
+Change the compiler id in the generated CodeBlocks project files.
+
+CodeBlocks uses its own compiler id string which differs from
+:variable:`CMAKE_<LANG>_COMPILER_ID`. If this variable is left empty,
+CMake tries to recognize the CodeBlocks compiler id automatically.
+Otherwise the specified string is used in the CodeBlocks project file.
+See the CodeBlocks documentation for valid compiler id strings.
+
+Other IDEs like QtCreator that also use the CodeBlocks generator may ignore
+this setting.
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_CPACK_COMMAND.rst b/Help/variable/CMAKE_CPACK_COMMAND.rst
new file mode 100644
index 000000000..559108a1a
--- /dev/null
+++ b/Help/variable/CMAKE_CPACK_COMMAND.rst
@@ -0,0 +1,8 @@
+CMAKE_CPACK_COMMAND
+-------------------
+
+Full path to :manual:`cpack(1)` command installed with CMake.
+
+This is the full path to the CPack executable :manual:`cpack(1)` which is
+useful from custom commands that want to use the :manual:`cmake(1)` ``-E``
+option for portable system commands.
diff --git a/Help/variable/CMAKE_CUDA_HOST_COMPILER.rst b/Help/variable/CMAKE_CUDA_HOST_COMPILER.rst
new file mode 100644
index 000000000..eea2c4fbd
--- /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_CUDA_SEPARABLE_COMPILATION.rst b/Help/variable/CMAKE_CUDA_SEPARABLE_COMPILATION.rst
new file mode 100644
index 000000000..eef92fb16
--- /dev/null
+++ b/Help/variable/CMAKE_CUDA_SEPARABLE_COMPILATION.rst
@@ -0,0 +1,6 @@
+CMAKE_CUDA_SEPARABLE_COMPILATION
+--------------------------------
+
+Default value for :prop_tgt:`CUDA_SEPARABLE_COMPILATION` target property.
+This variable is used to initialize the property on each target as it is
+created.
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_DOTNET_TARGET_FRAMEWORK_VERSION.rst b/Help/variable/CMAKE_DOTNET_TARGET_FRAMEWORK_VERSION.rst
new file mode 100644
index 000000000..124fefef1
--- /dev/null
+++ b/Help/variable/CMAKE_DOTNET_TARGET_FRAMEWORK_VERSION.rst
@@ -0,0 +1,16 @@
+CMAKE_DOTNET_TARGET_FRAMEWORK_VERSION
+-------------------------------------
+
+Default value for :prop_tgt:`DOTNET_TARGET_FRAMEWORK_VERSION`
+property of targets.
+
+This variable is used to initialize the
+:prop_tgt:`DOTNET_TARGET_FRAMEWORK_VERSION` property on all
+targets. See that target property for additional information.
+
+Setting ``CMAKE_DOTNET_TARGET_FRAMEWORK_VERSION`` may be necessary
+when working with ``C#`` and newer .NET framework versions to
+avoid referencing errors with the ``ALL_BUILD`` CMake target.
+
+This variable is only evaluated for :ref:`Visual Studio Generators`
+VS 2010 and above.
diff --git a/Help/variable/CMAKE_EXECUTE_PROCESS_COMMAND_ECHO.rst b/Help/variable/CMAKE_EXECUTE_PROCESS_COMMAND_ECHO.rst
new file mode 100644
index 000000000..76561d82b
--- /dev/null
+++ b/Help/variable/CMAKE_EXECUTE_PROCESS_COMMAND_ECHO.rst
@@ -0,0 +1,6 @@
+CMAKE_EXECUTE_PROCESS_COMMAND_ECHO
+----------------------------------
+
+If this variable is set to ``STDERR``, ``STDOUT`` or ``NONE`` then commands
+in :command:`execute_process` calls will be printed to either stderr or
+stdout or not at all.
diff --git a/Help/variable/CMAKE_EXPORT_PACKAGE_REGISTRY.rst b/Help/variable/CMAKE_EXPORT_PACKAGE_REGISTRY.rst
new file mode 100644
index 000000000..3476a199c
--- /dev/null
+++ b/Help/variable/CMAKE_EXPORT_PACKAGE_REGISTRY.rst
@@ -0,0 +1,15 @@
+CMAKE_EXPORT_PACKAGE_REGISTRY
+-----------------------------
+
+Enables the :command:`export(PACKAGE)` command when :policy:`CMP0090`
+is set to ``NEW``.
+
+The :command:`export(PACKAGE)` command does nothing by default. In some cases
+it is desirable to write to the user package registry, so the
+``CMAKE_EXPORT_PACKAGE_REGISTRY`` variable may be set to enable it.
+
+If :policy:`CMP0090` is *not* set to ``NEW`` this variable does nothing, and
+the :variable:`CMAKE_EXPORT_NO_PACKAGE_REGISTRY` variable controls the behavior
+instead.
+
+See also :ref:`Disabling the Package Registry`.
diff --git a/Help/variable/CMAKE_FIND_PACKAGE_PREFER_CONFIG.rst b/Help/variable/CMAKE_FIND_PACKAGE_PREFER_CONFIG.rst
new file mode 100644
index 000000000..db658a1e0
--- /dev/null
+++ b/Help/variable/CMAKE_FIND_PACKAGE_PREFER_CONFIG.rst
@@ -0,0 +1,27 @@
+CMAKE_FIND_PACKAGE_PREFER_CONFIG
+---------------------------------
+
+Tell :command:`find_package` to try "Config" mode before "Module" mode if no
+mode was specified.
+
+The command :command:`find_package` operates without an explicit mode when
+the reduced signature is used without the ``MODULE`` option. In this case,
+by default, CMake first tries Module mode by searching for a
+``Find<pkg>.cmake`` module. If it fails, CMake then searches for the package
+using Config mode.
+
+Set ``CMAKE_FIND_PACKAGE_PREFER_CONFIG`` to ``TRUE`` to tell
+:command:`find_package` to first search using Config mode before falling back
+to Module mode.
+
+This variable may be useful when a developer has compiled a custom version of
+a common library and wishes to link it to a dependent project. If this
+variable is set to ``TRUE``, it would prevent a dependent project's call
+to :command:`find_package` from selecting the default library located by the
+system's ``Find<pkg>.cmake`` module before finding the developer's custom
+built library.
+
+Once this variable is set, it is the responsibility of the exported
+``<pkg>Config.cmake`` files to provide the same result variables as the
+``Find<pkg>.cmake`` modules so that dependent projects can use them
+interchangeably.
diff --git a/Help/variable/CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS.rst b/Help/variable/CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS.rst
new file mode 100644
index 000000000..dfbde2035
--- /dev/null
+++ b/Help/variable/CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS.rst
@@ -0,0 +1,10 @@
+CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS
+-----------------------------------
+
+Set to ``TRUE`` to tell :command:`find_package` calls to resolve symbolic
+links in the value of ``<PackageName>_DIR``.
+
+This is helpful in use cases where the package search path points at a
+proxy directory in which symlinks to the real package locations appear.
+This is not enabled by default because there are also common use cases
+in which the symlinks should be preserved.
diff --git a/Help/variable/CMAKE_FOLDER.rst b/Help/variable/CMAKE_FOLDER.rst
new file mode 100644
index 000000000..50a2b88d7
--- /dev/null
+++ b/Help/variable/CMAKE_FOLDER.rst
@@ -0,0 +1,7 @@
+CMAKE_FOLDER
+------------
+
+Set the folder name. Use to organize targets in an IDE.
+
+This variable is used to initialize the :prop_tgt:`FOLDER` property on all the
+targets. See that target property for additional information.
diff --git a/Help/variable/CMAKE_FRAMEWORK.rst b/Help/variable/CMAKE_FRAMEWORK.rst
new file mode 100644
index 000000000..591041c8b
--- /dev/null
+++ b/Help/variable/CMAKE_FRAMEWORK.rst
@@ -0,0 +1,7 @@
+CMAKE_FRAMEWORK
+---------------
+
+Default value for :prop_tgt:`FRAMEWORK` of targets.
+
+This variable is used to initialize the :prop_tgt:`FRAMEWORK` property on
+all the targets. See that target property for additional information.
diff --git a/Help/variable/CMAKE_GENERATOR_INSTANCE.rst b/Help/variable/CMAKE_GENERATOR_INSTANCE.rst
new file mode 100644
index 000000000..3657ed4ff
--- /dev/null
+++ b/Help/variable/CMAKE_GENERATOR_INSTANCE.rst
@@ -0,0 +1,25 @@
+CMAKE_GENERATOR_INSTANCE
+------------------------
+
+Generator-specific instance specification provided by user.
+
+Some CMake generators support selection of an instance of the native build
+system when multiple instances are available. If the user specifies an
+instance (e.g. by setting this cache entry or via the
+:envvar:`CMAKE_GENERATOR_INSTANCE` environment variable), or after a default
+instance is chosen when a build tree is first configured, the value will be
+available in this variable.
+
+The value of this variable should never be modified by project code.
+A toolchain file specified by the :variable:`CMAKE_TOOLCHAIN_FILE`
+variable may initialize ``CMAKE_GENERATOR_INSTANCE`` as a cache entry.
+Once a given build tree has been initialized with a particular value
+for this variable, changing the value has undefined behavior.
+
+Instance specification is supported only on specific generators:
+
+* For the :generator:`Visual Studio 15 2017` generator (and above)
+ this specifies the absolute path to the VS installation directory
+ of the selected VS instance.
+
+See native build system documentation for allowed instance values.
diff --git a/Help/variable/CMAKE_GHS_NO_SOURCE_GROUP_FILE.rst b/Help/variable/CMAKE_GHS_NO_SOURCE_GROUP_FILE.rst
new file mode 100644
index 000000000..b6768a131
--- /dev/null
+++ b/Help/variable/CMAKE_GHS_NO_SOURCE_GROUP_FILE.rst
@@ -0,0 +1,6 @@
+CMAKE_GHS_NO_SOURCE_GROUP_FILE
+------------------------------
+
+``ON`` / ``OFF`` boolean to control if the project file for a target should
+be one single file or multiple files. Refer to
+:prop_tgt:`GHS_NO_SOURCE_GROUP_FILE` for further details.
diff --git a/Help/variable/CMAKE_GLOBAL_AUTOGEN_TARGET.rst b/Help/variable/CMAKE_GLOBAL_AUTOGEN_TARGET.rst
new file mode 100644
index 000000000..e82867dfd
--- /dev/null
+++ b/Help/variable/CMAKE_GLOBAL_AUTOGEN_TARGET.rst
@@ -0,0 +1,26 @@
+CMAKE_GLOBAL_AUTOGEN_TARGET
+---------------------------
+
+Switch to enable generation of a global ``autogen`` target.
+
+When :variable:`CMAKE_GLOBAL_AUTORCC_TARGET` is enabled, a custom target
+``autogen`` is generated. This target depends on all :prop_tgt:`AUTOMOC` and
+:prop_tgt:`AUTOUIC` generated ``<ORIGIN>_autogen`` targets in the project.
+By building the global ``autogen`` target, all :prop_tgt:`AUTOMOC` and
+:prop_tgt:`AUTOUIC` files in the project will be generated.
+
+The name of the global ``autogen`` target can be changed by setting
+:variable:`CMAKE_GLOBAL_AUTOGEN_TARGET_NAME`.
+
+By default :variable:`CMAKE_GLOBAL_AUTOGEN_TARGET` is unset.
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
+
+Note
+^^^^
+
+``<ORIGIN>_autogen`` targets by default inherit their origin target's
+dependencies. This might result in unintended dependency target
+builds when only ``<ORIGIN>_autogen`` targets are built. A solution is to
+disable :prop_tgt:`AUTOGEN_ORIGIN_DEPENDS` on the respective origin targets.
diff --git a/Help/variable/CMAKE_GLOBAL_AUTOGEN_TARGET_NAME.rst b/Help/variable/CMAKE_GLOBAL_AUTOGEN_TARGET_NAME.rst
new file mode 100644
index 000000000..c86a5d0af
--- /dev/null
+++ b/Help/variable/CMAKE_GLOBAL_AUTOGEN_TARGET_NAME.rst
@@ -0,0 +1,13 @@
+CMAKE_GLOBAL_AUTOGEN_TARGET_NAME
+--------------------------------
+
+Change the name of the global ``autogen`` target.
+
+When :variable:`CMAKE_GLOBAL_AUTOGEN_TARGET` is enabled, a global custom target
+named ``autogen`` is created. :variable:`CMAKE_GLOBAL_AUTOGEN_TARGET_NAME`
+allows to set a different name for that target.
+
+By default :variable:`CMAKE_GLOBAL_AUTOGEN_TARGET_NAME` is unset.
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
diff --git a/Help/variable/CMAKE_GLOBAL_AUTORCC_TARGET.rst b/Help/variable/CMAKE_GLOBAL_AUTORCC_TARGET.rst
new file mode 100644
index 000000000..f92128cda
--- /dev/null
+++ b/Help/variable/CMAKE_GLOBAL_AUTORCC_TARGET.rst
@@ -0,0 +1,18 @@
+CMAKE_GLOBAL_AUTORCC_TARGET
+---------------------------
+
+Switch to enable generation of a global ``autorcc`` target.
+
+When :variable:`CMAKE_GLOBAL_AUTORCC_TARGET` is enabled, a custom target
+``autorcc`` is generated. This target depends on all :prop_tgt:`AUTORCC`
+generated ``<ORIGIN>_arcc_<QRC>`` targets in the project.
+By building the global ``autorcc`` target, all :prop_tgt:`AUTORCC`
+files in the project will be generated.
+
+The name of the global ``autorcc`` target can be changed by setting
+:variable:`CMAKE_GLOBAL_AUTORCC_TARGET_NAME`.
+
+By default :variable:`CMAKE_GLOBAL_AUTORCC_TARGET` is unset.
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
diff --git a/Help/variable/CMAKE_GLOBAL_AUTORCC_TARGET_NAME.rst b/Help/variable/CMAKE_GLOBAL_AUTORCC_TARGET_NAME.rst
new file mode 100644
index 000000000..c6e05de4e
--- /dev/null
+++ b/Help/variable/CMAKE_GLOBAL_AUTORCC_TARGET_NAME.rst
@@ -0,0 +1,13 @@
+CMAKE_GLOBAL_AUTORCC_TARGET_NAME
+--------------------------------
+
+Change the name of the global ``autorcc`` target.
+
+When :variable:`CMAKE_GLOBAL_AUTORCC_TARGET` is enabled, a global custom target
+named ``autorcc`` is created. :variable:`CMAKE_GLOBAL_AUTORCC_TARGET_NAME`
+allows to set a different name for that target.
+
+By default :variable:`CMAKE_GLOBAL_AUTOGEN_TARGET_NAME` is unset.
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
diff --git a/Help/variable/CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS.rst b/Help/variable/CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS.rst
new file mode 100644
index 000000000..f994fbe87
--- /dev/null
+++ b/Help/variable/CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS.rst
@@ -0,0 +1,29 @@
+CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS
+-------------------------------------------
+
+Default permissions for directories created implicitly during installation
+of files by :command:`install` and :command:`file(INSTALL)`.
+
+If ``make install`` is invoked and directories are implicitly created they
+get permissions set by :variable:`CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS`
+variable or platform specific default permissions if the variable is not set.
+
+Implicitly created directories are created if they are not explicitly installed
+by :command:`install` command but are needed to install a file on a certain
+path. Example of such locations are directories created due to the setting of
+:variable:`CMAKE_INSTALL_PREFIX`.
+
+Expected content of the :variable:`CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS`
+variable is a list of permissions that can be used by :command:`install` command
+`PERMISSIONS` section.
+
+Example usage:
+
+::
+
+ set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS
+ OWNER_READ
+ OWNER_WRITE
+ OWNER_EXECUTE
+ GROUP_READ
+ )
diff --git a/Help/variable/CMAKE_JOB_POOLS.rst b/Help/variable/CMAKE_JOB_POOLS.rst
new file mode 100644
index 000000000..72b50b490
--- /dev/null
+++ b/Help/variable/CMAKE_JOB_POOLS.rst
@@ -0,0 +1,6 @@
+CMAKE_JOB_POOLS
+---------------
+
+If the :prop_gbl:`JOB_POOLS` global property is not set, the value
+of this variable is used in its place. See :prop_gbl:`JOB_POOLS`
+for additional information.
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_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_LANG_FLAGS_CONFIG.rst b/Help/variable/CMAKE_LANG_FLAGS_CONFIG.rst
new file mode 100644
index 000000000..1dbd03640
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_FLAGS_CONFIG.rst
@@ -0,0 +1,4 @@
+CMAKE_<LANG>_FLAGS_<CONFIG>
+---------------------------
+
+Flags for language ``<LANG>`` when building for the ``<CONFIG>`` configuration.
diff --git a/Help/variable/CMAKE_LANG_FLAGS_CONFIG_INIT.rst b/Help/variable/CMAKE_LANG_FLAGS_CONFIG_INIT.rst
new file mode 100644
index 000000000..1eb5b3f61
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_FLAGS_CONFIG_INIT.rst
@@ -0,0 +1,10 @@
+CMAKE_<LANG>_FLAGS_<CONFIG>_INIT
+--------------------------------
+
+Value used to initialize the :variable:`CMAKE_<LANG>_FLAGS_<CONFIG>` cache
+entry the first time a build tree is configured for language ``<LANG>``.
+This variable is meant to be set by a :variable:`toolchain file
+<CMAKE_TOOLCHAIN_FILE>`. CMake may prepend or append content to
+the value based on the environment and target platform.
+
+See also :variable:`CMAKE_<LANG>_FLAGS_INIT`.
diff --git a/Help/variable/CMAKE_LANG_LINKER_WRAPPER_FLAG.rst b/Help/variable/CMAKE_LANG_LINKER_WRAPPER_FLAG.rst
new file mode 100644
index 000000000..df514075c
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_LINKER_WRAPPER_FLAG.rst
@@ -0,0 +1,39 @@
+CMAKE_<LANG>_LINKER_WRAPPER_FLAG
+--------------------------------
+
+Defines the syntax of compiler driver option to pass options to the linker
+tool. It will be used to translate the ``LINKER:`` prefix in the link options
+(see :command:`add_link_options` and :command:`target_link_options`).
+
+This variable holds a :ref:`semicolon-separated list <CMake Language Lists>` of tokens.
+If a space (i.e. " ") is specified as last token, flag and ``LINKER:``
+arguments will be specified as separate arguments to the compiler driver.
+The :variable:`CMAKE_<LANG>_LINKER_WRAPPER_FLAG_SEP` variable can be specified
+to manage concatenation of arguments.
+
+For example, for ``Clang`` we have:
+
+.. code-block:: cmake
+
+ set (CMAKE_C_LINKER_WRAPPER_FLAG "-Xlinker" " ")
+
+Specifying ``"LINKER:-z,defs"`` will be transformed in
+``-Xlinker -z -Xlinker defs``.
+
+For ``GNU GCC``:
+
+.. code-block:: cmake
+
+ set (CMAKE_C_LINKER_WRAPPER_FLAG "-Wl,")
+ set (CMAKE_C_LINKER_WRAPPER_FLAG_SEP ",")
+
+Specifying ``"LINKER:-z,defs"`` will be transformed in ``-Wl,-z,defs``.
+
+And for ``SunPro``:
+
+.. code-block:: cmake
+
+ set (CMAKE_C_LINKER_WRAPPER_FLAG "-Qoption" "ld" " ")
+ set (CMAKE_C_LINKER_WRAPPER_FLAG_SEP ",")
+
+Specifying ``"LINKER:-z,defs"`` will be transformed in ``-Qoption ld -z,defs``.
diff --git a/Help/variable/CMAKE_LANG_LINKER_WRAPPER_FLAG_SEP.rst b/Help/variable/CMAKE_LANG_LINKER_WRAPPER_FLAG_SEP.rst
new file mode 100644
index 000000000..faf14815c
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_LINKER_WRAPPER_FLAG_SEP.rst
@@ -0,0 +1,9 @@
+CMAKE_<LANG>_LINKER_WRAPPER_FLAG_SEP
+------------------------------------
+
+This variable is used with :variable:`CMAKE_<LANG>_LINKER_WRAPPER_FLAG`
+variable to format ``LINKER:`` prefix in the link options
+(see :command:`add_link_options` and :command:`target_link_options`).
+
+When specified, arguments of the ``LINKER:`` prefix will be concatenated using
+this value as separator.
diff --git a/Help/variable/CMAKE_LINK_DIRECTORIES_BEFORE.rst b/Help/variable/CMAKE_LINK_DIRECTORIES_BEFORE.rst
new file mode 100644
index 000000000..026ca35b3
--- /dev/null
+++ b/Help/variable/CMAKE_LINK_DIRECTORIES_BEFORE.rst
@@ -0,0 +1,9 @@
+CMAKE_LINK_DIRECTORIES_BEFORE
+-----------------------------
+
+Whether to append or prepend directories by default in
+:command:`link_directories`.
+
+This variable affects the default behavior of the :command:`link_directories`
+command. Setting this variable to ``ON`` is equivalent to using the ``BEFORE``
+option in all uses of that command.
diff --git a/Help/variable/CMAKE_MAXIMUM_RECURSION_DEPTH.rst b/Help/variable/CMAKE_MAXIMUM_RECURSION_DEPTH.rst
new file mode 100644
index 000000000..7110b1685
--- /dev/null
+++ b/Help/variable/CMAKE_MAXIMUM_RECURSION_DEPTH.rst
@@ -0,0 +1,33 @@
+CMAKE_MAXIMUM_RECURSION_DEPTH
+-----------------------------
+
+Maximum recursion depth for CMake scripts. It is intended to be set on the
+command line with ``-DCMAKE_MAXIMUM_RECURSION_DEPTH=<x>``, or within
+``CMakeLists.txt`` by projects that require a large recursion depth. Projects
+that set this variable should provide the user with a way to override it. For
+example:
+
+.. code-block:: cmake
+
+ # About to perform deeply recursive actions
+ if(NOT CMAKE_MAXIMUM_RECURSION_DEPTH)
+ set(CMAKE_MAXIMUM_RECURSION_DEPTH 2000)
+ endif()
+
+If it is not set, or is set to a non-integer value, a sensible default limit is
+used. If the recursion limit is reached, the script terminates immediately with
+a fatal error.
+
+Calling any of the following commands increases the recursion depth:
+
+* :command:`include`
+* :command:`find_package`
+* :command:`add_subdirectory`
+* :command:`try_compile`
+* :command:`ctest_read_custom_files`
+* :command:`ctest_run_script` (unless ``NEW_PROCESS`` is specified)
+* User-defined :command:`function`'s and :command:`macro`'s (note that
+ :command:`function` and :command:`macro` themselves don't increase recursion
+ depth)
+* Reading or writing variables that are being watched by a
+ :command:`variable_watch`
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_MSVC_RUNTIME_LIBRARY.rst b/Help/variable/CMAKE_MSVC_RUNTIME_LIBRARY.rst
new file mode 100644
index 000000000..8b54e7ecc
--- /dev/null
+++ b/Help/variable/CMAKE_MSVC_RUNTIME_LIBRARY.rst
@@ -0,0 +1,32 @@
+CMAKE_MSVC_RUNTIME_LIBRARY
+--------------------------
+
+Select the MSVC runtime library for use by compilers targeting the MSVC ABI.
+This variable is used to initialize the :prop_tgt:`MSVC_RUNTIME_LIBRARY`
+property on all targets as they are created. It is also propagated by
+calls to the :command:`try_compile` command into the test project.
+
+The allowed values are:
+
+.. include:: ../prop_tgt/MSVC_RUNTIME_LIBRARY-VALUES.txt
+
+Use :manual:`generator expressions <cmake-generator-expressions(7)>` to
+support per-configuration specification. For example, the code:
+
+.. code-block:: cmake
+
+ set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
+
+selects for all following targets a multi-threaded statically-linked runtime
+library with or without debug information depending on the configuration.
+
+If this variable is not set then the :prop_tgt:`MSVC_RUNTIME_LIBRARY` target
+property will not be set automatically. If that property is not set then
+CMake uses the default value ``MultiThreaded$<$<CONFIG:Debug>:Debug>DLL``
+to select a MSVC runtime library.
+
+.. note::
+
+ This variable has effect only when policy :policy:`CMP0091` is set to ``NEW``
+ prior to the first :command:`project` or :command:`enable_language` command
+ that enables a language using a compiler targeting the MSVC ABI.
diff --git a/Help/variable/CMAKE_NETRC.rst b/Help/variable/CMAKE_NETRC.rst
new file mode 100644
index 000000000..903ec31b6
--- /dev/null
+++ b/Help/variable/CMAKE_NETRC.rst
@@ -0,0 +1,9 @@
+CMAKE_NETRC
+-----------
+
+This variable is used to initialize the ``NETRC`` option for
+:command:`file(DOWNLOAD)` and :command:`file(UPLOAD)` commands and the
+module :module:`ExternalProject`. See those commands for additional
+information.
+
+The local option takes precedence over this variable.
diff --git a/Help/variable/CMAKE_NETRC_FILE.rst b/Help/variable/CMAKE_NETRC_FILE.rst
new file mode 100644
index 000000000..0f09afe86
--- /dev/null
+++ b/Help/variable/CMAKE_NETRC_FILE.rst
@@ -0,0 +1,9 @@
+CMAKE_NETRC_FILE
+----------------
+
+This variable is used to initialize the ``NETRC_FILE`` option for
+:command:`file(DOWNLOAD)` and :command:`file(UPLOAD)` commands and the
+module :module:`ExternalProject`. See those commands for additional
+information.
+
+The local option takes precedence over this variable.
diff --git a/Help/variable/CMAKE_PROJECT_HOMEPAGE_URL.rst b/Help/variable/CMAKE_PROJECT_HOMEPAGE_URL.rst
new file mode 100644
index 000000000..ee0bf7c19
--- /dev/null
+++ b/Help/variable/CMAKE_PROJECT_HOMEPAGE_URL.rst
@@ -0,0 +1,35 @@
+CMAKE_PROJECT_HOMEPAGE_URL
+--------------------------
+
+The homepage URL of the top level project.
+
+This variable holds the homepage URL of the project as specified in the top
+level CMakeLists.txt file by a :command:`project` command. In the event that
+the top level CMakeLists.txt contains multiple :command:`project` calls,
+the most recently called one from that top level CMakeLists.txt will determine
+the value that ``CMAKE_PROJECT_HOMEPAGE_URL`` contains. For example, consider
+the following top level CMakeLists.txt:
+
+.. code-block:: cmake
+
+ cmake_minimum_required(VERSION 3.0)
+ project(First HOMEPAGE_URL "http://first.example.com")
+ project(Second HOMEPAGE_URL "http://second.example.com")
+ add_subdirectory(sub)
+ project(Third HOMEPAGE_URL "http://third.example.com")
+
+And ``sub/CMakeLists.txt`` with the following contents:
+
+.. code-block:: cmake
+
+ project(SubProj HOMEPAGE_URL "http://subproj.example.com")
+ message("CMAKE_PROJECT_HOMEPAGE_URL = ${CMAKE_PROJECT_HOMEPAGE_URL}")
+
+The most recently seen :command:`project` command from the top level
+CMakeLists.txt would be ``project(Second ...)``, so this will print::
+
+ CMAKE_PROJECT_HOMEPAGE_URL = http://second.example.com
+
+To obtain the homepage URL from the most recent call to :command:`project` in
+the current directory scope or above, see the :variable:`PROJECT_HOMEPAGE_URL`
+variable.
diff --git a/Help/variable/CMAKE_PROJECT_INCLUDE.rst b/Help/variable/CMAKE_PROJECT_INCLUDE.rst
new file mode 100644
index 000000000..965c94ee7
--- /dev/null
+++ b/Help/variable/CMAKE_PROJECT_INCLUDE.rst
@@ -0,0 +1,9 @@
+CMAKE_PROJECT_INCLUDE
+---------------------
+
+A CMake language file or module to be included as the last step of all
+:command:`project` command calls. This is intended for injecting custom code
+into project builds without modifying their source.
+
+See also the :variable:`CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE` and
+:variable:`CMAKE_PROJECT_INCLUDE_BEFORE` variables.
diff --git a/Help/variable/CMAKE_PROJECT_INCLUDE_BEFORE.rst b/Help/variable/CMAKE_PROJECT_INCLUDE_BEFORE.rst
new file mode 100644
index 000000000..70b15e662
--- /dev/null
+++ b/Help/variable/CMAKE_PROJECT_INCLUDE_BEFORE.rst
@@ -0,0 +1,9 @@
+CMAKE_PROJECT_INCLUDE_BEFORE
+----------------------------
+
+A CMake language file or module to be included as the first step of all
+:command:`project` command calls. This is intended for injecting custom code
+into project builds without modifying their source.
+
+See also the :variable:`CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE` and
+:variable:`CMAKE_PROJECT_INCLUDE` variables.
diff --git a/Help/variable/CMAKE_PROJECT_VERSION.rst b/Help/variable/CMAKE_PROJECT_VERSION.rst
new file mode 100644
index 000000000..4f8f55605
--- /dev/null
+++ b/Help/variable/CMAKE_PROJECT_VERSION.rst
@@ -0,0 +1,35 @@
+CMAKE_PROJECT_VERSION
+---------------------
+
+The version of the top level project.
+
+This variable holds the version of the project as specified in the top
+level CMakeLists.txt file by a :command:`project` command. In the event that
+the top level CMakeLists.txt contains multiple :command:`project` calls,
+the most recently called one from that top level CMakeLists.txt will determine
+the value that ``CMAKE_PROJECT_VERSION`` contains. For example, consider
+the following top level CMakeLists.txt:
+
+.. code-block:: cmake
+
+ cmake_minimum_required(VERSION 3.0)
+ project(First VERSION 1.2.3)
+ project(Second VERSION 3.4.5)
+ add_subdirectory(sub)
+ project(Third VERSION 6.7.8)
+
+And ``sub/CMakeLists.txt`` with the following contents:
+
+.. code-block:: cmake
+
+ project(SubProj VERSION 1)
+ message("CMAKE_PROJECT_VERSION = ${CMAKE_PROJECT_VERSION}")
+
+The most recently seen :command:`project` command from the top level
+CMakeLists.txt would be ``project(Second ...)``, so this will print::
+
+ CMAKE_PROJECT_VERSION = 3.4.5
+
+To obtain the version from the most recent call to :command:`project` in
+the current directory scope or above, see the :variable:`PROJECT_VERSION`
+variable.
diff --git a/Help/variable/CMAKE_PROJECT_VERSION_MAJOR.rst b/Help/variable/CMAKE_PROJECT_VERSION_MAJOR.rst
new file mode 100644
index 000000000..f1001acaf
--- /dev/null
+++ b/Help/variable/CMAKE_PROJECT_VERSION_MAJOR.rst
@@ -0,0 +1,9 @@
+CMAKE_PROJECT_VERSION_MAJOR
+---------------------------
+
+The major version of the top level project.
+
+This variable holds the major version of the project as specified in the top
+level CMakeLists.txt file by a :command:`project` command. Please see
+:variable:`CMAKE_PROJECT_VERSION` documentation for the behavior when
+multiple :command:`project` commands are used in the sources.
diff --git a/Help/variable/CMAKE_PROJECT_VERSION_MINOR.rst b/Help/variable/CMAKE_PROJECT_VERSION_MINOR.rst
new file mode 100644
index 000000000..13202be98
--- /dev/null
+++ b/Help/variable/CMAKE_PROJECT_VERSION_MINOR.rst
@@ -0,0 +1,9 @@
+CMAKE_PROJECT_VERSION_MINOR
+---------------------------
+
+The minor version of the top level project.
+
+This variable holds the minor version of the project as specified in the top
+level CMakeLists.txt file by a :command:`project` command. Please see
+:variable:`CMAKE_PROJECT_VERSION` documentation for the behavior when
+multiple :command:`project` commands are used in the sources.
diff --git a/Help/variable/CMAKE_PROJECT_VERSION_PATCH.rst b/Help/variable/CMAKE_PROJECT_VERSION_PATCH.rst
new file mode 100644
index 000000000..b8570d9fe
--- /dev/null
+++ b/Help/variable/CMAKE_PROJECT_VERSION_PATCH.rst
@@ -0,0 +1,9 @@
+CMAKE_PROJECT_VERSION_PATCH
+---------------------------
+
+The patch version of the top level project.
+
+This variable holds the patch version of the project as specified in the top
+level CMakeLists.txt file by a :command:`project` command. Please see
+:variable:`CMAKE_PROJECT_VERSION` documentation for the behavior when
+multiple :command:`project` commands are used in the sources.
diff --git a/Help/variable/CMAKE_PROJECT_VERSION_TWEAK.rst b/Help/variable/CMAKE_PROJECT_VERSION_TWEAK.rst
new file mode 100644
index 000000000..e1ad4be33
--- /dev/null
+++ b/Help/variable/CMAKE_PROJECT_VERSION_TWEAK.rst
@@ -0,0 +1,9 @@
+CMAKE_PROJECT_VERSION_TWEAK
+---------------------------
+
+The tweak version of the top level project.
+
+This variable holds the tweak version of the project as specified in the top
+level CMakeLists.txt file by a :command:`project` command. Please see
+:variable:`CMAKE_PROJECT_VERSION` documentation for the behavior when
+multiple :command:`project` commands are used in the sources.
diff --git a/Help/variable/CMAKE_RULE_MESSAGES.rst b/Help/variable/CMAKE_RULE_MESSAGES.rst
new file mode 100644
index 000000000..7460a81ee
--- /dev/null
+++ b/Help/variable/CMAKE_RULE_MESSAGES.rst
@@ -0,0 +1,8 @@
+CMAKE_RULE_MESSAGES
+-------------------
+
+Specify whether to report a message for each make rule.
+
+If set in the cache it is used to initialize the value of the :prop_gbl:`RULE_MESSAGES` property.
+Users may disable the option in their local build tree to disable granular messages
+and report only as each target completes in Makefile builds.
diff --git a/Help/variable/CMAKE_SUPPRESS_REGENERATION.rst b/Help/variable/CMAKE_SUPPRESS_REGENERATION.rst
new file mode 100644
index 000000000..96184dd5e
--- /dev/null
+++ b/Help/variable/CMAKE_SUPPRESS_REGENERATION.rst
@@ -0,0 +1,11 @@
+CMAKE_SUPPRESS_REGENERATION
+---------------------------
+
+If ``CMAKE_SUPPRESS_REGENERATION`` is ``OFF``, which is default, then CMake
+adds a special target on which all other targets depend that checks the build
+system and optionally re-runs CMake to regenerate the build system when
+the target specification source changes.
+
+If this variable evaluates to ``ON`` at the end of the top-level
+``CMakeLists.txt`` file, CMake will not add the regeneration target to the
+build system or perform any build system checks.
diff --git a/Help/variable/CMAKE_Swift_MODULE_DIRECTORY.rst b/Help/variable/CMAKE_Swift_MODULE_DIRECTORY.rst
new file mode 100644
index 000000000..b11253bc1
--- /dev/null
+++ b/Help/variable/CMAKE_Swift_MODULE_DIRECTORY.rst
@@ -0,0 +1,8 @@
+CMAKE_Swift_MODULE_DIRECTORY
+----------------------------
+
+Swift module output directory.
+
+This variable is used to initialise the :prop_tgt:`Swift_MODULE_DIRECTORY`
+property on all the targets. See the target property for additional
+information.
diff --git a/Help/variable/CMAKE_Swift_NUM_THREADS.rst b/Help/variable/CMAKE_Swift_NUM_THREADS.rst
new file mode 100644
index 000000000..cb3367855
--- /dev/null
+++ b/Help/variable/CMAKE_Swift_NUM_THREADS.rst
@@ -0,0 +1,8 @@
+CMAKE_Swift_NUM_THREADS
+-----------------------
+
+Number of threads for parallel compilation for Swift targets.
+
+This variable controls the number of parallel jobs that the swift driver creates
+for building targets. If not specified, it will default to the number of
+logical CPUs on the host.
diff --git a/Help/variable/CMAKE_VS_GLOBALS.rst b/Help/variable/CMAKE_VS_GLOBALS.rst
new file mode 100644
index 000000000..83777b619
--- /dev/null
+++ b/Help/variable/CMAKE_VS_GLOBALS.rst
@@ -0,0 +1,21 @@
+CMAKE_VS_GLOBALS
+----------------
+
+List of ``Key=Value`` records to be set per target as target properties
+:prop_tgt:`VS_GLOBAL_<variable>` with ``variable=Key`` and value ``Value``.
+
+For example:
+
+.. code-block:: cmake
+
+ set(CMAKE_VS_GLOBALS
+ "DefaultLanguage=en-US"
+ "MinimumVisualStudioVersion=14.0"
+ )
+
+will set properties ``VS_GLOBAL_DefaultLanguage`` to ``en-US`` and
+``VS_GLOBAL_MinimumVisualStudioVersion`` to ``14.0`` for all targets
+(except for ``INTERFACE`` libraries).
+
+This variable is meant to be set by a
+:variable:`toolchain file <CMAKE_TOOLCHAIN_FILE>`.
diff --git a/Help/variable/CMAKE_VS_JUST_MY_CODE_DEBUGGING.rst b/Help/variable/CMAKE_VS_JUST_MY_CODE_DEBUGGING.rst
new file mode 100644
index 000000000..546cdf492
--- /dev/null
+++ b/Help/variable/CMAKE_VS_JUST_MY_CODE_DEBUGGING.rst
@@ -0,0 +1,8 @@
+CMAKE_VS_JUST_MY_CODE_DEBUGGING
+-------------------------------
+
+Enable Just My Code with Visual Studio debugger.
+
+This variable is used to initialize the :prop_tgt:`VS_JUST_MY_CODE_DEBUGGING`
+property on all targets when they are created. See that target property for
+additional information.
diff --git a/Help/variable/CMAKE_VS_PLATFORM_NAME_DEFAULT.rst b/Help/variable/CMAKE_VS_PLATFORM_NAME_DEFAULT.rst
new file mode 100644
index 000000000..c18e6fd37
--- /dev/null
+++ b/Help/variable/CMAKE_VS_PLATFORM_NAME_DEFAULT.rst
@@ -0,0 +1,9 @@
+CMAKE_VS_PLATFORM_NAME_DEFAULT
+------------------------------
+
+Default for the Visual Studio target platform name for the current generator
+without considering the value of the :variable:`CMAKE_GENERATOR_PLATFORM`
+variable. For :ref:`Visual Studio Generators` for VS 2017 and below this is
+always ``Win32``. For VS 2019 and above this is based on the host platform.
+
+See also the :variable:`CMAKE_VS_PLATFORM_NAME` variable.
diff --git a/Help/variable/CMAKE_VS_PLATFORM_TOOLSET_VERSION.rst b/Help/variable/CMAKE_VS_PLATFORM_TOOLSET_VERSION.rst
new file mode 100644
index 000000000..4d9b978f4
--- /dev/null
+++ b/Help/variable/CMAKE_VS_PLATFORM_TOOLSET_VERSION.rst
@@ -0,0 +1,11 @@
+CMAKE_VS_PLATFORM_TOOLSET_VERSION
+---------------------------------
+
+Visual Studio Platform Toolset version.
+
+The :ref:`Visual Studio Generators` for VS 2017 and above allow to
+select minor versions of the same toolset. The toolset version number
+may be specified by a field in :variable:`CMAKE_GENERATOR_TOOLSET` of
+the form ``version=14.11``. If none is specified CMake will choose a default
+toolset. The value may be empty if no minor version was selected and the
+default is used.
diff --git a/Help/variable/CMAKE_VS_SDK_EXCLUDE_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_EXCLUDE_DIRECTORIES.rst
new file mode 100644
index 000000000..36c4dccca
--- /dev/null
+++ b/Help/variable/CMAKE_VS_SDK_EXCLUDE_DIRECTORIES.rst
@@ -0,0 +1,4 @@
+CMAKE_VS_SDK_EXCLUDE_DIRECTORIES
+--------------------------------
+
+This variable allows to override Visual Studio default Exclude Directories.
diff --git a/Help/variable/CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES.rst
new file mode 100644
index 000000000..3ec755ba9
--- /dev/null
+++ b/Help/variable/CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES.rst
@@ -0,0 +1,4 @@
+CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES
+-----------------------------------
+
+This variable allows to override Visual Studio default Executable Directories.
diff --git a/Help/variable/CMAKE_VS_SDK_INCLUDE_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_INCLUDE_DIRECTORIES.rst
new file mode 100644
index 000000000..da10bdea9
--- /dev/null
+++ b/Help/variable/CMAKE_VS_SDK_INCLUDE_DIRECTORIES.rst
@@ -0,0 +1,4 @@
+CMAKE_VS_SDK_INCLUDE_DIRECTORIES
+--------------------------------
+
+This variable allows to override Visual Studio default Include Directories.
diff --git a/Help/variable/CMAKE_VS_SDK_LIBRARY_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_LIBRARY_DIRECTORIES.rst
new file mode 100644
index 000000000..b33754a47
--- /dev/null
+++ b/Help/variable/CMAKE_VS_SDK_LIBRARY_DIRECTORIES.rst
@@ -0,0 +1,4 @@
+CMAKE_VS_SDK_LIBRARY_DIRECTORIES
+--------------------------------
+
+This variable allows to override Visual Studio default Library Directories.
diff --git a/Help/variable/CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES.rst
new file mode 100644
index 000000000..b0222157b
--- /dev/null
+++ b/Help/variable/CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES.rst
@@ -0,0 +1,5 @@
+CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES
+--------------------------------------
+
+This variable allows to override Visual Studio default Library WinRT
+Directories.
diff --git a/Help/variable/CMAKE_VS_SDK_REFERENCE_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_REFERENCE_DIRECTORIES.rst
new file mode 100644
index 000000000..c03f0aed2
--- /dev/null
+++ b/Help/variable/CMAKE_VS_SDK_REFERENCE_DIRECTORIES.rst
@@ -0,0 +1,4 @@
+CMAKE_VS_SDK_REFERENCE_DIRECTORIES
+----------------------------------
+
+This variable allows to override Visual Studio default Reference Directories.
diff --git a/Help/variable/CMAKE_VS_SDK_SOURCE_DIRECTORIES.rst b/Help/variable/CMAKE_VS_SDK_SOURCE_DIRECTORIES.rst
new file mode 100644
index 000000000..0c73f064a
--- /dev/null
+++ b/Help/variable/CMAKE_VS_SDK_SOURCE_DIRECTORIES.rst
@@ -0,0 +1,4 @@
+CMAKE_VS_SDK_SOURCE_DIRECTORIES
+-------------------------------
+
+This variable allows to override Visual Studio default Source Directories.
diff --git a/Help/variable/CMAKE_VS_WINRT_BY_DEFAULT.rst b/Help/variable/CMAKE_VS_WINRT_BY_DEFAULT.rst
new file mode 100644
index 000000000..2ba8fe27e
--- /dev/null
+++ b/Help/variable/CMAKE_VS_WINRT_BY_DEFAULT.rst
@@ -0,0 +1,8 @@
+CMAKE_VS_WINRT_BY_DEFAULT
+-------------------------
+
+Tell :ref:`Visual Studio Generators` for VS 2010 and above that the
+target platform compiles as WinRT by default (compiles with ``/ZW``).
+
+This variable is meant to be set by a
+:variable:`toolchain file <CMAKE_TOOLCHAIN_FILE>` for such platforms.
diff --git a/Help/variable/CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY.rst b/Help/variable/CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY.rst
new file mode 100644
index 000000000..ea3e240b1
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY.rst
@@ -0,0 +1,9 @@
+CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY
+-------------------------------------------
+
+If enabled, the :generator:`Xcode` generator will generate only a
+single Xcode project file for the topmost :command:`project()` command
+instead of generating one for every ``project()`` command.
+
+This could be useful to speed up the CMake generation step for
+large projects and to work-around a bug in the ``ZERO_CHECK`` logic.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER.rst b/Help/variable/CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER.rst
new file mode 100644
index 000000000..b972ba573
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER
+------------------------------------
+
+Whether to enable ``Address Sanitizer`` in the Diagnostics
+section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_ADDRESS_SANITIZER`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN.rst b/Help/variable/CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN.rst
new file mode 100644
index 000000000..59eb32df3
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN
+-----------------------------------------------------
+
+Whether to enable ``Detect use of stack after return``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER.rst b/Help/variable/CMAKE_XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER.rst
new file mode 100644
index 000000000..71bcf4235
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER
+----------------------------------------------
+
+Whether to disable the ``Main Thread Checker``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_DISABLE_MAIN_THREAD_CHECKER`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS.rst b/Help/variable/CMAKE_XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS.rst
new file mode 100644
index 000000000..53f55e604
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS
+----------------------------------------
+
+Whether to enable ``Dynamic Library Loads``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_DYNAMIC_LIBRARY_LOADS`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE.rst b/Help/variable/CMAKE_XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE.rst
new file mode 100644
index 000000000..784ceb6b7
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE
+-------------------------------------------
+
+Whether to enable ``Dynamic Linker API usage``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_DYNAMIC_LINKER_API_USAGE`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_GUARD_MALLOC.rst b/Help/variable/CMAKE_XCODE_SCHEME_GUARD_MALLOC.rst
new file mode 100644
index 000000000..9350244b0
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_GUARD_MALLOC.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_GUARD_MALLOC
+-------------------------------
+
+Whether to enable ``Guard Malloc``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_GUARD_MALLOC`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP.rst b/Help/variable/CMAKE_XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP.rst
new file mode 100644
index 000000000..45a2dad69
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP.rst
@@ -0,0 +1,13 @@
+CMAKE_XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP
+-------------------------------------------
+
+Whether to enable the ``Main Thread Checker`` option
+``Pause on issues``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_MAIN_THREAD_CHECKER_STOP`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_MALLOC_GUARD_EDGES.rst b/Help/variable/CMAKE_XCODE_SCHEME_MALLOC_GUARD_EDGES.rst
new file mode 100644
index 000000000..94d1c61fb
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_MALLOC_GUARD_EDGES.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_MALLOC_GUARD_EDGES
+-------------------------------------
+
+Whether to enable ``Malloc Guard Edges``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_MALLOC_GUARD_EDGES`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_MALLOC_SCRIBBLE.rst b/Help/variable/CMAKE_XCODE_SCHEME_MALLOC_SCRIBBLE.rst
new file mode 100644
index 000000000..9bf0eb419
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_MALLOC_SCRIBBLE.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_MALLOC_SCRIBBLE
+----------------------------------
+
+Whether to enable ``Malloc Scribble``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_MALLOC_SCRIBBLE`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_MALLOC_STACK.rst b/Help/variable/CMAKE_XCODE_SCHEME_MALLOC_STACK.rst
new file mode 100644
index 000000000..4cc21ee2b
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_MALLOC_STACK.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_MALLOC_STACK
+-------------------------------
+
+Whether to enable ``Malloc Stack`` in the Diagnostics
+section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_MALLOC_STACK`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_THREAD_SANITIZER.rst b/Help/variable/CMAKE_XCODE_SCHEME_THREAD_SANITIZER.rst
new file mode 100644
index 000000000..6d1b56eea
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_THREAD_SANITIZER.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_THREAD_SANITIZER
+-----------------------------------
+
+Whether to enable ``Thread Sanitizer`` in the Diagnostics
+section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_THREAD_SANITIZER`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_THREAD_SANITIZER_STOP.rst b/Help/variable/CMAKE_XCODE_SCHEME_THREAD_SANITIZER_STOP.rst
new file mode 100644
index 000000000..de40478ea
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_THREAD_SANITIZER_STOP.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_THREAD_SANITIZER_STOP
+----------------------------------------
+
+Whether to enable ``Thread Sanitizer - Pause on issues``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_THREAD_SANITIZER_STOP`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER.rst b/Help/variable/CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER.rst
new file mode 100644
index 000000000..ec5df6613
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER
+------------------------------------------------
+
+Whether to enable ``Undefined Behavior Sanitizer``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP.rst b/Help/variable/CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP.rst
new file mode 100644
index 000000000..dcec9b0ea
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP.rst
@@ -0,0 +1,13 @@
+CMAKE_XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP
+-----------------------------------------------------
+
+Whether to enable ``Undefined Behavior Sanitizer`` option
+``Pause on issues``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_UNDEFINED_BEHAVIOUR_SANITIZER_STOP`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CMAKE_XCODE_SCHEME_ZOMBIE_OBJECTS.rst b/Help/variable/CMAKE_XCODE_SCHEME_ZOMBIE_OBJECTS.rst
new file mode 100644
index 000000000..82e9d76cc
--- /dev/null
+++ b/Help/variable/CMAKE_XCODE_SCHEME_ZOMBIE_OBJECTS.rst
@@ -0,0 +1,12 @@
+CMAKE_XCODE_SCHEME_ZOMBIE_OBJECTS
+---------------------------------
+
+Whether to enable ``Zombie Objects``
+in the Diagnostics section of the generated Xcode scheme.
+
+This variable initializes the
+:prop_tgt:`XCODE_SCHEME_ZOMBIE_OBJECTS`
+property on all targets.
+
+Please refer to the :prop_tgt:`XCODE_GENERATE_SCHEME` target property
+documentation to see all Xcode schema related properties.
diff --git a/Help/variable/CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS.rst b/Help/variable/CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS.rst
new file mode 100644
index 000000000..83d5ce7fc
--- /dev/null
+++ b/Help/variable/CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS.rst
@@ -0,0 +1,11 @@
+CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS
+-------------------------------------------
+
+Default permissions for implicitly created directories during packaging.
+
+This variable serves the same purpose during packaging as the
+:variable:`CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS` variable
+serves during installation (e.g. ``make install``).
+
+If `include(CPack)` is used then by default this variable is set to the content
+of :variable:`CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS`.
diff --git a/Help/variable/CTEST_CUSTOM_TESTS_IGNORE.rst b/Help/variable/CTEST_CUSTOM_TESTS_IGNORE.rst
new file mode 100644
index 000000000..57222ca1e
--- /dev/null
+++ b/Help/variable/CTEST_CUSTOM_TESTS_IGNORE.rst
@@ -0,0 +1,7 @@
+CTEST_CUSTOM_TESTS_IGNORE
+-------------------------
+
+A list of regular expressions to use to exclude tests during the
+:command:`ctest_test` command.
+
+.. include:: CTEST_CUSTOM_XXX.txt
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/CTEST_RUN_CURRENT_SCRIPT.rst b/Help/variable/CTEST_RUN_CURRENT_SCRIPT.rst
new file mode 100644
index 000000000..abc123c09
--- /dev/null
+++ b/Help/variable/CTEST_RUN_CURRENT_SCRIPT.rst
@@ -0,0 +1,5 @@
+CTEST_RUN_CURRENT_SCRIPT
+------------------------
+
+Setting this to 0 prevents :manual:`ctest(1)` from being run again when it
+reaches the end of a script run by calling ``ctest -S``.
diff --git a/Help/variable/CTEST_SUBMIT_URL.rst b/Help/variable/CTEST_SUBMIT_URL.rst
new file mode 100644
index 000000000..7d84da4b4
--- /dev/null
+++ b/Help/variable/CTEST_SUBMIT_URL.rst
@@ -0,0 +1,5 @@
+CTEST_SUBMIT_URL
+----------------
+
+Specify the CTest ``SubmitURL`` setting
+in a :manual:`ctest(1)` dashboard client script.
diff --git a/Help/variable/CTEST_UPDATE_VERSION_OVERRIDE.rst b/Help/variable/CTEST_UPDATE_VERSION_OVERRIDE.rst
new file mode 100644
index 000000000..39fbaba79
--- /dev/null
+++ b/Help/variable/CTEST_UPDATE_VERSION_OVERRIDE.rst
@@ -0,0 +1,5 @@
+CTEST_UPDATE_VERSION_OVERRIDE
+-----------------------------
+
+Specify the CTest :ref:`UpdateVersionOverride <UpdateVersionOverride>` setting
+in a :manual:`ctest(1)` dashboard client script.
diff --git a/Help/variable/IOS.rst b/Help/variable/IOS.rst
new file mode 100644
index 000000000..e5cc3f69c
--- /dev/null
+++ b/Help/variable/IOS.rst
@@ -0,0 +1,4 @@
+IOS
+---
+
+Set to ``1`` when the target system (:variable:`CMAKE_SYSTEM_NAME`) is ``iOS``.
diff --git a/Help/variable/MSVC_TOOLSET_VERSION.rst b/Help/variable/MSVC_TOOLSET_VERSION.rst
new file mode 100644
index 000000000..f4a33e246
--- /dev/null
+++ b/Help/variable/MSVC_TOOLSET_VERSION.rst
@@ -0,0 +1,22 @@
+MSVC_TOOLSET_VERSION
+--------------------
+
+The toolset version of Microsoft Visual C/C++ being used if any.
+If MSVC-like is being used, this variable is set based on the version
+of the compiler as given by the :variable:`MSVC_VERSION` variable.
+
+Known toolset version numbers are::
+
+ 80 = VS 2005 (8.0)
+ 90 = VS 2008 (9.0)
+ 100 = VS 2010 (10.0)
+ 110 = VS 2012 (11.0)
+ 120 = VS 2013 (12.0)
+ 140 = VS 2015 (14.0)
+ 141 = VS 2017 (15.0)
+ 142 = VS 2019 (16.0)
+
+Compiler versions newer than those known to CMake will be reported
+as the latest known toolset version.
+
+See also the :variable:`MSVC_VERSION` variable.
diff --git a/Help/variable/MSYS.rst b/Help/variable/MSYS.rst
new file mode 100644
index 000000000..25ddc7f73
--- /dev/null
+++ b/Help/variable/MSYS.rst
@@ -0,0 +1,4 @@
+MSYS
+----
+
+``True`` when using the :generator:`MSYS Makefiles` generator.
diff --git a/Help/variable/PROJECT-NAME_DESCRIPTION.rst b/Help/variable/PROJECT-NAME_DESCRIPTION.rst
new file mode 100644
index 000000000..2b88b1acf
--- /dev/null
+++ b/Help/variable/PROJECT-NAME_DESCRIPTION.rst
@@ -0,0 +1,5 @@
+<PROJECT-NAME>_DESCRIPTION
+--------------------------
+
+Value given to the ``DESCRIPTION`` option of the most recent call to the
+:command:`project` command with project name ``<PROJECT-NAME>``, if any.
diff --git a/Help/variable/PROJECT-NAME_HOMEPAGE_URL.rst b/Help/variable/PROJECT-NAME_HOMEPAGE_URL.rst
new file mode 100644
index 000000000..22cc304b0
--- /dev/null
+++ b/Help/variable/PROJECT-NAME_HOMEPAGE_URL.rst
@@ -0,0 +1,5 @@
+<PROJECT-NAME>_HOMEPAGE_URL
+---------------------------
+
+Value given to the ``HOMEPAGE_URL`` option of the most recent call to the
+:command:`project` command with project name ``<PROJECT-NAME>``, if any.
diff --git a/Help/variable/PROJECT_HOMEPAGE_URL.rst b/Help/variable/PROJECT_HOMEPAGE_URL.rst
new file mode 100644
index 000000000..754c9e8b3
--- /dev/null
+++ b/Help/variable/PROJECT_HOMEPAGE_URL.rst
@@ -0,0 +1,9 @@
+PROJECT_HOMEPAGE_URL
+--------------------
+
+The homepage URL of the project.
+
+This is the homepage URL given to the most recently called :command:`project`
+command in the current directory scope or above. To obtain the homepage URL
+of the top level project, see the :variable:`CMAKE_PROJECT_HOMEPAGE_URL`
+variable.
diff --git a/Help/variable/PackageName_ROOT.rst b/Help/variable/PackageName_ROOT.rst
new file mode 100644
index 000000000..1c2fd34f3
--- /dev/null
+++ b/Help/variable/PackageName_ROOT.rst
@@ -0,0 +1,14 @@
+<PackageName>_ROOT
+------------------
+
+Calls to :command:`find_package(<PackageName>)` will search in prefixes
+specified by the ``<PackageName>_ROOT`` CMake variable, where
+``<PackageName>`` is the name given to the :command:`find_package` call
+and ``_ROOT`` is literal. For example, ``find_package(Foo)`` will search
+prefixes specified in the ``Foo_ROOT`` CMake variable (if set).
+See policy :policy:`CMP0074`.
+
+This variable may hold a single prefix or a
+:ref:`semicolon-separated list <CMake Language Lists>` of multiple prefixes.
+
+See also the :envvar:`<PackageName>_ROOT` environment variable.
diff --git a/Modules/BasicConfigVersion-SameMinorVersion.cmake.in b/Modules/BasicConfigVersion-SameMinorVersion.cmake.in
new file mode 100644
index 000000000..e2030d230
--- /dev/null
+++ b/Modules/BasicConfigVersion-SameMinorVersion.cmake.in
@@ -0,0 +1,55 @@
+# This is a basic version file for the Config-mode of find_package().
+# It is used by write_basic_package_version_file() as input file for configure_file()
+# to create a version-file which can be installed along a config.cmake file.
+#
+# The created file sets PACKAGE_VERSION_EXACT if the current version string and
+# the requested version string are exactly the same and it sets
+# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version,
+# but only if the requested major and minor versions are the same as the current
+# one.
+# The variable CVF_VERSION must be set before calling configure_file().
+
+
+set(PACKAGE_VERSION "@CVF_VERSION@")
+
+if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
+else()
+
+ if("@CVF_VERSION@" MATCHES "^([0-9]+)\\.([0-9]+)")
+ set(CVF_VERSION_MAJOR "${CMAKE_MATCH_1}")
+ set(CVF_VERSION_MINOR "${CMAKE_MATCH_2}")
+ else()
+ set(CVF_VERSION_MAJOR "@CVF_VERSION@")
+ set(CVF_VERSION_MINOR "")
+ endif()
+
+ if((PACKAGE_FIND_VERSION_MAJOR STREQUAL CVF_VERSION_MAJOR) AND
+ (PACKAGE_FIND_VERSION_MINOR STREQUAL CVF_VERSION_MINOR))
+ set(PACKAGE_VERSION_COMPATIBLE TRUE)
+ else()
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
+ endif()
+
+ if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
+ set(PACKAGE_VERSION_EXACT TRUE)
+ endif()
+endif()
+
+
+# if the installed project requested no architecture check, don't perform the check
+if("@CVF_ARCH_INDEPENDENT@")
+ return()
+endif()
+
+# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it:
+if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "@CMAKE_SIZEOF_VOID_P@" STREQUAL "")
+ return()
+endif()
+
+# check that the installed version has the same 32/64bit-ness as the one which is currently searching:
+if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "@CMAKE_SIZEOF_VOID_P@")
+ math(EXPR installedBits "@CMAKE_SIZEOF_VOID_P@ * 8")
+ set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)")
+ set(PACKAGE_VERSION_UNSUITABLE TRUE)
+endif()
diff --git a/Modules/CMakeFindSublimeText2.cmake b/Modules/CMakeFindSublimeText2.cmake
new file mode 100644
index 000000000..7f67bf03d
--- /dev/null
+++ b/Modules/CMakeFindSublimeText2.cmake
@@ -0,0 +1,23 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+
+# This file is included in CMakeSystemSpecificInformation.cmake if
+# the Sublime Text 2 extra generator has been selected.
+
+find_program(CMAKE_SUBLIMETEXT_EXECUTABLE
+ NAMES subl3 subl sublime_text
+ PATHS
+ "/Applications/Sublime Text.app/Contents/SharedSupport/bin"
+ "/Applications/Sublime Text 3.app/Contents/SharedSupport/bin"
+ "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin"
+ "$ENV{HOME}/Applications/Sublime Text.app/Contents/SharedSupport/bin"
+ "$ENV{HOME}/Applications/Sublime Text 3.app/Contents/SharedSupport/bin"
+ "$ENV{HOME}/Applications/Sublime Text 2.app/Contents/SharedSupport/bin"
+ "/opt/sublime_text"
+ "/opt/sublime_text_3"
+ DOC "The Sublime Text executable")
+
+if(CMAKE_SUBLIMETEXT_EXECUTABLE)
+ set(CMAKE_OPEN_PROJECT_COMMAND "${CMAKE_SUBLIMETEXT_EXECUTABLE} --project <PROJECT_FILE>" )
+endif()
diff --git a/Modules/CMakeInitializeConfigs.cmake b/Modules/CMakeInitializeConfigs.cmake
new file mode 100644
index 000000000..9dfe04086
--- /dev/null
+++ b/Modules/CMakeInitializeConfigs.cmake
@@ -0,0 +1,39 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+include_guard(GLOBAL)
+
+# Initializes `<_PREFIX>_<CONFIG>` variables from the corresponding
+# `<_PREFIX>_<CONFIG>_INIT`, for the configurations currently used.
+function(cmake_initialize_per_config_variable _PREFIX _DOCSTRING)
+ string(STRIP "${${_PREFIX}_INIT}" _INIT)
+ set("${_PREFIX}" "${_INIT}"
+ CACHE STRING "${_DOCSTRING} during all build types.")
+ mark_as_advanced("${_PREFIX}")
+
+ if (NOT CMAKE_NOT_USING_CONFIG_FLAGS)
+ set(_CONFIGS Debug Release MinSizeRel RelWithDebInfo)
+
+ get_property(_GENERATOR_IS_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
+ if (_GENERATOR_IS_MULTI_CONFIG)
+ list(APPEND _CONFIGS ${CMAKE_CONFIGURATION_TYPES})
+ else()
+ if (NOT CMAKE_NO_BUILD_TYPE)
+ set(CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE_INIT}" CACHE STRING
+ "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel ...")
+ endif()
+ list(APPEND _CONFIGS ${CMAKE_BUILD_TYPE})
+ endif()
+
+ list(REMOVE_DUPLICATES _CONFIGS)
+ foreach(_BUILD_TYPE IN LISTS _CONFIGS)
+ if (NOT "${_BUILD_TYPE}" STREQUAL "")
+ string(TOUPPER "${_BUILD_TYPE}" _BUILD_TYPE)
+ string(STRIP "${${_PREFIX}_${_BUILD_TYPE}_INIT}" _INIT)
+ set("${_PREFIX}_${_BUILD_TYPE}" "${_INIT}"
+ CACHE STRING "${_DOCSTRING} during ${_BUILD_TYPE} builds.")
+ mark_as_advanced("${_PREFIX}_${_BUILD_TYPE}")
+ endif()
+ endforeach()
+ endif()
+endfunction()
diff --git a/Modules/CMakeParseImplicitIncludeInfo.cmake b/Modules/CMakeParseImplicitIncludeInfo.cmake
new file mode 100644
index 000000000..ff4c32561
--- /dev/null
+++ b/Modules/CMakeParseImplicitIncludeInfo.cmake
@@ -0,0 +1,247 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# This is used internally by CMake and should not be included by user code.
+
+# helper function that parses implicit include dirs from a single line
+# for compilers that report them that way. on success we return the
+# list of dirs in id_var and set state_var to the 'done' state.
+function(cmake_parse_implicit_include_line line lang id_var log_var state_var)
+ # clear variables we append to (avoids possible polution from parent scopes)
+ unset(rv)
+ set(log "")
+
+ # Cray compiler (from cray wrapper, via PrgEnv-cray)
+ if("${CMAKE_${lang}_COMPILER_ID}" STREQUAL "Cray" AND
+ "${line}" MATCHES "^/" AND "${line}" MATCHES "/ccfe |/ftnfe " AND
+ "${line}" MATCHES " -isystem| -I")
+ string(REGEX MATCHALL " (-I ?|-isystem )(\"[^\"]+\"|[^ \"]+)" incs "${line}")
+ foreach(inc IN LISTS incs)
+ string(REGEX REPLACE " (-I ?|-isystem )(\"[^\"]+\"|[^ \"]+)" "\\2" idir "${inc}")
+ list(APPEND rv "${idir}")
+ endforeach()
+ if(rv)
+ string(APPEND log " got implicit includes via cray ccfe parser!\n")
+ else()
+ string(APPEND log " warning: cray ccfe parse failed!\n")
+ endif()
+ endif()
+
+ # PGI compiler
+ if("${CMAKE_${lang}_COMPILER_ID}" STREQUAL "PGI")
+ # pgc++ verbose output differs
+ if(("${lang}" STREQUAL "C" OR "${lang}" STREQUAL "Fortran") AND
+ "${line}" MATCHES "^/" AND
+ "${line}" MATCHES "/pgc |/pgf901 |/pgftnc " AND
+ "${line}" MATCHES " -cmdline ")
+ # cmdline has unparsed cmdline, remove it
+ string(REGEX REPLACE "-cmdline .*" "" line "${line}")
+ if("${line}" MATCHES " -nostdinc ")
+ set(rv "") # defined, but empty
+ else()
+ string(REGEX MATCHALL " -stdinc ([^ ]*)" incs "${line}")
+ foreach(inc IN LISTS incs)
+ string(REGEX REPLACE " -stdinc ([^ ]*)" "\\1" idir "${inc}")
+ string(REPLACE ":" ";" idir "${idir}")
+ list(APPEND rv ${idir})
+ endforeach()
+ endif()
+ if(DEFINED rv)
+ string(APPEND log " got implicit includes via PGI C/F parser!\n")
+ else()
+ string(APPEND log " warning: PGI C/F parse failed!\n")
+ endif()
+ elseif("${lang}" STREQUAL "CXX" AND "${line}" MATCHES "^/" AND
+ "${line}" MATCHES "/pggpp1 " AND "${line}" MATCHES " -I")
+ # oddly, -Mnostdinc does not get rid of system -I's, at least in
+ # PGI 18.10.1 ...
+ string(REGEX MATCHALL " (-I ?)([^ ]*)" incs "${line}")
+ foreach(inc IN LISTS incs)
+ string(REGEX REPLACE " (-I ?)([^ ]*)" "\\2" idir "${inc}")
+ if(NOT "${idir}" STREQUAL "-") # filter out "-I-"
+ list(APPEND rv "${idir}")
+ endif()
+ endforeach()
+ if(DEFINED rv)
+ string(APPEND log " got implicit includes via PGI CXX parser!\n")
+ else()
+ string(APPEND log " warning: PGI CXX parse failed!\n")
+ endif()
+ endif()
+ endif()
+
+ # SunPro compiler
+ if("${CMAKE_${lang}_COMPILER_ID}" STREQUAL "SunPro" AND
+ ("${line}" MATCHES "-D__SUNPRO_C" OR "${line}" MATCHES "-D__SUNPRO_F") )
+ string(REGEX MATCHALL " (-I ?)([^ ]*)" incs "${line}")
+ foreach(inc IN LISTS incs)
+ string(REGEX REPLACE " (-I ?)([^ ]*)" "\\2" idir "${inc}")
+ if(NOT "${idir}" STREQUAL "-xbuiltin")
+ list(APPEND rv "${idir}")
+ endif()
+ endforeach()
+ if(rv)
+ if ("${lang}" STREQUAL "C" OR "${lang}" STREQUAL "CXX")
+ # /usr/include appears to be hardwired in
+ list(APPEND rv "/usr/include")
+ endif()
+ string(APPEND log " got implicit includes via sunpro parser!\n")
+ else()
+ string(APPEND log " warning: sunpro parse failed!\n")
+ endif()
+ endif()
+
+ # XL compiler
+ if(("${CMAKE_${lang}_COMPILER_ID}" STREQUAL "XL"
+ OR "${CMAKE_${lang}_COMPILER_ID}" STREQUAL "XLClang")
+ AND "${line}" MATCHES "^/"
+ AND ( ("${lang}" STREQUAL "Fortran" AND
+ "${line}" MATCHES "/xl[fF]entry " AND
+ "${line}" MATCHES "OSVAR\\([^ ]+\\)")
+ OR
+ ( ("${lang}" STREQUAL "C" OR "${lang}" STREQUAL "CXX") AND
+ "${line}" MATCHES "/xl[cC]2?entry " AND
+ "${line}" MATCHES " -qosvar=")
+ ) )
+ # -qnostdinc cancels other stdinc flags, even if present
+ string(FIND "${line}" " -qnostdinc" nostd)
+ if(NOT ${nostd} EQUAL -1)
+ set(rv "") # defined but empty
+ string(APPEND log " got implicit includes via XL parser (nostdinc)\n")
+ else()
+ if("${lang}" STREQUAL "CXX")
+ string(REGEX MATCHALL " -qcpp_stdinc=([^ ]*)" std "${line}")
+ string(REGEX MATCHALL " -qgcc_cpp_stdinc=([^ ]*)" gcc_std "${line}")
+ else()
+ string(REGEX MATCHALL " -qc_stdinc=([^ ]*)" std "${line}")
+ string(REGEX MATCHALL " -qgcc_c_stdinc=([^ ]*)" gcc_std "${line}")
+ endif()
+ set(xlstd ${std} ${gcc_std})
+ foreach(inc IN LISTS xlstd)
+ string(REGEX REPLACE " -q(cpp|gcc_cpp|c|gcc_c)_stdinc=([^ ]*)" "\\2"
+ ipath "${inc}")
+ string(REPLACE ":" ";" ipath "${ipath}")
+ list(APPEND rv ${ipath})
+ endforeach()
+ endif()
+ # user can add -I flags via CMAKE_{C,CXX}_FLAGS, look for that too
+ string(REGEX MATCHALL " (-I ?)([^ ]*)" incs "${line}")
+ unset(urv)
+ foreach(inc IN LISTS incs)
+ string(REGEX REPLACE " (-I ?)([^ ]*)" "\\2" idir "${inc}")
+ list(APPEND urv "${idir}")
+ endforeach()
+ if(urv)
+ if ("${rv}" STREQUAL "")
+ set(rv ${urv})
+ else()
+ list(APPEND rv ${urv})
+ endif()
+ endif()
+
+ if(DEFINED rv)
+ string(APPEND log " got implicit includes via XL parser!\n")
+ else()
+ string(APPEND log " warning: XL parse failed!\n")
+ endif()
+ endif()
+
+ if(log)
+ set(${log_var} "${log}" PARENT_SCOPE)
+ else()
+ unset(${log_var} PARENT_SCOPE)
+ endif()
+ if(DEFINED rv)
+ set(${id_var} "${rv}" PARENT_SCOPE)
+ set(${state_var} "done" PARENT_SCOPE)
+ endif()
+endfunction()
+
+# top-level function to parse implicit include directory information
+# from verbose compiler output. sets state_var in parent to 'done' on success.
+function(cmake_parse_implicit_include_info text lang dir_var log_var state_var)
+ set(state start) # values: start, loading, done
+
+ # clear variables we append to (avoids possible polution from parent scopes)
+ set(implicit_dirs_tmp)
+ set(log "")
+
+ # go through each line of output...
+ string(REGEX REPLACE "\r*\n" ";" output_lines "${text}")
+ foreach(line IN LISTS output_lines)
+ if(state STREQUAL start)
+ string(FIND "${line}" "#include \"...\" search starts here:" rv)
+ if(rv GREATER -1)
+ set(state loading)
+ set(preload 1) # looking for include <...> now
+ string(APPEND log " found start of include info\n")
+ else()
+ cmake_parse_implicit_include_line("${line}" "${lang}" implicit_dirs_tmp
+ linelog state)
+ if(linelog)
+ string(APPEND log ${linelog})
+ endif()
+ if(state STREQUAL done)
+ break()
+ endif()
+ endif()
+ elseif(state STREQUAL loading)
+ string(FIND "${line}" "End of search list." rv)
+ if(rv GREATER -1)
+ set(state done)
+ string(APPEND log " end of search list found\n")
+ break()
+ endif()
+ if(preload)
+ string(FIND "${line}" "#include <...> search starts here:" rv)
+ if(rv GREATER -1)
+ set(preload 0)
+ string(APPEND log " found start of implicit include info\n")
+ endif()
+ continue()
+ endif()
+ if("${line}" MATCHES "^ ")
+ string(SUBSTRING "${line}" 1 -1 line) # remove leading space
+ endif()
+ if ("${line}" MATCHES " \\(framework directory\\)$")
+ continue() # frameworks are handled elsewhere, ignore them here
+ endif()
+ string(REPLACE "\\" "/" path "${line}")
+ list(APPEND implicit_dirs_tmp "${path}")
+ string(APPEND log " add: [${path}]\n")
+ endif()
+ endforeach()
+
+ set(implicit_dirs "")
+ foreach(d IN LISTS implicit_dirs_tmp)
+ if(IS_ABSOLUTE "${d}")
+ get_filename_component(dir "${d}" ABSOLUTE)
+ list(APPEND implicit_dirs "${dir}")
+ string(APPEND log " collapse include dir [${d}] ==> [${dir}]\n")
+ elseif("${d}" MATCHES [[^\.\.[\/]\.\.[\/](.*)$]])
+ # This relative path is deep enough to get out of the CMakeFiles/CMakeTmp
+ # directory where the ABI check is done. Assume that the compiler has
+ # computed this path adaptively based on the current working directory
+ # such that the effective result is absolute.
+ get_filename_component(dir "${CMAKE_BINARY_DIR}/${CMAKE_MATCH_1}" ABSOLUTE)
+ list(APPEND implicit_dirs "${dir}")
+ string(APPEND log " collapse relative include dir [${d}] ==> [${dir}]\n")
+ else()
+ string(APPEND log " skipping relative include dir [${d}]\n")
+ endif()
+ endforeach()
+ list(REMOVE_DUPLICATES implicit_dirs)
+
+ # Log results.
+ if(state STREQUAL done)
+ string(APPEND log " implicit include dirs: [${implicit_dirs}]\n")
+ else()
+ string(APPEND log " warn: unable to parse implicit include dirs!\n")
+ endif()
+
+ # Return results.
+ set(${dir_var} "${implicit_dirs}" PARENT_SCOPE)
+ set(${log_var} "${log}" PARENT_SCOPE)
+ set(${state_var} "${state}" PARENT_SCOPE)
+
+endfunction()
diff --git a/Modules/CPack.NuGet.nuspec.in b/Modules/CPack.NuGet.nuspec.in
new file mode 100644
index 000000000..b7beb5de0
--- /dev/null
+++ b/Modules/CPack.NuGet.nuspec.in
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
+ <metadata>
+ <!-- Required elements-->
+ <id>@CPACK_NUGET_PACKAGE_NAME@</id>
+ <version>@CPACK_NUGET_PACKAGE_VERSION@</version>
+ <description>@CPACK_NUGET_PACKAGE_DESCRIPTION@</description>
+ <authors>@CPACK_NUGET_PACKAGE_AUTHORS@</authors>
+
+ <!-- Optional elements -->
+ @_CPACK_NUGET_TITLE_TAG@
+ @_CPACK_NUGET_OWNERS_TAG@
+ @_CPACK_NUGET_PROJECTURL_TAG@
+ @_CPACK_NUGET_LICENSEURL_TAG@
+ @_CPACK_NUGET_ICONURL_TAG@
+ @_CPACK_NUGET_REQUIRELICENSEACCEPTANCE_TAG@
+ @_CPACK_NUGET_SUMMARY_TAG@
+ @_CPACK_NUGET_RELEASENOTES_TAG@
+ @_CPACK_NUGET_COPYRIGHT_TAG@
+ @_CPACK_NUGET_TAGS_TAG@
+ @_CPACK_NUGET_DEPENDENCIES_TAG@
+ </metadata>
+ @_CPACK_NUGET_FILES_TAG@
+</package>
diff --git a/Modules/CheckFortranSourceRuns.cmake b/Modules/CheckFortranSourceRuns.cmake
new file mode 100644
index 000000000..a80c13d00
--- /dev/null
+++ b/Modules/CheckFortranSourceRuns.cmake
@@ -0,0 +1,175 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+CheckFortranSourceRuns
+----------------------
+
+Check if given Fortran source compiles and links into an executable and can
+subsequently be run.
+
+.. command:: check_fortran_source_runs
+
+ .. code-block:: cmake
+
+ check_fortran_source_runs(<code> <resultVar>
+ [SRC_EXT <extension>])
+
+ Check that the source supplied in ``<code>`` can be compiled as a Fortran source
+ file, linked as an executable and then run. The ``<code>`` must be a Fortran program
+ containing at least an ``end`` statement--for example:
+
+ .. code-block:: cmake
+
+ check_fortran_source_runs("real :: x[*]; call co_sum(x); end" F2018coarrayOK)
+
+ This command can help avoid costly build processes when a compiler lacks support
+ for a necessary feature, or a particular vendor library is not compatible with
+ the Fortran compiler version being used. Some of these failures only occur at runtime
+ instead of linktime, and a trivial runtime example can catch the issue before the
+ main build process.
+
+ 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).
+
+ By default, the test source file will be given a ``.F90`` file extension. The
+ ``SRC_EXT`` option can be used to override this with ``.<extension>`` instead.
+
+ 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_fortran_source_runs()``:
+
+ ``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_run()``, i.e. the contents of the :prop_dir:`INCLUDE_DIRECTORIES`
+ directory property will be ignored.
+
+ ``CMAKE_REQUIRED_LINK_OPTIONS``
+ A :ref:`;-list <CMake Language Lists>` of options to add to the link
+ command (see :command:`try_run` for further details).
+
+ ``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.
+
+#]=======================================================================]
+
+include_guard(GLOBAL)
+
+macro(CHECK_Fortran_SOURCE_RUNS SOURCE VAR)
+ if(NOT DEFINED "${VAR}")
+ set(_SRC_EXT)
+ set(_key)
+ foreach(arg ${ARGN})
+ if("${arg}" MATCHES "^(SRC_EXT)$")
+ set(_key "${arg}")
+ elseif(_key)
+ list(APPEND _${_key} "${arg}")
+ else()
+ message(FATAL_ERROR "Unknown argument:\n ${arg}\n")
+ endif()
+ endforeach()
+ if(NOT _SRC_EXT)
+ set(_SRC_EXT F90)
+ endif()
+ set(MACRO_CHECK_FUNCTION_DEFINITIONS
+ "-D${VAR} ${CMAKE_REQUIRED_FLAGS}")
+ if(CMAKE_REQUIRED_LINK_OPTIONS)
+ set(CHECK_Fortran_SOURCE_COMPILES_ADD_LINK_OPTIONS
+ LINK_OPTIONS ${CMAKE_REQUIRED_LINK_OPTIONS})
+ else()
+ set(CHECK_Fortran_SOURCE_COMPILES_ADD_LINK_OPTIONS)
+ endif()
+ if(CMAKE_REQUIRED_LIBRARIES)
+ set(CHECK_Fortran_SOURCE_COMPILES_ADD_LIBRARIES
+ LINK_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES})
+ else()
+ set(CHECK_Fortran_SOURCE_COMPILES_ADD_LIBRARIES)
+ endif()
+ if(CMAKE_REQUIRED_INCLUDES)
+ set(CHECK_Fortran_SOURCE_COMPILES_ADD_INCLUDES
+ "-DINCLUDE_DIRECTORIES:STRING=${CMAKE_REQUIRED_INCLUDES}")
+ else()
+ set(CHECK_Fortran_SOURCE_COMPILES_ADD_INCLUDES)
+ endif()
+ file(WRITE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.${_SRC_EXT}"
+ "${SOURCE}\n")
+
+ if(NOT CMAKE_REQUIRED_QUIET)
+ message(STATUS "Performing Test ${VAR}")
+ endif()
+ try_run(${VAR}_EXITCODE ${VAR}_COMPILED
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/src.${_SRC_EXT}
+ COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS}
+ ${CHECK_Fortran_SOURCE_COMPILES_ADD_LINK_OPTIONS}
+ ${CHECK_Fortran_SOURCE_COMPILES_ADD_LIBRARIES}
+ CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${MACRO_CHECK_FUNCTION_DEFINITIONS}
+ -DCMAKE_SKIP_RPATH:BOOL=${CMAKE_SKIP_RPATH}
+ "${CHECK_Fortran_SOURCE_COMPILES_ADD_INCLUDES}"
+ COMPILE_OUTPUT_VARIABLE OUTPUT
+ RUN_OUTPUT_VARIABLE RUN_OUTPUT)
+
+ # if it did not compile make the return value fail code of 1
+ if(NOT ${VAR}_COMPILED)
+ set(${VAR}_EXITCODE 1)
+ endif()
+ # if the return value was 0 then it worked
+ if("${${VAR}_EXITCODE}" EQUAL 0)
+ set(${VAR} 1 CACHE INTERNAL "Test ${VAR}")
+ if(NOT CMAKE_REQUIRED_QUIET)
+ message(STATUS "Performing Test ${VAR} - Success")
+ endif()
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+ "Performing Fortran SOURCE FILE Test ${VAR} succeeded with the following output:\n"
+ "${OUTPUT}\n"
+ "...and run output:\n"
+ "${RUN_OUTPUT}\n"
+ "Return value: ${${VAR}}\n"
+ "Source file was:\n${SOURCE}\n")
+ else()
+ if(CMAKE_CROSSCOMPILING AND "${${VAR}_EXITCODE}" MATCHES "FAILED_TO_RUN")
+ set(${VAR} "${${VAR}_EXITCODE}")
+ else()
+ set(${VAR} "" CACHE INTERNAL "Test ${VAR}")
+ endif()
+
+ if(NOT CMAKE_REQUIRED_QUIET)
+ message(STATUS "Performing Test ${VAR} - Failed")
+ endif()
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+ "Performing Fortran SOURCE FILE Test ${VAR} failed with the following output:\n"
+ "${OUTPUT}\n"
+ "...and run output:\n"
+ "${RUN_OUTPUT}\n"
+ "Return value: ${${VAR}_EXITCODE}\n"
+ "Source file was:\n${SOURCE}\n")
+ endif()
+ endif()
+endmacro()
diff --git a/Modules/CheckPIESupported.cmake b/Modules/CheckPIESupported.cmake
new file mode 100644
index 000000000..6d63f0bad
--- /dev/null
+++ b/Modules/CheckPIESupported.cmake
@@ -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.
+
+#[=======================================================================[.rst:
+CheckPIESupported
+-----------------
+
+Check whether the linker supports Position Independent Code (PIE) or No
+Position Independent Code (NO_PIE) for executables.
+Use this to ensure that the :prop_tgt:`POSITION_INDEPENDENT_CODE` target
+property for executables will be honored at link time.
+
+.. command:: check_pie_supported
+
+ ::
+
+ check_pie_supported([OUTPUT_VARIABLE <output>]
+ [LANGUAGES <lang>...])
+
+ Options are:
+
+ ``OUTPUT_VARIABLE <output>``
+ Set ``<output>`` variable with details about any error.
+ ``LANGUAGES <lang>...``
+ Check the linkers used for each of the specified languages.
+ Supported languages are ``C``, ``CXX``, and ``Fortran``.
+
+It makes no sense to use this module when :policy:`CMP0083` is set to ``OLD``,
+so the command will return an error in this case. See policy :policy:`CMP0083`
+for details.
+
+Variables
+^^^^^^^^^
+
+For each language checked, two boolean cache variables are defined.
+
+ ``CMAKE_<lang>_LINK_PIE_SUPPORTED``
+ Set to ``YES`` if ``PIE`` is supported by the linker and ``NO`` otherwise.
+ ``CMAKE_<lang>_LINK_NO_PIE_SUPPORTED``
+ Set to ``YES`` if ``NO_PIE`` is supported by the linker and ``NO`` otherwise.
+
+Examples
+^^^^^^^^
+
+.. code-block:: cmake
+
+ check_pie_supported()
+ set_property(TARGET foo PROPERTY POSITION_INDEPENDENT_CODE TRUE)
+
+.. code-block:: cmake
+
+ # Retrieve any error message.
+ check_pie_supported(OUTPUT_VARIABLE output LANGUAGES C)
+ set_property(TARGET foo PROPERTY POSITION_INDEPENDENT_CODE TRUE)
+ if(NOT CMAKE_C_LINK_PIE_SUPPORTED)
+ message(WARNING "PIE is not supported at link time: ${output}.\n"
+ "PIE link options will not be passed to linker.")
+ endif()
+
+#]=======================================================================]
+
+
+include (Internal/CMakeCheckCompilerFlag)
+
+function (check_pie_supported)
+ cmake_policy(GET CMP0083 cmp0083)
+
+ if (NOT cmp0083)
+ message(FATAL_ERROR "check_pie_supported: Policy CMP0083 is not set")
+ endif()
+
+ if(cmp0083 STREQUAL "OLD")
+ message(FATAL_ERROR "check_pie_supported: Policy CMP0083 set to OLD")
+ endif()
+
+ set(optional)
+ set(one OUTPUT_VARIABLE)
+ set(multiple LANGUAGES)
+
+ cmake_parse_arguments(CHECK_PIE "${optional}" "${one}" "${multiple}" "${ARGN}")
+ if(CHECK_PIE_UNPARSED_ARGUMENTS)
+ message(FATAL_ERROR "check_pie_supported: Unparsed arguments: ${CHECK_PIE_UNPARSED_ARGUMENTS}")
+ endif()
+
+ if (CHECK_PIE_LANGUAGES)
+ set (unsupported_languages "${CHECK_PIE_LANGUAGES}")
+ list (REMOVE_ITEM unsupported_languages "C" "CXX" "Fortran")
+ if(unsupported_languages)
+ message(FATAL_ERROR "check_pie_supported: language(s) '${unsupported_languages}' not supported")
+ endif()
+ else()
+ # User did not set any languages, use defaults
+ get_property (enabled_languages GLOBAL PROPERTY ENABLED_LANGUAGES)
+ if (NOT enabled_languages)
+ return()
+ endif()
+
+ list (FILTER enabled_languages INCLUDE REGEX "^(C|CXX|Fortran)$")
+ if (NOT enabled_languages)
+ return()
+ endif()
+
+ set (CHECK_PIE_LANGUAGES ${enabled_languages})
+ endif()
+
+ set (outputs)
+
+ foreach(lang IN LISTS CHECK_PIE_LANGUAGES)
+ if(_CMAKE_${lang}_PIE_MAY_BE_SUPPORTED_BY_LINKER)
+ cmake_check_compiler_flag(${lang} "${CMAKE_${lang}_LINK_OPTIONS_PIE}"
+ CMAKE_${lang}_LINK_PIE_SUPPORTED
+ OUTPUT_VARIABLE output)
+ if (NOT CMAKE_${lang}_LINK_PIE_SUPPORTED)
+ string (APPEND outputs "PIE (${lang}): ${output}\n")
+ endif()
+
+ cmake_check_compiler_flag(${lang} "${CMAKE_${lang}_LINK_OPTIONS_NO_PIE}"
+ CMAKE_${lang}_LINK_NO_PIE_SUPPORTED
+ OUTPUT_VARIABLE output)
+ if (NOT CMAKE_${lang}_LINK_NO_PIE_SUPPORTED)
+ string (APPEND outputs "NO_PIE (${lang}): ${output}\n")
+ endif()
+ else()
+ # no support at link time. Set cache variables to NO
+ set(CMAKE_${lang}_LINK_PIE_SUPPORTED NO CACHE INTERNAL "PIE (${lang})")
+ set(CMAKE_${lang}_LINK_NO_PIE_SUPPORTED NO CACHE INTERNAL "NO_PIE (${lang})")
+ string (APPEND outputs "PIE and NO_PIE are not supported by linker for ${lang}")
+ endif()
+ endforeach()
+
+ if (CHECK_PIE_OUTPUT_VARIABLE)
+ set (${CHECK_PIE_OUTPUT_VARIABLE} "${outputs}" PARENT_SCOPE)
+ endif()
+endfunction()
diff --git a/Modules/Compiler/ARMClang-ASM.cmake b/Modules/Compiler/ARMClang-ASM.cmake
new file mode 100644
index 000000000..ceff3e8ce
--- /dev/null
+++ b/Modules/Compiler/ARMClang-ASM.cmake
@@ -0,0 +1,9 @@
+include(Compiler/ARMClang)
+
+set(CMAKE_ASM_OUTPUT_EXTENSION ".o")
+set(CMAKE_ASM_OUTPUT_EXTENSION_REPLACE 1)
+
+set(CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> <INCLUDES> <FLAGS> -c -o <OBJECT> <SOURCE>")
+set(CMAKE_ASM_SOURCE_FILE_EXTENSIONS S;s;asm;msa)
+
+__compiler_armclang(ASM)
diff --git a/Modules/Compiler/ARMClang-C-FeatureTests.cmake b/Modules/Compiler/ARMClang-C-FeatureTests.cmake
new file mode 100644
index 000000000..ef79229d0
--- /dev/null
+++ b/Modules/Compiler/ARMClang-C-FeatureTests.cmake
@@ -0,0 +1 @@
+include(Compiler/Clang-C-FeatureTests)
diff --git a/Modules/Compiler/ARMClang-C.cmake b/Modules/Compiler/ARMClang-C.cmake
new file mode 100644
index 000000000..0a64a8a4f
--- /dev/null
+++ b/Modules/Compiler/ARMClang-C.cmake
@@ -0,0 +1,15 @@
+include(Compiler/Clang-C)
+include(Compiler/ARMClang)
+__compiler_armclang(C)
+
+set(CMAKE_C90_STANDARD_COMPILE_OPTION "-std=c90")
+set(CMAKE_C90_EXTENSION_COMPILE_OPTION "-std=gnu90")
+set(CMAKE_C90_STANDARD__HAS_FULL_SUPPORT ON)
+
+set(CMAKE_C99_STANDARD_COMPILE_OPTION "-std=c99")
+set(CMAKE_C99_EXTENSION_COMPILE_OPTION "-std=gnu99")
+set(CMAKE_C99_STANDARD__HAS_FULL_SUPPORT ON)
+
+set(CMAKE_C11_STANDARD_COMPILE_OPTION "-std=c11")
+set(CMAKE_C11_EXTENSION_COMPILE_OPTION "-std=gnu11")
+set(CMAKE_C11_STANDARD__HAS_FULL_SUPPORT ON)
diff --git a/Modules/Compiler/ARMClang-CXX-FeatureTests.cmake b/Modules/Compiler/ARMClang-CXX-FeatureTests.cmake
new file mode 100644
index 000000000..e038e807b
--- /dev/null
+++ b/Modules/Compiler/ARMClang-CXX-FeatureTests.cmake
@@ -0,0 +1 @@
+include(Compiler/Clang-CXX-FeatureTests)
diff --git a/Modules/Compiler/ARMClang-CXX.cmake b/Modules/Compiler/ARMClang-CXX.cmake
new file mode 100644
index 000000000..5dfb4011e
--- /dev/null
+++ b/Modules/Compiler/ARMClang-CXX.cmake
@@ -0,0 +1,3 @@
+include(Compiler/Clang-CXX)
+include(Compiler/ARMClang)
+__compiler_armclang(CXX)
diff --git a/Modules/Compiler/ARMClang-DetermineCompiler.cmake b/Modules/Compiler/ARMClang-DetermineCompiler.cmake
new file mode 100644
index 000000000..eb0de5306
--- /dev/null
+++ b/Modules/Compiler/ARMClang-DetermineCompiler.cmake
@@ -0,0 +1,10 @@
+# ARMClang Toolchain
+set(_compiler_id_pp_test "defined(__clang__) && defined(__ARMCOMPILER_VERSION)")
+
+set(_compiler_id_version_compute "
+ # define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__ARMCOMPILER_VERSION/1000000)
+ # define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__ARMCOMPILER_VERSION/10000 % 100)
+ # define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__ARMCOMPILER_VERSION % 10000)")
+
+string(APPEND _compiler_id_version_compute "
+# define @PREFIX@COMPILER_VERSION_INTERNAL @MACRO_DEC@(__ARMCOMPILER_VERSION)")
diff --git a/Modules/Compiler/ARMClang.cmake b/Modules/Compiler/ARMClang.cmake
new file mode 100644
index 000000000..2518ac714
--- /dev/null
+++ b/Modules/Compiler/ARMClang.cmake
@@ -0,0 +1,71 @@
+if(_ARMClang_CMAKE_LOADED)
+ return()
+endif()
+set(_ARMClang_CMAKE_LOADED TRUE)
+
+cmake_policy(PUSH)
+cmake_policy(SET CMP0057 NEW) # if IN_LIST
+
+get_filename_component(_CMAKE_C_TOOLCHAIN_LOCATION "${CMAKE_C_COMPILER}" PATH)
+get_filename_component(_CMAKE_CXX_TOOLCHAIN_LOCATION "${CMAKE_CXX_COMPILER}" PATH)
+
+set(CMAKE_EXECUTABLE_SUFFIX ".elf")
+
+find_program(CMAKE_ARMClang_LINKER armlink HINTS "${_CMAKE_C_TOOLCHAIN_LOCATION}" "${_CMAKE_CXX_TOOLCHAIN_LOCATION}" )
+find_program(CMAKE_ARMClang_AR armar HINTS "${_CMAKE_C_TOOLCHAIN_LOCATION}" "${_CMAKE_CXX_TOOLCHAIN_LOCATION}" )
+
+set(CMAKE_LINKER "${CMAKE_ARMClang_LINKER}" CACHE FILEPATH "The ARMClang linker" FORCE)
+mark_as_advanced(CMAKE_ARMClang_LINKER)
+set(CMAKE_AR "${CMAKE_ARMClang_AR}" CACHE FILEPATH "The ARMClang archiver" FORCE)
+mark_as_advanced(CMAKE_ARMClang_AR)
+
+# get compiler supported cpu list
+function(__armclang_set_processor_list lang out_var)
+ execute_process(COMMAND "${CMAKE_${lang}_COMPILER}" --target=${CMAKE_${lang}_COMPILER_TARGET} -mcpu=list
+ OUTPUT_VARIABLE processor_list
+ ERROR_VARIABLE processor_list)
+ string(REGEX MATCHALL "-mcpu=([^ \n]*)" processor_list "${processor_list}")
+ string(REGEX REPLACE "-mcpu=" "" processor_list "${processor_list}")
+ set(${out_var} "${processor_list}" PARENT_SCOPE)
+endfunction()
+
+# check processor is in list
+function(__armclang_check_processor processor list out_var)
+ string(TOLOWER "${processor}" processor)
+ if(processor IN_LIST list)
+ set(${out_var} TRUE PARENT_SCOPE)
+ else()
+ set(${out_var} FALSE PARENT_SCOPE)
+ endif()
+endfunction()
+
+macro(__compiler_armclang lang)
+ if(NOT CMAKE_${lang}_COMPILER_TARGET)
+ set(CMAKE_${lang}_COMPILER_TARGET arm-arm-none-eabi)
+ endif()
+ if(NOT CMAKE_${lang}_COMPILER_PROCESSOR_LIST)
+ __armclang_set_processor_list(${lang} CMAKE_${lang}_COMPILER_PROCESSOR_LIST)
+ endif()
+ if(NOT CMAKE_SYSTEM_PROCESSOR)
+ message(FATAL_ERROR " CMAKE_SYSTEM_PROCESSOR must be set for ARMClang\n"
+ " Supported processor: ${CMAKE_${lang}_COMPILER_PROCESSOR_LIST}\n")
+ else()
+ __armclang_check_processor("${CMAKE_SYSTEM_PROCESSOR}" "${CMAKE_${lang}_COMPILER_PROCESSOR_LIST}" _CMAKE_${lang}_CHECK_RESULT)
+ if(NOT _CMAKE_${lang}_CHECK_RESULT)
+ message(FATAL_ERROR " System processor '${CMAKE_SYSTEM_PROCESSOR}' not supported by ARMClang ${lang} compiler\n"
+ " Supported processor: ${CMAKE_${lang}_COMPILER_PROCESSOR_LIST}\n")
+ endif()
+ unset(_CMAKE_${lang}_CHECK_RESULT)
+ endif()
+ string(APPEND CMAKE_${lang}_FLAGS_INIT "-mcpu=${CMAKE_SYSTEM_PROCESSOR}")
+ string(APPEND CMAKE_${lang}_LINK_FLAGS "--cpu=${CMAKE_SYSTEM_PROCESSOR}")
+
+ set(CMAKE_${lang}_LINK_EXECUTABLE "<CMAKE_LINKER> <CMAKE_${lang}_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> <OBJECTS> -o <TARGET> --list <TARGET_BASE>.map")
+ set(CMAKE_${lang}_CREATE_STATIC_LIBRARY "<CMAKE_AR> --create -cr <TARGET> <LINK_FLAGS> <OBJECTS>")
+ set(CMAKE_${lang}_ARCHIVE_CREATE "<CMAKE_AR> --create -cr <TARGET> <LINK_FLAGS> <OBJECTS>")
+ set(CMAKE_${lang}_RESPONSE_FILE_LINK_FLAG "--via=")
+ set(CMAKE_${lang}_OUTPUT_EXTENSION ".o")
+ set(CMAKE_${lang}_OUTPUT_EXTENSION_REPLACE 1)
+endmacro()
+
+cmake_policy(POP)
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..f0e61d824
--- /dev/null
+++ b/Modules/Compiler/Flang-Fortran.cmake
@@ -0,0 +1,13 @@
+include(Compiler/Clang)
+__compiler_clang(Fortran)
+
+set(CMAKE_Fortran_SUBMODULE_SEP "-")
+set(CMAKE_Fortran_SUBMODULE_EXT ".mod")
+
+set(CMAKE_Fortran_PREPROCESS_SOURCE
+ "<CMAKE_Fortran_COMPILER> -cpp <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> > <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/IAR-FindBinUtils.cmake b/Modules/Compiler/IAR-FindBinUtils.cmake
new file mode 100644
index 000000000..b7d466405
--- /dev/null
+++ b/Modules/Compiler/IAR-FindBinUtils.cmake
@@ -0,0 +1,61 @@
+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 the compiler 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_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM" OR
+ "${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "RX" OR
+ "${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "RH850" OR
+ "${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "RL78" OR
+ "${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "RISCV")
+
+ string(TOLOWER "${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" _archid_lower)
+
+ # Find linker
+ find_program(CMAKE_IAR_LINKER ilink${_archid_lower} HINTS ${__iar_hints}
+ DOC "The IAR ILINK linker")
+ find_program(CMAKE_IAR_ARCHIVE iarchive HINTS ${__iar_hints}
+ DOC "The IAR archiver")
+
+ # Find utility tools
+ find_program(CMAKE_IAR_ELFTOOL ielftool HINTS ${__iar_hints}
+ DOC "The IAR ELF Tool")
+ find_program(CMAKE_IAR_ELFDUMP ielfdump${_archid_lower} HINTS ${__iar_hints}
+ DOC "The IAR ELF Dumper")
+ find_program(CMAKE_IAR_OBJMANIP iobjmanip HINTS ${__iar_hints}
+ DOC "The IAR ELF Object Tool")
+ find_program(CMAKE_IAR_SYMEXPORT isymexport HINTS ${__iar_hints}
+ DOC "The IAR Absolute Symbol Exporter")
+ mark_as_advanced(CMAKE_IAR_LINKER 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_LINKER \"${CMAKE_IAR_LINKER}\")
+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_LINKER \"${CMAKE_IAR_LINKER}\")
+")
+
+elseif("${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR" OR
+ "${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_ARCHITECTURE_ID}" STREQUAL "MSP430")
+
+ # Find the "xlink" linker and "xar" archiver:
+ find_program(CMAKE_IAR_LINKER xlink HINTS ${__iar_hints}
+ DOC "The IAR XLINK linker")
+ find_program(CMAKE_IAR_AR xar 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/MSVC-ASM.cmake b/Modules/Compiler/MSVC-ASM.cmake
new file mode 100644
index 000000000..45978c5e2
--- /dev/null
+++ b/Modules/Compiler/MSVC-ASM.cmake
@@ -0,0 +1 @@
+# This file is loaded when Visual Studio is used for the ASM language.
diff --git a/Modules/Compiler/MSVC-C-FeatureTests.cmake b/Modules/Compiler/MSVC-C-FeatureTests.cmake
new file mode 100644
index 000000000..3f09be201
--- /dev/null
+++ b/Modules/Compiler/MSVC-C-FeatureTests.cmake
@@ -0,0 +1,8 @@
+set(_cmake_oldestSupported "_MSC_VER >= 1600")
+
+# Not yet supported:
+#set(_cmake_feature_test_c_static_assert "")
+#set(_cmake_feature_test_c_restrict "")
+
+set(_cmake_feature_test_c_variadic_macros "${_cmake_oldestSupported}")
+set(_cmake_feature_test_c_function_prototypes "${_cmake_oldestSupported}")
diff --git a/Modules/Compiler/MSVC-C.cmake b/Modules/Compiler/MSVC-C.cmake
new file mode 100644
index 000000000..20787a399
--- /dev/null
+++ b/Modules/Compiler/MSVC-C.cmake
@@ -0,0 +1,38 @@
+# MSVC has no specific options to set C language standards, but set them as
+# empty strings anyways so the feature test infrastructure can at least check
+# to see if they are defined.
+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 "")
+
+# There is no meaningful default for this
+set(CMAKE_C_STANDARD_DEFAULT "")
+
+# There are no C compiler modes so we hard-code the known compiler supported
+# features. Override the default macro for this special case. Pretend that
+# all language standards are available so that at least compilation
+# can be attempted.
+macro(cmake_record_c_compile_features)
+ list(APPEND CMAKE_C_COMPILE_FEATURES
+ c_std_90
+ c_std_99
+ c_std_11
+ c_function_prototypes
+ )
+ list(APPEND CMAKE_C90_COMPILE_FEATURES c_std_90 c_function_prototypes)
+ list(APPEND CMAKE_C99_COMPILE_FEATURES c_std_99)
+ list(APPEND CMAKE_C11_COMPILE_FEATURES c_std_11)
+ if (CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 14.0)
+ list(APPEND CMAKE_C_COMPILE_FEATURES c_variadic_macros)
+ list(APPEND CMAKE_C99_COMPILE_FEATURES c_variadic_macros)
+ endif()
+ set(_result 0) # expected by cmake_determine_compile_features
+endmacro()
+
+# /JMC "Just My Code" is only supported by MSVC 19.05 onward.
+if (CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 19.05)
+ set(CMAKE_C_COMPILE_OPTIONS_JMC "-JMC")
+endif()
diff --git a/Modules/Compiler/QCC-ASM.cmake b/Modules/Compiler/QCC-ASM.cmake
new file mode 100644
index 000000000..9a9935b27
--- /dev/null
+++ b/Modules/Compiler/QCC-ASM.cmake
@@ -0,0 +1,2 @@
+include(Compiler/QCC)
+__compiler_qcc(ASM)
diff --git a/Modules/Compiler/QCC-C-FeatureTests.cmake b/Modules/Compiler/QCC-C-FeatureTests.cmake
new file mode 100644
index 000000000..68f41970d
--- /dev/null
+++ b/Modules/Compiler/QCC-C-FeatureTests.cmake
@@ -0,0 +1 @@
+include(Compiler/GNU-C-FeatureTests)
diff --git a/Modules/Compiler/QCC-CXX-FeatureTests.cmake b/Modules/Compiler/QCC-CXX-FeatureTests.cmake
new file mode 100644
index 000000000..c836b9416
--- /dev/null
+++ b/Modules/Compiler/QCC-CXX-FeatureTests.cmake
@@ -0,0 +1 @@
+include(Compiler/GNU-CXX-FeatureTests)
diff --git a/Modules/Compiler/XLClang-C-DetermineCompiler.cmake b/Modules/Compiler/XLClang-C-DetermineCompiler.cmake
new file mode 100644
index 000000000..4d899213a
--- /dev/null
+++ b/Modules/Compiler/XLClang-C-DetermineCompiler.cmake
@@ -0,0 +1,8 @@
+set(_compiler_id_pp_test "defined(__ibmxl__) && defined(__clang__)")
+
+set(_compiler_id_version_compute "
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__ibmxl_version__)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__ibmxl_release__)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__ibmxl_modification__)
+# define @PREFIX@COMPILER_VERSION_TWEAK @MACRO_DEC@(__ibmxl_ptf_fix_level__)
+")
diff --git a/Modules/Compiler/XLClang-C.cmake b/Modules/Compiler/XLClang-C.cmake
new file mode 100644
index 000000000..54c18a668
--- /dev/null
+++ b/Modules/Compiler/XLClang-C.cmake
@@ -0,0 +1,20 @@
+include(Compiler/XLClang)
+__compiler_xlclang(C)
+
+if (CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 13.1.1)
+ set(CMAKE_C90_STANDARD_COMPILE_OPTION "-std=c89")
+ set(CMAKE_C90_EXTENSION_COMPILE_OPTION "-std=gnu89")
+ set(CMAKE_C90_STANDARD__HAS_FULL_SUPPORT ON)
+ set(CMAKE_C99_STANDARD_COMPILE_OPTION "-std=c99")
+ set(CMAKE_C99_EXTENSION_COMPILE_OPTION "-std=gnu99")
+ set(CMAKE_C99_STANDARD__HAS_FULL_SUPPORT ON)
+ set(CMAKE_C11_STANDARD_COMPILE_OPTION "-qlanglvl=extc1x")
+ set(CMAKE_C11_EXTENSION_COMPILE_OPTION "-qlanglvl=extc1x")
+ if (CMAKE_C_COMPILER_VERSION VERSION_GREATER_EQUAL 13.1.2)
+ set(CMAKE_C11_STANDARD_COMPILE_OPTION "-std=c11")
+ set(CMAKE_C11_EXTENSION_COMPILE_OPTION "-std=gnu11")
+ set(CMAKE_C11_STANDARD__HAS_FULL_SUPPORT ON)
+ endif ()
+endif()
+
+__compiler_check_default_language_standard(C 13.1.1 99)
diff --git a/Modules/Compiler/XLClang-CXX-DetermineCompiler.cmake b/Modules/Compiler/XLClang-CXX-DetermineCompiler.cmake
new file mode 100644
index 000000000..4d899213a
--- /dev/null
+++ b/Modules/Compiler/XLClang-CXX-DetermineCompiler.cmake
@@ -0,0 +1,8 @@
+set(_compiler_id_pp_test "defined(__ibmxl__) && defined(__clang__)")
+
+set(_compiler_id_version_compute "
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@(__ibmxl_version__)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(__ibmxl_release__)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@(__ibmxl_modification__)
+# define @PREFIX@COMPILER_VERSION_TWEAK @MACRO_DEC@(__ibmxl_ptf_fix_level__)
+")
diff --git a/Modules/Compiler/XLClang-CXX.cmake b/Modules/Compiler/XLClang-CXX.cmake
new file mode 100644
index 000000000..9ea3d7cac
--- /dev/null
+++ b/Modules/Compiler/XLClang-CXX.cmake
@@ -0,0 +1,27 @@
+include(Compiler/XLClang)
+__compiler_xlclang(CXX)
+
+if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 13.1.1)
+ set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "")
+ set(CMAKE_CXX98_STANDARD__HAS_FULL_SUPPORT ON)
+ set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "-qlanglvl=extended0x")
+ set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-qlanglvl=extended0x")
+ set(CMAKE_CXX11_STANDARD__HAS_FULL_SUPPORT ON)
+ if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 13.1.2)
+ set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "-std=c++11")
+ set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=gnu++11")
+ set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++1y")
+ set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++1y")
+ set(CMAKE_CXX14_STANDARD__HAS_FULL_SUPPORT ON)
+ endif ()
+ if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.1.0)
+ set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++14")
+ set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++14")
+ endif()
+endif()
+
+__compiler_check_default_language_standard(CXX 13.1.1 98)
+
+set(CMAKE_CXX_COMPILE_OBJECT
+ "<CMAKE_CXX_COMPILER> -x c++ <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT> -c <SOURCE>")
diff --git a/Modules/Compiler/XLClang.cmake b/Modules/Compiler/XLClang.cmake
new file mode 100644
index 000000000..cdf0fdca1
--- /dev/null
+++ b/Modules/Compiler/XLClang.cmake
@@ -0,0 +1,22 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+
+# This module is shared by multiple languages; use include blocker.
+if(__COMPILER_XLCLANG)
+ return()
+endif()
+set(__COMPILER_XLCLANG 1)
+
+include(Compiler/XL)
+
+macro(__compiler_xlclang lang)
+ __compiler_xl(${lang})
+
+ # Feature flags.
+ set(CMAKE_${lang}_VERBOSE_FLAG "-V")
+ set(CMAKE_${lang}_COMPILE_OPTIONS_PIC "-fPIC")
+ set(CMAKE_${lang}_COMPILE_OPTIONS_PIE "-fPIC")
+ set(CMAKE_${lang}_RESPONSE_FILE_FLAG "@")
+ set(CMAKE_${lang}_RESPONSE_FILE_LINK_FLAG "@")
+endmacro()
diff --git a/Modules/CompilerId/GHS_default.gpj.in b/Modules/CompilerId/GHS_default.gpj.in
new file mode 100644
index 000000000..b5cea5cf8
--- /dev/null
+++ b/Modules/CompilerId/GHS_default.gpj.in
@@ -0,0 +1,8 @@
+#!gbuild
+@bsp_name@
+@os_dir@
+primaryTarget=@ghs_primary_target@
+[Project]
+ {isdefined(GHS_BSP)} -bsp $GHS_BSP
+ {isdefined(GHS_OS)} -os_dir $GHS_OS
+GHS_lib.gpj [Library]
diff --git a/Modules/CompilerId/GHS_lib.gpj.in b/Modules/CompilerId/GHS_lib.gpj.in
new file mode 100644
index 000000000..149b98144
--- /dev/null
+++ b/Modules/CompilerId/GHS_lib.gpj.in
@@ -0,0 +1,3 @@
+#!gbuild
+[Library]
+@id_src@
diff --git a/Modules/FetchContent.cmake b/Modules/FetchContent.cmake
new file mode 100644
index 000000000..5716b0112
--- /dev/null
+++ b/Modules/FetchContent.cmake
@@ -0,0 +1,1061 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FetchContent
+------------------
+
+.. only:: html
+
+ .. contents::
+
+Overview
+^^^^^^^^
+
+This module enables populating content at configure time via any method
+supported by the :module:`ExternalProject` module. Whereas
+:command:`ExternalProject_Add` downloads at build time, the
+``FetchContent`` module makes content available immediately, allowing the
+configure step to use the content in commands like :command:`add_subdirectory`,
+:command:`include` or :command:`file` operations.
+
+Content population details would normally be defined separately from the
+command that performs the actual population. This separation ensures that
+all of the dependency details are defined before anything may try to use those
+details to populate content. This is particularly important in more complex
+project hierarchies where dependencies may be shared between multiple projects.
+
+The following shows a typical example of declaring content details:
+
+.. code-block:: cmake
+
+ FetchContent_Declare(
+ googletest
+ GIT_REPOSITORY https://github.com/google/googletest.git
+ GIT_TAG release-1.8.0
+ )
+
+For most typical cases, populating the content can then be done with a single
+command like so:
+
+.. code-block:: cmake
+
+ FetchContent_MakeAvailable(googletest)
+
+The above command not only populates the content, it also adds it to the main
+build (if possible) so that the main build can use the populated project's
+targets, etc. In some cases, the main project may need to have more precise
+control over the population or may be required to explicitly define the
+population steps (e.g. if CMake versions earlier than 3.14 need to be
+supported). The typical pattern of such custom steps looks like this:
+
+.. code-block:: cmake
+
+ FetchContent_GetProperties(googletest)
+ if(NOT googletest_POPULATED)
+ FetchContent_Populate(googletest)
+ add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
+ endif()
+
+Regardless of which population method is used, when using the
+declare-populate pattern with a hierarchical project arrangement, projects at
+higher levels in the hierarchy are able to override the population details of
+content specified anywhere lower in the project hierarchy. The ability to
+detect whether content has already been populated ensures that even if
+multiple child projects want certain content to be available, the first one
+to populate it wins. The other child project can simply make use of the
+already available content instead of repeating the population for itself.
+See the :ref:`Examples <fetch-content-examples>` section which demonstrates
+this scenario.
+
+The ``FetchContent`` module also supports defining and populating
+content in a single call, with no check for whether the content has been
+populated elsewhere in the project already. This is a more low level
+operation and would not normally be the way the module is used, but it is
+sometimes useful as part of implementing some higher level feature or to
+populate some content in CMake's script mode.
+
+
+Declaring Content Details
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. command:: FetchContent_Declare
+
+ .. code-block:: cmake
+
+ FetchContent_Declare(<name> <contentOptions>...)
+
+ The ``FetchContent_Declare()`` function records the options that describe
+ how to populate the specified content, but if such details have already
+ been recorded earlier in this project (regardless of where in the project
+ hierarchy), this and all later calls for the same content ``<name>`` are
+ ignored. This "first to record, wins" approach is what allows hierarchical
+ projects to have parent projects override content details of child projects.
+
+ The content ``<name>`` can be any string without spaces, but good practice
+ would be to use only letters, numbers and underscores. The name will be
+ treated case-insensitively and it should be obvious for the content it
+ represents, often being the name of the child project or the value given
+ to its top level :command:`project` command (if it is a CMake project).
+ For well-known public projects, the name should generally be the official
+ name of the project. Choosing an unusual name makes it unlikely that other
+ projects needing that same content will use the same name, leading to
+ the content being populated multiple times.
+
+ The ``<contentOptions>`` can be any of the download or update/patch options
+ that the :command:`ExternalProject_Add` command understands. The configure,
+ build, install and test steps are explicitly disabled and therefore options
+ related to them will be ignored. In most cases, ``<contentOptions>`` will
+ just be a couple of options defining the download method and method-specific
+ details like a commit tag or archive hash. For example:
+
+ .. code-block:: cmake
+
+ FetchContent_Declare(
+ googletest
+ GIT_REPOSITORY https://github.com/google/googletest.git
+ GIT_TAG release-1.8.0
+ )
+
+ FetchContent_Declare(
+ myCompanyIcons
+ URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
+ URL_HASH 5588a7b18261c20068beabfb4f530b87
+ )
+
+ FetchContent_Declare(
+ myCompanyCertificates
+ SVN_REPOSITORY svn+ssh://svn.mycompany.com/srv/svn/trunk/certs
+ SVN_REVISION -r12345
+ )
+
+Populating The Content
+^^^^^^^^^^^^^^^^^^^^^^
+
+For most common scenarios, population means making content available to the
+main build according to previously declared details for that dependency.
+There are two main patterns for populating content, one based on calling
+:command:`FetchContent_GetProperties` and
+:command:`FetchContent_Populate` for more precise control and the other on
+calling :command:`FetchContent_MakeAvailable` for a simpler, more automated
+approach. The former generally follows this canonical pattern:
+
+.. _`fetch-content-canonical-pattern`:
+
+.. code-block:: cmake
+
+ # Check if population has already been performed
+ FetchContent_GetProperties(<name>)
+ string(TOLOWER "<name>" lcName)
+ if(NOT ${lcName}_POPULATED)
+ # Fetch the content using previously declared details
+ FetchContent_Populate(<name>)
+
+ # Set custom variables, policies, etc.
+ # ...
+
+ # Bring the populated content into the build
+ add_subdirectory(${${lcName}_SOURCE_DIR} ${${lcName}_BINARY_DIR})
+ endif()
+
+The above is such a common pattern that, where no custom steps are needed
+between the calls to :command:`FetchContent_Populate` and
+:command:`add_subdirectory`, equivalent logic can be obtained by calling
+:command:`FetchContent_MakeAvailable` instead (and should be preferred where
+it meets the needs of the project).
+
+.. command:: FetchContent_Populate
+
+ .. code-block:: cmake
+
+ FetchContent_Populate( <name> )
+
+ In most cases, the only argument given to ``FetchContent_Populate()`` is the
+ ``<name>``. When used this way, the command assumes the content details have
+ been recorded by an earlier call to :command:`FetchContent_Declare`. The
+ details are stored in a global property, so they are unaffected by things
+ like variable or directory scope. Therefore, it doesn't matter where in the
+ project the details were previously declared, as long as they have been
+ declared before the call to ``FetchContent_Populate()``. Those saved details
+ are then used to construct a call to :command:`ExternalProject_Add` in a
+ private sub-build to perform the content population immediately. The
+ implementation of ``ExternalProject_Add()`` ensures that if the content has
+ already been populated in a previous CMake run, that content will be reused
+ rather than repopulating them again. For the common case where population
+ involves downloading content, the cost of the download is only paid once.
+
+ An internal global property records when a particular content population
+ request has been processed. If ``FetchContent_Populate()`` is called more
+ than once for the same content name within a configure run, the second call
+ will halt with an error. Projects can and should check whether content
+ population has already been processed with the
+ :command:`FetchContent_GetProperties` command before calling
+ ``FetchContent_Populate()``.
+
+ ``FetchContent_Populate()`` will set three variables in the scope of the
+ caller; ``<lcName>_POPULATED``, ``<lcName>_SOURCE_DIR`` and
+ ``<lcName>_BINARY_DIR``, where ``<lcName>`` is the lowercased ``<name>``.
+ ``<lcName>_POPULATED`` will always be set to ``True`` by the call.
+ ``<lcName>_SOURCE_DIR`` is the location where the
+ content can be found upon return (it will have already been populated), while
+ ``<lcName>_BINARY_DIR`` is a directory intended for use as a corresponding
+ build directory. The main use case for the two directory variables is to
+ call :command:`add_subdirectory` immediately after population, i.e.:
+
+ .. code-block:: cmake
+
+ FetchContent_Populate(FooBar ...)
+ add_subdirectory(${foobar_SOURCE_DIR} ${foobar_BINARY_DIR})
+
+ The values of the three variables can also be retrieved from anywhere in the
+ project hierarchy using the :command:`FetchContent_GetProperties` command.
+
+ A number of cache variables influence the behavior of all content population
+ performed using details saved from a :command:`FetchContent_Declare` call:
+
+ ``FETCHCONTENT_BASE_DIR``
+ In most cases, the saved details do not specify any options relating to the
+ directories to use for the internal sub-build, final source and build areas.
+ It is generally best to leave these decisions up to the ``FetchContent``
+ module to handle on the project's behalf. The ``FETCHCONTENT_BASE_DIR``
+ cache variable controls the point under which all content population
+ directories are collected, but in most cases developers would not need to
+ change this. The default location is ``${CMAKE_BINARY_DIR}/_deps``, but if
+ developers change this value, they should aim to keep the path short and
+ just below the top level of the build tree to avoid running into path
+ length problems on Windows.
+
+ ``FETCHCONTENT_QUIET``
+ The logging output during population can be quite verbose, making the
+ configure stage quite noisy. This cache option (``ON`` by default) hides
+ all population output unless an error is encountered. If experiencing
+ problems with hung downloads, temporarily switching this option off may
+ help diagnose which content population is causing the issue.
+
+ ``FETCHCONTENT_FULLY_DISCONNECTED``
+ When this option is enabled, no attempt is made to download or update
+ any content. It is assumed that all content has already been populated in
+ a previous run or the source directories have been pointed at existing
+ contents the developer has provided manually (using options described
+ further below). When the developer knows that no changes have been made to
+ any content details, turning this option ``ON`` can significantly speed up
+ the configure stage. It is ``OFF`` by default.
+
+ ``FETCHCONTENT_UPDATES_DISCONNECTED``
+ This is a less severe download/update control compared to
+ ``FETCHCONTENT_FULLY_DISCONNECTED``. Instead of bypassing all download and
+ update logic, the ``FETCHCONTENT_UPDATES_DISCONNECTED`` only disables the
+ update stage. Therefore, if content has not been downloaded previously,
+ it will still be downloaded when this option is enabled. This can speed up
+ the configure stage, but not as much as
+ ``FETCHCONTENT_FULLY_DISCONNECTED``. It is ``OFF`` by default.
+
+ In addition to the above cache variables, the following cache variables are
+ also defined for each content name (``<ucName>`` is the uppercased value of
+ ``<name>``):
+
+ ``FETCHCONTENT_SOURCE_DIR_<ucName>``
+ If this is set, no download or update steps are performed for the specified
+ content and the ``<lcName>_SOURCE_DIR`` variable returned to the caller is
+ pointed at this location. This gives developers a way to have a separate
+ checkout of the content that they can modify freely without interference
+ from the build. The build simply uses that existing source, but it still
+ defines ``<lcName>_BINARY_DIR`` to point inside its own build area.
+ Developers are strongly encouraged to use this mechanism rather than
+ editing the sources populated in the default location, as changes to
+ sources in the default location can be lost when content population details
+ are changed by the project.
+
+ ``FETCHCONTENT_UPDATES_DISCONNECTED_<ucName>``
+ This is the per-content equivalent of
+ ``FETCHCONTENT_UPDATES_DISCONNECTED``. If the global option or this option
+ is ``ON``, then updates will be disabled for the named content.
+ Disabling updates for individual content can be useful for content whose
+ details rarely change, while still leaving other frequently changing
+ content with updates enabled.
+
+
+ The ``FetchContent_Populate()`` command also supports a syntax allowing the
+ content details to be specified directly rather than using any saved
+ details. This is more low-level and use of this form is generally to be
+ avoided in favour of using saved content details as outlined above.
+ Nevertheless, in certain situations it can be useful to invoke the content
+ population as an isolated operation (typically as part of implementing some
+ other higher level feature or when using CMake in script mode):
+
+ .. code-block:: cmake
+
+ FetchContent_Populate( <name>
+ [QUIET]
+ [SUBBUILD_DIR <subBuildDir>]
+ [SOURCE_DIR <srcDir>]
+ [BINARY_DIR <binDir>]
+ ...
+ )
+
+ This form has a number of key differences to that where only ``<name>`` is
+ provided:
+
+ - All required population details are assumed to have been provided directly
+ in the call to ``FetchContent_Populate()``. Any saved details for
+ ``<name>`` are ignored.
+ - No check is made for whether content for ``<name>`` has already been
+ populated.
+ - No global property is set to record that the population has occurred.
+ - No global properties record the source or binary directories used for the
+ populated content.
+ - The ``FETCHCONTENT_FULLY_DISCONNECTED`` and
+ ``FETCHCONTENT_UPDATES_DISCONNECTED`` cache variables are ignored.
+
+ The ``<lcName>_SOURCE_DIR`` and ``<lcName>_BINARY_DIR`` variables are still
+ returned to the caller, but since these locations are not stored as global
+ properties when this form is used, they are only available to the calling
+ scope and below rather than the entire project hierarchy. No
+ ``<lcName>_POPULATED`` variable is set in the caller's scope with this form.
+
+ The supported options for ``FetchContent_Populate()`` are the same as those
+ for :command:`FetchContent_Declare()`. Those few options shown just
+ above are either specific to ``FetchContent_Populate()`` or their behavior is
+ slightly modified from how :command:`ExternalProject_Add` treats them.
+
+ ``QUIET``
+ The ``QUIET`` option can be given to hide the output associated with
+ populating the specified content. If the population fails, the output will
+ be shown regardless of whether this option was given or not so that the
+ cause of the failure can be diagnosed. The global ``FETCHCONTENT_QUIET``
+ cache variable has no effect on ``FetchContent_Populate()`` calls where the
+ content details are provided directly.
+
+ ``SUBBUILD_DIR``
+ The ``SUBBUILD_DIR`` argument can be provided to change the location of the
+ sub-build created to perform the population. The default value is
+ ``${CMAKE_CURRENT_BINARY_DIR}/<lcName>-subbuild`` and it would be unusual
+ to need to override this default. If a relative path is specified, it will
+ be interpreted as relative to :variable:`CMAKE_CURRENT_BINARY_DIR`.
+
+ ``SOURCE_DIR``, ``BINARY_DIR``
+ The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments are supported by
+ :command:`ExternalProject_Add`, but different default values are used by
+ ``FetchContent_Populate()``. ``SOURCE_DIR`` defaults to
+ ``${CMAKE_CURRENT_BINARY_DIR}/<lcName>-src`` and ``BINARY_DIR`` defaults to
+ ``${CMAKE_CURRENT_BINARY_DIR}/<lcName>-build``. If a relative path is
+ specified, it will be interpreted as relative to
+ :variable:`CMAKE_CURRENT_BINARY_DIR`.
+
+ In addition to the above explicit options, any other unrecognized options are
+ passed through unmodified to :command:`ExternalProject_Add` to perform the
+ download, patch and update steps. The following options are explicitly
+ prohibited (they are disabled by the ``FetchContent_Populate()`` command):
+
+ - ``CONFIGURE_COMMAND``
+ - ``BUILD_COMMAND``
+ - ``INSTALL_COMMAND``
+ - ``TEST_COMMAND``
+
+ If using ``FetchContent_Populate()`` within CMake's script mode, be aware
+ that the implementation sets up a sub-build which therefore requires a CMake
+ generator and build tool to be available. If these cannot be found by
+ default, then the :variable:`CMAKE_GENERATOR` and/or
+ :variable:`CMAKE_MAKE_PROGRAM` variables will need to be set appropriately
+ on the command line invoking the script.
+
+
+.. command:: FetchContent_GetProperties
+
+ When using saved content details, a call to :command:`FetchContent_Populate`
+ records information in global properties which can be queried at any time.
+ This information includes the source and binary directories associated with
+ the content and also whether or not the content population has been processed
+ during the current configure run.
+
+ .. code-block:: cmake
+
+ FetchContent_GetProperties( <name>
+ [SOURCE_DIR <srcDirVar>]
+ [BINARY_DIR <binDirVar>]
+ [POPULATED <doneVar>]
+ )
+
+ The ``SOURCE_DIR``, ``BINARY_DIR`` and ``POPULATED`` options can be used to
+ specify which properties should be retrieved. Each option accepts a value
+ which is the name of the variable in which to store that property. Most of
+ the time though, only ``<name>`` is given, in which case the call will then
+ set the same variables as a call to
+ :command:`FetchContent_Populate(name) <FetchContent_Populate>`. This allows
+ the following canonical pattern to be used, which ensures that the relevant
+ variables will always be defined regardless of whether or not the population
+ has been performed elsewhere in the project already:
+
+ .. code-block:: cmake
+
+ FetchContent_GetProperties(foobar)
+ if(NOT foobar_POPULATED)
+ FetchContent_Populate(foobar)
+ ...
+ endif()
+
+ The above pattern allows other parts of the overall project hierarchy to
+ re-use the same content and ensure that it is only populated once.
+
+
+.. command:: FetchContent_MakeAvailable
+
+ .. code-block:: cmake
+
+ FetchContent_MakeAvailable( <name1> [<name2>...] )
+
+ This command implements the common pattern typically needed for most
+ dependencies. It iterates over each of the named dependencies in turn
+ and for each one it loosely follows the same
+ :ref:`canonical pattern <fetch-content-canonical-pattern>` as
+ presented at the beginning of this section. One small difference to
+ that pattern is that it will only call :command:`add_subdirectory` on the
+ populated content if there is a ``CMakeLists.txt`` file in its top level
+ source directory. This allows the command to be used for dependencies
+ that make downloaded content available at a known location but which do
+ not need or support being added directly to the build.
+
+
+.. _`fetch-content-examples`:
+
+Examples
+^^^^^^^^
+
+This first fairly straightforward example ensures that some popular testing
+frameworks are available to the main build:
+
+.. code-block:: cmake
+
+ include(FetchContent)
+ FetchContent_Declare(
+ googletest
+ GIT_REPOSITORY https://github.com/google/googletest.git
+ GIT_TAG release-1.8.0
+ )
+ FetchContent_Declare(
+ Catch2
+ GIT_REPOSITORY https://github.com/catchorg/Catch2.git
+ GIT_TAG v2.5.0
+ )
+
+ # After the following call, the CMake targets defined by googletest and
+ # Catch2 will be defined and available to the rest of the build
+ FetchContent_MakeAvailable(googletest Catch2)
+
+
+In more complex project hierarchies, the dependency relationships can be more
+complicated. Consider a hierarchy where ``projA`` is the top level project and
+it depends directly on projects ``projB`` and ``projC``. Both ``projB`` and
+``projC`` can be built standalone and they also both depend on another project
+``projD``. ``projB`` additionally depends on ``projE``. This example assumes
+that all five projects are available on a company git server. The
+``CMakeLists.txt`` of each project might have sections like the following:
+
+*projA*:
+
+.. code-block:: cmake
+
+ include(FetchContent)
+ FetchContent_Declare(
+ projB
+ GIT_REPOSITORY git@mycompany.com:git/projB.git
+ GIT_TAG 4a89dc7e24ff212a7b5167bef7ab079d
+ )
+ FetchContent_Declare(
+ projC
+ GIT_REPOSITORY git@mycompany.com:git/projC.git
+ GIT_TAG 4ad4016bd1d8d5412d135cf8ceea1bb9
+ )
+ FetchContent_Declare(
+ projD
+ GIT_REPOSITORY git@mycompany.com:git/projD.git
+ GIT_TAG origin/integrationBranch
+ )
+ FetchContent_Declare(
+ projE
+ GIT_REPOSITORY git@mycompany.com:git/projE.git
+ GIT_TAG origin/release/2.3-rc1
+ )
+
+ # Order is important, see notes in the discussion further below
+ FetchContent_MakeAvailable(projD projB projC)
+
+*projB*:
+
+.. code-block:: cmake
+
+ include(FetchContent)
+ FetchContent_Declare(
+ projD
+ GIT_REPOSITORY git@mycompany.com:git/projD.git
+ GIT_TAG 20b415f9034bbd2a2e8216e9a5c9e632
+ )
+ FetchContent_Declare(
+ projE
+ GIT_REPOSITORY git@mycompany.com:git/projE.git
+ GIT_TAG 68e20f674a48be38d60e129f600faf7d
+ )
+
+ FetchContent_MakeAvailable(projD projE)
+
+*projC*:
+
+.. code-block:: cmake
+
+ include(FetchContent)
+ FetchContent_Declare(
+ projD
+ GIT_REPOSITORY git@mycompany.com:git/projD.git
+ GIT_TAG 7d9a17ad2c962aa13e2fbb8043fb6b8a
+ )
+
+ # This particular version of projD requires workarounds
+ FetchContent_GetProperties(projD)
+ if(NOT projd_POPULATED)
+ FetchContent_Populate(projD)
+
+ # Copy an additional/replacement file into the populated source
+ file(COPY someFile.c DESTINATION ${projd_SOURCE_DIR}/src)
+
+ add_subdirectory(${projd_SOURCE_DIR} ${projd_BINARY_DIR})
+ endif()
+
+A few key points should be noted in the above:
+
+- ``projB`` and ``projC`` define different content details for ``projD``,
+ but ``projA`` also defines a set of content details for ``projD``.
+ Because ``projA`` will define them first, the details from ``projB`` and
+ ``projC`` will not be used. The override details defined by ``projA``
+ are not required to match either of those from ``projB`` or ``projC``, but
+ it is up to the higher level project to ensure that the details it does
+ define still make sense for the child projects.
+- In the ``projA`` call to :command:`FetchContent_MakeAvailable`, ``projD``
+ is listed ahead of ``projB`` and ``projC`` to ensure that ``projA`` is in
+ control of how ``projD`` is populated.
+- While ``projA`` defines content details for ``projE``, it does not need
+ to explicitly call ``FetchContent_MakeAvailable(projE)`` or
+ ``FetchContent_Populate(projD)`` itself. Instead, it leaves that to the
+ child ``projB``. For higher level projects, it is often enough to just
+ define the override content details and leave the actual population to the
+ child projects. This saves repeating the same thing at each level of the
+ project hierarchy unnecessarily.
+
+
+Projects don't always need to add the populated content to the build.
+Sometimes the project just wants to make the downloaded content available at
+a predictable location. The next example ensures that a set of standard
+company toolchain files (and potentially even the toolchain binaries
+themselves) is available early enough to be used for that same build.
+
+.. code-block:: cmake
+
+ cmake_minimum_required(VERSION 3.14)
+
+ include(FetchContent)
+ FetchContent_Declare(
+ mycom_toolchains
+ URL https://intranet.mycompany.com//toolchains_1.3.2.tar.gz
+ )
+ FetchContent_MakeAvailable(mycom_toolchains)
+
+ project(CrossCompileExample)
+
+The project could be configured to use one of the downloaded toolchains like
+so:
+
+.. code-block:: shell
+
+ cmake -DCMAKE_TOOLCHAIN_FILE=_deps/mycom_toolchains-src/toolchain_arm.cmake /path/to/src
+
+When CMake processes the ``CMakeLists.txt`` file, it will download and unpack
+the tarball into ``_deps/mycompany_toolchains-src`` relative to the build
+directory. The :variable:`CMAKE_TOOLCHAIN_FILE` variable is not used until
+the :command:`project` command is reached, at which point CMake looks for the
+named toolchain file relative to the build directory. Because the tarball has
+already been downloaded and unpacked by then, the toolchain file will be in
+place, even the very first time that ``cmake`` is run in the build directory.
+
+Lastly, the following example demonstrates how one might download and unpack a
+firmware tarball using CMake's :manual:`script mode <cmake(1)>`. The call to
+:command:`FetchContent_Populate` specifies all the content details and the
+unpacked firmware will be placed in a ``firmware`` directory below the
+current working directory.
+
+*getFirmware.cmake*:
+
+.. code-block:: cmake
+
+ # NOTE: Intended to be run in script mode with cmake -P
+ include(FetchContent)
+ FetchContent_Populate(
+ firmware
+ URL https://mycompany.com/assets/firmware-1.23-arm.tar.gz
+ URL_HASH MD5=68247684da89b608d466253762b0ff11
+ SOURCE_DIR firmware
+ )
+
+#]=======================================================================]
+
+
+set(__FetchContent_privateDir "${CMAKE_CURRENT_LIST_DIR}/FetchContent")
+
+#=======================================================================
+# Recording and retrieving content details for later population
+#=======================================================================
+
+# Internal use, projects must not call this directly. It is
+# intended for use by FetchContent_Declare() only.
+#
+# Sets a content-specific global property (not meant for use
+# outside of functions defined here in this file) which can later
+# be retrieved using __FetchContent_getSavedDetails() with just the
+# same content name. If there is already a value stored in the
+# property, it is left unchanged and this call has no effect.
+# This allows parent projects to define the content details,
+# overriding anything a child project may try to set (properties
+# are not cached between runs, so the first thing to set it in a
+# build will be in control).
+function(__FetchContent_declareDetails contentName)
+
+ string(TOLOWER ${contentName} contentNameLower)
+ set(propertyName "_FetchContent_${contentNameLower}_savedDetails")
+ get_property(alreadyDefined GLOBAL PROPERTY ${propertyName} DEFINED)
+ if(NOT alreadyDefined)
+ define_property(GLOBAL PROPERTY ${propertyName}
+ BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
+ FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
+ )
+ set_property(GLOBAL PROPERTY ${propertyName} ${ARGN})
+ endif()
+
+endfunction()
+
+
+# Internal use, projects must not call this directly. It is
+# intended for use by the FetchContent_Declare() function.
+#
+# Retrieves details saved for the specified content in an
+# earlier call to __FetchContent_declareDetails().
+function(__FetchContent_getSavedDetails contentName outVar)
+
+ string(TOLOWER ${contentName} contentNameLower)
+ set(propertyName "_FetchContent_${contentNameLower}_savedDetails")
+ get_property(alreadyDefined GLOBAL PROPERTY ${propertyName} DEFINED)
+ if(NOT alreadyDefined)
+ message(FATAL_ERROR "No content details recorded for ${contentName}")
+ endif()
+ get_property(propertyValue GLOBAL PROPERTY ${propertyName})
+ set(${outVar} "${propertyValue}" PARENT_SCOPE)
+
+endfunction()
+
+
+# Saves population details of the content, sets defaults for the
+# SOURCE_DIR and BUILD_DIR.
+function(FetchContent_Declare contentName)
+
+ set(options "")
+ set(oneValueArgs SVN_REPOSITORY)
+ set(multiValueArgs "")
+
+ cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ unset(srcDirSuffix)
+ unset(svnRepoArgs)
+ if(ARG_SVN_REPOSITORY)
+ # Add a hash of the svn repository URL to the source dir. This works
+ # around the problem where if the URL changes, the download would
+ # fail because it tries to checkout/update rather than switch the
+ # old URL to the new one. We limit the hash to the first 7 characters
+ # so that the source path doesn't get overly long (which can be a
+ # problem on windows due to path length limits).
+ string(SHA1 urlSHA ${ARG_SVN_REPOSITORY})
+ string(SUBSTRING ${urlSHA} 0 7 urlSHA)
+ set(srcDirSuffix "-${urlSHA}")
+ set(svnRepoArgs SVN_REPOSITORY ${ARG_SVN_REPOSITORY})
+ endif()
+
+ string(TOLOWER ${contentName} contentNameLower)
+ __FetchContent_declareDetails(
+ ${contentNameLower}
+ SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src${srcDirSuffix}"
+ BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build"
+ ${svnRepoArgs}
+ # List these last so they can override things we set above
+ ${ARG_UNPARSED_ARGUMENTS}
+ )
+
+endfunction()
+
+
+#=======================================================================
+# Set/get whether the specified content has been populated yet.
+# The setter also records the source and binary dirs used.
+#=======================================================================
+
+# Internal use, projects must not call this directly. It is
+# intended for use by the FetchContent_Populate() function to
+# record when FetchContent_Populate() is called for a particular
+# content name.
+function(__FetchContent_setPopulated contentName sourceDir binaryDir)
+
+ string(TOLOWER ${contentName} contentNameLower)
+ set(prefix "_FetchContent_${contentNameLower}")
+
+ set(propertyName "${prefix}_sourceDir")
+ define_property(GLOBAL PROPERTY ${propertyName}
+ BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
+ FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
+ )
+ set_property(GLOBAL PROPERTY ${propertyName} ${sourceDir})
+
+ set(propertyName "${prefix}_binaryDir")
+ define_property(GLOBAL PROPERTY ${propertyName}
+ BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
+ FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
+ )
+ set_property(GLOBAL PROPERTY ${propertyName} ${binaryDir})
+
+ set(propertyName "${prefix}_populated")
+ define_property(GLOBAL PROPERTY ${propertyName}
+ BRIEF_DOCS "Internal implementation detail of FetchContent_Populate()"
+ FULL_DOCS "Details used by FetchContent_Populate() for ${contentName}"
+ )
+ set_property(GLOBAL PROPERTY ${propertyName} True)
+
+endfunction()
+
+
+# Set variables in the calling scope for any of the retrievable
+# properties. If no specific properties are requested, variables
+# will be set for all retrievable properties.
+#
+# This function is intended to also be used by projects as the canonical
+# way to detect whether they should call FetchContent_Populate()
+# and pull the populated source into the build with add_subdirectory(),
+# if they are using the populated content in that way.
+function(FetchContent_GetProperties contentName)
+
+ string(TOLOWER ${contentName} contentNameLower)
+
+ set(options "")
+ set(oneValueArgs SOURCE_DIR BINARY_DIR POPULATED)
+ set(multiValueArgs "")
+
+ cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ if(NOT ARG_SOURCE_DIR AND
+ NOT ARG_BINARY_DIR AND
+ NOT ARG_POPULATED)
+ # No specific properties requested, provide them all
+ set(ARG_SOURCE_DIR ${contentNameLower}_SOURCE_DIR)
+ set(ARG_BINARY_DIR ${contentNameLower}_BINARY_DIR)
+ set(ARG_POPULATED ${contentNameLower}_POPULATED)
+ endif()
+
+ set(prefix "_FetchContent_${contentNameLower}")
+
+ if(ARG_SOURCE_DIR)
+ set(propertyName "${prefix}_sourceDir")
+ get_property(value GLOBAL PROPERTY ${propertyName})
+ if(value)
+ set(${ARG_SOURCE_DIR} ${value} PARENT_SCOPE)
+ endif()
+ endif()
+
+ if(ARG_BINARY_DIR)
+ set(propertyName "${prefix}_binaryDir")
+ get_property(value GLOBAL PROPERTY ${propertyName})
+ if(value)
+ set(${ARG_BINARY_DIR} ${value} PARENT_SCOPE)
+ endif()
+ endif()
+
+ if(ARG_POPULATED)
+ set(propertyName "${prefix}_populated")
+ get_property(value GLOBAL PROPERTY ${propertyName} DEFINED)
+ set(${ARG_POPULATED} ${value} PARENT_SCOPE)
+ endif()
+
+endfunction()
+
+
+#=======================================================================
+# Performing the population
+#=======================================================================
+
+# The value of contentName will always have been lowercased by the caller.
+# All other arguments are assumed to be options that are understood by
+# ExternalProject_Add(), except for QUIET and SUBBUILD_DIR.
+function(__FetchContent_directPopulate contentName)
+
+ set(options
+ QUIET
+ )
+ set(oneValueArgs
+ SUBBUILD_DIR
+ SOURCE_DIR
+ BINARY_DIR
+ # Prevent the following from being passed through
+ CONFIGURE_COMMAND
+ BUILD_COMMAND
+ INSTALL_COMMAND
+ TEST_COMMAND
+ # We force both of these to be ON since we are always executing serially
+ # and we want all steps to have access to the terminal in case they
+ # need input from the command line (e.g. ask for a private key password)
+ # or they want to provide timely progress. We silently absorb and
+ # discard these if they are set by the caller.
+ USES_TERMINAL_DOWNLOAD
+ USES_TERMINAL_UPDATE
+ )
+ set(multiValueArgs "")
+
+ cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ if(NOT ARG_SUBBUILD_DIR)
+ message(FATAL_ERROR "Internal error: SUBBUILD_DIR not set")
+ elseif(NOT IS_ABSOLUTE "${ARG_SUBBUILD_DIR}")
+ set(ARG_SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SUBBUILD_DIR}")
+ endif()
+
+ if(NOT ARG_SOURCE_DIR)
+ message(FATAL_ERROR "Internal error: SOURCE_DIR not set")
+ elseif(NOT IS_ABSOLUTE "${ARG_SOURCE_DIR}")
+ set(ARG_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SOURCE_DIR}")
+ endif()
+
+ if(NOT ARG_BINARY_DIR)
+ message(FATAL_ERROR "Internal error: BINARY_DIR not set")
+ elseif(NOT IS_ABSOLUTE "${ARG_BINARY_DIR}")
+ set(ARG_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_BINARY_DIR}")
+ endif()
+
+ # Ensure the caller can know where to find the source and build directories
+ # with some convenient variables. Doing this here ensures the caller sees
+ # the correct result in the case where the default values are overridden by
+ # the content details set by the project.
+ set(${contentName}_SOURCE_DIR "${ARG_SOURCE_DIR}" PARENT_SCOPE)
+ set(${contentName}_BINARY_DIR "${ARG_BINARY_DIR}" PARENT_SCOPE)
+
+ # The unparsed arguments may contain spaces, so build up ARG_EXTRA
+ # in such a way that it correctly substitutes into the generated
+ # CMakeLists.txt file with each argument quoted.
+ unset(ARG_EXTRA)
+ foreach(arg IN LISTS ARG_UNPARSED_ARGUMENTS)
+ set(ARG_EXTRA "${ARG_EXTRA} \"${arg}\"")
+ endforeach()
+
+ # Hide output if requested, but save it to a variable in case there's an
+ # error so we can show the output upon failure. When not quiet, don't
+ # capture the output to a variable because the user may want to see the
+ # output as it happens (e.g. progress during long downloads). Combine both
+ # stdout and stderr in the one capture variable so the output stays in order.
+ if (ARG_QUIET)
+ set(outputOptions
+ OUTPUT_VARIABLE capturedOutput
+ ERROR_VARIABLE capturedOutput
+ )
+ else()
+ set(capturedOutput)
+ set(outputOptions)
+ message(STATUS "Populating ${contentName}")
+ endif()
+
+ if(CMAKE_GENERATOR)
+ set(generatorOpts "-G${CMAKE_GENERATOR}")
+ if(CMAKE_GENERATOR_PLATFORM)
+ list(APPEND generatorOpts "-A${CMAKE_GENERATOR_PLATFORM}")
+ endif()
+ if(CMAKE_GENERATOR_TOOLSET)
+ list(APPEND generatorOpts "-T${CMAKE_GENERATOR_TOOLSET}")
+ endif()
+
+ if(CMAKE_MAKE_PROGRAM)
+ list(APPEND generatorOpts "-DCMAKE_MAKE_PROGRAM:FILEPATH=${CMAKE_MAKE_PROGRAM}")
+ endif()
+
+ else()
+ # Likely we've been invoked via CMake's script mode where no
+ # generator is set (and hence CMAKE_MAKE_PROGRAM could not be
+ # trusted even if provided). We will have to rely on being
+ # able to find the default generator and build tool.
+ unset(generatorOpts)
+ endif()
+
+ # Create and build a separate CMake project to carry out the population.
+ # If we've already previously done these steps, they will not cause
+ # anything to be updated, so extra rebuilds of the project won't occur.
+ # Make sure to pass through CMAKE_MAKE_PROGRAM in case the main project
+ # has this set to something not findable on the PATH.
+ configure_file("${__FetchContent_privateDir}/CMakeLists.cmake.in"
+ "${ARG_SUBBUILD_DIR}/CMakeLists.txt")
+ execute_process(
+ COMMAND ${CMAKE_COMMAND} ${generatorOpts} .
+ RESULT_VARIABLE result
+ ${outputOptions}
+ WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
+ )
+ if(result)
+ if(capturedOutput)
+ message("${capturedOutput}")
+ endif()
+ message(FATAL_ERROR "CMake step for ${contentName} failed: ${result}")
+ endif()
+ execute_process(
+ COMMAND ${CMAKE_COMMAND} --build .
+ RESULT_VARIABLE result
+ ${outputOptions}
+ WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
+ )
+ if(result)
+ if(capturedOutput)
+ message("${capturedOutput}")
+ endif()
+ message(FATAL_ERROR "Build step for ${contentName} failed: ${result}")
+ endif()
+
+endfunction()
+
+
+option(FETCHCONTENT_FULLY_DISCONNECTED "Disables all attempts to download or update content and assumes source dirs already exist")
+option(FETCHCONTENT_UPDATES_DISCONNECTED "Enables UPDATE_DISCONNECTED behavior for all content population")
+option(FETCHCONTENT_QUIET "Enables QUIET option for all content population" ON)
+set(FETCHCONTENT_BASE_DIR "${CMAKE_BINARY_DIR}/_deps" CACHE PATH "Directory under which to collect all populated content")
+
+# Populate the specified content using details stored from
+# an earlier call to FetchContent_Declare().
+function(FetchContent_Populate contentName)
+
+ if(NOT contentName)
+ message(FATAL_ERROR "Empty contentName not allowed for FetchContent_Populate()")
+ endif()
+
+ string(TOLOWER ${contentName} contentNameLower)
+
+ if(ARGN)
+ # This is the direct population form with details fully specified
+ # as part of the call, so we already have everything we need
+ __FetchContent_directPopulate(
+ ${contentNameLower}
+ SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-subbuild"
+ SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-src"
+ BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-build"
+ ${ARGN} # Could override any of the above ..._DIR variables
+ )
+
+ # Pass source and binary dir variables back to the caller
+ set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
+ set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
+
+ # Don't set global properties, or record that we did this population, since
+ # this was a direct call outside of the normal declared details form.
+ # We only want to save values in the global properties for content that
+ # honours the hierarchical details mechanism so that projects are not
+ # robbed of the ability to override details set in nested projects.
+ return()
+ endif()
+
+ # No details provided, so assume they were saved from an earlier call
+ # to FetchContent_Declare(). Do a check that we haven't already
+ # populated this content before in case the caller forgot to check.
+ FetchContent_GetProperties(${contentName})
+ if(${contentNameLower}_POPULATED)
+ message(FATAL_ERROR "Content ${contentName} already populated in ${${contentNameLower}_SOURCE_DIR}")
+ endif()
+
+ string(TOUPPER ${contentName} contentNameUpper)
+ set(FETCHCONTENT_SOURCE_DIR_${contentNameUpper}
+ "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}"
+ CACHE PATH "When not empty, overrides where to find pre-populated content for ${contentName}")
+
+ if(FETCHCONTENT_SOURCE_DIR_${contentNameUpper})
+ # The source directory has been explicitly provided in the cache,
+ # so no population is required
+ set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
+ set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
+
+ elseif(FETCHCONTENT_FULLY_DISCONNECTED)
+ # Bypass population and assume source is already there from a previous run
+ set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src")
+ set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
+
+ else()
+ # Support both a global "disconnect all updates" and a per-content
+ # update test (either one being set disables updates for this content).
+ option(FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper}
+ "Enables UPDATE_DISCONNECTED behavior just for population of ${contentName}")
+ if(FETCHCONTENT_UPDATES_DISCONNECTED OR
+ FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper})
+ set(disconnectUpdates True)
+ else()
+ set(disconnectUpdates False)
+ endif()
+
+ if(FETCHCONTENT_QUIET)
+ set(quietFlag QUIET)
+ else()
+ unset(quietFlag)
+ endif()
+
+ __FetchContent_getSavedDetails(${contentName} contentDetails)
+ if("${contentDetails}" STREQUAL "")
+ message(FATAL_ERROR "No details have been set for content: ${contentName}")
+ endif()
+
+ __FetchContent_directPopulate(
+ ${contentNameLower}
+ ${quietFlag}
+ UPDATE_DISCONNECTED ${disconnectUpdates}
+ SUBBUILD_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-subbuild"
+ SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src"
+ BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build"
+ # Put the saved details last so they can override any of the
+ # the options we set above (this can include SOURCE_DIR or
+ # BUILD_DIR)
+ ${contentDetails}
+ )
+ endif()
+
+ __FetchContent_setPopulated(
+ ${contentName}
+ ${${contentNameLower}_SOURCE_DIR}
+ ${${contentNameLower}_BINARY_DIR}
+ )
+
+ # Pass variables back to the caller. The variables passed back here
+ # must match what FetchContent_GetProperties() sets when it is called
+ # with just the content name.
+ set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
+ set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
+ set(${contentNameLower}_POPULATED True PARENT_SCOPE)
+
+endfunction()
+
+# Arguments are assumed to be the names of dependencies that have been
+# declared previously and should be populated. It is not an error if
+# any of them have already been populated (they will just be skipped in
+# that case). The command is implemented as a macro so that the variables
+# defined by the FetchContent_GetProperties() and FetchContent_Populate()
+# calls will be available to the caller.
+macro(FetchContent_MakeAvailable)
+
+ foreach(contentName IN ITEMS ${ARGV})
+ string(TOLOWER ${contentName} contentNameLower)
+ FetchContent_GetProperties(${contentName})
+ if(NOT ${contentNameLower}_POPULATED)
+ FetchContent_Populate(${contentName})
+
+ # Only try to call add_subdirectory() if the populated content
+ # can be treated that way. Protecting the call with the check
+ # allows this function to be used for projects that just want
+ # to ensure the content exists, such as to provide content at
+ # a known location.
+ if(EXISTS ${${contentNameLower}_SOURCE_DIR}/CMakeLists.txt)
+ add_subdirectory(${${contentNameLower}_SOURCE_DIR}
+ ${${contentNameLower}_BINARY_DIR})
+ endif()
+ endif()
+ endforeach()
+
+endmacro()
diff --git a/Modules/FetchContent/CMakeLists.cmake.in b/Modules/FetchContent/CMakeLists.cmake.in
new file mode 100644
index 000000000..0095b111b
--- /dev/null
+++ b/Modules/FetchContent/CMakeLists.cmake.in
@@ -0,0 +1,23 @@
+# 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 ${CMAKE_VERSION})
+
+# We name the project and the target for the ExternalProject_Add() call
+# to something that will highlight to the user what we are working on if
+# something goes wrong and an error message is produced.
+
+project(${contentName}-populate NONE)
+
+include(ExternalProject)
+ExternalProject_Add(${contentName}-populate
+ ${ARG_EXTRA}
+ SOURCE_DIR "${ARG_SOURCE_DIR}"
+ BINARY_DIR "${ARG_BINARY_DIR}"
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND ""
+ INSTALL_COMMAND ""
+ TEST_COMMAND ""
+ USES_TERMINAL_DOWNLOAD YES
+ USES_TERMINAL_UPDATE YES
+)
diff --git a/Modules/FindEnvModules.cmake b/Modules/FindEnvModules.cmake
new file mode 100644
index 000000000..4dd5116cd
--- /dev/null
+++ b/Modules/FindEnvModules.cmake
@@ -0,0 +1,333 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindEnvModules
+--------------
+
+Locate an environment module implementation and make commands available to
+CMake scripts to use them. This is compatible with both Lua-based Lmod
+and TCL-based EnvironmentModules.
+
+This module is intended for the use case of setting up the compiler and library
+environment within a :ref:`CTest Script <CTest Script>` (``ctest -S``). It can
+also be used in a :ref:`CMake Script <Script Processing Mode>` (``cmake -P``).
+
+.. note::
+
+ The loaded environment will not survive past the end of the calling process.
+ Do not use this module in project code (``CMakeLists.txt`` files) to load
+ a compiler environment; it will not be available during the build. Instead
+ load the environment manually before running CMake or using the generated
+ build system.
+
+Example Usage
+^^^^^^^^^^^^^
+
+.. code-block:: cmake
+
+ set(CTEST_BUILD_NAME "CrayLinux-CrayPE-Cray-dynamic")
+ set(CTEST_BUILD_CONFIGURATION Release)
+ set(CTEST_BUILD_FLAGS "-k -j8")
+ set(CTEST_CMAKE_GENERATOR "Unix Makefiles")
+
+ ...
+
+ find_package(EnvModules REQUIRED)
+
+ env_module(purge)
+ env_module(load modules)
+ env_module(load craype)
+ env_module(load PrgEnv-cray)
+ env_module(load craype-knl)
+ env_module(load cray-mpich)
+ env_module(load cray-libsci)
+
+ set(ENV{CRAYPE_LINK_TYPE} dynamic)
+
+ ...
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This module will set the following variables in your project:
+
+``EnvModules_FOUND``
+ True if a compatible environment modules framework was found.
+
+Cache Variables
+^^^^^^^^^^^^^^^
+
+The following cache variable will be set:
+
+``EnvModules_COMMAND``
+ The low level module command to use. Currently supported
+ implementations are the Lua based Lmod and TCL based EnvironmentModules.
+
+Environment Variables
+^^^^^^^^^^^^^^^^^^^^^
+
+``ENV{MODULESHOME}``
+ Usually set by the module environment implementation, used as a hint to
+ locate the module command to execute.
+
+Provided Functions
+^^^^^^^^^^^^^^^^^^
+
+This defines the following CMake functions for interacting with environment
+modules:
+
+.. command:: env_module
+
+ Execute an aribitrary module command:
+
+ .. code-block:: cmake
+
+ env_module(cmd arg1 ... argN)
+ env_module(
+ COMMAND cmd arg1 ... argN
+ [OUTPUT_VARIABLE <out-var>]
+ [RESULT_VARIABLE <ret-var>]
+ )
+
+ The options are:
+
+ ``cmd arg1 ... argN``
+ The module sub-command and arguments to execute as if they were
+ passed directly to the module command in your shell environment.
+
+ ``OUTPUT_VARIABLE <out-var>``
+ The standard output from executing the module command.
+
+ ``RESULT_VARIABLE <ret-var>``
+ The return code from executing the module command.
+
+.. command:: env_module_swap
+
+ Swap one module for another:
+
+ .. code-block:: cmake
+
+ env_module_swap(out_mod in_mod
+ [OUTPUT_VARIABLE <out-var>]
+ [RESULT_VARIABLE <ret-var>]
+ )
+
+ This is functionally equivalent to the ``module swap out_mod in_mod`` shell
+ command. The options are:
+
+ ``OUTPUT_VARIABLE <out-var>``
+ The standard output from executing the module command.
+
+ ``RESULT_VARIABLE <ret-var>``
+ The return code from executing the module command.
+
+.. command:: env_module_list
+
+ Retrieve the list of currently loaded modules:
+
+ .. code-block:: cmake
+
+ env_module_list(<out-var>)
+
+ This is functionally equivalent to the ``module list`` shell command.
+ The result is stored in ``<out-var>`` as a properly formatted CMake
+ :ref:`semicolon-separated list <CMake Language Lists>` variable.
+
+.. command:: env_module_avail
+
+ Retrieve the list of available modules:
+
+ .. code-block:: cmake
+
+ env_module_avail([<mod-prefix>] <out-var>)
+
+ This is functionally equivalent to the ``module avail <mod-prefix>`` shell
+ command. The result is stored in ``<out-var>`` as a properly formatted
+ CMake :ref:`semicolon-separated list <CMake Language Lists>` variable.
+
+#]=======================================================================]
+
+function(env_module)
+ if(NOT EnvModules_COMMAND)
+ message(FATAL_ERROR "Failed to process module command. EnvModules_COMMAND not found")
+ return()
+ endif()
+
+ set(options)
+ set(oneValueArgs OUTPUT_VARIABLE RESULT_VARIABLE)
+ set(multiValueArgs COMMAND)
+ cmake_parse_arguments(MOD_ARGS
+ "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGV}
+ )
+ if(NOT MOD_ARGS_COMMAND)
+ # If no explicit command argument was given, then treat the calling syntax
+ # as: module(cmd args...)
+ set(exec_cmd ${ARGV})
+ else()
+ set(exec_cmd ${MOD_ARGS_COMMAND})
+ endif()
+
+ if(MOD_ARGS_OUTPUT_VARIABLE)
+ set(err_var_args ERROR_VARIABLE err_var)
+ endif()
+
+ execute_process(
+ COMMAND mktemp -t module.cmake.XXXXXXXXXXXX
+ OUTPUT_VARIABLE tempfile_name
+ )
+ string(STRIP "${tempfile_name}" tempfile_name)
+
+ # If the $MODULESHOME/init/cmake file exists then assume that the CMake
+ # "shell" functionality exits
+ if(EXISTS "$ENV{MODULESHOME}/init/cmake")
+ execute_process(
+ COMMAND ${EnvModules_COMMAND} cmake ${exec_cmd}
+ OUTPUT_FILE ${tempfile_name}
+ ${err_var_args}
+ RESULT_VARIABLE ret_var
+ )
+
+ else() # fallback to the sh shell and manually convert to CMake
+ execute_process(
+ COMMAND ${EnvModules_COMMAND} sh ${exec_cmd}
+ OUTPUT_VARIABLE out_var
+ ${err_var_args}
+ RESULT_VARIABLE ret_var
+ )
+ endif()
+
+ # If we executed successfully then process and cleanup the temp file
+ if(ret_var EQUAL 0)
+ # No CMake shell so we need to process the sh output into CMake code
+ if(NOT EXISTS "$ENV{MODULESHOME}/init/cmake")
+ file(WRITE ${tempfile_name} "")
+ string(REPLACE "\n" ";" out_var "${out_var}")
+ foreach(sh_cmd IN LISTS out_var)
+ if(sh_cmd MATCHES "^ *unset *([^ ]*)")
+ set(cmake_cmd "unset(ENV{${CMAKE_MATCH_1}})")
+ elseif(sh_cmd MATCHES "^ *export *([^ ]*)")
+ set(cmake_cmd "set(ENV{${CMAKE_MATCH_1}} \"\${${CMAKE_MATCH_1}}\")")
+ elseif(sh_cmd MATCHES " *([^ =]*) *= *(.*)")
+ set(var_name "${CMAKE_MATCH_1}")
+ set(var_value "${CMAKE_MATCH_2}")
+ if(var_value MATCHES "^\"(.*[^\\])\"")
+ # If it's in quotes, take the value as is
+ set(var_value "${CMAKE_MATCH_1}")
+ else()
+ # Otherwise, strip trailing spaces
+ string(REGEX REPLACE "([^\\])? +$" "\\1" var_value "${var_value}")
+ endif()
+ string(REPLACE "\\ " " " var_value "${var_value}")
+ set(cmake_cmd "set(${var_name} \"${var_value}\")")
+ else()
+ continue()
+ endif()
+ file(APPEND ${tempfile_name} "${cmake_cmd}\n")
+ endforeach()
+ endif()
+
+ # Process the change in environment variables
+ include(${tempfile_name})
+ file(REMOVE ${tempfile_name})
+ endif()
+
+ # Push the output back out to the calling scope
+ if(MOD_ARGS_OUTPUT_VARIABLE)
+ set(${MOD_ARGS_OUTPUT_VARIABLE} "${err_var}" PARENT_SCOPE)
+ endif()
+ if(MOD_ARGS_RESULT_VARIABLE)
+ set(${MOD_ARGS_RESULT_VARIABLE} ${ret_var} PARENT_SCOPE)
+ endif()
+endfunction(env_module)
+
+#------------------------------------------------------------------------------
+function(env_module_swap out_mod in_mod)
+ set(options)
+ set(oneValueArgs OUTPUT_VARIABLE RESULT_VARIABLE)
+ set(multiValueArgs)
+
+ cmake_parse_arguments(MOD_ARGS
+ "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGV}
+ )
+
+ env_module(COMMAND -t swap ${out_mod} ${in_mod}
+ OUTPUT_VARIABLE tmp_out
+ RETURN_VARIABLE tmp_ret
+ )
+
+ if(MOD_ARGS_OUTPUT_VARIABLE)
+ set(${MOD_ARGS_OUTPUT_VARIABLE} "${err_var}" PARENT_SCOPE)
+ endif()
+ if(MOD_ARGS_RESULT_VARIABLE)
+ set(${MOD_ARGS_RESULT_VARIABLE} ${tmp_ret} PARENT_SCOPE)
+ endif()
+endfunction()
+
+#------------------------------------------------------------------------------
+function(env_module_list out_var)
+ cmake_policy(SET CMP0007 NEW)
+ env_module(COMMAND -t list OUTPUT_VARIABLE tmp_out)
+
+ # Convert output into a CMake list
+ string(REPLACE "\n" ";" ${out_var} "${tmp_out}")
+
+ # Remove title headers and empty entries
+ list(REMOVE_ITEM ${out_var} "No modules loaded")
+ if(${out_var})
+ list(FILTER ${out_var} EXCLUDE REGEX "^(.*:)?$")
+ endif()
+ list(FILTER ${out_var} EXCLUDE REGEX "^(.*:)?$")
+
+ set(${out_var} ${${out_var}} PARENT_SCOPE)
+endfunction()
+
+#------------------------------------------------------------------------------
+function(env_module_avail)
+ cmake_policy(SET CMP0007 NEW)
+
+ if(ARGC EQUAL 1)
+ set(mod_prefix)
+ set(out_var ${ARGV0})
+ elseif(ARGC EQUAL 2)
+ set(mod_prefix ${ARGV0})
+ set(out_var ${ARGV1})
+ else()
+ message(FATAL_ERROR "Usage: env_module_avail([mod_prefix] out_var)")
+ endif()
+ env_module(COMMAND -t avail ${mod_prefix} OUTPUT_VARIABLE tmp_out)
+
+ # Convert output into a CMake list
+ string(REPLACE "\n" ";" tmp_out "${tmp_out}")
+
+ set(${out_var})
+ foreach(MOD IN LISTS tmp_out)
+ # Remove directory entries and empty values
+ if(MOD MATCHES "^(.*:)?$")
+ continue()
+ endif()
+
+ # Convert default modules
+ if(MOD MATCHES "^(.*)/$" ) # "foo/"
+ list(APPEND ${out_var} ${CMAKE_MATCH_1})
+ elseif(MOD MATCHES "^((.*)/.*)\\(default\\)$") # "foo/1.2.3(default)"
+ list(APPEND ${out_var} ${CMAKE_MATCH_2})
+ list(APPEND ${out_var} ${CMAKE_MATCH_1})
+ else()
+ list(APPEND ${out_var} ${MOD})
+ endif()
+ endforeach()
+
+ set(${out_var} ${${out_var}} PARENT_SCOPE)
+endfunction()
+
+#------------------------------------------------------------------------------
+# Make sure we know where the underlying module command is
+find_program(EnvModules_COMMAND
+ NAMES lmod modulecmd
+ HINTS ENV MODULESHOME
+ PATH_SUFFIXES libexec
+)
+
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
+find_package_handle_standard_args(EnvModules DEFAULT_MSG EnvModules_COMMAND)
diff --git a/Modules/FindFontconfig.cmake b/Modules/FindFontconfig.cmake
new file mode 100644
index 000000000..a6f0180b3
--- /dev/null
+++ b/Modules/FindFontconfig.cmake
@@ -0,0 +1,101 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindFontconfig
+--------------
+
+Find Fontconfig headers and library.
+
+Imported Targets
+^^^^^^^^^^^^^^^^
+
+``Fontconfig::Fontconfig``
+ The Fontconfig library, if found.
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This will define the following variables in your project:
+
+``Fontconfig_FOUND``
+ true if (the requested version of) Fontconfig is available.
+``Fontconfig_VERSION``
+ the version of Fontconfig.
+``Fontconfig_LIBRARIES``
+ the libraries to link against to use Fontconfig.
+``Fontconfig_INCLUDE_DIRS``
+ where to find the Fontconfig headers.
+``Fontconfig_COMPILE_OPTIONS``
+ this should be passed to target_compile_options(), if the
+ target is not used for linking
+
+#]=======================================================================]
+
+
+# use pkg-config to get the directories and then use these values
+# in the FIND_PATH() and FIND_LIBRARY() calls
+find_package(PkgConfig QUIET)
+pkg_check_modules(PKG_FONTCONFIG QUIET fontconfig)
+set(Fontconfig_COMPILE_OPTIONS ${PKG_FONTCONFIG_CFLAGS_OTHER})
+set(Fontconfig_VERSION ${PKG_FONTCONFIG_VERSION})
+
+find_path( Fontconfig_INCLUDE_DIR
+ NAMES
+ fontconfig/fontconfig.h
+ HINTS
+ ${PKG_FONTCONFIG_INCLUDE_DIRS}
+ /usr/X11/include
+)
+
+find_library( Fontconfig_LIBRARY
+ NAMES
+ fontconfig
+ PATHS
+ ${PKG_FONTCONFIG_LIBRARY_DIRS}
+)
+
+if (Fontconfig_INCLUDE_DIR AND NOT Fontconfig_VERSION)
+ file(STRINGS ${Fontconfig_INCLUDE_DIR}/fontconfig/fontconfig.h _contents REGEX "^#define[ \t]+FC_[A-Z]+[ \t]+[0-9]+$")
+ unset(Fontconfig_VERSION)
+ foreach(VPART MAJOR MINOR REVISION)
+ foreach(VLINE ${_contents})
+ if(VLINE MATCHES "^#define[\t ]+FC_${VPART}[\t ]+([0-9]+)$")
+ set(Fontconfig_VERSION_PART "${CMAKE_MATCH_1}")
+ if(Fontconfig_VERSION)
+ string(APPEND Fontconfig_VERSION ".${Fontconfig_VERSION_PART}")
+ else()
+ set(Fontconfig_VERSION "${Fontconfig_VERSION_PART}")
+ endif()
+ endif()
+ endforeach()
+ endforeach()
+endif ()
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(Fontconfig
+ FOUND_VAR
+ Fontconfig_FOUND
+ REQUIRED_VARS
+ Fontconfig_LIBRARY
+ Fontconfig_INCLUDE_DIR
+ VERSION_VAR
+ Fontconfig_VERSION
+)
+
+
+if(Fontconfig_FOUND AND NOT TARGET Fontconfig::Fontconfig)
+ add_library(Fontconfig::Fontconfig UNKNOWN IMPORTED)
+ set_target_properties(Fontconfig::Fontconfig PROPERTIES
+ IMPORTED_LOCATION "${Fontconfig_LIBRARY}"
+ INTERFACE_COMPILE_OPTIONS "${Fontconfig_COMPILE_OPTIONS}"
+ INTERFACE_INCLUDE_DIRECTORIES "${Fontconfig_INCLUDE_DIR}"
+ )
+endif()
+
+mark_as_advanced(Fontconfig_LIBRARY Fontconfig_INCLUDE_DIR)
+
+if(Fontconfig_FOUND)
+ set(Fontconfig_LIBRARIES ${Fontconfig_LIBRARY})
+ set(Fontconfig_INCLUDE_DIRS ${Fontconfig_INCLUDE_DIR})
+endif()
diff --git a/Modules/FindIconv.cmake b/Modules/FindIconv.cmake
new file mode 100644
index 000000000..bf20f6f7e
--- /dev/null
+++ b/Modules/FindIconv.cmake
@@ -0,0 +1,133 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindIconv
+---------
+
+This module finds the ``iconv()`` POSIX.1 functions on the system.
+These functions might be provided in the regular C library or externally
+in the form of an additional library.
+
+The following variables are provided to indicate iconv support:
+
+.. variable:: Iconv_FOUND
+
+ Variable indicating if the iconv support was found.
+
+.. variable:: Iconv_INCLUDE_DIRS
+
+ The directories containing the iconv headers.
+
+.. variable:: Iconv_LIBRARIES
+
+ The iconv libraries to be linked.
+
+.. variable:: Iconv_IS_BUILT_IN
+
+ A variable indicating whether iconv support is stemming from the
+ C library or not. Even if the C library provides `iconv()`, the presence of
+ an external `libiconv` implementation might lead to this being false.
+
+Additionally, the following :prop_tgt:`IMPORTED` target is being provided:
+
+.. variable:: Iconv::Iconv
+
+ Imported target for using iconv.
+
+The following cache variables may also be set:
+
+.. variable:: Iconv_INCLUDE_DIR
+
+ The directory containing the iconv headers.
+
+.. variable:: Iconv_LIBRARY
+
+ The iconv library (if not implicitly given in the C library).
+
+.. note::
+ On POSIX platforms, iconv might be part of the C library and the cache
+ variables ``Iconv_INCLUDE_DIR`` and ``Iconv_LIBRARY`` might be empty.
+
+#]=======================================================================]
+
+include(${CMAKE_CURRENT_LIST_DIR}/CMakePushCheckState.cmake)
+if(CMAKE_C_COMPILER_LOADED)
+ include(${CMAKE_CURRENT_LIST_DIR}/CheckCSourceCompiles.cmake)
+elseif(CMAKE_CXX_COMPILER_LOADED)
+ include(${CMAKE_CURRENT_LIST_DIR}/CheckCXXSourceCompiles.cmake)
+else()
+ # If neither C nor CXX are loaded, implicit iconv makes no sense.
+ set(Iconv_IS_BUILT_IN FALSE)
+endif()
+
+# iconv can only be provided in libc on a POSIX system.
+# If any cache variable is already set, we'll skip this test.
+if(NOT DEFINED Iconv_IS_BUILT_IN)
+ if(UNIX AND NOT DEFINED Iconv_INCLUDE_DIR AND NOT DEFINED Iconv_LIBRARY)
+ cmake_push_check_state(RESET)
+ # We always suppress the message here: Otherwise on supported systems
+ # not having iconv in their C library (e.g. those using libiconv)
+ # would always display a confusing "Looking for iconv - not found" message
+ set(CMAKE_FIND_QUIETLY TRUE)
+ # The following code will not work, but it's sufficient to see if it compiles.
+ # Note: libiconv will define the iconv functions as macros, so CheckSymbolExists
+ # will not yield correct results.
+ set(Iconv_IMPLICIT_TEST_CODE
+ "
+ #include <stddef.h>
+ #include <iconv.h>
+ int main() {
+ char *a, *b;
+ size_t i, j;
+ iconv_t ic;
+ ic = iconv_open(\"to\", \"from\");
+ iconv(ic, &a, &i, &b, &j);
+ iconv_close(ic);
+ }
+ "
+ )
+ if(CMAKE_C_COMPILER_LOADED)
+ check_c_source_compiles("${Iconv_IMPLICIT_TEST_CODE}" Iconv_IS_BUILT_IN)
+ else()
+ check_cxx_source_compiles("${Iconv_IMPLICIT_TEST_CODE}" Iconv_IS_BUILT_IN)
+ endif()
+ cmake_pop_check_state()
+ else()
+ set(Iconv_IS_BUILT_IN FALSE)
+ endif()
+endif()
+
+if(NOT Iconv_IS_BUILT_IN)
+ find_path(Iconv_INCLUDE_DIR
+ NAMES "iconv.h"
+ DOC "iconv include directory")
+ set(Iconv_LIBRARY_NAMES "iconv" "libiconv")
+else()
+ set(Iconv_INCLUDE_DIR "" CACHE FILEPATH "iconv include directory")
+ set(Iconv_LIBRARY_NAMES "c")
+endif()
+
+find_library(Iconv_LIBRARY
+ NAMES ${Iconv_LIBRARY_NAMES}
+ DOC "iconv library (potentially the C library)")
+
+mark_as_advanced(Iconv_INCLUDE_DIR)
+mark_as_advanced(Iconv_LIBRARY)
+
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
+if(NOT Iconv_IS_BUILT_IN)
+ find_package_handle_standard_args(Iconv REQUIRED_VARS Iconv_LIBRARY Iconv_INCLUDE_DIR)
+else()
+ find_package_handle_standard_args(Iconv REQUIRED_VARS Iconv_LIBRARY)
+endif()
+
+if(Iconv_FOUND)
+ set(Iconv_INCLUDE_DIRS "${Iconv_INCLUDE_DIR}")
+ set(Iconv_LIBRARIES "${Iconv_LIBRARY}")
+ if(NOT TARGET Iconv::Iconv)
+ add_library(Iconv::Iconv INTERFACE IMPORTED)
+ endif()
+ set_property(TARGET Iconv::Iconv PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${Iconv_INCLUDE_DIRS}")
+ set_property(TARGET Iconv::Iconv PROPERTY INTERFACE_LINK_LIBRARIES "${Iconv_LIBRARIES}")
+endif()
diff --git a/Modules/FindLibinput.cmake b/Modules/FindLibinput.cmake
new file mode 100644
index 000000000..c1fe45562
--- /dev/null
+++ b/Modules/FindLibinput.cmake
@@ -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.
+
+#[=======================================================================[.rst:
+FindLibinput
+------------
+
+Find libinput headers and library.
+
+Imported Targets
+^^^^^^^^^^^^^^^^
+
+``Libinput::Libinput``
+ The libinput library, if found.
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This will define the following variables in your project:
+
+``Libinput_FOUND``
+ true if (the requested version of) libinput is available.
+``Libinput_VERSION``
+ the version of libinput.
+``Libinput_LIBRARIES``
+ the libraries to link against to use libinput.
+``Libinput_INCLUDE_DIRS``
+ where to find the libinput headers.
+``Libinput_COMPILE_OPTIONS``
+ this should be passed to target_compile_options(), if the
+ target is not used for linking
+
+#]=======================================================================]
+
+
+# Use pkg-config to get the directories and then use these values
+# in the FIND_PATH() and FIND_LIBRARY() calls
+find_package(PkgConfig QUIET)
+pkg_check_modules(PKG_Libinput QUIET libinput)
+
+set(Libinput_COMPILE_OPTIONS ${PKG_Libinput_CFLAGS_OTHER})
+set(Libinput_VERSION ${PKG_Libinput_VERSION})
+
+find_path(Libinput_INCLUDE_DIR
+ NAMES
+ libinput.h
+ HINTS
+ ${PKG_Libinput_INCLUDE_DIRS}
+)
+find_library(Libinput_LIBRARY
+ NAMES
+ input
+ HINTS
+ ${PKG_Libinput_LIBRARY_DIRS}
+)
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(Libinput
+ FOUND_VAR
+ Libinput_FOUND
+ REQUIRED_VARS
+ Libinput_LIBRARY
+ Libinput_INCLUDE_DIR
+ VERSION_VAR
+ Libinput_VERSION
+)
+
+if(Libinput_FOUND AND NOT TARGET Libinput::Libinput)
+ add_library(Libinput::Libinput UNKNOWN IMPORTED)
+ set_target_properties(Libinput::Libinput PROPERTIES
+ IMPORTED_LOCATION "${Libinput_LIBRARY}"
+ INTERFACE_COMPILE_OPTIONS "${Libinput_COMPILE_OPTIONS}"
+ INTERFACE_INCLUDE_DIRECTORIES "${Libinput_INCLUDE_DIR}"
+ )
+endif()
+
+mark_as_advanced(Libinput_LIBRARY Libinput_INCLUDE_DIR)
+
+if(Libinput_FOUND)
+ set(Libinput_LIBRARIES ${Libinput_LIBRARY})
+ set(Libinput_INCLUDE_DIRS ${Libinput_INCLUDE_DIR})
+endif()
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..d89328a01
--- /dev/null
+++ b/Modules/FindMPI/libver_mpi.c
@@ -0,0 +1,20 @@
+#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
+ return 0;
+}
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..7c96d54a8
--- /dev/null
+++ b/Modules/FindMPI/test_mpi.c
@@ -0,0 +1,38 @@
+#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
+ return 0;
+}
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/FindODBC.cmake b/Modules/FindODBC.cmake
new file mode 100644
index 000000000..29d7af9e8
--- /dev/null
+++ b/Modules/FindODBC.cmake
@@ -0,0 +1,229 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindODBC
+--------
+
+Find an Open Database Connectivity (ODBC) include directory and library.
+
+On Windows, when building with Visual Studio, this module assumes the ODBC
+library is provided by the available Windows SDK.
+
+On Unix, this module allows to search for ODBC library provided by
+unixODBC or iODBC implementations of ODBC API.
+This module reads hint about location of the config program:
+
+.. variable:: ODBC_CONFIG
+
+ Location of odbc_config or iodbc-config program
+
+Otherwise, this module tries to find the config program,
+first from unixODBC, then from iODBC.
+If no config program found, this module searches for ODBC header
+and library in list of known locations.
+
+Imported targets
+^^^^^^^^^^^^^^^^
+
+This module defines the following :prop_tgt:`IMPORTED` targets:
+
+.. variable:: ODBC::ODBC
+
+ Imported target for using the ODBC library, if found.
+
+Result variables
+^^^^^^^^^^^^^^^^
+
+.. variable:: ODBC_FOUND
+
+ Set to true if ODBC library found, otherwise false or undefined.
+
+.. variable:: ODBC_INCLUDE_DIRS
+
+ Paths to include directories listed in one variable for use by ODBC client.
+ May be empty on Windows, where the include directory corresponding to the
+ expected Windows SDK is already available in the compilation environment.
+
+.. variable:: ODBC_LIBRARIES
+
+ Paths to libraries to linked against to use ODBC.
+ May just a library name on Windows, where the library directory corresponding
+ to the expected Windows SDK is already available in the compilation environment.
+
+.. variable:: ODBC_CONFIG
+
+ Path to unixODBC or iODBC config program, if found or specified.
+
+Cache variables
+^^^^^^^^^^^^^^^
+
+For users who wish to edit and control the module behavior, this module
+reads hints about search locations from the following variables:
+
+.. variable:: ODBC_INCLUDE_DIR
+
+ Path to ODBC include directory with ``sql.h`` header.
+
+.. variable:: ODBC_LIBRARY
+
+ Path to ODBC library to be linked.
+
+These variables should not be used directly by project code.
+
+Limitations
+^^^^^^^^^^^
+
+On Windows, this module does not search for iODBC.
+On Unix, there is no way to prefer unixODBC over iODBC, or vice versa,
+other than providing the config program location using the ``ODBC_CONFIG``.
+This module does not allow to search for a specific ODBC driver.
+
+#]=======================================================================]
+
+# Define lists used internally
+set(_odbc_include_paths)
+set(_odbc_lib_paths)
+set(_odbc_lib_names)
+set(_odbc_required_libs_names)
+
+### Try Windows Kits ##########################################################
+if(WIN32)
+ # List names of ODBC libraries on Windows
+ if(NOT MINGW)
+ set(ODBC_LIBRARY odbc32.lib)
+ endif()
+ set(_odbc_lib_names odbc32;)
+
+ # List additional libraries required to use ODBC library
+ if(MSVC OR CMAKE_CXX_COMPILER_ID MATCHES "Intel")
+ set(_odbc_required_libs_names odbccp32;ws2_32)
+ elseif(MINGW)
+ set(_odbc_required_libs_names odbccp32)
+ endif()
+endif()
+
+### Try unixODBC or iODBC config program ######################################
+if (UNIX)
+ find_program(ODBC_CONFIG
+ NAMES odbc_config iodbc-config
+ DOC "Path to unixODBC or iODBC config program")
+ mark_as_advanced(ODBC_CONFIG)
+endif()
+
+if (UNIX AND ODBC_CONFIG)
+ # unixODBC and iODBC accept unified command line options
+ execute_process(COMMAND ${ODBC_CONFIG} --cflags
+ OUTPUT_VARIABLE _cflags OUTPUT_STRIP_TRAILING_WHITESPACE)
+ execute_process(COMMAND ${ODBC_CONFIG} --libs
+ OUTPUT_VARIABLE _libs OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+ # Collect paths of include directories from CFLAGS
+ separate_arguments(_cflags NATIVE_COMMAND "${_cflags}")
+ foreach(arg IN LISTS _cflags)
+ if("${arg}" MATCHES "^-I(.*)$")
+ list(APPEND _odbc_include_paths "${CMAKE_MATCH_1}")
+ endif()
+ endforeach()
+ unset(_cflags)
+
+ # Collect paths of library names and directories from LIBS
+ separate_arguments(_libs NATIVE_COMMAND "${_libs}")
+ foreach(arg IN LISTS _libs)
+ if("${arg}" MATCHES "^-L(.*)$")
+ list(APPEND _odbc_lib_paths "${CMAKE_MATCH_1}")
+ elseif("${arg}" MATCHES "^-l(.*)$")
+ set(_lib_name ${CMAKE_MATCH_1})
+ string(REGEX MATCH "odbc" _is_odbc ${_lib_name})
+ if(_is_odbc)
+ list(APPEND _odbc_lib_names ${_lib_name})
+ else()
+ list(APPEND _odbc_required_libs_names ${_lib_name})
+ endif()
+ unset(_lib_name)
+ endif()
+ endforeach()
+ unset(_libs)
+endif()
+
+### Try unixODBC or iODBC in include/lib filesystems ##########################
+if (UNIX AND NOT ODBC_CONFIG)
+ # List names of both ODBC libraries, unixODBC and iODBC
+ set(_odbc_lib_names odbc;iodbc;unixodbc;)
+endif()
+
+### Find include directories ##################################################
+find_path(ODBC_INCLUDE_DIR
+ NAMES sql.h
+ PATHS ${_odbc_include_paths})
+
+if(NOT ODBC_INCLUDE_DIR AND WIN32)
+ set(ODBC_INCLUDE_DIR "")
+endif()
+
+### Find libraries ############################################################
+if(NOT ODBC_LIBRARY)
+ find_library(ODBC_LIBRARY
+ NAMES ${_odbc_lib_names}
+ PATHS ${_odbc_lib_paths}
+ PATH_SUFFIXES odbc)
+
+ foreach(_lib IN LISTS _odbc_required_libs_names)
+ find_library(_lib_path
+ NAMES ${_lib}
+ PATHS ${_odbc_lib_paths} # system parths or collected from ODBC_CONFIG
+ PATH_SUFFIXES odbc)
+ if(_lib_path)
+ list(APPEND _odbc_required_libs_paths ${_lib_path})
+ endif()
+ unset(_lib_path CACHE)
+ endforeach()
+endif()
+
+# Unset internal lists as no longer used
+unset(_odbc_include_paths)
+unset(_odbc_lib_paths)
+unset(_odbc_lib_names)
+unset(_odbc_required_libs_names)
+
+### Set result variables ######################################################
+set(_odbc_required_vars ODBC_LIBRARY)
+if(NOT WIN32)
+ list(APPEND _odbc_required_vars ODBC_INCLUDE_DIR)
+endif()
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(ODBC DEFAULT_MSG ${_odbc_required_vars})
+
+unset(_odbc_required_vars)
+
+mark_as_advanced(ODBC_LIBRARY ODBC_INCLUDE_DIR)
+
+set(ODBC_INCLUDE_DIRS ${ODBC_INCLUDE_DIR})
+list(APPEND ODBC_LIBRARIES ${ODBC_LIBRARY})
+list(APPEND ODBC_LIBRARIES ${_odbc_required_libs_paths})
+
+### Import targets ############################################################
+if(ODBC_FOUND)
+ if(NOT TARGET ODBC::ODBC)
+ if(IS_ABSOLUTE "${ODBC_LIBRARY}")
+ add_library(ODBC::ODBC UNKNOWN IMPORTED)
+ set_target_properties(ODBC::ODBC PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES "C"
+ IMPORTED_LOCATION "${ODBC_LIBRARY}")
+ else()
+ add_library(ODBC::ODBC INTERFACE IMPORTED)
+ set_target_properties(ODBC::ODBC PROPERTIES
+ IMPORTED_LIBNAME "${ODBC_LIBRARY}")
+ endif()
+ set_target_properties(ODBC::ODBC PROPERTIES
+ INTERFACE_INCLUDE_DIRECTORIES "${ODBC_INCLUDE_DIR}")
+
+ if(_odbc_required_libs_paths)
+ set_property(TARGET ODBC::ODBC APPEND PROPERTY
+ INTERFACE_LINK_LIBRARIES "${_odbc_required_libs_paths}")
+ endif()
+ endif()
+endif()
+
+unset(_odbc_required_libs_paths)
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/FindPatch.cmake b/Modules/FindPatch.cmake
new file mode 100644
index 000000000..49988395b
--- /dev/null
+++ b/Modules/FindPatch.cmake
@@ -0,0 +1,69 @@
+# 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/FindPython.cmake b/Modules/FindPython.cmake
new file mode 100644
index 000000000..e2f3bf349
--- /dev/null
+++ b/Modules/FindPython.cmake
@@ -0,0 +1,258 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindPython
+----------
+
+Find Python interpreter, compiler and development environment (include
+directories and libraries).
+
+Three components are supported:
+
+* ``Interpreter``: search for Python interpreter.
+* ``Compiler``: search for Python compiler. Only offered by IronPython.
+* ``Development``: search for development artifacts (include directories and
+ libraries).
+* ``NumPy``: search for NumPy include directories.
+
+If no ``COMPONENTS`` is specified, ``Interpreter`` is assumed.
+
+To ensure consistent versions between components ``Interpreter``, ``Compiler``,
+``Development`` and ``NumPy``, specify all components at the same time::
+
+ find_package (Python COMPONENTS Interpreter Development)
+
+This module looks preferably for version 3 of Python. If not found, version 2
+is searched.
+To manage concurrent versions 3 and 2 of Python, use :module:`FindPython3` and
+:module:`FindPython2` modules rather than this one.
+
+.. note::
+
+ If components ``Interpreter`` and ``Development`` are both specified, this
+ module search only for interpreter with same platform architecture as the one
+ defined by ``CMake`` configuration. This contraint does not apply if only
+ ``Interpreter`` component is specified.
+
+Imported Targets
+^^^^^^^^^^^^^^^^
+
+This module defines the following :ref:`Imported Targets <Imported Targets>`
+(when :prop_gbl:`CMAKE_ROLE` is ``PROJECT``):
+
+``Python::Interpreter``
+ Python interpreter. Target defined if component ``Interpreter`` is found.
+``Python::Compiler``
+ Python compiler. Target defined if component ``Compiler`` is found.
+``Python::Python``
+ Python library for Python embedding. Target defined if component
+ ``Development`` is found.
+``Python::Module``
+ Python library for Python module. Target defined if component ``Development``
+ is found.
+``Python::NumPy``
+ NumPy Python library. Target defined if component ``NumPy`` is found.
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This module will set the following variables in your project
+(see :ref:`Standard Variable Names <CMake Developer Standard Variable Names>`):
+
+``Python_FOUND``
+ System has the Python requested components.
+``Python_Interpreter_FOUND``
+ System has the Python interpreter.
+``Python_EXECUTABLE``
+ Path to the Python interpreter.
+``Python_INTERPRETER_ID``
+ A short string unique to the interpreter. Possible values include:
+ * Python
+ * ActivePython
+ * Anaconda
+ * Canopy
+ * IronPython
+``Python_STDLIB``
+ Standard platform independent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=True)``.
+``Python_STDARCH``
+ Standard platform dependent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=True)``.
+``Python_SITELIB``
+ Third-party platform independent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=False)``.
+``Python_SITEARCH``
+ Third-party platform dependent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=False)``.
+``Python_Compiler_FOUND``
+ System has the Python compiler.
+``Python_COMPILER``
+ Path to the Python compiler. Only offered by IronPython.
+``Python_COMPILER_ID``
+ A short string unique to the compiler. Possible values include:
+ * IronPython
+``Python_Development_FOUND``
+ System has the Python development artifacts.
+``Python_INCLUDE_DIRS``
+ The Python include directories.
+``Python_LIBRARIES``
+ The Python libraries.
+``Python_LIBRARY_DIRS``
+ The Python library directories.
+``Python_RUNTIME_LIBRARY_DIRS``
+ The Python runtime library directories.
+``Python_VERSION``
+ Python version.
+``Python_VERSION_MAJOR``
+ Python major version.
+``Python_VERSION_MINOR``
+ Python minor version.
+``Python_VERSION_PATCH``
+ Python patch version.
+``Python_NumPy_FOUND``
+ System has the NumPy.
+``Python_NumPy_INCLUDE_DIRS``
+ The NumPy include directries.
+``Python_NumPy_VERSION``
+ The NumPy version.
+
+Hints
+^^^^^
+
+``Python_ROOT_DIR``
+ Define the root directory of a Python installation.
+
+``Python_USE_STATIC_LIBS``
+ * If not defined, search for shared libraries and static libraries in that
+ order.
+ * If set to TRUE, search **only** for static libraries.
+ * If set to FALSE, search **only** for shared libraries.
+
+``Python_FIND_STRATEGY``
+ This variable defines how lookup will be done.
+ The ``Python_FIND_STRATEGY`` variable can be set to empty or one of the
+ following:
+
+ * ``VERSION``: Try to find the most recent version in all specified
+ locations.
+ This is the default if policy :policy:`CMP0094` is undefined or set to
+ ``OLD``.
+ * ``LOCATION``: Stops lookup as soon as a version satisfying version
+ constraints is founded.
+ This is the default if policy :policy:`CMP0094` is set to ``NEW``.
+
+``Python_FIND_REGISTRY``
+ On Windows the ``Python_FIND_REGISTRY`` variable determine the order
+ of preference between registry and environment variables.
+ the ``Python_FIND_REGISTRY`` variable can be set to empty or one of the
+ following:
+
+ * ``FIRST``: Try to use registry before environment variables.
+ This is the default.
+ * ``LAST``: Try to use registry after environment variables.
+ * ``NEVER``: Never try to use registry.
+
+``Python_FIND_FRAMEWORK``
+ On macOS the ``Python_FIND_FRAMEWORK`` variable determine the order of
+ preference between Apple-style and unix-style package components.
+ This variable can be set to empty or take same values as
+ :variable:`CMAKE_FIND_FRAMEWORK` variable.
+
+ .. note::
+
+ Value ``ONLY`` is not supported so ``FIRST`` will be used instead.
+
+ If ``Python_FIND_FRAMEWORK`` is not defined, :variable:`CMAKE_FIND_FRAMEWORK`
+ variable will be used, if any.
+
+``Python_FIND_VIRTUALENV``
+ This variable defines the handling of virtual environments. It is meaningfull
+ only when a virtual environment is active (i.e. the ``activate`` script has
+ been evaluated). In this case, it takes precedence over
+ ``Python_FIND_REGISTRY`` and ``CMAKE_FIND_FRAMEWORK`` variables.
+ The ``Python_FIND_VIRTUALENV`` variable can be set to empty or one of the
+ following:
+
+ * ``FIRST``: The virtual environment is used before any other standard
+ paths to look-up for the interpreter. This is the default.
+ * ``ONLY``: Only the virtual environment is used to look-up for the
+ interpreter.
+ * ``STANDARD``: The virtual environment is not used to look-up for the
+ interpreter. In this case, variable ``Python_FIND_REGISTRY`` (Windows)
+ or ``CMAKE_FIND_FRAMEWORK`` (macOS) can be set with value ``LAST`` or
+ ``NEVER`` to select preferably the interpreter from the virtual
+ environment.
+
+Commands
+^^^^^^^^
+
+This module defines the command ``Python_add_library`` (when
+:prop_gbl:`CMAKE_ROLE` is ``PROJECT``), which has the same semantics as
+:command:`add_library` and adds a dependency to target ``Python::Python`` or,
+when library type is ``MODULE``, to target ``Python::Module`` and takes care of
+Python module naming rules::
+
+ Python_add_library (my_module MODULE src1.cpp)
+
+If library type is not specified, ``MODULE`` is assumed.
+#]=======================================================================]
+
+
+set (_PYTHON_PREFIX Python)
+
+if (DEFINED Python_FIND_VERSION)
+ set (_Python_REQUIRED_VERSION_MAJOR ${Python_FIND_VERSION_MAJOR})
+
+ include (${CMAKE_CURRENT_LIST_DIR}/FindPython/Support.cmake)
+else()
+ # iterate over versions in quiet and NOT required modes to avoid multiple
+ # "Found" messages and prematurally failure.
+ set (_Python_QUIETLY ${Python_FIND_QUIETLY})
+ set (_Python_REQUIRED ${Python_FIND_REQUIRED})
+ set (Python_FIND_QUIETLY TRUE)
+ set (Python_FIND_REQUIRED FALSE)
+
+ set (_Python_REQUIRED_VERSIONS 3 2)
+ set (_Python_REQUIRED_VERSION_LAST 2)
+
+ foreach (_Python_REQUIRED_VERSION_MAJOR IN LISTS _Python_REQUIRED_VERSIONS)
+ set (Python_FIND_VERSION ${_Python_REQUIRED_VERSION_MAJOR})
+ include (${CMAKE_CURRENT_LIST_DIR}/FindPython/Support.cmake)
+ if (Python_FOUND OR
+ _Python_REQUIRED_VERSION_MAJOR EQUAL _Python_REQUIRED_VERSION_LAST)
+ break()
+ endif()
+ # clean-up some CACHE variables to ensure look-up restart from scratch
+ foreach (_Python_ITEM IN LISTS _Python_CACHED_VARS)
+ unset (${_Python_ITEM} CACHE)
+ endforeach()
+ endforeach()
+
+ unset (Python_FIND_VERSION)
+
+ set (Python_FIND_QUIETLY ${_Python_QUIETLY})
+ set (Python_FIND_REQUIRED ${_Python_REQUIRED})
+ if (Python_FIND_REQUIRED OR NOT Python_FIND_QUIETLY)
+ # call again validation command to get "Found" or error message
+ find_package_handle_standard_args (Python HANDLE_COMPONENTS
+ REQUIRED_VARS ${_Python_REQUIRED_VARS}
+ VERSION_VAR Python_VERSION)
+ endif()
+endif()
+
+if (COMMAND __Python_add_library)
+ macro (Python_add_library)
+ __Python_add_library (Python ${ARGV})
+ endmacro()
+endif()
+
+unset (_PYTHON_PREFIX)
diff --git a/Modules/FindPython/Support.cmake b/Modules/FindPython/Support.cmake
new file mode 100644
index 000000000..590c7af4e
--- /dev/null
+++ b/Modules/FindPython/Support.cmake
@@ -0,0 +1,1835 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#
+# This file is a "template" file used by various FindPython modules.
+#
+
+cmake_policy (GET CMP0094 _${_PYTHON_PREFIX}_LOOKUP_POLICY)
+
+cmake_policy (VERSION 3.7)
+
+if (_${_PYTHON_PREFIX}_LOOKUP_POLICY)
+ cmake_policy (SET CMP0094 ${_${_PYTHON_PREFIX}_LOOKUP_POLICY})
+endif()
+
+#
+# Initial configuration
+#
+if (NOT DEFINED _PYTHON_PREFIX)
+ message (FATAL_ERROR "FindPython: INTERNAL ERROR")
+endif()
+if (NOT DEFINED _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR)
+ message (FATAL_ERROR "FindPython: INTERNAL ERROR")
+endif()
+if (_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR EQUAL 3)
+ set(_${_PYTHON_PREFIX}_VERSIONS 3.8 3.7 3.6 3.5 3.4 3.3 3.2 3.1 3.0)
+elseif (_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR EQUAL 2)
+ set(_${_PYTHON_PREFIX}_VERSIONS 2.7 2.6 2.5 2.4 2.3 2.2 2.1 2.0)
+else()
+ message (FATAL_ERROR "FindPython: INTERNAL ERROR")
+endif()
+
+get_property(_${_PYTHON_PREFIX}_CMAKE_ROLE GLOBAL PROPERTY CMAKE_ROLE)
+
+
+#
+# helper commands
+#
+macro (_PYTHON_DISPLAY_FAILURE _PYTHON_MSG)
+ if (${_PYTHON_PREFIX}_FIND_REQUIRED)
+ message (FATAL_ERROR "${_PYTHON_MSG}")
+ else()
+ if (NOT ${_PYTHON_PREFIX}_FIND_QUIETLY)
+ message(STATUS "${_PYTHON_MSG}")
+ endif ()
+ endif()
+
+ set (${_PYTHON_PREFIX}_FOUND FALSE)
+ string (TOUPPER "${_PYTHON_PREFIX}" _${_PYTHON_PREFIX}_UPPER_PREFIX)
+ set (${_PYTHON_UPPER_PREFIX}_FOUND FALSE)
+ return()
+endmacro()
+
+
+macro (_PYTHON_FIND_FRAMEWORKS)
+ set (${_PYTHON_PREFIX}_FRAMEWORKS)
+ if (CMAKE_HOST_APPLE OR APPLE)
+ set (_pff_frameworks ${CMAKE_FRAMEWORK_PATH}
+ $ENV{CMAKE_FRAMEWORK_PATH}
+ ~/Library/Frameworks
+ /usr/local/Frameworks
+ ${CMAKE_SYSTEM_FRAMEWORK_PATH})
+ list (REMOVE_DUPLICATES _pff_frameworks)
+ foreach (_pff_framework IN LISTS _pff_frameworks)
+ if (EXISTS ${_pff_framework}/Python.framework)
+ list (APPEND ${_PYTHON_PREFIX}_FRAMEWORKS ${_pff_framework}/Python.framework)
+ endif()
+ endforeach()
+ unset (_pff_frameworks)
+ unset (_pff_framework)
+ endif()
+endmacro()
+
+function (_PYTHON_GET_FRAMEWORKS _PYTHON_PGF_FRAMEWORK_PATHS _PYTHON_VERSION)
+ set (_PYTHON_FRAMEWORK_PATHS)
+ foreach (_PYTHON_FRAMEWORK IN LISTS ${_PYTHON_PREFIX}_FRAMEWORKS)
+ list (APPEND _PYTHON_FRAMEWORK_PATHS
+ "${_PYTHON_FRAMEWORK}/Versions/${_PYTHON_VERSION}")
+ endforeach()
+ set (${_PYTHON_PGF_FRAMEWORK_PATHS} ${_PYTHON_FRAMEWORK_PATHS} PARENT_SCOPE)
+endfunction()
+
+function (_PYTHON_GET_REGISTRIES _PYTHON_PGR_REGISTRY_PATHS _PYTHON_VERSION)
+ string (REPLACE "." "" _PYTHON_VERSION_NO_DOTS ${_PYTHON_VERSION})
+ set (${_PYTHON_PGR_REGISTRY_PATHS}
+ [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_PYTHON_VERSION}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath]
+ [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_PYTHON_VERSION}-${_${_PYTHON_PREFIX}_ARCH2}\\InstallPath]
+ [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_PYTHON_VERSION}\\InstallPath]
+ [HKEY_CURRENT_USER\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_PYTHON_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath]
+ [HKEY_CURRENT_USER\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_PYTHON_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH2}\\InstallPath]
+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_PYTHON_VERSION}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath]
+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_PYTHON_VERSION}-${_${_PYTHON_PREFIX}_ARCH2}\\InstallPath]
+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_PYTHON_VERSION}\\InstallPath]
+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_PYTHON_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH}\\InstallPath]
+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\ContinuumAnalytics\\Anaconda${_PYTHON_VERSION_NO_DOTS}-${_${_PYTHON_PREFIX}_ARCH2}\\InstallPath]
+ PARENT_SCOPE)
+endfunction()
+
+function (_PYTHON_GET_PATH_SUFFIXES _PYTHON_PGPS_PATH_SUFFIXES _PYTHON_VERSION _PYTHON_TYPE)
+ set (path_suffixes)
+
+ if (_PYTHON_TYPE STREQUAL "LIBRARY")
+ if (CMAKE_LIBRARY_ARCHITECTURE)
+ list (APPEND path_suffixes lib/${CMAKE_LIBRARY_ARCHITECTURE})
+ endif()
+ list (APPEND path_suffixes lib libs)
+
+ if (CMAKE_LIBRARY_ARCHITECTURE)
+ list (APPEND path_suffixes lib/python${_PYTHON_VERSION}/config-${_PYTHON_VERSION}mu-${CMAKE_LIBRARY_ARCHITECTURE}
+ lib/python${_PYTHON_VERSION}/config-${_PYTHON_VERSION}m-${CMAKE_LIBRARY_ARCHITECTURE}
+ lib/python${_PYTHON_VERSION}/config-${CMAKE_MATCH_1}u-${CMAKE_LIBRARY_ARCHITECTURE}
+ lib/python${_PYTHON_VERSION}/config-${CMAKE_MATCH_1}-${CMAKE_LIBRARY_ARCHITECTURE})
+ endif()
+ list (APPEND path_suffixes lib/python${_PYTHON_VERSION}/config-${_PYTHON_VERSION}mu
+ lib/python${_PYTHON_VERSION}/config-${_PYTHON_VERSION}m
+ lib/python${_PYTHON_VERSION}/config-${_PYTHON_VERSION}u
+ lib/python${_PYTHON_VERSION}/config-${_PYTHON_VERSION}
+ lib/python${_PYTHON_VERSION}/config)
+
+ elseif (_PYTHON_TYPE STREQUAL "INCLUDE")
+ list (APPEND path_suffixes include/python${_PYTHON_VERSION}mu
+ include/python${_PYTHON_VERSION}m
+ include/python${_PYTHON_VERSION}u
+ include/python${_PYTHON_VERSION}
+ include)
+ endif()
+
+ set (${_PYTHON_PGPS_PATH_SUFFIXES} ${path_suffixes} PARENT_SCOPE)
+endfunction()
+
+function (_PYTHON_GET_LIB_NAMES _PYTHON_PGLN_NAMES _PYTHON_VERSION)
+ string (REPLACE "." "" _PYTHON_VERSION_NO_DOTS ${_PYTHON_VERSION})
+
+ if (ARGC EQUAL 3 AND ARGV2 STREQUAL "DEBUG")
+ set (${_PYTHON_PGLN_NAMES} python${_PYTHON_VERSION_NO_DOTS}_d PARENT_SCOPE)
+ else()
+ set (${_PYTHON_PGLN_NAMES} python${_PYTHON_VERSION_NO_DOTS}
+ python${_PYTHON_VERSION}mu
+ python${_PYTHON_VERSION}m
+ python${_PYTHON_VERSION}u
+ python${_PYTHON_VERSION}
+ PARENT_SCOPE)
+ endif()
+endfunction()
+
+
+function (_PYTHON_VALIDATE_INTERPRETER)
+ if (NOT ${_PYTHON_PREFIX}_EXECUTABLE)
+ return()
+ endif()
+
+ cmake_parse_arguments (_PVI "EXACT" "" "" ${ARGN})
+ if (_PVI_UNPARSED_ARGUMENTS)
+ set (expected_version ${_PVI_UNPARSED_ARGUMENTS})
+ else()
+ unset (expected_version)
+ endif()
+
+ get_filename_component (python_name "${${_PYTHON_PREFIX}_EXECUTABLE}" NAME)
+
+ if (expected_version AND NOT python_name STREQUAL "python${expected_version}${CMAKE_EXECUTABLE_SUFFIX}")
+ # executable found must have a specific version
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c
+ "import sys; sys.stdout.write('.'.join([str(x) for x in sys.version_info[:2]]))"
+ RESULT_VARIABLE result
+ OUTPUT_VARIABLE version
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (result OR (_PVI_EXACT AND NOT version VERSION_EQUAL expected_version) OR (version VERSION_LESS expected_version))
+ # interpreter not usable or has wrong major version
+ set (${_PYTHON_PREFIX}_EXECUTABLE ${_PYTHON_PREFIX}_EXECUTABLE-NOTFOUND CACHE INTERNAL "" FORCE)
+ return()
+ endif()
+ else()
+ if (NOT python_name STREQUAL "python${_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR}${CMAKE_EXECUTABLE_SUFFIX}")
+ # executable found do not have version in name
+ # ensure major version is OK
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c
+ "import sys; sys.stdout.write(str(sys.version_info[0]))"
+ RESULT_VARIABLE result
+ OUTPUT_VARIABLE version
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (result OR NOT version EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR)
+ # interpreter not usable or has wrong major version
+ set (${_PYTHON_PREFIX}_EXECUTABLE ${_PYTHON_PREFIX}_EXECUTABLE-NOTFOUND CACHE INTERNAL "" FORCE)
+ return()
+ endif()
+ endif()
+ endif()
+
+ if (CMAKE_SIZEOF_VOID_P AND "Development" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS
+ AND NOT CMAKE_CROSSCOMPILING)
+ # In this case, interpreter must have same architecture as environment
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c
+ "import sys, struct; sys.stdout.write(str(struct.calcsize(\"P\")))"
+ RESULT_VARIABLE result
+ OUTPUT_VARIABLE size
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (result OR NOT size EQUAL CMAKE_SIZEOF_VOID_P)
+ # interpreter not usable or has wrong architecture
+ set (${_PYTHON_PREFIX}_EXECUTABLE ${_PYTHON_PREFIX}_EXECUTABLE-NOTFOUND CACHE INTERNAL "" FORCE)
+ return()
+ endif()
+ endif()
+endfunction()
+
+
+function (_PYTHON_VALIDATE_COMPILER expected_version)
+ if (NOT ${_PYTHON_PREFIX}_COMPILER)
+ return()
+ endif()
+
+ cmake_parse_arguments (_PVC "EXACT" "" "" ${ARGN})
+ if (_PVC_UNPARSED_ARGUMENTS)
+ set (major_version FALSE)
+ set (expected_version ${_PVC_UNPARSED_ARGUMENTS})
+ else()
+ set (major_version TRUE)
+ set (expected_version ${_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR})
+ set (_PVC_EXACT TRUE)
+ endif()
+
+ # retrieve python environment version from compiler
+ set (working_dir "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/PythonCompilerVersion.dir")
+ if (major_version)
+ # check only major version
+ file (WRITE "${working_dir}/version.py" "import sys; sys.stdout.write(str(sys.version_info[0]))")
+ else()
+ file (WRITE "${working_dir}/version.py" "import sys; sys.stdout.write('.'.join([str(x) for x in sys.version_info[:2]]))\n")
+ endif()
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_COMPILER}" /target:exe /embed "${working_dir}/version.py"
+ WORKING_DIRECTORY "${working_dir}"
+ OUTPUT_QUIET
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ execute_process (COMMAND "${working_dir}/version"
+ WORKING_DIRECTORY "${working_dir}"
+ RESULT_VARIABLE result
+ OUTPUT_VARIABLE version
+ ERROR_QUIET)
+ file (REMOVE_RECURSE "${_${_PYTHON_PREFIX}_VERSION_DIR}")
+
+ if (result OR (_PVC_EXACT AND NOT version VERSION_EQUAL expected_version) OR (version VERSION_LESS expected_version))
+ # Compiler not usable or has wrong version
+ set (${_PYTHON_PREFIX}_COMPILER ${_PYTHON_PREFIX}_COMPILER-NOTFOUND CACHE INTERNAL "" FORCE)
+ endif()
+endfunction()
+
+
+function (_PYTHON_FIND_RUNTIME_LIBRARY _PYTHON_LIB)
+ string (REPLACE "_RUNTIME" "" _PYTHON_LIB "${_PYTHON_LIB}")
+ # look at runtime part on systems supporting it
+ if (CMAKE_SYSTEM_NAME STREQUAL "Windows" OR
+ (CMAKE_SYSTEM_NAME MATCHES "MSYS|CYGWIN"
+ AND ${_PYTHON_LIB} MATCHES "${CMAKE_IMPORT_LIBRARY_SUFFIX}$"))
+ set (CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_SHARED_LIBRARY_SUFFIX})
+ # MSYS has a special syntax for runtime libraries
+ if (CMAKE_SYSTEM_NAME MATCHES "MSYS")
+ list (APPEND CMAKE_FIND_LIBRARY_PREFIXES "msys-")
+ endif()
+ find_library (${ARGV})
+ endif()
+endfunction()
+
+
+function (_PYTHON_SET_LIBRARY_DIRS _PYTHON_SLD_RESULT)
+ unset (_PYTHON_DIRS)
+ set (_PYTHON_LIBS ${ARGV})
+ list (REMOVE_AT _PYTHON_LIBS 0)
+ foreach (_PYTHON_LIB IN LISTS _PYTHON_LIBS)
+ if (${_PYTHON_LIB})
+ get_filename_component (_PYTHON_DIR "${${_PYTHON_LIB}}" DIRECTORY)
+ list (APPEND _PYTHON_DIRS "${_PYTHON_DIR}")
+ endif()
+ endforeach()
+ if (_PYTHON_DIRS)
+ list (REMOVE_DUPLICATES _PYTHON_DIRS)
+ endif()
+ set (${_PYTHON_SLD_RESULT} ${_PYTHON_DIRS} PARENT_SCOPE)
+endfunction()
+
+
+# If major version is specified, it must be the same as internal major version
+if (DEFINED ${_PYTHON_PREFIX}_FIND_VERSION_MAJOR
+ AND NOT ${_PYTHON_PREFIX}_FIND_VERSION_MAJOR VERSION_EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR)
+ _python_display_failure ("Could NOT find ${_PYTHON_PREFIX}: Wrong major version specified is \"${${_PYTHON_PREFIX}_FIND_VERSION_MAJOR}\", but expected major version is \"${_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR}\"")
+endif()
+
+
+# handle components
+if (NOT ${_PYTHON_PREFIX}_FIND_COMPONENTS)
+ set (${_PYTHON_PREFIX}_FIND_COMPONENTS Interpreter)
+ set (${_PYTHON_PREFIX}_FIND_REQUIRED_Interpreter TRUE)
+endif()
+if ("NumPy" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS)
+ list (APPEND ${_PYTHON_PREFIX}_FIND_COMPONENTS "Interpreter" "Development")
+ list (REMOVE_DUPLICATES ${_PYTHON_PREFIX}_FIND_COMPONENTS)
+endif()
+foreach (_${_PYTHON_PREFIX}_COMPONENT IN LISTS ${_PYTHON_PREFIX}_FIND_COMPONENTS)
+ set (${_PYTHON_PREFIX}_${_${_PYTHON_PREFIX}_COMPONENT}_FOUND FALSE)
+endforeach()
+unset (_${_PYTHON_PREFIX}_FIND_VERSIONS)
+
+# Set versions to search
+## default: search any version
+set (_${_PYTHON_PREFIX}_FIND_VERSIONS ${_${_PYTHON_PREFIX}_VERSIONS})
+
+if (${_PYTHON_PREFIX}_FIND_VERSION_COUNT GREATER 1)
+ if (${_PYTHON_PREFIX}_FIND_VERSION_EXACT)
+ set (_${_PYTHON_PREFIX}_FIND_VERSIONS ${${_PYTHON_PREFIX}_FIND_VERSION_MAJOR}.${${_PYTHON_PREFIX}_FIND_VERSION_MINOR})
+ else()
+ unset (_${_PYTHON_PREFIX}_FIND_VERSIONS)
+ # add all compatible versions
+ foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_VERSIONS)
+ if (_${_PYTHON_PREFIX}_VERSION VERSION_GREATER_EQUAL ${_PYTHON_PREFIX}_FIND_VERSION)
+ list (APPEND _${_PYTHON_PREFIX}_FIND_VERSIONS ${_${_PYTHON_PREFIX}_VERSION})
+ endif()
+ endforeach()
+ endif()
+endif()
+
+# Define lookup strategy
+if (_${_PYTHON_PREFIX}_LOOKUP_POLICY STREQUAL "NEW")
+ set (_${_PYTHON_PREFIX}_FIND_STRATEGY "LOCATION")
+else()
+ set (_${_PYTHON_PREFIX}_FIND_STRATEGY "VERSION")
+endif()
+if (DEFINED ${_PYTHON_PREFIX}_FIND_STRATEGY)
+ if (NOT ${_PYTHON_PREFIX}_FIND_STRATEGY MATCHES "^(VERSION|LOCATION)$")
+ message (AUTHOR_WARNING "Find${_PYTHON_PREFIX}: ${${_PYTHON_PREFIX}_FIND_STRATEGY}: invalid value for '${_PYTHON_PREFIX}_FIND_STRATEGY'. 'VERSION' or 'LOCATION' expected.")
+ set (_${_PYTHON_PREFIX}_FIND_STRATEGY "VERSION")
+ else()
+ set (_${_PYTHON_PREFIX}_FIND_STRATEGY "${${_PYTHON_PREFIX}_FIND_STRATEGY}")
+ endif()
+endif()
+
+# Python and Anaconda distributions: define which architectures can be used
+if (CMAKE_SIZEOF_VOID_P)
+ # In this case, search only for 64bit or 32bit
+ math (EXPR _${_PYTHON_PREFIX}_ARCH "${CMAKE_SIZEOF_VOID_P} * 8")
+ set (_${_PYTHON_PREFIX}_ARCH2 ${_${_PYTHON_PREFIX}_ARCH})
+else()
+ # architecture unknown, search for both 64bit and 32bit
+ set (_${_PYTHON_PREFIX}_ARCH 64)
+ set (_${_PYTHON_PREFIX}_ARCH2 32)
+endif()
+
+# IronPython support
+if (CMAKE_SIZEOF_VOID_P)
+ # In this case, search only for 64bit or 32bit
+ math (EXPR _${_PYTHON_PREFIX}_ARCH "${CMAKE_SIZEOF_VOID_P} * 8")
+ set (_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES ipy${_${_PYTHON_PREFIX}_ARCH} ipy)
+else()
+ # architecture unknown, search for natural interpreter
+ set (_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES ipy)
+endif()
+set (_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES net45 net40)
+
+# Apple frameworks handling
+_python_find_frameworks ()
+
+set (_${_PYTHON_PREFIX}_FIND_FRAMEWORK "FIRST")
+
+if (DEFINED ${_PYTHON_PREFIX}_FIND_FRAMEWORK)
+ if (NOT ${_PYTHON_PREFIX}_FIND_FRAMEWORK MATCHES "^(FIRST|LAST|NEVER)$")
+ message (AUTHOR_WARNING "Find${_PYTHON_PREFIX}: ${${_PYTHON_PREFIX}_FIND_FRAMEWORK}: invalid value for '${_PYTHON_PREFIX}_FIND_FRAMEWORK'. 'FIRST', 'LAST' or 'NEVER' expected. 'FIRST' will be used instead.")
+ else()
+ set (_${_PYTHON_PREFIX}_FIND_FRAMEWORK ${${_PYTHON_PREFIX}_FIND_FRAMEWORK})
+ endif()
+elseif (DEFINED CMAKE_FIND_FRAMEWORK)
+ if (CMAKE_FIND_FRAMEWORK STREQUAL "ONLY")
+ message (AUTHOR_WARNING "Find${_PYTHON_PREFIX}: CMAKE_FIND_FRAMEWORK: 'ONLY' value is not supported. 'FIRST' will be used instead.")
+ elseif (NOT CMAKE_FIND_FRAMEWORK MATCHES "^(FIRST|LAST|NEVER)$")
+ message (AUTHOR_WARNING "Find${_PYTHON_PREFIX}: ${CMAKE_FIND_FRAMEWORK}: invalid value for 'CMAKE_FIND_FRAMEWORK'. 'FIRST', 'LAST' or 'NEVER' expected. 'FIRST' will be used instead.")
+ else()
+ set (_${_PYTHON_PREFIX}_FIND_FRAMEWORK ${CMAKE_FIND_FRAMEWORK})
+ endif()
+endif()
+
+# Save CMAKE_FIND_APPBUNDLE
+if (DEFINED CMAKE_FIND_APPBUNDLE)
+ set (_${_PYTHON_PREFIX}_CMAKE_FIND_APPBUNDLE ${CMAKE_FIND_APPBUNDLE})
+else()
+ unset (_${_PYTHON_PREFIX}_CMAKE_FIND_APPBUNDLE)
+endif()
+# To avoid app bundle lookup
+set (CMAKE_FIND_APPBUNDLE "NEVER")
+
+# Save CMAKE_FIND_FRAMEWORK
+if (DEFINED CMAKE_FIND_FRAMEWORK)
+ set (_${_PYTHON_PREFIX}_CMAKE_FIND_FRAMEWORK ${CMAKE_FIND_FRAMEWORK})
+else()
+ unset (_${_PYTHON_PREFIX}_CMAKE_FIND_FRAMEWORK)
+endif()
+# To avoid framework lookup
+set (CMAKE_FIND_FRAMEWORK "NEVER")
+
+# Windows Registry handling
+if (DEFINED ${_PYTHON_PREFIX}_FIND_REGISTRY)
+ if (NOT ${_PYTHON_PREFIX}_FIND_REGISTRY MATCHES "^(FIRST|LAST|NEVER)$")
+ message (AUTHOR_WARNING "Find${_PYTHON_PREFIX}: ${${_PYTHON_PREFIX}_FIND_REGISTRY}: invalid value for '${_PYTHON_PREFIX}_FIND_REGISTRY'. 'FIRST', 'LAST' or 'NEVER' expected. 'FIRST' will be used instead.")
+ set (_${_PYTHON_PREFIX}_FIND_REGISTRY "FIRST")
+ else()
+ set (_${_PYTHON_PREFIX}_FIND_REGISTRY ${${_PYTHON_PREFIX}_FIND_REGISTRY})
+ endif()
+else()
+ set (_${_PYTHON_PREFIX}_FIND_REGISTRY "FIRST")
+endif()
+
+# virtual environments handling
+if (DEFINED ENV{VIRTUAL_ENV})
+ if (DEFINED ${_PYTHON_PREFIX}_FIND_VIRTUALENV)
+ if (NOT ${_PYTHON_PREFIX}_FIND_VIRTUALENV MATCHES "^(FIRST|ONLY|STANDARD)$")
+ message (AUTHOR_WARNING "Find${_PYTHON_PREFIX}: ${${_PYTHON_PREFIX}_FIND_VIRTUALENV}: invalid value for '${_PYTHON_PREFIX}_FIND_VIRTUALENV'. 'FIRST', 'ONLY' or 'STANDARD' expected. 'FIRST' will be used instead.")
+ set (_${_PYTHON_PREFIX}_FIND_VIRTUALENV "FIRST")
+ else()
+ set (_${_PYTHON_PREFIX}_FIND_VIRTUALENV ${${_PYTHON_PREFIX}_FIND_VIRTUALENV})
+ endif()
+ else()
+ set (_${_PYTHON_PREFIX}_FIND_VIRTUALENV FIRST)
+ endif()
+else()
+ set (_${_PYTHON_PREFIX}_FIND_VIRTUALENV STANDARD)
+endif()
+
+
+unset (_${_PYTHON_PREFIX}_REQUIRED_VARS)
+unset (_${_PYTHON_PREFIX}_CACHED_VARS)
+
+
+# first step, search for the interpreter
+if ("Interpreter" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS)
+ list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_EXECUTABLE)
+ if (${_PYTHON_PREFIX}_FIND_REQUIRED_Interpreter)
+ list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_EXECUTABLE)
+ endif()
+
+ set (_${_PYTHON_PREFIX}_HINTS "${${_PYTHON_PREFIX}_ROOT_DIR}" ENV ${_PYTHON_PREFIX}_ROOT_DIR)
+
+ if (_${_PYTHON_PREFIX}_FIND_STRATEGY STREQUAL "LOCATION")
+ unset (_${_PYTHON_PREFIX}_NAMES)
+ unset (_${_PYTHON_PREFIX}_FRAMEWORK_PATHS)
+ unset (_${_PYTHON_PREFIX}_REGISTRY_PATHS)
+
+ foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS)
+ # build all executable names
+ list (APPEND _${_PYTHON_PREFIX}_NAMES python${_${_PYTHON_PREFIX}_VERSION})
+
+ # Framework Paths
+ _python_get_frameworks (_${_PYTHON_PREFIX}_VERSION_PATHS ${_${_PYTHON_PREFIX}_VERSION})
+ list (APPEND _${_PYTHON_PREFIX}_FRAMEWORK_PATHS ${_${_PYTHON_PREFIX}_VERSION_PATHS})
+
+ # Registry Paths
+ _python_get_registries (_${_PYTHON_PREFIX}_VERSION_PATHS ${_${_PYTHON_PREFIX}_VERSION})
+ list (APPEND _${_PYTHON_PREFIX}_REGISTRY_PATHS ${_${_PYTHON_PREFIX}_VERSION_PATHS}
+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\IronPython\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath])
+ endforeach()
+ list (APPEND _${_PYTHON_PREFIX}_NAMES python${_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR} python)
+
+ while (TRUE)
+ # Virtual environments handling
+ if (_${_PYTHON_PREFIX}_FIND_VIRTUALENV MATCHES "^(FIRST|ONLY)$")
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ENV VIRTUAL_ENV
+ PATH_SUFFIXES bin Scripts
+ NO_CMAKE_PATH
+ NO_CMAKE_ENVIRONMENT_PATH
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+
+ _python_validate_interpreter (${${_PYTHON_PREFIX}_FIND_VERSION})
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+ if (NOT _${_PYTHON_PREFIX}_FIND_VIRTUALENV STREQUAL "ONLY")
+ break()
+ endif()
+ endif()
+
+ # Apple frameworks handling
+ if (CMAKE_HOST_APPLE AND _${_PYTHON_PREFIX}_FIND_FRAMEWORK STREQUAL "FIRST")
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS}
+ PATH_SUFFIXES bin
+ NO_CMAKE_PATH
+ NO_CMAKE_ENVIRONMENT_PATH
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ _python_validate_interpreter (${${_PYTHON_PREFIX}_FIND_VERSION})
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+ endif()
+ # Windows registry
+ if (CMAKE_HOST_WIN32 AND _${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "FIRST")
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ ${_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES bin ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ _python_validate_interpreter (${${_PYTHON_PREFIX}_FIND_VERSION})
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+ endif()
+
+ # try using HINTS and standard paths
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ ${_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES bin ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES})
+ _python_validate_interpreter (${${_PYTHON_PREFIX}_FIND_VERSION})
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+
+ # Apple frameworks handling
+ if (CMAKE_HOST_APPLE AND _${_PYTHON_PREFIX}_FIND_FRAMEWORK STREQUAL "LAST")
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ NAMES_PER_DIR
+ PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS}
+ PATH_SUFFIXES bin
+ NO_DEFAULT_PATH)
+ _python_validate_interpreter (${${_PYTHON_PREFIX}_FIND_VERSION})
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+ endif()
+ # Windows registry
+ if (CMAKE_HOST_WIN32 AND _${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "LAST")
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ ${_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES}
+ NAMES_PER_DIR
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES bin ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_DEFAULT_PATH)
+ _python_validate_interpreter (${${_PYTHON_PREFIX}_FIND_VERSION})
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+ endif()
+
+ break()
+ endwhile()
+ else()
+ # look-up for various versions and locations
+ foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS)
+ set (_${_PYTHON_PREFIX}_NAMES python${_${_PYTHON_PREFIX}_VERSION}
+ python${_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR}
+ python)
+
+ _python_get_frameworks (_${_PYTHON_PREFIX}_FRAMEWORK_PATHS ${_${_PYTHON_PREFIX}_VERSION})
+ _python_get_registries (_${_PYTHON_PREFIX}_REGISTRY_PATHS ${_${_PYTHON_PREFIX}_VERSION})
+
+ # Virtual environments handling
+ if (_${_PYTHON_PREFIX}_FIND_VIRTUALENV MATCHES "^(FIRST|ONLY)$")
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ENV VIRTUAL_ENV
+ PATH_SUFFIXES bin Scripts
+ NO_CMAKE_PATH
+ NO_CMAKE_ENVIRONMENT_PATH
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+
+ _python_validate_interpreter (${_${_PYTHON_PREFIX}_VERSION} EXACT)
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+ if (_${_PYTHON_PREFIX}_FIND_VIRTUALENV STREQUAL "ONLY")
+ continue()
+ endif()
+ endif()
+
+ # Apple frameworks handling
+ if (CMAKE_HOST_APPLE AND _${_PYTHON_PREFIX}_FIND_FRAMEWORK STREQUAL "FIRST")
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS}
+ PATH_SUFFIXES bin
+ NO_CMAKE_PATH
+ NO_CMAKE_ENVIRONMENT_PATH
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+
+ # Windows registry
+ if (CMAKE_HOST_WIN32 AND _${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "FIRST")
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ ${_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\IronPython\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath]
+ PATH_SUFFIXES bin ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+ _python_validate_interpreter (${_${_PYTHON_PREFIX}_VERSION} EXACT)
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+
+ # try using HINTS
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ ${_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES bin ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ _python_validate_interpreter (${_${_PYTHON_PREFIX}_VERSION} EXACT)
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+ # try using standard paths.
+ # NAMES_PER_DIR is not defined on purpose to have a chance to find
+ # expected version.
+ # For example, typical systems have 'python' for version 2.* and 'python3'
+ # for version 3.*. So looking for names per dir will find, potentially,
+ # systematically 'python' (i.e. version 2) even if version 3 is searched.
+ if (CMAKE_HOST_WIN32)
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES python${_${_PYTHON_PREFIX}_VERSION}
+ python
+ ${_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES})
+ else()
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES python${_${_PYTHON_PREFIX}_VERSION})
+ endif()
+ _python_validate_interpreter (${_${_PYTHON_PREFIX}_VERSION} EXACT)
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+
+ # Apple frameworks handling
+ if (CMAKE_HOST_APPLE AND _${_PYTHON_PREFIX}_FIND_FRAMEWORK STREQUAL "LAST")
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ NAMES_PER_DIR
+ PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS}
+ PATH_SUFFIXES bin
+ NO_DEFAULT_PATH)
+ endif()
+
+ # Windows registry
+ if (CMAKE_HOST_WIN32 AND _${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "LAST")
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES ${_${_PYTHON_PREFIX}_NAMES}
+ ${_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES}
+ NAMES_PER_DIR
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\IronPython\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath]
+ PATH_SUFFIXES bin ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_DEFAULT_PATH)
+ endif()
+
+ _python_validate_interpreter (${_${_PYTHON_PREFIX}_VERSION} EXACT)
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ break()
+ endif()
+ endforeach()
+
+ if (NOT ${_PYTHON_PREFIX}_EXECUTABLE AND
+ NOT _${_PYTHON_PREFIX}_FIND_VIRTUALENV STREQUAL "ONLY")
+ # No specific version found. Retry with generic names and standard paths.
+ # NAMES_PER_DIR is not defined on purpose to have a chance to find
+ # expected version.
+ # For example, typical systems have 'python' for version 2.* and 'python3'
+ # for version 3.*. So looking for names per dir will find, potentially,
+ # systematically 'python' (i.e. version 2) even if version 3 is searched.
+ find_program (${_PYTHON_PREFIX}_EXECUTABLE
+ NAMES python${_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR}
+ python
+ ${_${_PYTHON_PREFIX}_IRON_PYTHON_NAMES})
+
+ _python_validate_interpreter ()
+ endif()
+ endif()
+
+ # retrieve exact version of executable found
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c
+ "import sys; sys.stdout.write('.'.join([str(x) for x in sys.version_info[:3]]))"
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE ${_PYTHON_PREFIX}_VERSION
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ string (REGEX MATCHALL "[0-9]+" _${_PYTHON_PREFIX}_VERSIONS "${${_PYTHON_PREFIX}_VERSION}")
+ list (GET _${_PYTHON_PREFIX}_VERSIONS 0 ${_PYTHON_PREFIX}_VERSION_MAJOR)
+ list (GET _${_PYTHON_PREFIX}_VERSIONS 1 ${_PYTHON_PREFIX}_VERSION_MINOR)
+ list (GET _${_PYTHON_PREFIX}_VERSIONS 2 ${_PYTHON_PREFIX}_VERSION_PATCH)
+ else()
+ # Interpreter is not usable
+ set (${_PYTHON_PREFIX}_EXECUTABLE ${_PYTHON_PREFIX}_EXECUTABLE-NOTFOUND CACHE INTERNAL "" FORCE)
+ unset (${_PYTHON_PREFIX}_VERSION)
+ endif()
+ endif()
+
+ if (${_PYTHON_PREFIX}_EXECUTABLE
+ AND ${_PYTHON_PREFIX}_VERSION_MAJOR VERSION_EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR)
+ set (${_PYTHON_PREFIX}_Interpreter_FOUND TRUE)
+ # Use interpreter version for future searches to ensure consistency
+ set (_${_PYTHON_PREFIX}_FIND_VERSIONS ${${_PYTHON_PREFIX}_VERSION_MAJOR}.${${_PYTHON_PREFIX}_VERSION_MINOR})
+ endif()
+
+ if (${_PYTHON_PREFIX}_Interpreter_FOUND)
+ if (NOT CMAKE_SIZEOF_VOID_P)
+ # determine interpreter architecture
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c "import sys; print(sys.maxsize > 2**32)"
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE ${_PYTHON_PREFIX}_IS64BIT
+ ERROR_VARIABLE ${_PYTHON_PREFIX}_IS64BIT)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ if (${_PYTHON_PREFIX}_IS64BIT)
+ set (_${_PYTHON_PREFIX}_ARCH 64)
+ set (_${_PYTHON_PREFIX}_ARCH2 64)
+ else()
+ set (_${_PYTHON_PREFIX}_ARCH 32)
+ set (_${_PYTHON_PREFIX}_ARCH2 32)
+ endif()
+ endif()
+ endif()
+
+ # retrieve interpreter identity
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -V
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE ${_PYTHON_PREFIX}_INTERPRETER_ID
+ ERROR_VARIABLE ${_PYTHON_PREFIX}_INTERPRETER_ID)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ if (${_PYTHON_PREFIX}_INTERPRETER_ID MATCHES "Anaconda")
+ set (${_PYTHON_PREFIX}_INTERPRETER_ID "Anaconda")
+ elseif (${_PYTHON_PREFIX}_INTERPRETER_ID MATCHES "Enthought")
+ set (${_PYTHON_PREFIX}_INTERPRETER_ID "Canopy")
+ else()
+ string (REGEX REPLACE "^([^ ]+).*" "\\1" ${_PYTHON_PREFIX}_INTERPRETER_ID "${${_PYTHON_PREFIX}_INTERPRETER_ID}")
+ if (${_PYTHON_PREFIX}_INTERPRETER_ID STREQUAL "Python")
+ # try to get a more precise ID
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c "import sys; print(sys.copyright)"
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE ${_PYTHON_PREFIX}_COPYRIGHT
+ ERROR_QUIET)
+ if (${_PYTHON_PREFIX}_COPYRIGHT MATCHES "ActiveState")
+ set (${_PYTHON_PREFIX}_INTERPRETER_ID "ActivePython")
+ endif()
+ endif()
+ endif()
+ else()
+ set (${_PYTHON_PREFIX}_INTERPRETER_ID Python)
+ endif()
+ else()
+ unset (${_PYTHON_PREFIX}_INTERPRETER_ID)
+ endif()
+
+ # retrieve various package installation directories
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c "import sys; from distutils import sysconfig;sys.stdout.write(';'.join([sysconfig.get_python_lib(plat_specific=False,standard_lib=True),sysconfig.get_python_lib(plat_specific=True,standard_lib=True),sysconfig.get_python_lib(plat_specific=False,standard_lib=False),sysconfig.get_python_lib(plat_specific=True,standard_lib=False)]))"
+
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_LIBPATHS
+ ERROR_QUIET)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ list (GET _${_PYTHON_PREFIX}_LIBPATHS 0 ${_PYTHON_PREFIX}_STDLIB)
+ list (GET _${_PYTHON_PREFIX}_LIBPATHS 1 ${_PYTHON_PREFIX}_STDARCH)
+ list (GET _${_PYTHON_PREFIX}_LIBPATHS 2 ${_PYTHON_PREFIX}_SITELIB)
+ list (GET _${_PYTHON_PREFIX}_LIBPATHS 3 ${_PYTHON_PREFIX}_SITEARCH)
+ else()
+ unset (${_PYTHON_PREFIX}_STDLIB)
+ unset (${_PYTHON_PREFIX}_STDARCH)
+ unset (${_PYTHON_PREFIX}_SITELIB)
+ unset (${_PYTHON_PREFIX}_SITEARCH)
+ endif()
+
+ mark_as_advanced (${_PYTHON_PREFIX}_EXECUTABLE)
+endif()
+
+
+# second step, search for compiler (IronPython)
+if ("Compiler" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS)
+ list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_COMPILER)
+ if (${_PYTHON_PREFIX}_FIND_REQUIRED_Compiler)
+ list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_COMPILER)
+ endif()
+
+ # IronPython specific artifacts
+ # If IronPython interpreter is found, use its path
+ unset (_${_PYTHON_PREFIX}_IRON_ROOT)
+ if (${_PYTHON_PREFIX}_Interpreter_FOUND AND ${_PYTHON_PREFIX}_INTERPRETER_ID STREQUAL "IronPython")
+ get_filename_component (_${_PYTHON_PREFIX}_IRON_ROOT "${${_PYTHON_PREFIX}_EXECUTABLE}" DIRECTORY)
+ endif()
+
+ if (_${_PYTHON_PREFIX}_FIND_STRATEGY STREQUAL "LOCATION")
+ set (_${_PYTHON_PREFIX}_REGISTRY_PATHS)
+
+ foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS)
+ # Registry Paths
+ list (APPEND _${_PYTHON_PREFIX}_REGISTRY_PATHS
+ [HKEY_LOCAL_MACHINE\\SOFTWARE\\IronPython\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath])
+ endforeach()
+
+ while (TRUE)
+ if (_${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "FIRST")
+ find_program (${_PYTHON_PREFIX}_COMPILER
+ NAMES ipyc
+ HINTS ${_${_PYTHON_PREFIX}_IRON_ROOT} ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ _python_validate_compiler (${${_PYTHON_PREFIX}_FIND_VERSION})
+ if (${_PYTHON_PREFIX}_COMPILER)
+ break()
+ endif()
+ endif()
+
+ find_program (${_PYTHON_PREFIX}_COMPILER
+ NAMES ipyc
+ HINTS ${_${_PYTHON_PREFIX}_IRON_ROOT} ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ _python_validate_compiler (${${_PYTHON_PREFIX}_FIND_VERSION})
+ if (${_PYTHON_PREFIX}_COMPILER)
+ break()
+ endif()
+
+ if (_${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "LAST")
+ find_program (${_PYTHON_PREFIX}_COMPILER
+ NAMES ipyc
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_DEFAULT_PATH)
+ endif()
+
+ break()
+ endwhile()
+ else()
+ # try using root dir and registry
+ foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS)
+ if (_${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "FIRST")
+ find_program (${_PYTHON_PREFIX}_COMPILER
+ NAMES ipyc
+ HINTS ${_${_PYTHON_PREFIX}_IRON_ROOT} ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS [HKEY_LOCAL_MACHINE\\SOFTWARE\\IronPython\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath]
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ _python_validate_compiler (${_${_PYTHON_PREFIX}_VERSION} EXACT)
+ if (${_PYTHON_PREFIX}_COMPILER)
+ break()
+ endif()
+ endif()
+
+ find_program (${_PYTHON_PREFIX}_COMPILER
+ NAMES ipyc
+ HINTS ${_${_PYTHON_PREFIX}_IRON_ROOT} ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ _python_validate_compiler (${_${_PYTHON_PREFIX}_VERSION} EXACT)
+ if (${_PYTHON_PREFIX}_COMPILER)
+ break()
+ endif()
+
+ if (_${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "LAST")
+ find_program (${_PYTHON_PREFIX}_COMPILER
+ NAMES ipyc
+ PATHS [HKEY_LOCAL_MACHINE\\SOFTWARE\\IronPython\\${_${_PYTHON_PREFIX}_VERSION}\\InstallPath]
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES}
+ NO_DEFAULT_PATH)
+ _python_validate_compiler (${_${_PYTHON_PREFIX}_VERSION} EXACT)
+ if (${_PYTHON_PREFIX}_COMPILER)
+ break()
+ endif()
+ endif()
+ endforeach()
+
+ # no specific version found, re-try in standard paths
+ find_program (${_PYTHON_PREFIX}_COMPILER
+ NAMES ipyc
+ HINTS ${_${_PYTHON_PREFIX}_IRON_ROOT} ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_IRON_PYTHON_PATH_SUFFIXES})
+ endif()
+
+ if (${_PYTHON_PREFIX}_COMPILER)
+ # retrieve python environment version from compiler
+ set (_${_PYTHON_PREFIX}_VERSION_DIR "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/PythonCompilerVersion.dir")
+ file (WRITE "${_${_PYTHON_PREFIX}_VERSION_DIR}/version.py" "import sys; sys.stdout.write('.'.join([str(x) for x in sys.version_info[:3]]))\n")
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_COMPILER}" /target:exe /embed "${_${_PYTHON_PREFIX}_VERSION_DIR}/version.py"
+ WORKING_DIRECTORY "${_${_PYTHON_PREFIX}_VERSION_DIR}"
+ OUTPUT_QUIET
+ ERROR_QUIET)
+ execute_process (COMMAND "${_${_PYTHON_PREFIX}_VERSION_DIR}/version"
+ WORKING_DIRECTORY "${_${_PYTHON_PREFIX}_VERSION_DIR}"
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_VERSION
+ ERROR_QUIET)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ string (REGEX MATCHALL "[0-9]+" _${_PYTHON_PREFIX}_VERSIONS "${_${_PYTHON_PREFIX}_VERSION}")
+ list (GET _${_PYTHON_PREFIX}_VERSIONS 0 _${_PYTHON_PREFIX}_VERSION_MAJOR)
+ list (GET _${_PYTHON_PREFIX}_VERSIONS 1 _${_PYTHON_PREFIX}_VERSION_MINOR)
+ list (GET _${_PYTHON_PREFIX}_VERSIONS 2 _${_PYTHON_PREFIX}_VERSION_PATCH)
+
+ if (NOT ${_PYTHON_PREFIX}_Interpreter_FOUND)
+ # set public version information
+ set (${_PYTHON_PREFIX}_VERSION ${_${_PYTHON_PREFIX}_VERSION})
+ set (${_PYTHON_PREFIX}_VERSION_MAJOR ${_${_PYTHON_PREFIX}_VERSION_MAJOR})
+ set (${_PYTHON_PREFIX}_VERSION_MINOR ${_${_PYTHON_PREFIX}_VERSION_MINOR})
+ set (${_PYTHON_PREFIX}_VERSION_PATCH ${_${_PYTHON_PREFIX}_VERSION_PATCH})
+ endif()
+ else()
+ # compiler not usable
+ set (${_PYTHON_PREFIX}_COMPILER ${_PYTHON_PREFIX}_COMPILER-NOTFOUND CACHE INTERNAL "" FORCE)
+ endif()
+ file (REMOVE_RECURSE "${_${_PYTHON_PREFIX}_VERSION_DIR}")
+ endif()
+
+ if (${_PYTHON_PREFIX}_COMPILER)
+ if (${_PYTHON_PREFIX}_Interpreter_FOUND)
+ # Compiler must be compatible with interpreter
+ if (${_${_PYTHON_PREFIX}_VERSION_MAJOR}.${_${_PYTHON_PREFIX}_VERSION_MINOR} VERSION_EQUAL ${${_PYTHON_PREFIX}_VERSION_MAJOR}.${${_PYTHON_PREFIX}_VERSION_MINOR})
+ set (${_PYTHON_PREFIX}_Compiler_FOUND TRUE)
+ endif()
+ elseif (${_PYTHON_PREFIX}_VERSION_MAJOR VERSION_EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR)
+ set (${_PYTHON_PREFIX}_Compiler_FOUND TRUE)
+ # Use compiler version for future searches to ensure consistency
+ set (_${_PYTHON_PREFIX}_FIND_VERSIONS ${${_PYTHON_PREFIX}_VERSION_MAJOR}.${${_PYTHON_PREFIX}_VERSION_MINOR})
+ endif()
+ endif()
+
+ if (${_PYTHON_PREFIX}_Compiler_FOUND)
+ set (${_PYTHON_PREFIX}_COMPILER_ID IronPython)
+ else()
+ unset (${_PYTHON_PREFIX}_COMPILER_ID)
+ endif()
+
+ mark_as_advanced (${_PYTHON_PREFIX}_COMPILER)
+endif()
+
+
+# third step, search for the development artifacts
+## Development environment is not compatible with IronPython interpreter
+if ("Development" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS
+ AND NOT ${_PYTHON_PREFIX}_INTERPRETER_ID STREQUAL "IronPython")
+ list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_LIBRARY
+ ${_PYTHON_PREFIX}_LIBRARY_RELEASE
+ ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE
+ ${_PYTHON_PREFIX}_LIBRARY_DEBUG
+ ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG
+ ${_PYTHON_PREFIX}_INCLUDE_DIR)
+ if (${_PYTHON_PREFIX}_FIND_REQUIRED_Development)
+ list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_LIBRARY
+ ${_PYTHON_PREFIX}_INCLUDE_DIR)
+ endif()
+
+ # Support preference of static libs by adjusting CMAKE_FIND_LIBRARY_SUFFIXES
+ unset (_${_PYTHON_PREFIX}_CMAKE_FIND_LIBRARY_SUFFIXES)
+ if (DEFINED ${_PYTHON_PREFIX}_USE_STATIC_LIBS AND NOT WIN32)
+ set(_${_PYTHON_PREFIX}_CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES})
+ if(${_PYTHON_PREFIX}_USE_STATIC_LIBS)
+ set (CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX})
+ else()
+ list (REMOVE_ITEM CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX})
+ endif()
+ endif()
+
+ # if python interpreter is found, use its location and version to ensure consistency
+ # between interpreter and development environment
+ unset (_${_PYTHON_PREFIX}_PREFIX)
+ unset (_${_PYTHON_PREFIX}_EXEC_PREFIX)
+ unset (_${_PYTHON_PREFIX}_BASE_EXEC_PREFIX)
+ if (${_PYTHON_PREFIX}_Interpreter_FOUND)
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c
+ "import sys; from distutils import sysconfig; sys.stdout.write(sysconfig.EXEC_PREFIX)"
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_EXEC_PREFIX
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (_${_PYTHON_PREFIX}_RESULT)
+ unset (_${_PYTHON_PREFIX}_EXEC_PREFIX)
+ endif()
+
+ if (NOT ${_PYTHON_PREFIX}_FIND_VIRTUALENV STREQUAL "STANDARD")
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c
+ "import sys; from distutils import sysconfig; sys.stdout.write(sysconfig.BASE_EXEC_PREFIX)"
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_BASE_EXEC_PREFIX
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (_${_PYTHON_PREFIX}_RESULT)
+ unset (_${_PYTHON_PREFIX}_BASE_EXEC_PREFIX)
+ endif()
+ endif()
+ endif()
+ set (_${_PYTHON_PREFIX}_HINTS "${_${_PYTHON_PREFIX}_EXEC_PREFIX}" "${_${_PYTHON_PREFIX}_BASE_EXEC_PREFIX}" "${${_PYTHON_PREFIX}_ROOT_DIR}" ENV ${_PYTHON_PREFIX}_ROOT_DIR)
+
+ if (_${_PYTHON_PREFIX}_FIND_STRATEGY STREQUAL "LOCATION")
+ set (_${_PYTHON_PREFIX}_CONFIG_NAMES)
+
+ foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS)
+ if (DEFINED CMAKE_LIBRARY_ARCHITECTURE)
+ list (APPEND _${_PYTHON_PREFIX}_CONFIG_NAMES "${CMAKE_LIBRARY_ARCHITECTURE}-python${_${_PYTHON_PREFIX}_VERSION}-config")
+ endif()
+ list (APPEND _${_PYTHON_PREFIX}_CONFIG_NAMES "python${_${_PYTHON_PREFIX}_VERSION}-config")
+ endforeach()
+
+ find_program (_${_PYTHON_PREFIX}_CONFIG
+ NAMES ${_${_PYTHON_PREFIX}_CONFIG_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES bin)
+
+ if (_${_PYTHON_PREFIX}_CONFIG AND DEFINED CMAKE_LIBRARY_ARCHITECTURE)
+ # check that config tool match library architecture
+ execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --configdir
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_CONFIGDIR
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (_${_PYTHON_PREFIX}_RESULT)
+ unset (_${_PYTHON_PREFIX}_CONFIG CACHE)
+ else()
+ string(FIND "${_${_PYTHON_PREFIX}_CONFIGDIR}" "${CMAKE_LIBRARY_ARCHITECTURE}" _${_PYTHON_PREFIX}_RESULT)
+ if (_${_PYTHON_PREFIX}_RESULT EQUAL -1)
+ unset (_${_PYTHON_PREFIX}_CONFIG CACHE)
+ endif()
+ endif()
+ endif()
+ else()
+ foreach (_${_PYTHON_PREFIX}_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS)
+ # try to use pythonX.Y-config tool
+ set (_${_PYTHON_PREFIX}_CONFIG_NAMES)
+ if (DEFINED CMAKE_LIBRARY_ARCHITECTURE)
+ set (_${_PYTHON_PREFIX}_CONFIG_NAMES "${CMAKE_LIBRARY_ARCHITECTURE}-python${_${_PYTHON_PREFIX}_VERSION}-config")
+ endif()
+ list (APPEND _${_PYTHON_PREFIX}_CONFIG_NAMES "python${_${_PYTHON_PREFIX}_VERSION}-config")
+ find_program (_${_PYTHON_PREFIX}_CONFIG
+ NAMES ${_${_PYTHON_PREFIX}_CONFIG_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES bin)
+ unset (_${_PYTHON_PREFIX}_CONFIG_NAMES)
+
+ if (NOT _${_PYTHON_PREFIX}_CONFIG)
+ continue()
+ endif()
+ if (DEFINED CMAKE_LIBRARY_ARCHITECTURE)
+ # check that config tool match library architecture
+ execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --configdir
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_CONFIGDIR
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (_${_PYTHON_PREFIX}_RESULT)
+ unset (_${_PYTHON_PREFIX}_CONFIG CACHE)
+ continue()
+ endif()
+ string(FIND "${_${_PYTHON_PREFIX}_CONFIGDIR}" "${CMAKE_LIBRARY_ARCHITECTURE}" _${_PYTHON_PREFIX}_RESULT)
+ if (_${_PYTHON_PREFIX}_RESULT EQUAL -1)
+ unset (_${_PYTHON_PREFIX}_CONFIG CACHE)
+ continue()
+ endif()
+ endif()
+
+ if (_${_PYTHON_PREFIX}_CONFIG)
+ break()
+ endif()
+ endforeach()
+ endif()
+
+ if (_${_PYTHON_PREFIX}_CONFIG)
+ # retrieve root install directory
+ execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --prefix
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_PREFIX
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (_${_PYTHON_PREFIX}_RESULT)
+ # python-config is not usable
+ unset (_${_PYTHON_PREFIX}_CONFIG CACHE)
+ endif()
+ endif()
+
+ if (_${_PYTHON_PREFIX}_CONFIG)
+ set (_${_PYTHON_PREFIX}_HINTS "${_${_PYTHON_PREFIX}_PREFIX}")
+
+ unset (_${_PYTHON_PREFIX}_LIB_DIRS)
+ unset (_${_PYTHON_PREFIX}_PATH_SUFFIXES)
+ unset (_${_PYTHON_PREFIX}_LIB_NAMES)
+
+ # retrieve library
+ execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --ldflags
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_FLAGS
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ # retrieve library directory
+ string (REGEX MATCHALL "-L[^ ]+" _${_PYTHON_PREFIX}_LIB_DIRS "${_${_PYTHON_PREFIX}_FLAGS}")
+ string (REPLACE "-L" "" _${_PYTHON_PREFIX}_LIB_DIRS "${_${_PYTHON_PREFIX}_LIB_DIRS}")
+ if (_${_PYTHON_PREFIX}_CONFIG MATCHES "python([0-9.]+)-config")
+ _python_get_path_suffixes (_${_PYTHON_PREFIX}_PATH_SUFFIXES ${CMAKE_MATCH_1} LIBRARY)
+ endif()
+
+ # retrieve library name
+ string (REGEX MATCHALL "-lpython[^ ]+" _${_PYTHON_PREFIX}_LIB_NAMES "${_${_PYTHON_PREFIX}_FLAGS}")
+ string (REPLACE "-l" "" _${_PYTHON_PREFIX}_LIB_NAMES "${_${_PYTHON_PREFIX}_LIB_NAMES}")
+ list (REMOVE_DUPLICATES _${_PYTHON_PREFIX}_LIB_NAMES)
+ endif()
+
+ execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --configdir
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_CONFIGDIR
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ list (APPEND _${_PYTHON_PREFIX}_LIB_DIRS "${_${_PYTHON_PREFIX}_CONFIGDIR}")
+ endif()
+ list (REMOVE_DUPLICATES _${_PYTHON_PREFIX}_LIB_DIRS)
+ list (APPEND _${_PYTHON_PREFIX}_HINTS ${_${_PYTHON_PREFIX}_LIB_DIRS})
+
+ if (NOT _${_PYTHON_PREFIX}_LIB_NAMES)
+ # config tool do not specify "-l" option (it is the case starting with 3.8)
+ # extract version from the config tool name and list all possible lib names
+ if (_${_PYTHON_PREFIX}_CONFIG MATCHES "python([0-9.]+)-config")
+ _python_get_lib_names (_${_PYTHON_PREFIX}_LIB_NAMES ${CMAKE_MATCH_1})
+ endif()
+ endif()
+
+ list (APPEND _${_PYTHON_PREFIX}_HINTS "${${_PYTHON_PREFIX}_ROOT_DIR}" ENV ${_PYTHON_PREFIX}_ROOT_DIR)
+
+ find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+
+ # retrieve runtime library
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE)
+ get_filename_component (_${_PYTHON_PREFIX}_PATH "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}" DIRECTORY)
+ get_filename_component (_${_PYTHON_PREFIX}_PATH2 "${_${_PYTHON_PREFIX}_PATH}" DIRECTORY)
+ _python_find_runtime_library (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ HINTS "${_${_PYTHON_PREFIX}_PATH}" "${_${_PYTHON_PREFIX}_PATH2}" ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES bin
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+
+ # retrieve include directory
+ execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --includes
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_FLAGS
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ # retrieve include directory
+ string (REGEX MATCHALL "-I[^ ]+" _${_PYTHON_PREFIX}_INCLUDE_DIRS "${_${_PYTHON_PREFIX}_FLAGS}")
+ string (REPLACE "-I" "" _${_PYTHON_PREFIX}_INCLUDE_DIRS "${_${_PYTHON_PREFIX}_INCLUDE_DIRS}")
+ list (REMOVE_DUPLICATES _${_PYTHON_PREFIX}_INCLUDE_DIRS)
+
+ find_path (${_PYTHON_PREFIX}_INCLUDE_DIR
+ NAMES Python.h
+ HINTS ${_${_PYTHON_PREFIX}_INCLUDE_DIRS}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+ endif()
+
+ # Rely on HINTS and standard paths if config tool failed to locate artifacts
+ if (NOT ${_PYTHON_PREFIX}_LIBRARY_RELEASE OR NOT ${_PYTHON_PREFIX}_INCLUDE_DIR)
+ set (_${_PYTHON_PREFIX}_HINTS "${${_PYTHON_PREFIX}_ROOT_DIR}" ENV ${_PYTHON_PREFIX}_ROOT_DIR)
+
+ if (_${_PYTHON_PREFIX}_FIND_STRATEGY STREQUAL "LOCATION")
+ unset (_${_PYTHON_PREFIX}_LIB_NAMES)
+ unset (_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG)
+ unset (_${_PYTHON_PREFIX}_FRAMEWORK_PATHS)
+ unset (_${_PYTHON_PREFIX}_REGISTRY_PATHS)
+ unset (_${_PYTHON_PREFIX}_PATH_SUFFIXES)
+
+ foreach (_${_PYTHON_PREFIX}_LIB_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS)
+ # library names
+ _python_get_lib_names (_${_PYTHON_PREFIX}_VERSION_NAMES ${_${_PYTHON_PREFIX}_LIB_VERSION})
+ list (APPEND _${_PYTHON_PREFIX}_LIB_NAMES ${_${_PYTHON_PREFIX}_VERSION_NAMES})
+ _python_get_lib_names (_${_PYTHON_PREFIX}_VERSION_NAMES ${_${_PYTHON_PREFIX}_LIB_VERSION} DEBUG)
+ list (APPEND _${_PYTHON_PREFIX}_LIB_NAMES_DEBUG ${_${_PYTHON_PREFIX}_VERSION_NAMES})
+
+ # Framework Paths
+ _python_get_frameworks (_${_PYTHON_PREFIX}_VERSION_PATHS ${_${_PYTHON_PREFIX}_LIB_VERSION})
+ list (APPEND _${_PYTHON_PREFIX}_FRAMEWORK_PATHS ${_${_PYTHON_PREFIX}_VERSION_PATHS})
+
+ # Registry Paths
+ _python_get_registries (_${_PYTHON_PREFIX}_VERSION_PATHS ${_${_PYTHON_PREFIX}_LIB_VERSION})
+ list (APPEND _${_PYTHON_PREFIX}_REGISTRY_PATHS ${_${_PYTHON_PREFIX}_VERSION_PATHS})
+
+ # Paths suffixes
+ _python_get_path_suffixes (_${_PYTHON_PREFIX}_VERSION_PATHS ${_${_PYTHON_PREFIX}_LIB_VERSION} LIBRARY)
+ list (APPEND _${_PYTHON_PREFIX}_PATH_SUFFIXES ${_${_PYTHON_PREFIX}_VERSION_PATHS})
+ endforeach()
+
+ if (APPLE AND _${_PYTHON_PREFIX}_FIND_FRAMEWORK STREQUAL "FIRST")
+ find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES}
+ NO_CMAKE_PATH
+ NO_CMAKE_ENVIRONMENT_PATH
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+
+ if (WIN32 AND _${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "FIRST")
+ find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+
+ # search in HINTS locations
+ find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+
+ if (APPLE AND _${_PYTHON_PREFIX}_FIND_FRAMEWORK STREQUAL "LAST")
+ set (__${_PYTHON_PREFIX}_FRAMEWORK_PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS})
+ else()
+ unset (__${_PYTHON_PREFIX}_FRAMEWORK_PATHS)
+ endif()
+
+ if (WIN32 AND _${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "LAST")
+ set (__${_PYTHON_PREFIX}_REGISTRY_PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS})
+ else()
+ unset (__${_PYTHON_PREFIX}_REGISTRY_PATHS)
+ endif()
+
+ # search in all default paths
+ find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ PATHS ${__${_PYTHON_PREFIX}_FRAMEWORK_PATHS}
+ ${__${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES})
+
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE)
+ # extract version from library name
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE MATCHES "python([23])([0-9]+)")
+ set (_${_PYTHON_PREFIX}_VERSION "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}")
+ elseif (${_PYTHON_PREFIX}_LIBRARY_RELEASE MATCHES "python([23])\\.([0-9]+)")
+ set (_${_PYTHON_PREFIX}_VERSION "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}")
+ endif()
+ endif()
+
+ if (WIN32)
+ # search for debug library
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE)
+ # use library location as a hint
+ _python_get_lib_names (_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG ${_${_PYTHON_PREFIX}_VERSION} DEBUG)
+ get_filename_component (_${_PYTHON_PREFIX}_PATH "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}" DIRECTORY)
+ find_library (${_PYTHON_PREFIX}_LIBRARY_DEBUG
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG}
+ NAMES_PER_DIR
+ HINTS "${_${_PYTHON_PREFIX}_PATH}" ${_${_PYTHON_PREFIX}_HINTS}
+ NO_DEFAULT_PATH)
+ else()
+ # search first in known locations
+ if (_${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "FIRST")
+ find_library (${_PYTHON_PREFIX}_LIBRARY_DEBUG
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES lib libs
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+ # search in all default paths
+ find_library (${_PYTHON_PREFIX}_LIBRARY_DEBUG
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${__${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES lib libs)
+
+ # extract version from library name
+ if (${_PYTHON_PREFIX}_LIBRARY_DEBUG MATCHES "python([23])([0-9]+)")
+ set (_${_PYTHON_PREFIX}_VERSION "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}")
+ elseif (${_PYTHON_PREFIX}_LIBRARY_DEBUG MATCHES "python([23])\\.([0-9]+)")
+ set (_${_PYTHON_PREFIX}_VERSION "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}")
+ endif()
+ endif()
+ endif()
+ else()
+ foreach (_${_PYTHON_PREFIX}_LIB_VERSION IN LISTS _${_PYTHON_PREFIX}_FIND_VERSIONS)
+ _python_get_lib_names (_${_PYTHON_PREFIX}_LIB_NAMES ${_${_PYTHON_PREFIX}_LIB_VERSION})
+ _python_get_lib_names (_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG ${_${_PYTHON_PREFIX}_LIB_VERSION} DEBUG)
+
+ _python_get_frameworks (_${_PYTHON_PREFIX}_FRAMEWORK_PATHS ${_${_PYTHON_PREFIX}_LIB_VERSION})
+ _python_get_registries (_${_PYTHON_PREFIX}_REGISTRY_PATHS ${_${_PYTHON_PREFIX}_LIB_VERSION})
+
+ _python_get_path_suffixes (_${_PYTHON_PREFIX}_PATH_SUFFIXES ${_${_PYTHON_PREFIX}_LIB_VERSION} LIBRARY)
+
+ if (APPLE AND _${_PYTHON_PREFIX}_FIND_FRAMEWORK STREQUAL "FIRST")
+ find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES}
+ NO_CMAKE_PATH
+ NO_CMAKE_ENVIRONMENT_PATH
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+
+ if (WIN32 AND _${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "FIRST")
+ find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+
+ # search in HINTS locations
+ find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+
+ if (APPLE AND _${_PYTHON_PREFIX}_FIND_FRAMEWORK STREQUAL "LAST")
+ set (__${_PYTHON_PREFIX}_FRAMEWORK_PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS})
+ else()
+ unset (__${_PYTHON_PREFIX}_FRAMEWORK_PATHS)
+ endif()
+
+ if (WIN32 AND _${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "LAST")
+ set (__${_PYTHON_PREFIX}_REGISTRY_PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS})
+ else()
+ unset (__${_PYTHON_PREFIX}_REGISTRY_PATHS)
+ endif()
+
+ # search in all default paths
+ find_library (${_PYTHON_PREFIX}_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ PATHS ${__${_PYTHON_PREFIX}_FRAMEWORK_PATHS}
+ ${__${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES})
+
+ if (WIN32)
+ # search for debug library
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE)
+ # use library location as a hint
+ get_filename_component (_${_PYTHON_PREFIX}_PATH "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}" DIRECTORY)
+ find_library (${_PYTHON_PREFIX}_LIBRARY_DEBUG
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG}
+ NAMES_PER_DIR
+ HINTS "${_${_PYTHON_PREFIX}_PATH}" ${_${_PYTHON_PREFIX}_HINTS}
+ NO_DEFAULT_PATH)
+ else()
+ # search first in known locations
+ if (_${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "FIRST")
+ find_library (${_PYTHON_PREFIX}_LIBRARY_DEBUG
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES lib libs
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+ # search in all default paths
+ find_library (${_PYTHON_PREFIX}_LIBRARY_DEBUG
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG}
+ NAMES_PER_DIR
+ HINTS ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${__${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES lib libs)
+ endif()
+ endif()
+
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE OR ${_PYTHON_PREFIX}_LIBRARY_DEBUG)
+ set (_${_PYTHON_PREFIX}_VERSION ${_${_PYTHON_PREFIX}_LIB_VERSION})
+ break()
+ endif()
+ endforeach()
+ endif()
+
+ # retrieve runtime libraries
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE)
+ _python_get_lib_names (_${_PYTHON_PREFIX}_LIB_NAMES ${_${_PYTHON_PREFIX}_VERSION})
+ get_filename_component (_${_PYTHON_PREFIX}_PATH "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}" DIRECTORY)
+ get_filename_component (_${_PYTHON_PREFIX}_PATH2 "${_${_PYTHON_PREFIX}_PATH}" DIRECTORY)
+ _python_find_runtime_library (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES}
+ NAMES_PER_DIR
+ HINTS "${_${_PYTHON_PREFIX}_PATH}" "${_${_PYTHON_PREFIX}_PATH2}" ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES bin)
+ endif()
+ if (${_PYTHON_PREFIX}_LIBRARY_DEBUG)
+ _python_get_lib_names (_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG ${_${_PYTHON_PREFIX}_VERSION} DEBUG)
+ get_filename_component (_${_PYTHON_PREFIX}_PATH "${${_PYTHON_PREFIX}_LIBRARY_DEBUG}" DIRECTORY)
+ get_filename_component (_${_PYTHON_PREFIX}_PATH2 "${_${_PYTHON_PREFIX}_PATH}" DIRECTORY)
+ _python_find_runtime_library (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG
+ NAMES ${_${_PYTHON_PREFIX}_LIB_NAMES_DEBUG}
+ NAMES_PER_DIR
+ HINTS "${_${_PYTHON_PREFIX}_PATH}" "${_${_PYTHON_PREFIX}_PATH2}" ${_${_PYTHON_PREFIX}_HINTS}
+ PATH_SUFFIXES bin)
+ endif()
+
+ # Don't search for include dir if no library was founded
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE OR ${_PYTHON_PREFIX}_LIBRARY_DEBUG)
+ unset (_${_PYTHON_PREFIX}_INCLUDE_HINTS)
+
+ if (${_PYTHON_PREFIX}_EXECUTABLE)
+ # pick up include directory from configuration
+ execute_process (COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c
+ "import sys; import sysconfig; sys.stdout.write(sysconfig.get_path('include'))"
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_PATH
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ file (TO_CMAKE_PATH "${_${_PYTHON_PREFIX}_PATH}" _${_PYTHON_PREFIX}_PATH)
+ list (APPEND _${_PYTHON_PREFIX}_INCLUDE_HINTS "${_${_PYTHON_PREFIX}_PATH}")
+ endif()
+ endif()
+
+ foreach (_${_PYTHON_PREFIX}_LIB IN ITEMS ${_PYTHON_PREFIX}_LIBRARY_RELEASE ${_PYTHON_PREFIX}_LIBRARY_DEBUG)
+ if (${_${_PYTHON_PREFIX}_LIB})
+ # Use the library's install prefix as a hint
+ if (${_${_PYTHON_PREFIX}_LIB} MATCHES "^(.+/Frameworks/Python.framework/Versions/[0-9.]+)")
+ list (APPEND _${_PYTHON_PREFIX}_INCLUDE_HINTS "${CMAKE_MATCH_1}")
+ elseif (${_${_PYTHON_PREFIX}_LIB} MATCHES "^(.+)/lib(64|32)?/python[0-9.]+/config")
+ list (APPEND _${_PYTHON_PREFIX}_INCLUDE_HINTS "${CMAKE_MATCH_1}")
+ elseif (DEFINED CMAKE_LIBRARY_ARCHITECTURE AND ${_${_PYTHON_PREFIX}_LIB} MATCHES "^(.+)/lib/${CMAKE_LIBRARY_ARCHITECTURE}")
+ list (APPEND _${_PYTHON_PREFIX}_INCLUDE_HINTS "${CMAKE_MATCH_1}")
+ else()
+ # assume library is in a directory under root
+ get_filename_component (_${_PYTHON_PREFIX}_PREFIX "${${_${_PYTHON_PREFIX}_LIB}}" DIRECTORY)
+ get_filename_component (_${_PYTHON_PREFIX}_PREFIX "${_${_PYTHON_PREFIX}_PREFIX}" DIRECTORY)
+ list (APPEND _${_PYTHON_PREFIX}_INCLUDE_HINTS "${_${_PYTHON_PREFIX}_PREFIX}")
+ endif()
+ endif()
+ endforeach()
+ list (REMOVE_DUPLICATES _${_PYTHON_PREFIX}_INCLUDE_HINTS)
+
+ _python_get_frameworks (_${_PYTHON_PREFIX}_FRAMEWORK_PATHS ${_${_PYTHON_PREFIX}_VERSION})
+ _python_get_registries (_${_PYTHON_PREFIX}_REGISTRY_PATHS ${_${_PYTHON_PREFIX}_VERSION})
+ _python_get_path_suffixes (_${_PYTHON_PREFIX}_PATH_SUFFIXES ${_${_PYTHON_PREFIX}_VERSION} INCLUDE)
+
+ if (APPLE AND _${_PYTHON_PREFIX}_FIND_FRAMEWORK STREQUAL "FIRST")
+ find_path (${_PYTHON_PREFIX}_INCLUDE_DIR
+ NAMES Python.h
+ HINTS ${_${_PYTHON_PREFIX}_INCLUDE_HINTS} ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES}
+ NO_CMAKE_PATH
+ NO_CMAKE_ENVIRONMENT_PATH
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+
+ if (WIN32 AND _${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "FIRST")
+ find_path (${_PYTHON_PREFIX}_INCLUDE_DIR
+ NAMES Python.h
+ HINTS ${_${_PYTHON_PREFIX}_INCLUDE_HINTS} ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+
+ if (APPLE AND _${_PYTHON_PREFIX}_FIND_FRAMEWORK STREQUAL "LAST")
+ set (__${_PYTHON_PREFIX}_FRAMEWORK_PATHS ${_${_PYTHON_PREFIX}_FRAMEWORK_PATHS})
+ else()
+ unset (__${_PYTHON_PREFIX}_FRAMEWORK_PATHS)
+ endif()
+
+ if (WIN32 AND _${_PYTHON_PREFIX}_FIND_REGISTRY STREQUAL "LAST")
+ set (__${_PYTHON_PREFIX}_REGISTRY_PATHS ${_${_PYTHON_PREFIX}_REGISTRY_PATHS})
+ else()
+ unset (__${_PYTHON_PREFIX}_REGISTRY_PATHS)
+ endif()
+
+ find_path (${_PYTHON_PREFIX}_INCLUDE_DIR
+ NAMES Python.h
+ HINTS ${_${_PYTHON_PREFIX}_INCLUDE_HINTS} ${_${_PYTHON_PREFIX}_HINTS}
+ PATHS ${__${_PYTHON_PREFIX}_FRAMEWORK_PATHS}
+ ${__${_PYTHON_PREFIX}_REGISTRY_PATHS}
+ PATH_SUFFIXES ${_${_PYTHON_PREFIX}_PATH_SUFFIXES}
+ NO_SYSTEM_ENVIRONMENT_PATH
+ NO_CMAKE_SYSTEM_PATH)
+ endif()
+
+ # search header file in standard locations
+ find_path (${_PYTHON_PREFIX}_INCLUDE_DIR
+ NAMES Python.h)
+ endif()
+
+ if (${_PYTHON_PREFIX}_INCLUDE_DIR)
+ # retrieve version from header file
+ file (STRINGS "${${_PYTHON_PREFIX}_INCLUDE_DIR}/patchlevel.h" _${_PYTHON_PREFIX}_VERSION
+ REGEX "^#define[ \t]+PY_VERSION[ \t]+\"[^\"]+\"")
+ string (REGEX REPLACE "^#define[ \t]+PY_VERSION[ \t]+\"([^\"]+)\".*" "\\1"
+ _${_PYTHON_PREFIX}_VERSION "${_${_PYTHON_PREFIX}_VERSION}")
+ string (REGEX MATCHALL "[0-9]+" _${_PYTHON_PREFIX}_VERSIONS "${_${_PYTHON_PREFIX}_VERSION}")
+ list (GET _${_PYTHON_PREFIX}_VERSIONS 0 _${_PYTHON_PREFIX}_VERSION_MAJOR)
+ list (GET _${_PYTHON_PREFIX}_VERSIONS 1 _${_PYTHON_PREFIX}_VERSION_MINOR)
+ list (GET _${_PYTHON_PREFIX}_VERSIONS 2 _${_PYTHON_PREFIX}_VERSION_PATCH)
+
+ if (NOT ${_PYTHON_PREFIX}_Interpreter_FOUND AND NOT ${_PYTHON_PREFIX}_Compiler_FOUND)
+ # set public version information
+ set (${_PYTHON_PREFIX}_VERSION ${_${_PYTHON_PREFIX}_VERSION})
+ set (${_PYTHON_PREFIX}_VERSION_MAJOR ${_${_PYTHON_PREFIX}_VERSION_MAJOR})
+ set (${_PYTHON_PREFIX}_VERSION_MINOR ${_${_PYTHON_PREFIX}_VERSION_MINOR})
+ set (${_PYTHON_PREFIX}_VERSION_PATCH ${_${_PYTHON_PREFIX}_VERSION_PATCH})
+ endif()
+ endif()
+
+ # define public variables
+ include (${CMAKE_CURRENT_LIST_DIR}/../SelectLibraryConfigurations.cmake)
+ select_library_configurations (${_PYTHON_PREFIX})
+ if (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE)
+ set (${_PYTHON_PREFIX}_RUNTIME_LIBRARY "${${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE}")
+ elseif (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG)
+ set (${_PYTHON_PREFIX}_RUNTIME_LIBRARY "${${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG}")
+ else()
+ set (${_PYTHON_PREFIX}_RUNTIME_LIBRARY "$${_PYTHON_PREFIX}_RUNTIME_LIBRARY-NOTFOUND")
+ endif()
+
+ _python_set_library_dirs (${_PYTHON_PREFIX}_LIBRARY_DIRS
+ ${_PYTHON_PREFIX}_LIBRARY_RELEASE ${_PYTHON_PREFIX}_LIBRARY_DEBUG)
+ if (UNIX)
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE MATCHES "${CMAKE_SHARED_LIBRARY_SUFFIX}$"
+ OR ${_PYTHON_PREFIX}_LIBRARY_RELEASE MATCHES "${CMAKE_SHARED_LIBRARY_SUFFIX}$")
+ set (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DIRS ${${_PYTHON_PREFIX}_LIBRARY_DIRS})
+ endif()
+ else()
+ _python_set_library_dirs (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DIRS
+ ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG)
+ endif()
+
+ set (${_PYTHON_PREFIX}_INCLUDE_DIRS "${${_PYTHON_PREFIX}_INCLUDE_DIR}")
+
+ mark_as_advanced (${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE
+ ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG
+ ${_PYTHON_PREFIX}_INCLUDE_DIR)
+
+ if ((${_PYTHON_PREFIX}_LIBRARY_RELEASE OR ${_PYTHON_PREFIX}_LIBRARY_DEBUG)
+ AND ${_PYTHON_PREFIX}_INCLUDE_DIR)
+ if (${_PYTHON_PREFIX}_Interpreter_FOUND OR ${_PYTHON_PREFIX}_Compiler_FOUND)
+ # development environment must be compatible with interpreter/compiler
+ if (${_${_PYTHON_PREFIX}_VERSION_MAJOR}.${_${_PYTHON_PREFIX}_VERSION_MINOR} VERSION_EQUAL ${${_PYTHON_PREFIX}_VERSION_MAJOR}.${${_PYTHON_PREFIX}_VERSION_MINOR})
+ set (${_PYTHON_PREFIX}_Development_FOUND TRUE)
+ endif()
+ elseif (${_PYTHON_PREFIX}_VERSION_MAJOR VERSION_EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR)
+ set (${_PYTHON_PREFIX}_Development_FOUND TRUE)
+ endif()
+ endif()
+
+ # Restore the original find library ordering
+ if (DEFINED _${_PYTHON_PREFIX}_CMAKE_FIND_LIBRARY_SUFFIXES)
+ set (CMAKE_FIND_LIBRARY_SUFFIXES ${_${_PYTHON_PREFIX}_CMAKE_FIND_LIBRARY_SUFFIXES})
+ endif()
+endif()
+
+if ("NumPy" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS AND ${_PYTHON_PREFIX}_Interpreter_FOUND)
+ list (APPEND _${_PYTHON_PREFIX}_CACHED_VARS ${_PYTHON_PREFIX}_NumPy_INCLUDE_DIR)
+ if (${_PYTHON_PREFIX}_FIND_REQUIRED_NumPy)
+ list (APPEND _${_PYTHON_PREFIX}_REQUIRED_VARS ${_PYTHON_PREFIX}_NumPy_INCLUDE_DIR)
+ endif()
+ execute_process(
+ COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c
+ "from __future__ import print_function\ntry: import numpy; print(numpy.get_include(), end='')\nexcept:pass\n"
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_NumPy_PATH
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ find_path(${_PYTHON_PREFIX}_NumPy_INCLUDE_DIR
+ NAMES "numpy/arrayobject.h" "numpy/numpyconfig.h"
+ HINTS "${_${_PYTHON_PREFIX}_NumPy_PATH}"
+ NO_DEFAULT_PATH)
+ endif()
+ if(${_PYTHON_PREFIX}_NumPy_INCLUDE_DIR)
+ set(${_PYTHON_PREFIX}_NumPy_INCLUDE_DIRS "${${_PYTHON_PREFIX}_NumPy_INCLUDE_DIR}")
+ set(${_PYTHON_PREFIX}_NumPy_FOUND TRUE)
+ endif()
+ if(${_PYTHON_PREFIX}_NumPy_FOUND)
+ execute_process(
+ COMMAND "${${_PYTHON_PREFIX}_EXECUTABLE}" -c
+ "from __future__ import print_function\ntry: import numpy; print(numpy.__version__, end='')\nexcept:pass\n"
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_NumPy_VERSION)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ set(${_PYTHON_PREFIX}_NumPy_VERSION "${_${_PYTHON_PREFIX}_NumPy_VERSION}")
+ endif()
+ endif()
+ # final step: set NumPy founded only if Development component is founded as well
+ if (NOT ${_PYTHON_PREFIX}_Development_FOUND)
+ set(${_PYTHON_PREFIX}_NumPy_FOUND FALSE)
+ endif()
+endif()
+
+# final validation
+if (${_PYTHON_PREFIX}_VERSION_MAJOR AND
+ NOT ${_PYTHON_PREFIX}_VERSION_MAJOR VERSION_EQUAL _${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR)
+ _python_display_failure ("Could NOT find ${_PYTHON_PREFIX}: Found unsuitable major version \"${${_PYTHON_PREFIX}_VERSION_MAJOR}\", but required major version is exact version \"${_${_PYTHON_PREFIX}_REQUIRED_VERSION_MAJOR}\"")
+endif()
+
+include (${CMAKE_CURRENT_LIST_DIR}/../FindPackageHandleStandardArgs.cmake)
+find_package_handle_standard_args (${_PYTHON_PREFIX}
+ REQUIRED_VARS ${_${_PYTHON_PREFIX}_REQUIRED_VARS}
+ VERSION_VAR ${_PYTHON_PREFIX}_VERSION
+ HANDLE_COMPONENTS)
+
+# Create imported targets and helper functions
+if(_${_PYTHON_PREFIX}_CMAKE_ROLE STREQUAL "PROJECT")
+ if ("Interpreter" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS
+ AND ${_PYTHON_PREFIX}_Interpreter_FOUND
+ AND NOT TARGET ${_PYTHON_PREFIX}::Interpreter)
+ add_executable (${_PYTHON_PREFIX}::Interpreter IMPORTED)
+ set_property (TARGET ${_PYTHON_PREFIX}::Interpreter
+ PROPERTY IMPORTED_LOCATION "${${_PYTHON_PREFIX}_EXECUTABLE}")
+ endif()
+
+ if ("Compiler" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS
+ AND ${_PYTHON_PREFIX}_Compiler_FOUND
+ AND NOT TARGET ${_PYTHON_PREFIX}::Compiler)
+ add_executable (${_PYTHON_PREFIX}::Compiler IMPORTED)
+ set_property (TARGET ${_PYTHON_PREFIX}::Compiler
+ PROPERTY IMPORTED_LOCATION "${${_PYTHON_PREFIX}_COMPILER}")
+ endif()
+
+ if ("Development" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS
+ AND ${_PYTHON_PREFIX}_Development_FOUND)
+
+ macro (__PYTHON_IMPORT_LIBRARY __name)
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE MATCHES "${CMAKE_SHARED_LIBRARY_SUFFIX}$"
+ OR ${_PYTHON_PREFIX}_LIBRARY_DEBUG MATCHES "${CMAKE_SHARED_LIBRARY_SUFFIX}$"
+ OR ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE OR ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG)
+ set (_${_PYTHON_PREFIX}_LIBRARY_TYPE SHARED)
+ else()
+ set (_${_PYTHON_PREFIX}_LIBRARY_TYPE STATIC)
+ endif()
+
+ add_library (${__name} ${_${_PYTHON_PREFIX}_LIBRARY_TYPE} IMPORTED)
+
+ set_property (TARGET ${__name}
+ PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${${_PYTHON_PREFIX}_INCLUDE_DIR}")
+
+ if ((${_PYTHON_PREFIX}_LIBRARY_RELEASE AND ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE)
+ OR (${_PYTHON_PREFIX}_LIBRARY_DEBUG AND ${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG))
+ # System manage shared libraries in two parts: import and runtime
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE AND ${_PYTHON_PREFIX}_LIBRARY_DEBUG)
+ set_property (TARGET ${__name} PROPERTY IMPORTED_CONFIGURATIONS RELEASE DEBUG)
+ set_target_properties (${__name}
+ PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C"
+ IMPORTED_IMPLIB_RELEASE "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}"
+ IMPORTED_LOCATION_RELEASE "${${_PYTHON_PREFIX}_RUNTIME_LIBRARY_RELEASE}")
+ set_target_properties (${__name}
+ PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
+ IMPORTED_IMPLIB_DEBUG "${${_PYTHON_PREFIX}_LIBRARY_DEBUG}"
+ IMPORTED_LOCATION_DEBUG "${${_PYTHON_PREFIX}_RUNTIME_LIBRARY_DEBUG}")
+ else()
+ set_target_properties (${__name}
+ PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES "C"
+ IMPORTED_IMPLIB "${${_PYTHON_PREFIX}_LIBRARY}"
+ IMPORTED_LOCATION "${${_PYTHON_PREFIX}_RUNTIME_LIBRARY}")
+ endif()
+ else()
+ if (${_PYTHON_PREFIX}_LIBRARY_RELEASE AND ${_PYTHON_PREFIX}_LIBRARY_DEBUG)
+ set_property (TARGET ${_PYTHON_PREFIX}::Python PROPERTY IMPORTED_CONFIGURATIONS RELEASE DEBUG)
+ set_target_properties (${__name}
+ PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C"
+ IMPORTED_LOCATION_RELEASE "${${_PYTHON_PREFIX}_LIBRARY_RELEASE}")
+ set_target_properties (${__name}
+ PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
+ IMPORTED_LOCATION_DEBUG "${${_PYTHON_PREFIX}_LIBRARY_DEBUG}")
+ else()
+ set_target_properties (${__name}
+ PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES "C"
+ IMPORTED_LOCATION "${${_PYTHON_PREFIX}_LIBRARY}")
+ endif()
+ endif()
+
+ if (_${_PYTHON_PREFIX}_CONFIG AND _${_PYTHON_PREFIX}_LIBRARY_TYPE STREQUAL "STATIC")
+ # extend link information with dependent libraries
+ execute_process (COMMAND "${_${_PYTHON_PREFIX}_CONFIG}" --ldflags
+ RESULT_VARIABLE _${_PYTHON_PREFIX}_RESULT
+ OUTPUT_VARIABLE _${_PYTHON_PREFIX}_FLAGS
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (NOT _${_PYTHON_PREFIX}_RESULT)
+ string (REGEX MATCHALL "-[Ll][^ ]+" _${_PYTHON_PREFIX}_LINK_LIBRARIES "${_${_PYTHON_PREFIX}_FLAGS}")
+ # remove elements relative to python library itself
+ list (FILTER _${_PYTHON_PREFIX}_LINK_LIBRARIES EXCLUDE REGEX "-lpython")
+ foreach (_${_PYTHON_PREFIX}_DIR IN LISTS ${_PYTHON_PREFIX}_LIBRARY_DIRS)
+ list (FILTER _${_PYTHON_PREFIX}_LINK_LIBRARIES EXCLUDE REGEX "-L${${_PYTHON_PREFIX}_DIR}")
+ endforeach()
+ set_property (TARGET ${__name}
+ PROPERTY INTERFACE_LINK_LIBRARIES ${_${_PYTHON_PREFIX}_LINK_LIBRARIES})
+ endif()
+ endif()
+ endmacro()
+
+ if (NOT TARGET ${_PYTHON_PREFIX}::Python)
+ __python_import_library (${_PYTHON_PREFIX}::Python)
+ endif()
+
+ if (NOT TARGET ${_PYTHON_PREFIX}::Module)
+ if (CMAKE_SYSTEM_NAME MATCHES "^(Windows.*|CYGWIN|MSYS)$")
+ # On Windows/CYGWIN/MSYS, Python::Module is the same as Python::Python
+ # but ALIAS cannot be used because the imported library is not GLOBAL.
+ __python_import_library (${_PYTHON_PREFIX}::Module)
+ else()
+ add_library (${_PYTHON_PREFIX}::Module INTERFACE IMPORTED)
+ set_property (TARGET ${_PYTHON_PREFIX}::Module
+ PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${${_PYTHON_PREFIX}_INCLUDE_DIR}")
+
+ # When available, enforce shared library generation with undefined symbols
+ if (APPLE)
+ set_property (TARGET ${_PYTHON_PREFIX}::Module
+ PROPERTY INTERFACE_LINK_OPTIONS "LINKER:-undefined,dynamic_lookup")
+ endif()
+ if (CMAKE_SYSTEM_NAME STREQUAL "SunOS")
+ set_property (TARGET ${_PYTHON_PREFIX}::Module
+ PROPERTY INTERFACE_LINK_OPTIONS "LINKER:-z,nodefs")
+ endif()
+ if (CMAKE_SYSTEM_NAME STREQUAL "AIX")
+ set_property (TARGET ${_PYTHON_PREFIX}::Module
+ PROPERTY INTERFACE_LINK_OPTIONS "LINKER:-b,erok")
+ endif()
+ endif()
+ endif()
+
+ #
+ # PYTHON_ADD_LIBRARY (<name> [STATIC|SHARED|MODULE] src1 src2 ... srcN)
+ # It is used to build modules for python.
+ #
+ function (__${_PYTHON_PREFIX}_ADD_LIBRARY prefix name)
+ cmake_parse_arguments (PARSE_ARGV 2 PYTHON_ADD_LIBRARY
+ "STATIC;SHARED;MODULE" "" "")
+
+ unset (type)
+ if (NOT (PYTHON_ADD_LIBRARY_STATIC
+ OR PYTHON_ADD_LIBRARY_SHARED
+ OR PYTHON_ADD_LIBRARY_MODULE))
+ set (type MODULE)
+ endif()
+ add_library (${name} ${type} ${ARGN})
+
+ get_property (type TARGET ${name} PROPERTY TYPE)
+
+ if (type STREQUAL "MODULE_LIBRARY")
+ target_link_libraries (${name} PRIVATE ${prefix}::Module)
+ # customize library name to follow module name rules
+ set_property (TARGET ${name} PROPERTY PREFIX "")
+ if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
+ set_property (TARGET ${name} PROPERTY SUFFIX ".pyd")
+ endif()
+ else()
+ target_link_libraries (${name} PRIVATE ${prefix}::Python)
+ endif()
+ endfunction()
+ endif()
+
+ if ("NumPy" IN_LIST ${_PYTHON_PREFIX}_FIND_COMPONENTS AND ${_PYTHON_PREFIX}_NumPy_FOUND
+ AND NOT TARGET ${_PYTHON_PREFIX}::NumPy AND TARGET ${_PYTHON_PREFIX}::Module)
+ add_library (${_PYTHON_PREFIX}::NumPy INTERFACE IMPORTED)
+ set_property (TARGET ${_PYTHON_PREFIX}::NumPy
+ PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${${_PYTHON_PREFIX}_NumPy_INCLUDE_DIR}")
+ target_link_libraries (${_PYTHON_PREFIX}::NumPy INTERFACE ${_PYTHON_PREFIX}::Module)
+ endif()
+endif()
+
+# final clean-up
+
+# Restore CMAKE_FIND_APPBUNDLE
+if (DEFINED _${_PYTHON_PREFIX}_CMAKE_FIND_APPBUNDLE)
+ set (CMAKE_FIND_APPBUNDLE ${_${_PYTHON_PREFIX}_CMAKE_FIND_APPBUNDLE})
+ unset (_${_PYTHON_PREFIX}_CMAKE_FIND_APPBUNDLE)
+else()
+ unset (CMAKE_FIND_APPBUNDLE)
+endif()
+# Restore CMAKE_FIND_FRAMEWORK
+if (DEFINED _${_PYTHON_PREFIX}_CMAKE_FIND_FRAMEWORK)
+ set (CMAKE_FIND_FRAMEWORK ${_${_PYTHON_PREFIX}_CMAKE_FIND_FRAMEWORK})
+ unset (_${_PYTHON_PREFIX}_CMAKE_FIND_FRAMEWORK)
+else()
+ unset (CMAKE_FIND_FRAMEWORK)
+endif()
+
+unset (_${_PYTHON_PREFIX}_CONFIG CACHE)
diff --git a/Modules/FindPython2.cmake b/Modules/FindPython2.cmake
new file mode 100644
index 000000000..8372ce74f
--- /dev/null
+++ b/Modules/FindPython2.cmake
@@ -0,0 +1,223 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindPython2
+-----------
+
+Find Python 2 interpreter, compiler and development environment (include
+directories and libraries).
+
+Three components are supported:
+
+* ``Interpreter``: search for Python 2 interpreter
+* ``Compiler``: search for Python 2 compiler. Only offered by IronPython.
+* ``Development``: search for development artifacts (include directories and
+ libraries)
+* ``NumPy``: search for NumPy include directories.
+
+If no ``COMPONENTS`` is specified, ``Interpreter`` is assumed.
+
+To ensure consistent versions between components ``Interpreter``, ``Compiler``,
+``Development`` and ``NumPy``, specify all components at the same time::
+
+ find_package (Python2 COMPONENTS Interpreter Development)
+
+This module looks only for version 2 of Python. This module can be used
+concurrently with :module:`FindPython3` module to use both Python versions.
+
+The :module:`FindPython` module can be used if Python version does not matter
+for you.
+
+.. note::
+
+ If components ``Interpreter`` and ``Development`` are both specified, this
+ module search only for interpreter with same platform architecture as the one
+ defined by ``CMake`` configuration. This contraint does not apply if only
+ ``Interpreter`` component is specified.
+
+Imported Targets
+^^^^^^^^^^^^^^^^
+
+This module defines the following :ref:`Imported Targets <Imported Targets>`
+(when :prop_gbl:`CMAKE_ROLE` is ``PROJECT``):
+
+``Python2::Interpreter``
+ Python 2 interpreter. Target defined if component ``Interpreter`` is found.
+``Python2::Compiler``
+ Python 2 compiler. Target defined if component ``Compiler`` is found.
+``Python2::Python``
+ Python 2 library for Python embedding. Target defined if component
+ ``Development`` is found.
+``Python2::Module``
+ Python 2 library for Python module. Target defined if component
+ ``Development`` is found.
+``Python2::NumPy``
+ NumPy library for Python 2. Target defined if component ``NumPy`` is found.
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This module will set the following variables in your project
+(see :ref:`Standard Variable Names <CMake Developer Standard Variable Names>`):
+
+``Python2_FOUND``
+ System has the Python 2 requested components.
+``Python2_Interpreter_FOUND``
+ System has the Python 2 interpreter.
+``Python2_EXECUTABLE``
+ Path to the Python 2 interpreter.
+``Python2_INTERPRETER_ID``
+ A short string unique to the interpreter. Possible values include:
+ * Python
+ * ActivePython
+ * Anaconda
+ * Canopy
+ * IronPython
+``Python2_STDLIB``
+ Standard platform independent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=True)``.
+``Python2_STDARCH``
+ Standard platform dependent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=True)``.
+``Python2_SITELIB``
+ Third-party platform independent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=False)``.
+``Python2_SITEARCH``
+ Third-party platform dependent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=False)``.
+``Python2_Compiler_FOUND``
+ System has the Python 2 compiler.
+``Python2_COMPILER``
+ Path to the Python 2 compiler. Only offered by IronPython.
+``Python2_COMPILER_ID``
+ A short string unique to the compiler. Possible values include:
+ * IronPython
+``Python2_Development_FOUND``
+ System has the Python 2 development artifacts.
+``Python2_INCLUDE_DIRS``
+ The Python 2 include directories.
+``Python2_LIBRARIES``
+ The Python 2 libraries.
+``Python2_LIBRARY_DIRS``
+ The Python 2 library directories.
+``Python2_RUNTIME_LIBRARY_DIRS``
+ The Python 2 runtime library directories.
+``Python2_VERSION``
+ Python 2 version.
+``Python2_VERSION_MAJOR``
+ Python 2 major version.
+``Python2_VERSION_MINOR``
+ Python 2 minor version.
+``Python2_VERSION_PATCH``
+ Python 2 patch version.
+``Python2_NumPy_FOUND``
+ System has the NumPy.
+``Python2_NumPy_INCLUDE_DIRS``
+ The NumPy include directries.
+``Python2_NumPy_VERSION``
+ The NumPy version.
+
+Hints
+^^^^^
+
+``Python2_ROOT_DIR``
+ Define the root directory of a Python 2 installation.
+
+``Python2_USE_STATIC_LIBS``
+ * If not defined, search for shared libraries and static libraries in that
+ order.
+ * If set to TRUE, search **only** for static libraries.
+ * If set to FALSE, search **only** for shared libraries.
+
+``Python2_FIND_STRATEGY``
+ This variable defines how lookup will be done.
+ The ``Python2_FIND_STRATEGY`` variable can be set to empty or one of the
+ following:
+
+ * ``VERSION``: Try to find the most recent version in all specified
+ locations.
+ This is the default if policy :policy:`CMP0094` is undefined or set to
+ ``OLD``.
+ * ``LOCATION``: Stops lookup as soon as a version satisfying version
+ constraints is founded.
+ This is the default if policy :policy:`CMP0094` is set to ``NEW``.
+
+``Python2_FIND_REGISTRY``
+ On Windows the ``Python2_FIND_REGISTRY`` variable determine the order
+ of preference between registry and environment variables.
+ the ``Python2_FIND_REGISTRY`` variable can be set to empty or one of the
+ following:
+
+ * ``FIRST``: Try to use registry before environment variables.
+ This is the default.
+ * ``LAST``: Try to use registry after environment variables.
+ * ``NEVER``: Never try to use registry.
+
+``Python2_FIND_FRAMEWORK``
+ On macOS the ``Python2_FIND_FRAMEWORK`` variable determine the order of
+ preference between Apple-style and unix-style package components.
+ This variable can be set to empty or take same values as
+ :variable:`CMAKE_FIND_FRAMEWORK` variable.
+
+ .. note::
+
+ Value ``ONLY`` is not supported so ``FIRST`` will be used instead.
+
+ If ``Python2_FIND_FRAMEWORK`` is not defined, :variable:`CMAKE_FIND_FRAMEWORK`
+ variable will be used, if any.
+
+``Python2_FIND_VIRTUALENV``
+ This variable defines the handling of virtual environments. It is meaningfull
+ only when a virtual environment is active (i.e. the ``activate`` script has
+ been evaluated). In this case, it takes precedence over
+ ``Python2_FIND_REGISTRY`` and ``CMAKE_FIND_FRAMEWORK`` variables.
+ The ``Python2_FIND_VIRTUALENV`` variable can be set to empty or one of the
+ following:
+
+ * ``FIRST``: The virtual environment is used before any other standard
+ paths to look-up for the interpreter. This is the default.
+ * ``ONLY``: Only the virtual environment is used to look-up for the
+ interpreter.
+ * ``STANDARD``: The virtual environment is not used to look-up for the
+ interpreter. In this case, variable ``Python2_FIND_REGISTRY`` (Windows)
+ or ``CMAKE_FIND_FRAMEWORK`` (macOS) can be set with value ``LAST`` or
+ ``NEVER`` to select preferably the interpreter from the virtual
+ environment.
+
+Commands
+^^^^^^^^
+
+This module defines the command ``Python_add_library`` (when
+:prop_gbl:`CMAKE_ROLE` is ``PROJECT``), which has the same semantics as
+:command:`add_library` and adds a dependency to target ``Python2::Python`` or,
+when library type is ``MODULE``, to target ``Python2::Module`` and takes care
+of Python module naming rules::
+
+ Python2_add_library (my_module MODULE src1.cpp)
+
+If library type is not specified, ``MODULE`` is assumed.
+#]=======================================================================]
+
+
+set (_PYTHON_PREFIX Python2)
+
+set (_Python2_REQUIRED_VERSION_MAJOR 2)
+
+include (${CMAKE_CURRENT_LIST_DIR}/FindPython/Support.cmake)
+
+if (COMMAND __Python2_add_library)
+ macro (Python2_add_library)
+ __Python2_add_library (Python2 ${ARGV})
+ endmacro()
+endif()
+
+unset (_PYTHON_PREFIX)
diff --git a/Modules/FindPython3.cmake b/Modules/FindPython3.cmake
new file mode 100644
index 000000000..2ead5b6a5
--- /dev/null
+++ b/Modules/FindPython3.cmake
@@ -0,0 +1,223 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindPython3
+-----------
+
+Find Python 3 interpreter, compiler and development environment (include
+directories and libraries).
+
+Three components are supported:
+
+* ``Interpreter``: search for Python 3 interpreter
+* ``Compiler``: search for Python 3 compiler. Only offered by IronPython.
+* ``Development``: search for development artifacts (include directories and
+ libraries)
+* ``NumPy``: search for NumPy include directories.
+
+If no ``COMPONENTS`` is specified, ``Interpreter`` is assumed.
+
+To ensure consistent versions between components ``Interpreter``, ``Compiler``,
+``Development`` and ``NumPy``, specify all components at the same time::
+
+ find_package (Python3 COMPONENTS Interpreter Development)
+
+This module looks only for version 3 of Python. This module can be used
+concurrently with :module:`FindPython2` module to use both Python versions.
+
+The :module:`FindPython` module can be used if Python version does not matter
+for you.
+
+.. note::
+
+ If components ``Interpreter`` and ``Development`` are both specified, this
+ module search only for interpreter with same platform architecture as the one
+ defined by ``CMake`` configuration. This contraint does not apply if only
+ ``Interpreter`` component is specified.
+
+Imported Targets
+^^^^^^^^^^^^^^^^
+
+This module defines the following :ref:`Imported Targets <Imported Targets>`
+(when :prop_gbl:`CMAKE_ROLE` is ``PROJECT``):
+
+``Python3::Interpreter``
+ Python 3 interpreter. Target defined if component ``Interpreter`` is found.
+``Python3::Compiler``
+ Python 3 compiler. Target defined if component ``Compiler`` is found.
+``Python3::Python``
+ Python 3 library for Python embedding. Target defined if component
+ ``Development`` is found.
+``Python3::Module``
+ Python 3 library for Python module. Target defined if component
+ ``Development`` is found.
+``Python3::NumPy``
+ NumPy library for Python 3. Target defined if component ``NumPy`` is found.
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This module will set the following variables in your project
+(see :ref:`Standard Variable Names <CMake Developer Standard Variable Names>`):
+
+``Python3_FOUND``
+ System has the Python 3 requested components.
+``Python3_Interpreter_FOUND``
+ System has the Python 3 interpreter.
+``Python3_EXECUTABLE``
+ Path to the Python 3 interpreter.
+``Python3_INTERPRETER_ID``
+ A short string unique to the interpreter. Possible values include:
+ * Python
+ * ActivePython
+ * Anaconda
+ * Canopy
+ * IronPython
+``Python3_STDLIB``
+ Standard platform independent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=True)``.
+``Python3_STDARCH``
+ Standard platform dependent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=True)``.
+``Python3_SITELIB``
+ Third-party platform independent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=False,standard_lib=False)``.
+``Python3_SITEARCH``
+ Third-party platform dependent installation directory.
+
+ Information returned by
+ ``distutils.sysconfig.get_python_lib(plat_specific=True,standard_lib=False)``.
+``Python3_Compiler_FOUND``
+ System has the Python 3 compiler.
+``Python3_COMPILER``
+ Path to the Python 3 compiler. Only offered by IronPython.
+``Python3_COMPILER_ID``
+ A short string unique to the compiler. Possible values include:
+ * IronPython
+``Python3_Development_FOUND``
+ System has the Python 3 development artifacts.
+``Python3_INCLUDE_DIRS``
+ The Python 3 include directories.
+``Python3_LIBRARIES``
+ The Python 3 libraries.
+``Python3_LIBRARY_DIRS``
+ The Python 3 library directories.
+``Python3_RUNTIME_LIBRARY_DIRS``
+ The Python 3 runtime library directories.
+``Python3_VERSION``
+ Python 3 version.
+``Python3_VERSION_MAJOR``
+ Python 3 major version.
+``Python3_VERSION_MINOR``
+ Python 3 minor version.
+``Python3_VERSION_PATCH``
+ Python 3 patch version.
+``Python3_NumPy_FOUND``
+ System has the NumPy.
+``Python3_NumPy_INCLUDE_DIRS``
+ The NumPy include directries.
+``Python3_NumPy_VERSION``
+ The NumPy version.
+
+Hints
+^^^^^
+
+``Python3_ROOT_DIR``
+ Define the root directory of a Python 3 installation.
+
+``Python3_USE_STATIC_LIBS``
+ * If not defined, search for shared libraries and static libraries in that
+ order.
+ * If set to TRUE, search **only** for static libraries.
+ * If set to FALSE, search **only** for shared libraries.
+
+``Python3_FIND_STRATEGY``
+ This variable defines how lookup will be done.
+ The ``Python3_FIND_STRATEGY`` variable can be set to empty or one of the
+ following:
+
+ * ``VERSION``: Try to find the most recent version in all specified
+ locations.
+ This is the default if policy :policy:`CMP0094` is undefined or set to
+ ``OLD``.
+ * ``LOCATION``: Stops lookup as soon as a version satisfying version
+ constraints is founded.
+ This is the default if policy :policy:`CMP0094` is set to ``NEW``.
+
+``Python3_FIND_REGISTRY``
+ On Windows the ``Python3_FIND_REGISTRY`` variable determine the order
+ of preference between registry and environment variables.
+ The ``Python3_FIND_REGISTRY`` variable can be set to empty or one of the
+ following:
+
+ * ``FIRST``: Try to use registry before environment variables.
+ This is the default.
+ * ``LAST``: Try to use registry after environment variables.
+ * ``NEVER``: Never try to use registry.
+
+``Python3_FIND_FRAMEWORK``
+ On macOS the ``Python3_FIND_FRAMEWORK`` variable determine the order of
+ preference between Apple-style and unix-style package components.
+ This variable can be set to empty or take same values as
+ :variable:`CMAKE_FIND_FRAMEWORK` variable.
+
+ .. note::
+
+ Value ``ONLY`` is not supported so ``FIRST`` will be used instead.
+
+ If ``Python3_FIND_FRAMEWORK`` is not defined, :variable:`CMAKE_FIND_FRAMEWORK`
+ variable will be used, if any.
+
+``Python3_FIND_VIRTUALENV``
+ This variable defines the handling of virtual environments. It is meaningfull
+ only when a virtual environment is active (i.e. the ``activate`` script has
+ been evaluated). In this case, it takes precedence over
+ ``Python3_FIND_REGISTRY`` and ``CMAKE_FIND_FRAMEWORK`` variables.
+ The ``Python3_FIND_VIRTUALENV`` variable can be set to empty or one of the
+ following:
+
+ * ``FIRST``: The virtual environment is used before any other standard
+ paths to look-up for the interpreter. This is the default.
+ * ``ONLY``: Only the virtual environment is used to look-up for the
+ interpreter.
+ * ``STANDARD``: The virtual environment is not used to look-up for the
+ interpreter. In this case, variable ``Python3_FIND_REGISTRY`` (Windows)
+ or ``CMAKE_FIND_FRAMEWORK`` (macOS) can be set with value ``LAST`` or
+ ``NEVER`` to select preferably the interpreter from the virtual
+ environment.
+
+Commands
+^^^^^^^^
+
+This module defines the command ``Python_add_library`` (when
+:prop_gbl:`CMAKE_ROLE` is ``PROJECT``), which has the same semantics as
+:command:`add_library` and adds a dependency to target ``Python3::Python`` or,
+when library type is ``MODULE``, to target ``Python3::Module`` and takes care
+of Python module naming rules::
+
+ Python3_add_library (my_module MODULE src1.cpp)
+
+If library type is not specified, ``MODULE`` is assumed.
+#]=======================================================================]
+
+
+set (_PYTHON_PREFIX Python3)
+
+set (_Python3_REQUIRED_VERSION_MAJOR 3)
+
+include (${CMAKE_CURRENT_LIST_DIR}/FindPython/Support.cmake)
+
+if (COMMAND __Python3_add_library)
+ macro (Python3_add_library)
+ __Python3_add_library (Python3 ${ARGV})
+ endmacro()
+endif()
+
+unset (_PYTHON_PREFIX)
diff --git a/Modules/FindSQLite3.cmake b/Modules/FindSQLite3.cmake
new file mode 100644
index 000000000..374d7af6c
--- /dev/null
+++ b/Modules/FindSQLite3.cmake
@@ -0,0 +1,66 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindSQLite3
+-----------
+
+Find the SQLite libraries, v3
+
+IMPORTED targets
+^^^^^^^^^^^^^^^^
+
+This module defines the following :prop_tgt:`IMPORTED` target:
+
+``SQLite::SQLite3``
+
+Result variables
+^^^^^^^^^^^^^^^^
+
+This module will set the following variables if found:
+
+``SQLite3_INCLUDE_DIRS``
+ where to find sqlite3.h, etc.
+``SQLite3_LIBRARIES``
+ the libraries to link against to use SQLite3.
+``SQLite3_VERSION``
+ version of the SQLite3 library found
+``SQLite3_FOUND``
+ TRUE if found
+
+#]=======================================================================]
+
+# Look for the necessary header
+find_path(SQLite3_INCLUDE_DIR NAMES sqlite3.h)
+mark_as_advanced(SQLite3_INCLUDE_DIR)
+
+# Look for the necessary library
+find_library(SQLite3_LIBRARY NAMES sqlite3 sqlite)
+mark_as_advanced(SQLite3_LIBRARY)
+
+# Extract version information from the header file
+if(SQLite3_INCLUDE_DIR)
+ file(STRINGS ${SQLite3_INCLUDE_DIR}/sqlite3.h _ver_line
+ REGEX "^#define SQLITE_VERSION *\"[0-9]+\\.[0-9]+\\.[0-9]+\""
+ LIMIT_COUNT 1)
+ string(REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+"
+ SQLite3_VERSION "${_ver_line}")
+ unset(_ver_line)
+endif()
+
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
+find_package_handle_standard_args(SQLite3
+ REQUIRED_VARS SQLite3_INCLUDE_DIR SQLite3_LIBRARY
+ VERSION_VAR SQLite3_VERSION)
+
+# Create the imported target
+if(SQLite3_FOUND)
+ set(SQLite3_INCLUDE_DIRS ${SQLite3_INCLUDE_DIR})
+ set(SQLite3_LIBRARIES ${SQLite3_LIBRARY})
+ if(NOT TARGET SQLite::SQLite3)
+ add_library(SQLite::SQLite3 UNKNOWN IMPORTED)
+ set_target_properties(SQLite::SQLite3 PROPERTIES
+ IMPORTED_LOCATION "${SQLite3_LIBRARY}"
+ INTERFACE_INCLUDE_DIRECTORIES "${SQLite3_INCLUDE_DIR}")
+ endif()
+endif()
diff --git a/Modules/GoogleTestAddTests.cmake b/Modules/GoogleTestAddTests.cmake
new file mode 100644
index 000000000..4abbbecf7
--- /dev/null
+++ b/Modules/GoogleTestAddTests.cmake
@@ -0,0 +1,106 @@
+# 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 does not exist.\n"
+ " Path: '${TEST_EXECUTABLE}'"
+ )
+endif()
+execute_process(
+ COMMAND ${TEST_EXECUTOR} "${TEST_EXECUTABLE}" --gtest_list_tests
+ WORKING_DIRECTORY "${TEST_WORKING_DIR}"
+ TIMEOUT ${TEST_DISCOVERY_TIMEOUT}
+ OUTPUT_VARIABLE output
+ RESULT_VARIABLE result
+)
+if(NOT ${result} EQUAL 0)
+ string(REPLACE "\n" "\n " output "${output}")
+ message(FATAL_ERROR
+ "Error running test executable.\n"
+ " Path: '${TEST_EXECUTABLE}'\n"
+ " Result: ${result}\n"
+ " Output:\n"
+ " ${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/Internal/CMakeCheckCompilerFlag.cmake b/Modules/Internal/CMakeCheckCompilerFlag.cmake
new file mode 100644
index 000000000..9c8dfb617
--- /dev/null
+++ b/Modules/Internal/CMakeCheckCompilerFlag.cmake
@@ -0,0 +1,158 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=[
+
+NOTE: This function is used internally by CMake. Projects should not include
+ this file directly.
+
+The cmake_check_compiler_flag() function can be used to compile and link a
+source file to check whether a specific compiler or linker flag is supported.
+The function does not use the try_compile() command so as to avoid infinite
+recursion. It may not work for all platforms or toolchains, the caller is
+responsible for ensuring it is only called in valid situations.
+
+ cmake_check_compiler_flag(<lang> <flag> <result>
+ [SRC_EXT <ext>] [COMMAND_PATTERN <pattern>]
+ [FAIL_REGEX <regex> ...]
+ [OUTPUT_VARIABLE <output>])
+
+Parameters:
+ <lang> - Language to check.
+ <flag> - The flag to add to the compile/link command line.
+ <result> - Boolean output variable. It will be stored in the cache as an
+ internal variable and if true, will cause future tests that assign
+ to that variable to be bypassed.
+
+Optional parameters:
+ SRC_EXT - Overrides the extension of the source file used for the
+ check. Defaults are 'c' (C), 'cxx' (CXX), 'F' (Fortran).
+ COMMAND_PATTERN - Pattern to be used for the command line. The default is
+ '<FLAG> -o <OUTPUT> <SOURCE>'
+ FAIL_REGEX - List of additional regular expressions that, if matched by
+ the output, give a failed result for the check. A common
+ set of regular expressions will be included in addition to
+ those given by FAIL_REGEX.
+ OUTPUT_VARIABLE - Set <output> variable with details about any error.
+#]=]
+
+include_guard(GLOBAL)
+include(CMakeCheckCompilerFlagCommonPatterns)
+
+function(CMAKE_CHECK_COMPILER_FLAG lang flag result)
+ # Cache results between runs similar to check_<lang>_source_compiles()
+ if(DEFINED ${result})
+ return()
+ endif()
+
+ set(comment "Is the '${flag}' option(s) supported")
+ string(REPLACE ";" " " comment "${comment}")
+
+ if (NOT lang MATCHES "^(C|CXX|Fortran|ASM)$")
+ # other possible languages are not supported
+ # log message to keep trace of this problem...
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+ "Function 'CMAKE_CHECK_COMPILER_FLAG' called with unsupported language: ${lang}\n")
+ set(${result} FALSE CACHE INTERNAL ${comment})
+ return()
+ endif()
+ if (lang STREQUAL "ASM")
+ # assume ASM compiler is a multi-language compiler, so supports C language as well
+ set(check_lang C)
+ else()
+ set(check_lang ${lang})
+ endif()
+
+ cmake_parse_arguments(CCCF "" "SRC_EXT;COMMAND_PATTERN;OUTPUT_VARIABLE" "FAIL_REGEX" ${ARGN})
+
+ if (NOT CCCF_COMMAND_PATTERN)
+ set (CCCF_COMMAND_PATTERN "<FLAG> -o <OUTPUT> <SOURCE>")
+ endif()
+
+ list (APPEND CCCF_FAIL_REGEX "argument unused during compilation") # clang
+ if (check_lang STREQUAL "C")
+ list(APPEND CCCF_FAIL_REGEX
+ "command line option .* is valid for .* but not for C") # GNU
+ elseif(check_lang STREQUAL "CXX")
+ list(APPEND CCCF_FAIL_REGEX
+ "command line option .* is valid for .* but not for C\\+\\+") # GNU
+ elseif(check_lang STREQUAL "Fortran")
+ list(APPEND CCCF_FAIL_REGEX
+ "command line option .* is valid for .* but not for Fortran") # GNU
+ endif()
+
+ # Add patterns for common errors
+ check_compiler_flag_common_patterns(COMPILER_FLAG_COMMON_PATTERNS)
+ foreach(arg IN LISTS COMPILER_FLAG_COMMON_PATTERNS)
+ if(arg MATCHES "^FAIL_REGEX$")
+ continue()
+ endif()
+ list(APPEND CCCF_FAIL_REGEX "${arg}")
+ endforeach()
+
+ if(NOT CCCF_SRC_EXT)
+ if (check_lang STREQUAL "C")
+ set(CCCF_SRC_EXT c)
+ elseif(check_lang STREQUAL "CXX")
+ set(CCCF_SRC_EXT cxx)
+ elseif(check_lang STREQUAL "Fortran")
+ set(CCCF_SRC_EXT F)
+ endif()
+ endif()
+
+ if (CCCF_OUTPUT_VARIABLE)
+ unset(${CCCF_OUTPUT_VARIABLE} PARENT_SCOPE)
+ endif()
+
+ # Compute the directory in which to run the test.
+ set(COMPILER_FLAG_DIR "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp")
+ # Compute source and output files.
+ set(COMPILER_FLAG_SRC
+ "${COMPILER_FLAG_DIR}/CompilerFlag${lang}.${CCCF_SRC_EXT}")
+ if(check_lang STREQUAL "Fortran")
+ file(WRITE "${COMPILER_FLAG_SRC}"
+ " program simple\n end program simple\n")
+ else()
+ file(WRITE "${COMPILER_FLAG_SRC}" "int main (void)\n{ return 0; }\n")
+ endif()
+ get_filename_component(COMPILER_FLAG_EXE "${COMPILER_FLAG_SRC}" NAME_WE)
+ string(APPEND COMPILER_FLAG_EXE "${CMAKE_EXECUTABLE_SUFFIX}")
+
+ # Build command line
+ separate_arguments(CCCF_COMMAND_PATTERN UNIX_COMMAND
+ "${CCCF_COMMAND_PATTERN}")
+ list(TRANSFORM CCCF_COMMAND_PATTERN REPLACE "<SOURCE>" "${COMPILER_FLAG_SRC}")
+ list(TRANSFORM CCCF_COMMAND_PATTERN REPLACE "<OUTPUT>" "${COMPILER_FLAG_EXE}")
+ list(TRANSFORM CCCF_COMMAND_PATTERN REPLACE "<FLAG>" "${flag}")
+
+ execute_process(
+ COMMAND "${CMAKE_COMMAND}" -E env LC_ALL=C LC_MESSAGES=C LANG=C
+ "${CMAKE_${lang}_COMPILER}" ${CCCF_COMMAND_PATTERN}
+ WORKING_DIRECTORY "${COMPILER_FLAG_DIR}"
+ OUTPUT_VARIABLE COMPILER_FLAG_OUTPUT
+ ERROR_VARIABLE COMPILER_FLAG_OUTPUT
+ RESULT_VARIABLE COMPILER_FLAG_RESULT)
+
+ # Record result in the cache so we can avoid re-testing every CMake run
+ if (COMPILER_FLAG_RESULT)
+ set(${result} FALSE CACHE INTERNAL ${comment})
+ else()
+ foreach(regex IN LISTS CCCF_FAIL_REGEX)
+ if(COMPILER_FLAG_OUTPUT MATCHES "${regex}")
+ set(${result} FALSE CACHE INTERNAL ${comment})
+ endif()
+ endforeach()
+ endif()
+ if (DEFINED ${result})
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+ "Determining if the ${flag} option "
+ "is supported for ${lang} language failed with the following output:\n"
+ "${COMPILER_FLAG_OUTPUT}\n")
+ if (CCCF_OUTPUT_VARIABLE)
+ set(${CCCF_OUTPUT_VARIABLE} "${COMPILER_FLAG_OUTPUT}" PARENT_SCOPE)
+ endif()
+ return()
+ endif()
+
+ set(${result} TRUE CACHE INTERNAL ${comment})
+endfunction()
diff --git a/Modules/Internal/CPack/CPackDeb.cmake b/Modules/Internal/CPack/CPackDeb.cmake
new file mode 100644
index 000000000..89dc6f024
--- /dev/null
+++ b/Modules/Internal/CPack/CPackDeb.cmake
@@ -0,0 +1,681 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# CPack script for creating Debian package
+# Author: Mathieu Malaterre
+#
+# http://wiki.debian.org/HowToPackageForDebian
+
+if(CMAKE_BINARY_DIR)
+ message(FATAL_ERROR "CPackDeb.cmake may only be used by CPack internally.")
+endif()
+
+cmake_policy(PUSH)
+cmake_policy(SET CMP0057 NEW) # if IN_LIST
+
+function(cpack_deb_variable_fallback OUTPUT_VAR_NAME)
+ set(FALLBACK_VAR_NAMES ${ARGN})
+
+ foreach(variable_name IN LISTS FALLBACK_VAR_NAMES)
+ if(${variable_name})
+ set(${OUTPUT_VAR_NAME} "${${variable_name}}" PARENT_SCOPE)
+ break()
+ endif()
+ endforeach()
+endfunction()
+
+function(get_component_package_name var component)
+ string(TOUPPER "${component}" component_upcase)
+ if(CPACK_DEBIAN_${component_upcase}_PACKAGE_NAME)
+ string(TOLOWER "${CPACK_DEBIAN_${component_upcase}_PACKAGE_NAME}" package_name)
+ else()
+ string(TOLOWER "${CPACK_DEBIAN_PACKAGE_NAME}-${component}" package_name)
+ endif()
+
+ set("${var}" "${package_name}" PARENT_SCOPE)
+endfunction()
+
+#extract library name and version for given shared object
+function(extract_so_info shared_object libname version)
+ if(READELF_EXECUTABLE)
+ execute_process(COMMAND "${READELF_EXECUTABLE}" -d "${shared_object}"
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ RESULT_VARIABLE result
+ OUTPUT_VARIABLE output
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if(result EQUAL 0)
+ string(REGEX MATCH "\\(SONAME\\)[^\n]*\\[([^\n]+)\\.so\\.([^\n]*)\\]" soname "${output}")
+ set(${libname} "${CMAKE_MATCH_1}" PARENT_SCOPE)
+ set(${version} "${CMAKE_MATCH_2}" PARENT_SCOPE)
+ else()
+ message(WARNING "Error running readelf for \"${shared_object}\"")
+ endif()
+ else()
+ message(FATAL_ERROR "Readelf utility is not available.")
+ endif()
+endfunction()
+
+function(cpack_deb_prepare_package_vars)
+ # CPACK_DEBIAN_PACKAGE_SHLIBDEPS
+ # If specify OFF, only user depends are used
+ if(NOT DEFINED CPACK_DEBIAN_PACKAGE_SHLIBDEPS)
+ set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS OFF)
+ endif()
+
+ set(WDIR "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}${CPACK_DEB_PACKAGE_COMPONENT_PART_PATH}")
+ set(DBGSYMDIR "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}${CPACK_DEB_PACKAGE_COMPONENT_PART_PATH}-dbgsym")
+ file(REMOVE_RECURSE "${DBGSYMDIR}")
+
+ # per component automatic discover: some of the component might not have
+ # binaries.
+ if(CPACK_DEB_PACKAGE_COMPONENT)
+ string(TOUPPER "${CPACK_DEB_PACKAGE_COMPONENT}" _local_component_name)
+ set(_component_shlibdeps_var "CPACK_DEBIAN_${_local_component_name}_PACKAGE_SHLIBDEPS")
+
+ # if set, overrides the global configuration
+ if(DEFINED ${_component_shlibdeps_var})
+ set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS "${${_component_shlibdeps_var}}")
+ if(CPACK_DEBIAN_PACKAGE_DEBUG)
+ message("CPackDeb Debug: component '${CPACK_DEB_PACKAGE_COMPONENT}' dpkg-shlibdeps set to ${CPACK_DEBIAN_PACKAGE_SHLIBDEPS}")
+ endif()
+ endif()
+ endif()
+
+ cpack_deb_variable_fallback("CPACK_DEBIAN_DEBUGINFO_PACKAGE"
+ "CPACK_DEBIAN_${_local_component_name}_DEBUGINFO_PACKAGE"
+ "CPACK_DEBIAN_DEBUGINFO_PACKAGE")
+ if(CPACK_DEBIAN_PACKAGE_SHLIBDEPS OR CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS OR CPACK_DEBIAN_DEBUGINFO_PACKAGE)
+ # Generating binary list - Get type of all install files
+ file(GLOB_RECURSE FILE_PATHS_ LIST_DIRECTORIES false RELATIVE "${WDIR}" "${WDIR}/*")
+
+ find_program(FILE_EXECUTABLE file)
+ if(NOT FILE_EXECUTABLE)
+ message(FATAL_ERROR "CPackDeb: file utility is not available. CPACK_DEBIAN_PACKAGE_SHLIBDEPS and CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS options are not available.")
+ endif()
+
+ # get file info so that we can determine if file is executable or not
+ unset(CPACK_DEB_INSTALL_FILES)
+ foreach(FILE_ IN LISTS FILE_PATHS_)
+ execute_process(COMMAND ${CMAKE_COMMAND} -E env LC_ALL=C ${FILE_EXECUTABLE} "./${FILE_}"
+ WORKING_DIRECTORY "${WDIR}"
+ RESULT_VARIABLE FILE_RESULT_
+ OUTPUT_VARIABLE INSTALL_FILE_)
+ if(NOT FILE_RESULT_ EQUAL 0)
+ message (FATAL_ERROR "CPackDeb: execution of command: '${FILE_EXECUTABLE} ./${FILE_}' failed with exit code: ${FILE_RESULT_}")
+ endif()
+ list(APPEND CPACK_DEB_INSTALL_FILES "${INSTALL_FILE_}")
+ endforeach()
+
+ # Only dynamically linked ELF files are included
+ # Extract only file name infront of ":"
+ foreach(_FILE IN LISTS CPACK_DEB_INSTALL_FILES)
+ if(_FILE MATCHES "ELF.*dynamically linked")
+ string(REGEX MATCH "(^.*):" _FILE_NAME "${_FILE}")
+ list(APPEND CPACK_DEB_BINARY_FILES "${CMAKE_MATCH_1}")
+ set(CONTAINS_EXECUTABLE_FILES_ TRUE)
+ endif()
+ if(_FILE MATCHES "ELF.*shared object")
+ string(REGEX MATCH "(^.*):" _FILE_NAME "${_FILE}")
+ list(APPEND CPACK_DEB_SHARED_OBJECT_FILES "${CMAKE_MATCH_1}")
+ endif()
+ if(_FILE MATCHES "ELF.*not stripped")
+ string(REGEX MATCH "(^.*):" _FILE_NAME "${_FILE}")
+ list(APPEND CPACK_DEB_UNSTRIPPED_FILES "${CMAKE_MATCH_1}")
+ endif()
+ endforeach()
+ endif()
+
+ find_program(READELF_EXECUTABLE NAMES readelf)
+
+ if(CPACK_DEBIAN_DEBUGINFO_PACKAGE AND CPACK_DEB_UNSTRIPPED_FILES)
+ find_program(OBJCOPY_EXECUTABLE NAMES objcopy)
+
+ if(NOT OBJCOPY_EXECUTABLE)
+ message(FATAL_ERROR "debuginfo packages require the objcopy tool")
+ endif()
+ if(NOT READELF_EXECUTABLE)
+ message(FATAL_ERROR "debuginfo packages require the readelf tool")
+ endif()
+
+ file(RELATIVE_PATH _DBGSYM_ROOT "${CPACK_TEMPORARY_DIRECTORY}" "${DBGSYMDIR}")
+ foreach(_FILE IN LISTS CPACK_DEB_UNSTRIPPED_FILES)
+
+ # Get the file's Build ID
+ execute_process(COMMAND env LC_ALL=C ${READELF_EXECUTABLE} -n "${_FILE}"
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ OUTPUT_VARIABLE READELF_OUTPUT
+ RESULT_VARIABLE READELF_RESULT
+ ERROR_VARIABLE READELF_ERROR
+ OUTPUT_STRIP_TRAILING_WHITESPACE )
+ if(NOT READELF_RESULT EQUAL 0)
+ message(FATAL_ERROR "CPackDeb: readelf: '${READELF_ERROR}';\n"
+ "executed command: '${READELF_EXECUTABLE} -n ${_FILE}'")
+ endif()
+ if(READELF_OUTPUT MATCHES "Build ID: ([0-9a-zA-Z][0-9a-zA-Z])([0-9a-zA-Z]*)")
+ set(_BUILD_ID_START ${CMAKE_MATCH_1})
+ set(_BUILD_ID_REMAINING ${CMAKE_MATCH_2})
+ list(APPEND BUILD_IDS ${_BUILD_ID_START}${_BUILD_ID_REMAINING})
+ else()
+ message(FATAL_ERROR "Unable to determine Build ID for ${_FILE}")
+ endif()
+
+ # Split out the debug symbols from the binaries
+ set(_FILE_DBGSYM ${_DBGSYM_ROOT}/usr/lib/debug/.build-id/${_BUILD_ID_START}/${_BUILD_ID_REMAINING}.debug)
+ get_filename_component(_OUT_DIR "${_FILE_DBGSYM}" DIRECTORY)
+ file(MAKE_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}/${_OUT_DIR}")
+ execute_process(COMMAND ${OBJCOPY_EXECUTABLE} --only-keep-debug "${_FILE}" "${_FILE_DBGSYM}"
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ OUTPUT_VARIABLE OBJCOPY_OUTPUT
+ RESULT_VARIABLE OBJCOPY_RESULT
+ ERROR_VARIABLE OBJCOPY_ERROR
+ OUTPUT_STRIP_TRAILING_WHITESPACE )
+ if(NOT OBJCOPY_RESULT EQUAL 0)
+ message(FATAL_ERROR "CPackDeb: objcopy: '${OBJCOPY_ERROR}';\n"
+ "executed command: '${OBJCOPY_EXECUTABLE} --only-keep-debug ${_FILE} ${_FILE_DBGSYM}'")
+ endif()
+ execute_process(COMMAND ${OBJCOPY_EXECUTABLE} --strip-unneeded ${_FILE}
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ OUTPUT_VARIABLE OBJCOPY_OUTPUT
+ RESULT_VARIABLE OBJCOPY_RESULT
+ ERROR_VARIABLE OBJCOPY_ERROR
+ OUTPUT_STRIP_TRAILING_WHITESPACE )
+ if(NOT OBJCOPY_RESULT EQUAL 0)
+ message(FATAL_ERROR "CPackDeb: objcopy: '${OBJCOPY_ERROR}';\n"
+ "executed command: '${OBJCOPY_EXECUTABLE} --strip-debug ${_FILE}'")
+ endif()
+ execute_process(COMMAND ${OBJCOPY_EXECUTABLE} --add-gnu-debuglink=${_FILE_DBGSYM} ${_FILE}
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ OUTPUT_VARIABLE OBJCOPY_OUTPUT
+ RESULT_VARIABLE OBJCOPY_RESULT
+ ERROR_VARIABLE OBJCOPY_ERROR
+ OUTPUT_STRIP_TRAILING_WHITESPACE )
+ if(NOT OBJCOPY_RESULT EQUAL 0)
+ message(FATAL_ERROR "CPackDeb: objcopy: '${OBJCOPY_ERROR}';\n"
+ "executed command: '${OBJCOPY_EXECUTABLE} --add-gnu-debuglink=${_FILE_DBGSYM} ${_FILE}'")
+ endif()
+ endforeach()
+ endif()
+
+ if(CPACK_DEBIAN_PACKAGE_SHLIBDEPS)
+ # dpkg-shlibdeps is a Debian utility for generating dependency list
+ find_program(SHLIBDEPS_EXECUTABLE dpkg-shlibdeps)
+
+ if(SHLIBDEPS_EXECUTABLE)
+ # Check version of the dpkg-shlibdeps tool using CPackDEB method
+ execute_process(COMMAND ${CMAKE_COMMAND} -E env LC_ALL=C ${SHLIBDEPS_EXECUTABLE} --version
+ OUTPUT_VARIABLE _TMP_VERSION
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if(_TMP_VERSION MATCHES "dpkg-shlibdeps version ([0-9]+\\.[0-9]+\\.[0-9]+)")
+ set(SHLIBDEPS_EXECUTABLE_VERSION "${CMAKE_MATCH_1}")
+ else()
+ set(SHLIBDEPS_EXECUTABLE_VERSION "")
+ endif()
+
+ if(CPACK_DEBIAN_PACKAGE_DEBUG)
+ message("CPackDeb Debug: dpkg-shlibdeps --version output is '${_TMP_VERSION}'")
+ message("CPackDeb Debug: dpkg-shlibdeps version is <${SHLIBDEPS_EXECUTABLE_VERSION}>")
+ endif()
+
+ if(CONTAINS_EXECUTABLE_FILES_)
+ message("CPackDeb: - Generating dependency list")
+
+ # Create blank control file for running dpkg-shlibdeps
+ # There might be some other way to invoke dpkg-shlibdeps without creating this file
+ # but standard debian package should not have anything that can collide with this file or directory
+ file(MAKE_DIRECTORY ${CPACK_TEMPORARY_DIRECTORY}/debian)
+ file(WRITE ${CPACK_TEMPORARY_DIRECTORY}/debian/control "")
+
+ # Create a DEBIAN directory so that dpkg-shlibdeps can find the package dir when resolving $ORIGIN.
+ file(MAKE_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}/DEBIAN")
+
+ # Add --ignore-missing-info if the tool supports it
+ execute_process(COMMAND ${CMAKE_COMMAND} -E env LC_ALL=C ${SHLIBDEPS_EXECUTABLE} --help
+ OUTPUT_VARIABLE _TMP_HELP
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if(_TMP_HELP MATCHES "--ignore-missing-info")
+ set(IGNORE_MISSING_INFO_FLAG "--ignore-missing-info")
+ endif()
+
+ # Execute dpkg-shlibdeps
+ # --ignore-missing-info : allow dpkg-shlibdeps to run even if some libs do not belong to a package
+ # -O : print to STDOUT
+ execute_process(COMMAND ${SHLIBDEPS_EXECUTABLE} ${IGNORE_MISSING_INFO_FLAG} -O ${CPACK_DEB_BINARY_FILES}
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ OUTPUT_VARIABLE SHLIBDEPS_OUTPUT
+ RESULT_VARIABLE SHLIBDEPS_RESULT
+ ERROR_VARIABLE SHLIBDEPS_ERROR
+ OUTPUT_STRIP_TRAILING_WHITESPACE )
+ if(CPACK_DEBIAN_PACKAGE_DEBUG)
+ # dpkg-shlibdeps will throw some warnings if some input files are not binary
+ message( "CPackDeb Debug: dpkg-shlibdeps warnings \n${SHLIBDEPS_ERROR}")
+ endif()
+ if(NOT SHLIBDEPS_RESULT EQUAL 0)
+ message (FATAL_ERROR "CPackDeb: dpkg-shlibdeps: '${SHLIBDEPS_ERROR}';\n"
+ "executed command: '${SHLIBDEPS_EXECUTABLE} ${IGNORE_MISSING_INFO_FLAG} -O ${CPACK_DEB_BINARY_FILES}';\n"
+ "found files: '${INSTALL_FILE_}';\n"
+ "files info: '${CPACK_DEB_INSTALL_FILES}';\n"
+ "binary files: '${CPACK_DEB_BINARY_FILES}'")
+ endif()
+
+ #Get rid of prefix generated by dpkg-shlibdeps
+ string(REGEX REPLACE "^.*Depends=" "" CPACK_DEBIAN_PACKAGE_AUTO_DEPENDS "${SHLIBDEPS_OUTPUT}")
+
+ if(CPACK_DEBIAN_PACKAGE_DEBUG)
+ message("CPackDeb Debug: Found dependency: ${CPACK_DEBIAN_PACKAGE_AUTO_DEPENDS} from output ${SHLIBDEPS_OUTPUT}")
+ endif()
+
+ # Remove blank control file
+ # Might not be safe if package actual contain file or directory named debian
+ file(REMOVE_RECURSE "${CPACK_TEMPORARY_DIRECTORY}/debian")
+
+ # remove temporary directory that was created only for dpkg-shlibdeps execution
+ file(REMOVE_RECURSE "${CPACK_TEMPORARY_DIRECTORY}/DEBIAN")
+ else()
+ if(CPACK_DEBIAN_PACKAGE_DEBUG)
+ message(AUTHOR_WARNING "CPackDeb Debug: Using only user-provided depends because package does not contain executable files that link to shared libraries.")
+ endif()
+ endif()
+ else()
+ message("CPackDeb: Using only user-provided dependencies because dpkg-shlibdeps is not found.")
+ endif()
+
+ else()
+ if(CPACK_DEBIAN_PACKAGE_DEBUG)
+ message("CPackDeb Debug: Using only user-provided dependencies")
+ endif()
+ endif()
+
+ # Let's define the control file found in debian package:
+
+ # Binary package:
+ # http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-binarycontrolfiles
+
+ # DEBIAN/control
+ # debian policy enforce lower case for package name
+ # Package: (mandatory)
+ if(NOT CPACK_DEBIAN_PACKAGE_NAME)
+ string(TOLOWER "${CPACK_PACKAGE_NAME}" CPACK_DEBIAN_PACKAGE_NAME)
+ endif()
+
+ # Version: (mandatory)
+ if(NOT CPACK_DEBIAN_PACKAGE_VERSION)
+ if(NOT CPACK_PACKAGE_VERSION)
+ message(FATAL_ERROR "CPackDeb: Debian package requires a package version")
+ endif()
+ 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}")
+ elseif(NOT CPACK_DEBIAN_PACKAGE_ARCHITECTURE)
+ # There is no such thing as i686 architecture on debian, you should use i386 instead
+ # $ dpkg --print-architecture
+ find_program(DPKG_CMD dpkg)
+ if(NOT DPKG_CMD)
+ message(STATUS "CPackDeb: Can not find dpkg in your path, default to i386.")
+ set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE i386)
+ endif()
+ execute_process(COMMAND "${DPKG_CMD}" --print-architecture
+ OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ )
+ endif()
+
+ # Source: (optional)
+ # in case several packages are constructed from a unique source
+ # (multipackaging), the source may be indicated as well.
+ # The source might contain a version if the generated package
+ # version is different from the source version
+ if(NOT CPACK_DEBIAN_PACKAGE_SOURCE)
+ set(CPACK_DEBIAN_PACKAGE_SOURCE "")
+ endif()
+
+ # have a look at get_property(result GLOBAL PROPERTY ENABLED_FEATURES),
+ # this returns the successful find_package() calls, maybe this can help
+ # Depends:
+ # You should set: DEBIAN_PACKAGE_DEPENDS
+ # TODO: automate 'objdump -p | grep NEEDED'
+
+ # if per-component variable, overrides the global CPACK_DEBIAN_PACKAGE_${variable_type_}
+ # automatic dependency discovery will be performed afterwards.
+ if(CPACK_DEB_PACKAGE_COMPONENT)
+ foreach(value_type_ DEPENDS RECOMMENDS SUGGESTS PREDEPENDS ENHANCES BREAKS CONFLICTS PROVIDES REPLACES SOURCE SECTION PRIORITY NAME)
+ set(_component_var "CPACK_DEBIAN_${_local_component_name}_PACKAGE_${value_type_}")
+
+ # if set, overrides the global variable
+ if(DEFINED ${_component_var})
+ set(CPACK_DEBIAN_PACKAGE_${value_type_} "${${_component_var}}")
+ if(CPACK_DEBIAN_PACKAGE_DEBUG)
+ message("CPackDeb Debug: component '${_local_component_name}' ${value_type_} "
+ "value set to '${CPACK_DEBIAN_PACKAGE_${value_type_}}'")
+ endif()
+ endif()
+ endforeach()
+
+ if(CPACK_DEBIAN_ENABLE_COMPONENT_DEPENDS)
+ set(COMPONENT_DEPENDS "")
+ foreach (_PACK ${CPACK_COMPONENT_${_local_component_name}_DEPENDS})
+ get_component_package_name(_PACK_NAME "${_PACK}")
+ if(COMPONENT_DEPENDS)
+ set(COMPONENT_DEPENDS "${_PACK_NAME} (= ${CPACK_DEBIAN_PACKAGE_VERSION}), ${COMPONENT_DEPENDS}")
+ else()
+ set(COMPONENT_DEPENDS "${_PACK_NAME} (= ${CPACK_DEBIAN_PACKAGE_VERSION})")
+ endif()
+ endforeach()
+ if(COMPONENT_DEPENDS)
+ if(CPACK_DEBIAN_PACKAGE_DEPENDS)
+ set(CPACK_DEBIAN_PACKAGE_DEPENDS "${COMPONENT_DEPENDS}, ${CPACK_DEBIAN_PACKAGE_DEPENDS}")
+ else()
+ set(CPACK_DEBIAN_PACKAGE_DEPENDS "${COMPONENT_DEPENDS}")
+ endif()
+ endif()
+ endif()
+ endif()
+
+ # at this point, the CPACK_DEBIAN_PACKAGE_DEPENDS is properly set
+ # to the minimal dependency of the package
+ # Append automatically discovered dependencies .
+ if(NOT "${CPACK_DEBIAN_PACKAGE_AUTO_DEPENDS}" STREQUAL "")
+ if (CPACK_DEBIAN_PACKAGE_DEPENDS)
+ set (CPACK_DEBIAN_PACKAGE_DEPENDS "${CPACK_DEBIAN_PACKAGE_DEPENDS}, ${CPACK_DEBIAN_PACKAGE_AUTO_DEPENDS}")
+ else ()
+ set (CPACK_DEBIAN_PACKAGE_DEPENDS "${CPACK_DEBIAN_PACKAGE_AUTO_DEPENDS}")
+ endif ()
+ endif()
+
+ if(NOT CPACK_DEBIAN_PACKAGE_DEPENDS)
+ message(STATUS "CPACK_DEBIAN_PACKAGE_DEPENDS not set, the package will have no dependencies.")
+ endif()
+
+ # Maintainer: (mandatory)
+ if(NOT CPACK_DEBIAN_PACKAGE_MAINTAINER)
+ if(NOT CPACK_PACKAGE_CONTACT)
+ message(FATAL_ERROR "CPackDeb: Debian package requires a maintainer for a package, set CPACK_PACKAGE_CONTACT or CPACK_DEBIAN_PACKAGE_MAINTAINER")
+ endif()
+ set(CPACK_DEBIAN_PACKAGE_MAINTAINER ${CPACK_PACKAGE_CONTACT})
+ endif()
+
+ # Description: (mandatory)
+ if(NOT CPACK_DEB_PACKAGE_COMPONENT)
+ if(NOT CPACK_DEBIAN_PACKAGE_DESCRIPTION)
+ if(NOT CPACK_PACKAGE_DESCRIPTION_SUMMARY)
+ message(FATAL_ERROR "CPackDeb: Debian package requires a summary for a package, set CPACK_PACKAGE_DESCRIPTION_SUMMARY or CPACK_DEBIAN_PACKAGE_DESCRIPTION")
+ endif()
+ set(CPACK_DEBIAN_PACKAGE_DESCRIPTION ${CPACK_PACKAGE_DESCRIPTION_SUMMARY})
+ endif()
+ else()
+ set(component_description_var CPACK_COMPONENT_${_local_component_name}_DESCRIPTION)
+
+ # component description overrides package description
+ if(${component_description_var})
+ set(CPACK_DEBIAN_PACKAGE_DESCRIPTION ${${component_description_var}})
+ elseif(NOT CPACK_DEBIAN_PACKAGE_DESCRIPTION)
+ if(NOT CPACK_PACKAGE_DESCRIPTION_SUMMARY)
+ message(FATAL_ERROR "CPackDeb: Debian package requires a summary for a package, set CPACK_PACKAGE_DESCRIPTION_SUMMARY or CPACK_DEBIAN_PACKAGE_DESCRIPTION or ${component_description_var}")
+ endif()
+ set(CPACK_DEBIAN_PACKAGE_DESCRIPTION ${CPACK_PACKAGE_DESCRIPTION_SUMMARY})
+ endif()
+ endif()
+
+ # Homepage: (optional)
+ if(NOT CPACK_DEBIAN_PACKAGE_HOMEPAGE AND CMAKE_PROJECT_HOMEPAGE_URL)
+ set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "${CMAKE_PROJECT_HOMEPAGE_URL}")
+ endif()
+
+ # Section: (recommended)
+ if(NOT CPACK_DEBIAN_PACKAGE_SECTION)
+ set(CPACK_DEBIAN_PACKAGE_SECTION "devel")
+ endif()
+
+ # Priority: (recommended)
+ if(NOT CPACK_DEBIAN_PACKAGE_PRIORITY)
+ set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
+ endif()
+
+ if(CPACK_DEBIAN_ARCHIVE_TYPE)
+ if(CPACK_DEBIAN_ARCHIVE_TYPE STREQUAL "paxr")
+ message(DEPRECATION "CPACK_DEBIAN_ARCHIVE_TYPE set to old and invalid "
+ "type 'paxr', mapping to 'gnutar'")
+ set(CPACK_DEBIAN_ARCHIVE_TYPE "gnutar")
+ elseif(NOT CPACK_DEBIAN_ARCHIVE_TYPE STREQUAL "gnutar")
+ message(FATAL_ERROR "CPACK_DEBIAN_ARCHIVE_TYPE set to unsupported"
+ "type ${CPACK_DEBIAN_ARCHIVE_TYPE}")
+ endif()
+ else()
+ set(CPACK_DEBIAN_ARCHIVE_TYPE "gnutar")
+ endif()
+
+ # Compression: (recommended)
+ if(NOT CPACK_DEBIAN_COMPRESSION_TYPE)
+ set(CPACK_DEBIAN_COMPRESSION_TYPE "gzip")
+ endif()
+
+ # Recommends:
+ # You should set: CPACK_DEBIAN_PACKAGE_RECOMMENDS
+
+ # Suggests:
+ # You should set: CPACK_DEBIAN_PACKAGE_SUGGESTS
+
+ # CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA
+ # This variable allow advanced user to add custom script to the control.tar.gz (inside the .deb archive)
+ # Typical examples are:
+ # - conffiles
+ # - postinst
+ # - postrm
+ # - prerm
+ # Usage:
+ # set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA
+ # "${CMAKE_CURRENT_SOURCE_DIR}/prerm;${CMAKE_CURRENT_SOURCE_DIR}/postrm")
+
+ # Are we packaging components ?
+ if(CPACK_DEB_PACKAGE_COMPONENT)
+ # override values with per component version if set
+ foreach(VAR_NAME_ "PACKAGE_CONTROL_EXTRA" "PACKAGE_CONTROL_STRICT_PERMISSION")
+ if(CPACK_DEBIAN_${_local_component_name}_${VAR_NAME_})
+ set(CPACK_DEBIAN_${VAR_NAME_} "${CPACK_DEBIAN_${_local_component_name}_${VAR_NAME_}}")
+ endif()
+ endforeach()
+ get_component_package_name(CPACK_DEBIAN_PACKAGE_NAME ${_local_component_name})
+ endif()
+
+ set(CPACK_DEBIAN_PACKAGE_SHLIBS_LIST "")
+
+ if (NOT CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY)
+ set(CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY "=")
+ endif()
+
+ if(CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS)
+ if(READELF_EXECUTABLE)
+ foreach(_FILE IN LISTS CPACK_DEB_SHARED_OBJECT_FILES)
+ extract_so_info("${_FILE}" libname soversion)
+ if(libname AND DEFINED soversion)
+ list(APPEND CPACK_DEBIAN_PACKAGE_SHLIBS_LIST
+ "${libname} ${soversion} ${CPACK_DEBIAN_PACKAGE_NAME} (${CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS_POLICY} ${CPACK_DEBIAN_PACKAGE_VERSION})")
+ else()
+ message(AUTHOR_WARNING "Shared library '${_FILE}' is missing soname or soversion. Library will not be added to DEBIAN/shlibs control file.")
+ endif()
+ endforeach()
+ if (CPACK_DEBIAN_PACKAGE_SHLIBS_LIST)
+ string(REPLACE ";" "\n" CPACK_DEBIAN_PACKAGE_SHLIBS_LIST "${CPACK_DEBIAN_PACKAGE_SHLIBS_LIST}")
+ endif()
+ else()
+ message(FATAL_ERROR "Readelf utility is not available. CPACK_DEBIAN_PACKAGE_GENERATE_SHLIBS option is not available.")
+ endif()
+ endif()
+
+ # add ldconfig call in default postrm and postint
+ set(CPACK_ADD_LDCONFIG_CALL 0)
+ foreach(_FILE ${CPACK_DEB_SHARED_OBJECT_FILES})
+ get_filename_component(_DIR ${_FILE} DIRECTORY)
+ # all files in CPACK_DEB_SHARED_OBJECT_FILES have dot at the beginning
+ if(_DIR STREQUAL "./lib" OR _DIR STREQUAL "./usr/lib")
+ set(CPACK_ADD_LDCONFIG_CALL 1)
+ endif()
+ endforeach()
+
+ if(CPACK_ADD_LDCONFIG_CALL)
+ set(CPACK_DEBIAN_GENERATE_POSTINST 1)
+ set(CPACK_DEBIAN_GENERATE_POSTRM 1)
+ foreach(f ${PACKAGE_CONTROL_EXTRA})
+ get_filename_component(n "${f}" NAME)
+ if("${n}" STREQUAL "postinst")
+ set(CPACK_DEBIAN_GENERATE_POSTINST 0)
+ endif()
+ if("${n}" STREQUAL "postrm")
+ set(CPACK_DEBIAN_GENERATE_POSTRM 0)
+ endif()
+ endforeach()
+ else()
+ set(CPACK_DEBIAN_GENERATE_POSTINST 0)
+ set(CPACK_DEBIAN_GENERATE_POSTRM 0)
+ endif()
+
+ cpack_deb_variable_fallback("CPACK_DEBIAN_FILE_NAME"
+ "CPACK_DEBIAN_${_local_component_name}_FILE_NAME"
+ "CPACK_DEBIAN_FILE_NAME")
+ if(CPACK_DEBIAN_FILE_NAME)
+ if(CPACK_DEBIAN_FILE_NAME STREQUAL "DEB-DEFAULT")
+ # Patch package file name to be in correct debian format:
+ # <foo>_<VersionNumber>-<DebianRevisionNumber>_<DebianArchitecture>.deb
+ set(CPACK_OUTPUT_FILE_NAME
+ "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}.deb")
+ set(CPACK_DBGSYM_OUTPUT_FILE_NAME
+ "${CPACK_DEBIAN_PACKAGE_NAME}-dbgsym_${CPACK_DEBIAN_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}.ddeb")
+ else()
+ if(NOT CPACK_DEBIAN_FILE_NAME MATCHES ".*\\.(deb|ipk)")
+ message(FATAL_ERROR "'${CPACK_DEBIAN_FILE_NAME}' is not a valid DEB package file name as it must end with '.deb' or '.ipk'!")
+ endif()
+
+ set(CPACK_OUTPUT_FILE_NAME "${CPACK_DEBIAN_FILE_NAME}")
+ string(REGEX REPLACE "\.deb$" "-dbgsym.ddeb" CPACK_DBGSYM_OUTPUT_FILE_NAME "${CPACK_DEBIAN_FILE_NAME}")
+ endif()
+
+ set(CPACK_TEMPORARY_PACKAGE_FILE_NAME "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_OUTPUT_FILE_NAME}")
+ get_filename_component(BINARY_DIR "${CPACK_OUTPUT_FILE_PATH}" DIRECTORY)
+ set(CPACK_OUTPUT_FILE_PATH "${BINARY_DIR}/${CPACK_OUTPUT_FILE_NAME}")
+ else()
+ # back compatibility - don't change the name
+ string(REGEX REPLACE "\.deb$" "-dbgsym.ddeb" CPACK_DBGSYM_OUTPUT_FILE_NAME "${CPACK_OUTPUT_FILE_NAME}")
+ endif()
+
+ # Print out some debug information if we were asked for that
+ if(CPACK_DEBIAN_PACKAGE_DEBUG)
+ message("CPackDeb:Debug: CPACK_TOPLEVEL_DIRECTORY = '${CPACK_TOPLEVEL_DIRECTORY}'")
+ message("CPackDeb:Debug: CPACK_TOPLEVEL_TAG = '${CPACK_TOPLEVEL_TAG}'")
+ message("CPackDeb:Debug: CPACK_TEMPORARY_DIRECTORY = '${CPACK_TEMPORARY_DIRECTORY}'")
+ message("CPackDeb:Debug: CPACK_OUTPUT_FILE_NAME = '${CPACK_OUTPUT_FILE_NAME}'")
+ message("CPackDeb:Debug: CPACK_OUTPUT_FILE_PATH = '${CPACK_OUTPUT_FILE_PATH}'")
+ message("CPackDeb:Debug: CPACK_PACKAGE_FILE_NAME = '${CPACK_PACKAGE_FILE_NAME}'")
+ message("CPackDeb:Debug: CPACK_PACKAGE_INSTALL_DIRECTORY = '${CPACK_PACKAGE_INSTALL_DIRECTORY}'")
+ message("CPackDeb:Debug: CPACK_TEMPORARY_PACKAGE_FILE_NAME = '${CPACK_TEMPORARY_PACKAGE_FILE_NAME}'")
+ message("CPackDeb:Debug: CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION = '${CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION}'")
+ message("CPackDeb:Debug: CPACK_DEBIAN_PACKAGE_SOURCE = '${CPACK_DEBIAN_PACKAGE_SOURCE}'")
+ endif()
+
+ # For debian source packages:
+ # debian/control
+ # http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-sourcecontrolfiles
+
+ # .dsc
+ # http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-debiansourcecontrolfiles
+
+ # Builds-Depends:
+ #if(NOT CPACK_DEBIAN_PACKAGE_BUILDS_DEPENDS)
+ # set(CPACK_DEBIAN_PACKAGE_BUILDS_DEPENDS
+ # "debhelper (>> 5.0.0), libncurses5-dev, tcl8.4"
+ # )
+ #endif()
+
+ # move variables to parent scope so that they may be used to create debian package
+ set(GEN_CPACK_OUTPUT_FILE_NAME "${CPACK_OUTPUT_FILE_NAME}" PARENT_SCOPE)
+ set(GEN_CPACK_TEMPORARY_PACKAGE_FILE_NAME "${CPACK_TEMPORARY_PACKAGE_FILE_NAME}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_NAME "${CPACK_DEBIAN_PACKAGE_NAME}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_DEBIAN_PACKAGE_VERSION}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_SECTION "${CPACK_DEBIAN_PACKAGE_SECTION}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_PRIORITY "${CPACK_DEBIAN_PACKAGE_PRIORITY}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_ARCHITECTURE "${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_MAINTAINER "${CPACK_DEBIAN_PACKAGE_MAINTAINER}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_DESCRIPTION "${CPACK_DEBIAN_PACKAGE_DESCRIPTION}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_DEPENDS "${CPACK_DEBIAN_PACKAGE_DEPENDS}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_ARCHIVE_TYPE "${CPACK_DEBIAN_ARCHIVE_TYPE}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_COMPRESSION_TYPE "${CPACK_DEBIAN_COMPRESSION_TYPE}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_RECOMMENDS "${CPACK_DEBIAN_PACKAGE_RECOMMENDS}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_SUGGESTS "${CPACK_DEBIAN_PACKAGE_SUGGESTS}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_HOMEPAGE "${CPACK_DEBIAN_PACKAGE_HOMEPAGE}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_PREDEPENDS "${CPACK_DEBIAN_PACKAGE_PREDEPENDS}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_ENHANCES "${CPACK_DEBIAN_PACKAGE_ENHANCES}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_BREAKS "${CPACK_DEBIAN_PACKAGE_BREAKS}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_CONFLICTS "${CPACK_DEBIAN_PACKAGE_CONFLICTS}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_PROVIDES "${CPACK_DEBIAN_PACKAGE_PROVIDES}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_REPLACES "${CPACK_DEBIAN_PACKAGE_REPLACES}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_SHLIBS "${CPACK_DEBIAN_PACKAGE_SHLIBS_LIST}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION
+ "${CPACK_DEBIAN_PACKAGE_CONTROL_STRICT_PERMISSION}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_PACKAGE_SOURCE
+ "${CPACK_DEBIAN_PACKAGE_SOURCE}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_GENERATE_POSTINST "${CPACK_DEBIAN_GENERATE_POSTINST}" PARENT_SCOPE)
+ set(GEN_CPACK_DEBIAN_GENERATE_POSTRM "${CPACK_DEBIAN_GENERATE_POSTRM}" PARENT_SCOPE)
+ set(GEN_WDIR "${WDIR}" PARENT_SCOPE)
+
+ set(GEN_CPACK_DEBIAN_DEBUGINFO_PACKAGE "${CPACK_DEBIAN_DEBUGINFO_PACKAGE}" PARENT_SCOPE)
+ if(BUILD_IDS)
+ set(GEN_DBGSYMDIR "${DBGSYMDIR}" PARENT_SCOPE)
+ set(GEN_CPACK_DBGSYM_OUTPUT_FILE_NAME "${CPACK_DBGSYM_OUTPUT_FILE_NAME}" PARENT_SCOPE)
+ string(REPLACE ";" " " BUILD_IDS "${BUILD_IDS}")
+ set(GEN_BUILD_IDS "${BUILD_IDS}" PARENT_SCOPE)
+ endif()
+endfunction()
+
+cpack_deb_prepare_package_vars()
+
+cmake_policy(POP)
diff --git a/Modules/Internal/CPack/CPackExternal.cmake b/Modules/Internal/CPack/CPackExternal.cmake
new file mode 100644
index 000000000..e4d055a2d
--- /dev/null
+++ b/Modules/Internal/CPack/CPackExternal.cmake
@@ -0,0 +1,53 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+if(NOT "${CPACK_EXTERNAL_REQUESTED_VERSIONS}" STREQUAL "")
+ unset(_found_major)
+
+ foreach(_req_version IN LISTS CPACK_EXTERNAL_REQUESTED_VERSIONS)
+ if(_req_version MATCHES "^([0-9]+)\\.([0-9]+)$")
+ set(_req_major "${CMAKE_MATCH_1}")
+ set(_req_minor "${CMAKE_MATCH_2}")
+
+ foreach(_known_version IN LISTS CPACK_EXTERNAL_KNOWN_VERSIONS)
+ string(REGEX MATCH
+ "^([0-9]+)\\.([0-9]+)$"
+ _known_version_dummy
+ "${_known_version}"
+ )
+
+ set(_known_major "${CMAKE_MATCH_1}")
+ set(_known_minor "${CMAKE_MATCH_2}")
+
+ if(_req_major EQUAL _known_major AND NOT _known_minor LESS _req_minor)
+ set(_found_major "${_known_major}")
+ set(_found_minor "${_known_minor}")
+ break()
+ endif()
+ endforeach()
+
+ if(DEFINED _found_major)
+ break()
+ endif()
+ endif()
+ endforeach()
+
+ if(DEFINED _found_major)
+ set(CPACK_EXTERNAL_SELECTED_MAJOR "${_found_major}")
+ set(CPACK_EXTERNAL_SELECTED_MINOR "${_found_minor}")
+ set(CPACK_EXTERNAL_SELECTED_VERSION "${_found_major}.${_found_minor}")
+ else()
+ message(FATAL_ERROR
+ "Could not find a suitable version in CPACK_EXTERNAL_REQUESTED_VERSIONS"
+ )
+ endif()
+else()
+ list(GET CPACK_EXTERNAL_KNOWN_VERSIONS 0 CPACK_EXTERNAL_SELECTED_VERSION)
+ string(REGEX MATCH
+ "^([0-9]+)\\.([0-9]+)$"
+ _dummy
+ "${CPACK_EXTERNAL_SELECTED_VERSION}"
+ )
+ set(CPACK_EXTERNAL_SELECTED_MAJOR "${CMAKE_MATCH_1}")
+ set(CPACK_EXTERNAL_SELECTED_MINOR "${CMAKE_MATCH_2}")
+endif()
diff --git a/Modules/Internal/CPack/CPackFreeBSD.cmake b/Modules/Internal/CPack/CPackFreeBSD.cmake
new file mode 100644
index 000000000..16f906cac
--- /dev/null
+++ b/Modules/Internal/CPack/CPackFreeBSD.cmake
@@ -0,0 +1,107 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+
+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"
+ "CMAKE_PROJECT_HOMEPAGE_URL"
+ "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/Internal/CPack/CPackNuGet.cmake b/Modules/Internal/CPack/CPackNuGet.cmake
new file mode 100644
index 000000000..4b2ce9248
--- /dev/null
+++ b/Modules/Internal/CPack/CPackNuGet.cmake
@@ -0,0 +1,363 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# Author: Alex Turbov
+
+if(CMAKE_BINARY_DIR)
+ message(FATAL_ERROR "CPackNuGet.cmake may only be used by CPack internally.")
+endif()
+
+function(_cpack_nuget_debug)
+ if(CPACK_NUGET_PACKAGE_DEBUG)
+ message("CPackNuGet:Debug: " ${ARGN})
+ endif()
+endfunction()
+
+function(_cpack_nuget_debug_var NAME)
+ if(CPACK_NUGET_PACKAGE_DEBUG)
+ message("CPackNuGet:Debug: ${NAME}=`${${NAME}}`")
+ endif()
+endfunction()
+
+function(_cpack_nuget_variable_fallback OUTPUT_VAR_NAME NUGET_VAR_NAME)
+ if(ARGN)
+ list(JOIN ARGN "`, `" _va_args)
+ set(_va_args ", ARGN: `${_va_args}`")
+ endif()
+ _cpack_nuget_debug(
+ "_cpack_nuget_variable_fallback: "
+ "OUTPUT_VAR_NAME=`${OUTPUT_VAR_NAME}`, "
+ "NUGET_VAR_NAME=`${NUGET_VAR_NAME}`"
+ "${_va_args}"
+ )
+
+ set(_options USE_CDATA)
+ set(_one_value_args LIST_GLUE)
+ set(_multi_value_args FALLBACK_VARS)
+ cmake_parse_arguments(PARSE_ARGV 0 _args "${_options}" "${_one_value_args}" "${_multi_value_args}")
+
+ if(CPACK_NUGET_PACKAGE_COMPONENT)
+ string(
+ TOUPPER "${CPACK_NUGET_PACKAGE_COMPONENT}"
+ CPACK_NUGET_PACKAGE_COMPONENT_UPPER
+ )
+ endif()
+
+ if(CPACK_NUGET_PACKAGE_COMPONENT
+ AND CPACK_NUGET_${CPACK_NUGET_PACKAGE_COMPONENT}_PACKAGE_${NUGET_VAR_NAME}
+ )
+ set(
+ _result
+ "${CPACK_NUGET_${CPACK_NUGET_PACKAGE_COMPONENT}_PACKAGE_${NUGET_VAR_NAME}}"
+ )
+ _cpack_nuget_debug(
+ " CPACK_NUGET_${CPACK_NUGET_PACKAGE_COMPONENT}_PACKAGE_${NUGET_VAR_NAME}: "
+ "OUTPUT_VAR_NAME->${OUTPUT_VAR_NAME}=`${_result}`"
+ )
+
+ elseif(CPACK_NUGET_PACKAGE_COMPONENT_UPPER
+ AND CPACK_NUGET_${CPACK_NUGET_PACKAGE_COMPONENT_UPPER}_PACKAGE_${NUGET_VAR_NAME}
+ )
+ set(
+ _result
+ "${CPACK_NUGET_${CPACK_NUGET_PACKAGE_COMPONENT_UPPER}_PACKAGE_${NUGET_VAR_NAME}}"
+ )
+ _cpack_nuget_debug(
+ " CPACK_NUGET_${CPACK_NUGET_PACKAGE_COMPONENT_UPPER}_PACKAGE_${NUGET_VAR_NAME}: "
+ "OUTPUT_VAR_NAME->${OUTPUT_VAR_NAME}=`${_result}`"
+ )
+
+ elseif(CPACK_NUGET_PACKAGE_${NUGET_VAR_NAME})
+ set(_result "${CPACK_NUGET_PACKAGE_${NUGET_VAR_NAME}}")
+ _cpack_nuget_debug(
+ " CPACK_NUGET_PACKAGE_${NUGET_VAR_NAME}: "
+ "OUTPUT_VAR_NAME->${OUTPUT_VAR_NAME}=`${_result}`"
+ )
+
+ else()
+ foreach(_var IN LISTS _args_FALLBACK_VARS)
+ _cpack_nuget_debug(" Fallback: ${_var} ...")
+ if(${_var})
+ _cpack_nuget_debug(" ${_var}=`${${_var}}`")
+ set(_result "${${_var}}")
+ _cpack_nuget_debug(
+ " ${_var}: OUTPUT_VAR_NAME->${OUTPUT_VAR_NAME}=`${_result}`"
+ )
+ break()
+ endif()
+ endforeach()
+ endif()
+
+ if(_result)
+ if(_args_USE_CDATA)
+ set(_value_before "<![CDATA[")
+ set(_value_after "]]>")
+ endif()
+
+ list(LENGTH _result _result_len)
+ if(_result_len GREATER 1 AND _args_LIST_GLUE)
+ list(JOIN _result "${_args_LIST_GLUE}" _result)
+ endif()
+
+ set(${OUTPUT_VAR_NAME} "${_value_before}${_result}${_value_after}" PARENT_SCOPE)
+ endif()
+
+endfunction()
+
+function(_cpack_nuget_variable_fallback_and_wrap_into_element ELEMENT NUGET_VAR_NAME)
+ set(_options)
+ set(_one_value_args)
+ set(_multi_value_args FALLBACK_VARS)
+ cmake_parse_arguments(PARSE_ARGV 0 _args "${_options}" "${_one_value_args}" "${_multi_value_args}")
+
+ _cpack_nuget_variable_fallback(_value ${NUGET_VAR_NAME} ${ARGN} USE_CDATA)
+
+ if(_value)
+ string(TOUPPER "${ELEMENT}" _ELEMENT_UP)
+ set(
+ _CPACK_NUGET_${_ELEMENT_UP}_TAG
+ "<${ELEMENT}>${_value}</${ELEMENT}>"
+ PARENT_SCOPE
+ )
+ endif()
+endfunction()
+
+# Print some debug info
+_cpack_nuget_debug("---[CPack NuGet Input Variables]---")
+_cpack_nuget_debug_var(CPACK_PACKAGE_NAME)
+_cpack_nuget_debug_var(CPACK_PACKAGE_VERSION)
+_cpack_nuget_debug_var(CPACK_TOPLEVEL_TAG)
+_cpack_nuget_debug_var(CPACK_TOPLEVEL_DIRECTORY)
+_cpack_nuget_debug_var(CPACK_TEMPORARY_DIRECTORY)
+_cpack_nuget_debug_var(CPACK_NUGET_GROUPS)
+if(CPACK_NUGET_GROUPS)
+ foreach(_group IN LISTS CPACK_NUGET_GROUPS)
+ string(MAKE_C_IDENTIFIER "${_group}" _group_up)
+ string(TOUPPER "${_group_up}" _group_up)
+ _cpack_nuget_debug_var(CPACK_NUGET_${_group_up}_GROUP_COMPONENTS)
+ endforeach()
+endif()
+_cpack_nuget_debug_var(CPACK_NUGET_COMPONENTS)
+_cpack_nuget_debug_var(CPACK_NUGET_ALL_IN_ONE)
+_cpack_nuget_debug_var(CPACK_NUGET_ORDINAL_MONOLITIC)
+_cpack_nuget_debug("-----------------------------------")
+
+function(_cpack_nuget_render_spec)
+ # Make a variable w/ upper-cased component name
+ if(CPACK_NUGET_PACKAGE_COMPONENT)
+ string(TOUPPER "${CPACK_NUGET_PACKAGE_COMPONENT}" CPACK_NUGET_PACKAGE_COMPONENT_UPPER)
+ endif()
+
+ # Set mandatory variables (not wrapped into XML elements)
+ # https://docs.microsoft.com/en-us/nuget/reference/nuspec#required-metadata-elements
+ if(CPACK_NUGET_PACKAGE_COMPONENT)
+ if(CPACK_NUGET_${CPACK_NUGET_PACKAGE_COMPONENT_UPPER}_PACKAGE_NAME)
+ set(
+ CPACK_NUGET_PACKAGE_NAME
+ "${CPACK_NUGET_${CPACK_NUGET_PACKAGE_COMPONENT_UPPER}_PACKAGE_NAME}"
+ )
+ elseif(NOT CPACK_NUGET_PACKAGE_COMPONENT STREQUAL "Unspecified")
+ set(
+ CPACK_NUGET_PACKAGE_NAME
+ "${CPACK_PACKAGE_NAME}.${CPACK_NUGET_PACKAGE_COMPONENT}"
+ )
+ else()
+ set(CPACK_NUGET_PACKAGE_NAME "${CPACK_PACKAGE_NAME}")
+ endif()
+ elseif(NOT CPACK_NUGET_PACKAGE_NAME)
+ set(CPACK_NUGET_PACKAGE_NAME "${CPACK_PACKAGE_NAME}")
+ endif()
+
+ _cpack_nuget_variable_fallback(
+ CPACK_NUGET_PACKAGE_VERSION VERSION
+ FALLBACK_VARS
+ CPACK_PACKAGE_VERSION
+ )
+ _cpack_nuget_variable_fallback(
+ CPACK_NUGET_PACKAGE_DESCRIPTION DESCRIPTION
+ FALLBACK_VARS
+ CPACK_COMPONENT_${CPACK_NUGET_PACKAGE_COMPONENT}_DESCRIPTION
+ CPACK_COMPONENT_${CPACK_NUGET_PACKAGE_COMPONENT_UPPER}_DESCRIPTION
+ CPACK_COMPONENT_GROUP_${CPACK_NUGET_PACKAGE_COMPONENT_UPPER}_DESCRIPTION
+ CPACK_PACKAGE_DESCRIPTION
+ USE_CDATA
+ )
+ _cpack_nuget_variable_fallback(
+ CPACK_NUGET_PACKAGE_AUTHORS AUTHORS
+ FALLBACK_VARS
+ CPACK_PACKAGE_VENDOR
+ USE_CDATA
+ LIST_GLUE ","
+ )
+
+ # Set optional variables (wrapped into XML elements)
+ # https://docs.microsoft.com/en-us/nuget/reference/nuspec#optional-metadata-elements
+ _cpack_nuget_variable_fallback_and_wrap_into_element(
+ title
+ TITLE
+ FALLBACK_VARS
+ CPACK_COMPONENT_${CPACK_NUGET_PACKAGE_COMPONENT}_DISPLAY_NAME
+ CPACK_COMPONENT_${CPACK_NUGET_PACKAGE_COMPONENT_UPPER}_DISPLAY_NAME
+ CPACK_COMPONENT_GROUP_${CPACK_NUGET_PACKAGE_COMPONENT_UPPER}_DISPLAY_NAME
+ )
+ _cpack_nuget_variable_fallback_and_wrap_into_element(owners OWNERS LIST_GLUE ",")
+ _cpack_nuget_variable_fallback_and_wrap_into_element(
+ projectUrl
+ HOMEPAGE_URL
+ FALLBACK_VARS
+ CPACK_PACKAGE_HOMEPAGE_URL
+ )
+ _cpack_nuget_variable_fallback_and_wrap_into_element(licenseUrl LICENSEURL)
+ _cpack_nuget_variable_fallback_and_wrap_into_element(iconUrl ICONURL)
+ _cpack_nuget_variable_fallback_and_wrap_into_element(
+ summary DESCRIPTION_SUMMARY
+ FALLBACK_VARS
+ CPACK_PACKAGE_DESCRIPTION_SUMMARY
+ )
+ if(CPACK_NUGET_PACKAGE_REQUIRE_LICENSE_ACCEPTANCE)
+ set(
+ _CPACK_NUGET_REQUIRELICENSEACCEPTANCE_TAG
+ "<requireLicenseAcceptance>true</requireLicenseAcceptance>"
+ )
+ endif()
+ _cpack_nuget_variable_fallback_and_wrap_into_element(releaseNotes RELEASE_NOTES)
+ _cpack_nuget_variable_fallback_and_wrap_into_element(copyright COPYRIGHT)
+ _cpack_nuget_variable_fallback_and_wrap_into_element(tags TAGS LIST_GLUE " ")
+
+ # Handle dependencies
+ _cpack_nuget_variable_fallback(_deps DEPENDENCIES)
+ set(_collected_deps)
+ foreach(_dep IN LISTS _deps)
+ _cpack_nuget_debug(" checking dependency `${_dep}`")
+
+ string(MAKE_C_IDENTIFIER "${_dep}" _dep_id)
+
+ _cpack_nuget_variable_fallback(_ver DEPENDENCIES_${_dep_id}_VERSION)
+
+ if(NOT _ver)
+ string(TOUPPER "${_dep_id}" _dep_id)
+ _cpack_nuget_variable_fallback(_ver DEPENDENCIES_${_dep_id}_VERSION)
+ endif()
+
+ if(_ver)
+ _cpack_nuget_debug(" got `${_dep}` dependency version ${_ver}")
+ list(APPEND _collected_deps "<dependency id=\"${_dep}\" version=\"${_ver}\" />")
+ endif()
+ endforeach()
+
+ # Render deps into the variable
+ if(_collected_deps)
+ set(_CPACK_NUGET_DEPENDENCIES_TAG "<dependencies>\n")
+ foreach(_line IN LISTS _collected_deps)
+ string(
+ APPEND _CPACK_NUGET_DEPENDENCIES_TAG
+ " ${_line}\n"
+ )
+ endforeach()
+ string(APPEND _CPACK_NUGET_DEPENDENCIES_TAG " </dependencies>")
+ endif()
+
+ # Render the spec file
+ # NOTE The spec filename doesn't matter. Being included into a package,
+ # NuGet will name it properly.
+ _cpack_nuget_debug("Rendering `${CPACK_TEMPORARY_DIRECTORY}/CPack.NuGet.nuspec` file...")
+ configure_file(
+ "${CMAKE_ROOT}/Modules/CPack.NuGet.nuspec.in"
+ "${CPACK_TEMPORARY_DIRECTORY}/CPack.NuGet.nuspec"
+ @ONLY
+ )
+endfunction()
+
+function(_cpack_nuget_make_files_tag)
+ set(_files)
+ foreach(_comp IN LISTS ARGN)
+ string(APPEND _files " <file src=\"${_comp}\\**\" target=\".\" />\n")
+ endforeach()
+ set(_CPACK_NUGET_FILES_TAG "<files>\n${_files} </files>" PARENT_SCOPE)
+endfunction()
+
+find_program(NUGET_EXECUTABLE nuget)
+_cpack_nuget_debug_var(NUGET_EXECUTABLE)
+if(NOT NUGET_EXECUTABLE)
+ message(FATAL_ERROR "NuGet executable not found")
+endif()
+
+# Add details for debug run
+if(CPACK_NUGET_PACKAGE_DEBUG)
+ list(APPEND CPACK_NUGET_PACK_ADDITIONAL_OPTIONS "-Verbosity" "detailed")
+endif()
+
+# Case one: ordinal all-in-one package
+if(CPACK_NUGET_ORDINAL_MONOLITIC)
+ # This variable `CPACK_NUGET_ALL_IN_ONE` set by C++ code:
+ # Meaning to pack all installed files into a single package
+ _cpack_nuget_debug("---[Making an ordinal monolitic package]---")
+ _cpack_nuget_render_spec()
+ execute_process(
+ COMMAND "${NUGET_EXECUTABLE}" pack ${CPACK_NUGET_PACK_ADDITIONAL_OPTIONS}
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ )
+
+elseif(CPACK_NUGET_ALL_IN_ONE)
+ # This variable `CPACK_NUGET_ALL_IN_ONE` set by C++ code:
+ # Meaning to pack all installed components into a single package
+ _cpack_nuget_debug("---[Making a monolitic package from installed components]---")
+
+ # Prepare the `files` element which include files from several components
+ _cpack_nuget_make_files_tag(${CPACK_NUGET_COMPONENTS})
+ _cpack_nuget_render_spec()
+ execute_process(
+ COMMAND "${NUGET_EXECUTABLE}" pack ${CPACK_NUGET_PACK_ADDITIONAL_OPTIONS}
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ )
+
+else()
+ # Is there any grouped component?
+ if(CPACK_NUGET_GROUPS)
+ _cpack_nuget_debug("---[Making grouped component(s) package(s)]---")
+ foreach(_group IN LISTS CPACK_NUGET_GROUPS)
+ _cpack_nuget_debug("Starting to make the package for group `${_group}`")
+ string(MAKE_C_IDENTIFIER "${_group}" _group_up)
+ string(TOUPPER "${_group_up}" _group_up)
+
+ # Render a spec file which includes all components in the current group
+ unset(_CPACK_NUGET_FILES_TAG)
+ _cpack_nuget_make_files_tag(${CPACK_NUGET_${_group_up}_GROUP_COMPONENTS})
+ # Temporary set `CPACK_NUGET_PACKAGE_COMPONENT` to the group name
+ # to properly collect various per group settings
+ set(CPACK_NUGET_PACKAGE_COMPONENT ${_group})
+ _cpack_nuget_render_spec()
+ unset(CPACK_NUGET_PACKAGE_COMPONENT)
+ execute_process(
+ COMMAND "${NUGET_EXECUTABLE}" pack ${CPACK_NUGET_PACK_ADDITIONAL_OPTIONS}
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ )
+ endforeach()
+ endif()
+ # Is there any single component package needed?
+ if(CPACK_NUGET_COMPONENTS)
+ _cpack_nuget_debug("---[Making single-component(s) package(s)]---")
+ foreach(_comp IN LISTS CPACK_NUGET_COMPONENTS)
+ _cpack_nuget_debug("Starting to make the package for component `${_comp}`")
+ # Render a spec file which includes only given component
+ unset(_CPACK_NUGET_FILES_TAG)
+ _cpack_nuget_make_files_tag(${_comp})
+ # Temporary set `CPACK_NUGET_PACKAGE_COMPONENT` to the current
+ # component name to properly collect various per group settings
+ set(CPACK_NUGET_PACKAGE_COMPONENT ${_comp})
+ _cpack_nuget_render_spec()
+ unset(CPACK_NUGET_PACKAGE_COMPONENT)
+ execute_process(
+ COMMAND "${NUGET_EXECUTABLE}" pack ${CPACK_NUGET_PACK_ADDITIONAL_OPTIONS}
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ )
+ endforeach()
+ endif()
+endif()
+
+file(GLOB_RECURSE GEN_CPACK_OUTPUT_FILES "${CPACK_TEMPORARY_DIRECTORY}/*.nupkg")
+if(NOT GEN_CPACK_OUTPUT_FILES)
+ message(FATAL_ERROR "NuGet package was not generated at `${CPACK_TEMPORARY_DIRECTORY}`!")
+endif()
+
+_cpack_nuget_debug("Generated files: ${GEN_CPACK_OUTPUT_FILES}")
diff --git a/Modules/Internal/CPack/CPackRPM.cmake b/Modules/Internal/CPack/CPackRPM.cmake
new file mode 100644
index 000000000..ffb24e2d9
--- /dev/null
+++ b/Modules/Internal/CPack/CPackRPM.cmake
@@ -0,0 +1,1881 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# Author: Eric Noulard with the help of Alexander Neundorf.
+
+cmake_policy(PUSH)
+cmake_policy(SET CMP0057 NEW) # if IN_LIST
+
+function(get_file_permissions FILE RETURN_VAR)
+ execute_process(COMMAND ls -l ${FILE}
+ OUTPUT_VARIABLE permissions_
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+ string(REPLACE " " ";" permissions_ "${permissions_}")
+ list(GET permissions_ 0 permissions_)
+
+ unset(text_notation_)
+ set(any_chars_ ".")
+ foreach(PERMISSION_TYPE "OWNER" "GROUP" "WORLD")
+ if(permissions_ MATCHES "${any_chars_}r.*")
+ list(APPEND text_notation_ "${PERMISSION_TYPE}_READ")
+ endif()
+ string(APPEND any_chars_ ".")
+ if(permissions_ MATCHES "${any_chars_}w.*")
+ list(APPEND text_notation_ "${PERMISSION_TYPE}_WRITE")
+ endif()
+ string(APPEND any_chars_ ".")
+ if(permissions_ MATCHES "${any_chars_}x.*")
+ list(APPEND text_notation_ "${PERMISSION_TYPE}_EXECUTE")
+ endif()
+ endforeach()
+
+ set(${RETURN_VAR} "${text_notation_}" PARENT_SCOPE)
+endfunction()
+
+function(get_unix_permissions_octal_notation PERMISSIONS_VAR RETURN_VAR)
+ set(PERMISSIONS ${${PERMISSIONS_VAR}})
+ list(LENGTH PERMISSIONS PERM_LEN_PRE)
+ list(REMOVE_DUPLICATES PERMISSIONS)
+ list(LENGTH PERMISSIONS PERM_LEN_POST)
+
+ if(NOT ${PERM_LEN_PRE} EQUAL ${PERM_LEN_POST})
+ message(FATAL_ERROR "${PERMISSIONS_VAR} contains duplicate values.")
+ endif()
+
+ foreach(PERMISSION_TYPE "OWNER" "GROUP" "WORLD")
+ set(${PERMISSION_TYPE}_PERMISSIONS 0)
+
+ foreach(PERMISSION ${PERMISSIONS})
+ if("${PERMISSION}" STREQUAL "${PERMISSION_TYPE}_READ")
+ math(EXPR ${PERMISSION_TYPE}_PERMISSIONS "${${PERMISSION_TYPE}_PERMISSIONS} + 4")
+ elseif("${PERMISSION}" STREQUAL "${PERMISSION_TYPE}_WRITE")
+ math(EXPR ${PERMISSION_TYPE}_PERMISSIONS "${${PERMISSION_TYPE}_PERMISSIONS} + 2")
+ elseif("${PERMISSION}" STREQUAL "${PERMISSION_TYPE}_EXECUTE")
+ math(EXPR ${PERMISSION_TYPE}_PERMISSIONS "${${PERMISSION_TYPE}_PERMISSIONS} + 1")
+ elseif(PERMISSION MATCHES "${PERMISSION_TYPE}.*")
+ message(FATAL_ERROR "${PERMISSIONS_VAR} contains invalid values.")
+ endif()
+ endforeach()
+ endforeach()
+
+ set(${RETURN_VAR} "${OWNER_PERMISSIONS}${GROUP_PERMISSIONS}${WORLD_PERMISSIONS}" PARENT_SCOPE)
+endfunction()
+
+function(cpack_rpm_exact_regex regex_var string)
+ string(REGEX REPLACE "([][+.*()^])" "\\\\\\1" regex "${string}")
+ set("${regex_var}" "${regex}" PARENT_SCOPE)
+endfunction()
+
+function(cpack_rpm_prepare_relocation_paths)
+ # set appropriate prefix, remove possible trailing slash and convert backslashes to slashes
+ if(CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_PREFIX)
+ file(TO_CMAKE_PATH "${CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_PREFIX}" PATH_PREFIX)
+ elseif(CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_PACKAGE_PREFIX)
+ file(TO_CMAKE_PATH "${CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_PACKAGE_PREFIX}" PATH_PREFIX)
+ else()
+ file(TO_CMAKE_PATH "${CPACK_PACKAGING_INSTALL_PREFIX}" PATH_PREFIX)
+ endif()
+
+ set(RPM_RELOCATION_PATHS "${CPACK_RPM_RELOCATION_PATHS}")
+ list(REMOVE_DUPLICATES RPM_RELOCATION_PATHS)
+
+ # set base path prefix
+ if(EXISTS "${WDIR}/${PATH_PREFIX}")
+ if(NOT CPACK_RPM_NO_INSTALL_PREFIX_RELOCATION AND
+ NOT CPACK_RPM_NO_${CPACK_RPM_PACKAGE_COMPONENT}_INSTALL_PREFIX_RELOCATION AND
+ NOT CPACK_RPM_NO_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_INSTALL_PREFIX_RELOCATION)
+ string(APPEND TMP_RPM_PREFIXES "Prefix: ${PATH_PREFIX}\n")
+ list(APPEND RPM_USED_PACKAGE_PREFIXES "${PATH_PREFIX}")
+
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: removing '${PATH_PREFIX}' from relocation paths")
+ endif()
+ endif()
+ endif()
+
+ # set other path prefixes
+ foreach(RELOCATION_PATH ${RPM_RELOCATION_PATHS})
+ if(IS_ABSOLUTE "${RELOCATION_PATH}")
+ set(PREPARED_RELOCATION_PATH "${RELOCATION_PATH}")
+ elseif(PATH_PREFIX STREQUAL "/")
+ # don't prefix path with a second slash as "//" is treated as network path
+ # by get_filename_component() so it remains in path even inside rpm
+ # package where it may cause problems with relocation
+ set(PREPARED_RELOCATION_PATH "/${RELOCATION_PATH}")
+ else()
+ set(PREPARED_RELOCATION_PATH "${PATH_PREFIX}/${RELOCATION_PATH}")
+ endif()
+
+ # handle cases where path contains extra slashes (e.g. /a//b/ instead of
+ # /a/b)
+ get_filename_component(PREPARED_RELOCATION_PATH
+ "${PREPARED_RELOCATION_PATH}" ABSOLUTE)
+
+ if(EXISTS "${WDIR}/${PREPARED_RELOCATION_PATH}")
+ string(APPEND TMP_RPM_PREFIXES "Prefix: ${PREPARED_RELOCATION_PATH}\n")
+ list(APPEND RPM_USED_PACKAGE_PREFIXES "${PREPARED_RELOCATION_PATH}")
+ endif()
+ endforeach()
+
+ # warn about all the paths that are not relocatable
+ file(GLOB_RECURSE FILE_PATHS_ "${WDIR}/*")
+ foreach(TMP_PATH ${FILE_PATHS_})
+ string(LENGTH "${WDIR}" WDIR_LEN)
+ string(SUBSTRING "${TMP_PATH}" ${WDIR_LEN} -1 TMP_PATH)
+ unset(TMP_PATH_FOUND_)
+
+ foreach(RELOCATION_PATH ${RPM_USED_PACKAGE_PREFIXES})
+ file(RELATIVE_PATH REL_PATH_ "${RELOCATION_PATH}" "${TMP_PATH}")
+ string(SUBSTRING "${REL_PATH_}" 0 2 PREFIX_)
+
+ if(NOT "${PREFIX_}" STREQUAL "..")
+ set(TPM_PATH_FOUND_ TRUE)
+ break()
+ endif()
+ endforeach()
+
+ if(NOT TPM_PATH_FOUND_)
+ message(AUTHOR_WARNING "CPackRPM:Warning: Path ${TMP_PATH} is not on one of the relocatable paths! Package will be partially relocatable.")
+ endif()
+ endforeach()
+
+ set(RPM_USED_PACKAGE_PREFIXES "${RPM_USED_PACKAGE_PREFIXES}" PARENT_SCOPE)
+ set(TMP_RPM_PREFIXES "${TMP_RPM_PREFIXES}" PARENT_SCOPE)
+endfunction()
+
+function(cpack_rpm_prepare_content_list)
+ # get files list
+ file(GLOB_RECURSE CPACK_RPM_INSTALL_FILES LIST_DIRECTORIES true RELATIVE "${WDIR}" "${WDIR}/*")
+ set(CPACK_RPM_INSTALL_FILES "/${CPACK_RPM_INSTALL_FILES}")
+ string(REPLACE ";" ";/" CPACK_RPM_INSTALL_FILES "${CPACK_RPM_INSTALL_FILES}")
+
+ # if we are creating a relocatable package, omit parent directories of
+ # CPACK_RPM_PACKAGE_PREFIX. This is achieved by building a "filter list"
+ # which is passed to the find command that generates the content-list
+ if(CPACK_RPM_PACKAGE_RELOCATABLE)
+ # get a list of the elements in CPACK_RPM_PACKAGE_PREFIXES that are
+ # destinct parent paths of other relocation paths and remove the
+ # final element (so the install-prefix dir itself is not omitted
+ # from the RPM's content-list)
+ list(SORT RPM_USED_PACKAGE_PREFIXES)
+ set(_DISTINCT_PATH "NOT_SET")
+ foreach(_RPM_RELOCATION_PREFIX ${RPM_USED_PACKAGE_PREFIXES})
+ if(NOT "${_RPM_RELOCATION_PREFIX}" MATCHES "${_DISTINCT_PATH}/.*")
+ set(_DISTINCT_PATH "${_RPM_RELOCATION_PREFIX}")
+
+ string(REPLACE "/" ";" _CPACK_RPM_PACKAGE_PREFIX_ELEMS " ${_RPM_RELOCATION_PREFIX}")
+ list(REMOVE_AT _CPACK_RPM_PACKAGE_PREFIX_ELEMS -1)
+ unset(_TMP_LIST)
+ # Now generate all of the parent dirs of the relocation path
+ foreach(_PREFIX_PATH_ELEM ${_CPACK_RPM_PACKAGE_PREFIX_ELEMS})
+ list(APPEND _TMP_LIST "${_PREFIX_PATH_ELEM}")
+ string(REPLACE ";" "/" _OMIT_DIR "${_TMP_LIST}")
+ separate_arguments(_OMIT_DIR)
+ list(APPEND _RPM_DIRS_TO_OMIT ${_OMIT_DIR})
+ endforeach()
+ endif()
+ endforeach()
+ endif()
+
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: Initial list of path to OMIT in RPM: ${_RPM_DIRS_TO_OMIT}")
+ endif()
+
+ if(NOT DEFINED CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST)
+ 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.")
+ endif()
+ list(APPEND CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST "${CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION}")
+ endif()
+ endif()
+
+ if(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST)
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST= ${CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST}")
+ endif()
+ list(APPEND _RPM_DIRS_TO_OMIT ${CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST})
+ endif()
+
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: Final list of path to OMIT in RPM: ${_RPM_DIRS_TO_OMIT}")
+ endif()
+
+ list(REMOVE_ITEM CPACK_RPM_INSTALL_FILES ${_RPM_DIRS_TO_OMIT})
+
+ # add man paths that will be compressed
+ # (copied from /usr/lib/rpm/brp-compress - script that does the actual
+ # compressing)
+ list(APPEND MAN_LOCATIONS "/usr/man/man.*" "/usr/man/.*/man.*" "/usr/info.*"
+ "/usr/share/man/man.*" "/usr/share/man/.*/man.*" "/usr/share/info.*"
+ "/usr/kerberos/man.*" "/usr/X11R6/man/man.*" "/usr/lib/perl5/man/man.*"
+ "/usr/share/doc/.*/man/man.*" "/usr/lib/.*/man/man.*")
+
+ if(CPACK_RPM_ADDITIONAL_MAN_DIRS)
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: CPACK_RPM_ADDITIONAL_MAN_DIRS= ${CPACK_RPM_ADDITIONAL_MAN_DIRS}")
+ endif()
+ list(APPEND MAN_LOCATIONS ${CPACK_RPM_ADDITIONAL_MAN_DIRS})
+ endif()
+
+ foreach(PACK_LOCATION IN LISTS CPACK_RPM_INSTALL_FILES)
+ foreach(MAN_LOCATION IN LISTS MAN_LOCATIONS)
+ # man pages are files inside a certain location
+ if(PACK_LOCATION MATCHES "${MAN_LOCATION}/"
+ AND NOT IS_DIRECTORY "${WDIR}${PACK_LOCATION}"
+ AND NOT IS_SYMLINK "${WDIR}${PACK_LOCATION}")
+ list(FIND CPACK_RPM_INSTALL_FILES "${PACK_LOCATION}" INDEX)
+ # insert file location that covers compressed man pages
+ # even if using a wildcard causes duplicates as those are
+ # handled by RPM and we still keep the same file list
+ # in spec file - wildcard only represents file type (e.g. .gz)
+ list(INSERT CPACK_RPM_INSTALL_FILES ${INDEX} "${PACK_LOCATION}*")
+ # remove file location that doesn't cover compressed man pages
+ math(EXPR INDEX ${INDEX}+1)
+ list(REMOVE_AT CPACK_RPM_INSTALL_FILES ${INDEX})
+
+ break()
+ endif()
+ endforeach()
+ endforeach()
+
+ set(CPACK_RPM_INSTALL_FILES "${CPACK_RPM_INSTALL_FILES}" PARENT_SCOPE)
+endfunction()
+
+function(cpack_rpm_symlink_get_relocation_prefixes LOCATION PACKAGE_PREFIXES RETURN_VARIABLE)
+ foreach(PKG_PREFIX IN LISTS PACKAGE_PREFIXES)
+ string(REGEX MATCH "^${PKG_PREFIX}/.*" FOUND_ "${LOCATION}")
+ if(FOUND_)
+ list(APPEND TMP_PREFIXES "${PKG_PREFIX}")
+ endif()
+ endforeach()
+
+ set(${RETURN_VARIABLE} "${TMP_PREFIXES}" PARENT_SCOPE)
+endfunction()
+
+function(cpack_rpm_symlink_create_relocation_script PACKAGE_PREFIXES)
+ list(LENGTH PACKAGE_PREFIXES LAST_INDEX)
+ set(SORTED_PACKAGE_PREFIXES "${PACKAGE_PREFIXES}")
+ list(SORT SORTED_PACKAGE_PREFIXES)
+ list(REVERSE SORTED_PACKAGE_PREFIXES)
+ math(EXPR LAST_INDEX ${LAST_INDEX}-1)
+
+ foreach(SYMLINK_INDEX RANGE ${LAST_INDEX})
+ list(GET SORTED_PACKAGE_PREFIXES ${SYMLINK_INDEX} SRC_PATH)
+ list(FIND PACKAGE_PREFIXES "${SRC_PATH}" SYMLINK_INDEX) # reverse magic
+ string(LENGTH "${SRC_PATH}" SRC_PATH_LEN)
+
+ set(PARTS_CNT 0)
+ set(SCRIPT_PART "if [ \"$RPM_INSTALL_PREFIX${SYMLINK_INDEX}\" != \"${SRC_PATH}\" ]; then\n")
+
+ # both paths relocated
+ foreach(POINT_INDEX RANGE ${LAST_INDEX})
+ list(GET SORTED_PACKAGE_PREFIXES ${POINT_INDEX} POINT_PATH)
+ list(FIND PACKAGE_PREFIXES "${POINT_PATH}" POINT_INDEX) # reverse magic
+ string(LENGTH "${POINT_PATH}" POINT_PATH_LEN)
+
+ if(_RPM_RELOCATION_SCRIPT_${SYMLINK_INDEX}_${POINT_INDEX})
+ if("${SYMLINK_INDEX}" EQUAL "${POINT_INDEX}")
+ set(INDENT "")
+ else()
+ string(APPEND SCRIPT_PART " if [ \"$RPM_INSTALL_PREFIX${POINT_INDEX}\" != \"${POINT_PATH}\" ]; then\n")
+ set(INDENT " ")
+ endif()
+
+ foreach(RELOCATION_NO IN LISTS _RPM_RELOCATION_SCRIPT_${SYMLINK_INDEX}_${POINT_INDEX})
+ math(EXPR PARTS_CNT ${PARTS_CNT}+1)
+
+ math(EXPR RELOCATION_INDEX ${RELOCATION_NO}-1)
+ list(GET _RPM_RELOCATION_SCRIPT_PAIRS ${RELOCATION_INDEX} RELOCATION_SCRIPT_PAIR)
+ string(FIND "${RELOCATION_SCRIPT_PAIR}" ":" SPLIT_INDEX)
+
+ math(EXPR SRC_PATH_END ${SPLIT_INDEX}-${SRC_PATH_LEN})
+ string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} ${SRC_PATH_LEN} ${SRC_PATH_END} SYMLINK_)
+
+ math(EXPR POINT_PATH_START ${SPLIT_INDEX}+1+${POINT_PATH_LEN})
+ string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} ${POINT_PATH_START} -1 POINT_)
+
+ string(APPEND SCRIPT_PART " ${INDENT}if [ -z \"$CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}\" ]; then\n")
+ string(APPEND SCRIPT_PART " ${INDENT}ln -s \"$RPM_INSTALL_PREFIX${POINT_INDEX}${POINT_}\" \"$RPM_INSTALL_PREFIX${SYMLINK_INDEX}${SYMLINK_}\"\n")
+ string(APPEND SCRIPT_PART " ${INDENT}CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}=true\n")
+ string(APPEND SCRIPT_PART " ${INDENT}fi\n")
+ endforeach()
+
+ if(NOT "${SYMLINK_INDEX}" EQUAL "${POINT_INDEX}")
+ string(APPEND SCRIPT_PART " fi\n")
+ endif()
+ endif()
+ endforeach()
+
+ # source path relocated
+ if(_RPM_RELOCATION_SCRIPT_${SYMLINK_INDEX}_X)
+ foreach(RELOCATION_NO IN LISTS _RPM_RELOCATION_SCRIPT_${SYMLINK_INDEX}_X)
+ math(EXPR PARTS_CNT ${PARTS_CNT}+1)
+
+ math(EXPR RELOCATION_INDEX ${RELOCATION_NO}-1)
+ list(GET _RPM_RELOCATION_SCRIPT_PAIRS ${RELOCATION_INDEX} RELOCATION_SCRIPT_PAIR)
+ string(FIND "${RELOCATION_SCRIPT_PAIR}" ":" SPLIT_INDEX)
+
+ math(EXPR SRC_PATH_END ${SPLIT_INDEX}-${SRC_PATH_LEN})
+ string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} ${SRC_PATH_LEN} ${SRC_PATH_END} SYMLINK_)
+
+ math(EXPR POINT_PATH_START ${SPLIT_INDEX}+1)
+ string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} ${POINT_PATH_START} -1 POINT_)
+
+ string(APPEND SCRIPT_PART " if [ -z \"$CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}\" ]; then\n")
+ string(APPEND SCRIPT_PART " ln -s \"${POINT_}\" \"$RPM_INSTALL_PREFIX${SYMLINK_INDEX}${SYMLINK_}\"\n")
+ string(APPEND SCRIPT_PART " CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}=true\n")
+ string(APPEND SCRIPT_PART " fi\n")
+ endforeach()
+ endif()
+
+ if(PARTS_CNT)
+ set(SCRIPT "${SCRIPT_PART}")
+ string(APPEND SCRIPT "fi\n")
+ endif()
+ endforeach()
+
+ # point path relocated
+ foreach(POINT_INDEX RANGE ${LAST_INDEX})
+ list(GET SORTED_PACKAGE_PREFIXES ${POINT_INDEX} POINT_PATH)
+ list(FIND PACKAGE_PREFIXES "${POINT_PATH}" POINT_INDEX) # reverse magic
+ string(LENGTH "${POINT_PATH}" POINT_PATH_LEN)
+
+ if(_RPM_RELOCATION_SCRIPT_X_${POINT_INDEX})
+ string(APPEND SCRIPT "if [ \"$RPM_INSTALL_PREFIX${POINT_INDEX}\" != \"${POINT_PATH}\" ]; then\n")
+
+ foreach(RELOCATION_NO IN LISTS _RPM_RELOCATION_SCRIPT_X_${POINT_INDEX})
+ math(EXPR RELOCATION_INDEX ${RELOCATION_NO}-1)
+ list(GET _RPM_RELOCATION_SCRIPT_PAIRS ${RELOCATION_INDEX} RELOCATION_SCRIPT_PAIR)
+ string(FIND "${RELOCATION_SCRIPT_PAIR}" ":" SPLIT_INDEX)
+
+ string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} 0 ${SPLIT_INDEX} SYMLINK_)
+
+ math(EXPR POINT_PATH_START ${SPLIT_INDEX}+1+${POINT_PATH_LEN})
+ string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} ${POINT_PATH_START} -1 POINT_)
+
+ string(APPEND SCRIPT " if [ -z \"$CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}\" ]; then\n")
+ string(APPEND SCRIPT " ln -s \"$RPM_INSTALL_PREFIX${POINT_INDEX}${POINT_}\" \"${SYMLINK_}\"\n")
+ string(APPEND SCRIPT " CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}=true\n")
+ string(APPEND SCRIPT " fi\n")
+ endforeach()
+
+ string(APPEND SCRIPT "fi\n")
+ endif()
+ endforeach()
+
+ # no path relocated
+ if(_RPM_RELOCATION_SCRIPT_X_X)
+ foreach(RELOCATION_NO IN LISTS _RPM_RELOCATION_SCRIPT_X_X)
+ math(EXPR RELOCATION_INDEX ${RELOCATION_NO}-1)
+ list(GET _RPM_RELOCATION_SCRIPT_PAIRS ${RELOCATION_INDEX} RELOCATION_SCRIPT_PAIR)
+ string(FIND "${RELOCATION_SCRIPT_PAIR}" ":" SPLIT_INDEX)
+
+ string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} 0 ${SPLIT_INDEX} SYMLINK_)
+
+ math(EXPR POINT_PATH_START ${SPLIT_INDEX}+1)
+ string(SUBSTRING ${RELOCATION_SCRIPT_PAIR} ${POINT_PATH_START} -1 POINT_)
+
+ string(APPEND SCRIPT "if [ -z \"$CPACK_RPM_RELOCATED_SYMLINK_${RELOCATION_INDEX}\" ]; then\n")
+ string(APPEND SCRIPT " ln -s \"${POINT_}\" \"${SYMLINK_}\"\n")
+ string(APPEND SCRIPT "fi\n")
+ endforeach()
+ endif()
+
+ set(RPM_SYMLINK_POSTINSTALL "${SCRIPT}" PARENT_SCOPE)
+endfunction()
+
+function(cpack_rpm_symlink_add_for_relocation_script PACKAGE_PREFIXES SYMLINK SYMLINK_RELOCATION_PATHS POINT POINT_RELOCATION_PATHS)
+ list(LENGTH SYMLINK_RELOCATION_PATHS SYMLINK_PATHS_COUTN)
+ list(LENGTH POINT_RELOCATION_PATHS POINT_PATHS_COUNT)
+
+ list(APPEND _RPM_RELOCATION_SCRIPT_PAIRS "${SYMLINK}:${POINT}")
+ list(LENGTH _RPM_RELOCATION_SCRIPT_PAIRS PAIR_NO)
+
+ if(SYMLINK_PATHS_COUTN)
+ foreach(SYMLINK_RELOC_PATH IN LISTS SYMLINK_RELOCATION_PATHS)
+ list(FIND PACKAGE_PREFIXES "${SYMLINK_RELOC_PATH}" SYMLINK_INDEX)
+
+ # source path relocated
+ list(APPEND _RPM_RELOCATION_SCRIPT_${SYMLINK_INDEX}_X "${PAIR_NO}")
+ list(APPEND RELOCATION_VARS "_RPM_RELOCATION_SCRIPT_${SYMLINK_INDEX}_X")
+
+ foreach(POINT_RELOC_PATH IN LISTS POINT_RELOCATION_PATHS)
+ list(FIND PACKAGE_PREFIXES "${POINT_RELOC_PATH}" POINT_INDEX)
+
+ # both paths relocated
+ list(APPEND _RPM_RELOCATION_SCRIPT_${SYMLINK_INDEX}_${POINT_INDEX} "${PAIR_NO}")
+ list(APPEND RELOCATION_VARS "_RPM_RELOCATION_SCRIPT_${SYMLINK_INDEX}_${POINT_INDEX}")
+
+ # point path relocated
+ list(APPEND _RPM_RELOCATION_SCRIPT_X_${POINT_INDEX} "${PAIR_NO}")
+ list(APPEND RELOCATION_VARS "_RPM_RELOCATION_SCRIPT_X_${POINT_INDEX}")
+ endforeach()
+ endforeach()
+ elseif(POINT_PATHS_COUNT)
+ foreach(POINT_RELOC_PATH IN LISTS POINT_RELOCATION_PATHS)
+ list(FIND PACKAGE_PREFIXES "${POINT_RELOC_PATH}" POINT_INDEX)
+
+ # point path relocated
+ list(APPEND _RPM_RELOCATION_SCRIPT_X_${POINT_INDEX} "${PAIR_NO}")
+ list(APPEND RELOCATION_VARS "_RPM_RELOCATION_SCRIPT_X_${POINT_INDEX}")
+ endforeach()
+ endif()
+
+ # no path relocated
+ list(APPEND _RPM_RELOCATION_SCRIPT_X_X "${PAIR_NO}")
+ list(APPEND RELOCATION_VARS "_RPM_RELOCATION_SCRIPT_X_X")
+
+ # place variables into parent scope
+ foreach(VAR IN LISTS RELOCATION_VARS)
+ set(${VAR} "${${VAR}}" PARENT_SCOPE)
+ endforeach()
+ set(_RPM_RELOCATION_SCRIPT_PAIRS "${_RPM_RELOCATION_SCRIPT_PAIRS}" PARENT_SCOPE)
+ set(REQUIRES_SYMLINK_RELOCATION_SCRIPT "true" PARENT_SCOPE)
+ set(DIRECTIVE "%ghost " PARENT_SCOPE)
+endfunction()
+
+function(cpack_rpm_prepare_install_files INSTALL_FILES_LIST WDIR PACKAGE_PREFIXES IS_RELOCATABLE)
+ # Prepend directories in ${CPACK_RPM_INSTALL_FILES} with %dir
+ # This is necessary to avoid duplicate files since rpmbuild does
+ # recursion on its own when encountering a pathname which is a directory
+ # which is not flagged as %dir
+ string(STRIP "${INSTALL_FILES_LIST}" INSTALL_FILES_LIST)
+ string(REPLACE "\n" ";" INSTALL_FILES_LIST
+ "${INSTALL_FILES_LIST}")
+ string(REPLACE "\"" "" INSTALL_FILES_LIST
+ "${INSTALL_FILES_LIST}")
+ string(LENGTH "${WDIR}" WDR_LEN_)
+
+ list(SORT INSTALL_FILES_LIST) # make file order consistent on all platforms
+
+ foreach(F IN LISTS INSTALL_FILES_LIST)
+ unset(DIRECTIVE)
+
+ if(IS_SYMLINK "${WDIR}/${F}")
+ if(IS_RELOCATABLE)
+ # check that symlink has relocatable format
+ get_filename_component(SYMLINK_LOCATION_ "${WDIR}/${F}" DIRECTORY)
+ execute_process(COMMAND ls -la "${WDIR}/${F}"
+ WORKING_DIRECTORY "${WDIR}"
+ OUTPUT_VARIABLE SYMLINK_POINT_
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+ string(FIND "${SYMLINK_POINT_}" "->" SYMLINK_POINT_INDEX_ REVERSE)
+ math(EXPR SYMLINK_POINT_INDEX_ ${SYMLINK_POINT_INDEX_}+3)
+ string(LENGTH "${SYMLINK_POINT_}" SYMLINK_POINT_LENGTH_)
+
+ # get destination path
+ string(SUBSTRING "${SYMLINK_POINT_}" ${SYMLINK_POINT_INDEX_} ${SYMLINK_POINT_LENGTH_} SYMLINK_POINT_)
+
+ # check if path is relative or absolute
+ string(SUBSTRING "${SYMLINK_POINT_}" 0 1 SYMLINK_IS_ABSOLUTE_)
+
+ if(${SYMLINK_IS_ABSOLUTE_} STREQUAL "/")
+ # prevent absolute paths from having /../ or /./ section inside of them
+ get_filename_component(SYMLINK_POINT_ "${SYMLINK_POINT_}" ABSOLUTE)
+ else()
+ # handle relative path
+ get_filename_component(SYMLINK_POINT_ "${SYMLINK_LOCATION_}/${SYMLINK_POINT_}" ABSOLUTE)
+ endif()
+
+ # recalculate path length after conversion to canonical form
+ string(LENGTH "${SYMLINK_POINT_}" SYMLINK_POINT_LENGTH_)
+
+ cpack_rpm_exact_regex(IN_SYMLINK_POINT_REGEX "${WDIR}")
+ string(APPEND IN_SYMLINK_POINT_REGEX "/.*")
+ if(SYMLINK_POINT_ MATCHES "${IN_SYMLINK_POINT_REGEX}")
+ # only symlinks that are pointing inside the packaging structure should be checked for relocation
+ string(SUBSTRING "${SYMLINK_POINT_}" ${WDR_LEN_} -1 SYMLINK_POINT_WD_)
+ cpack_rpm_symlink_get_relocation_prefixes("${F}" "${PACKAGE_PREFIXES}" "SYMLINK_RELOCATIONS")
+ cpack_rpm_symlink_get_relocation_prefixes("${SYMLINK_POINT_WD_}" "${PACKAGE_PREFIXES}" "POINT_RELOCATIONS")
+
+ list(LENGTH SYMLINK_RELOCATIONS SYMLINK_RELOCATIONS_COUNT)
+ list(LENGTH POINT_RELOCATIONS POINT_RELOCATIONS_COUNT)
+ else()
+ # location pointed to is outside WDR so it should be treated as a permanent symlink
+ set(SYMLINK_POINT_WD_ "${SYMLINK_POINT_}")
+
+ unset(SYMLINK_RELOCATIONS)
+ unset(POINT_RELOCATIONS)
+ unset(SYMLINK_RELOCATIONS_COUNT)
+ unset(POINT_RELOCATIONS_COUNT)
+
+ message(AUTHOR_WARNING "CPackRPM:Warning: Symbolic link '${F}' points to location that is outside packaging path! Link will possibly not be relocatable.")
+ endif()
+
+ if(SYMLINK_RELOCATIONS_COUNT AND POINT_RELOCATIONS_COUNT)
+ # find matching
+ foreach(SYMLINK_RELOCATION_PREFIX IN LISTS SYMLINK_RELOCATIONS)
+ list(FIND POINT_RELOCATIONS "${SYMLINK_RELOCATION_PREFIX}" FOUND_INDEX)
+ if(NOT ${FOUND_INDEX} EQUAL -1)
+ break()
+ endif()
+ endforeach()
+
+ if(NOT ${FOUND_INDEX} EQUAL -1)
+ # symlinks have the same subpath
+ if(${SYMLINK_RELOCATIONS_COUNT} EQUAL 1 AND ${POINT_RELOCATIONS_COUNT} EQUAL 1)
+ # permanent symlink
+ get_filename_component(SYMLINK_LOCATION_ "${F}" DIRECTORY)
+ file(RELATIVE_PATH FINAL_PATH_ ${SYMLINK_LOCATION_} ${SYMLINK_POINT_WD_})
+ execute_process(COMMAND "${CMAKE_COMMAND}" -E create_symlink "${FINAL_PATH_}" "${WDIR}/${F}")
+ else()
+ # relocation subpaths
+ cpack_rpm_symlink_add_for_relocation_script("${PACKAGE_PREFIXES}" "${F}" "${SYMLINK_RELOCATIONS}"
+ "${SYMLINK_POINT_WD_}" "${POINT_RELOCATIONS}")
+ endif()
+ else()
+ # not on the same relocation path
+ cpack_rpm_symlink_add_for_relocation_script("${PACKAGE_PREFIXES}" "${F}" "${SYMLINK_RELOCATIONS}"
+ "${SYMLINK_POINT_WD_}" "${POINT_RELOCATIONS}")
+ endif()
+ elseif(POINT_RELOCATIONS_COUNT)
+ # point is relocatable
+ cpack_rpm_symlink_add_for_relocation_script("${PACKAGE_PREFIXES}" "${F}" "${SYMLINK_RELOCATIONS}"
+ "${SYMLINK_POINT_WD_}" "${POINT_RELOCATIONS}")
+ else()
+ # is not relocatable or points to non relocatable path - permanent symlink
+ execute_process(COMMAND "${CMAKE_COMMAND}" -E create_symlink "${SYMLINK_POINT_WD_}" "${WDIR}/${F}")
+ endif()
+ endif()
+ elseif(IS_DIRECTORY "${WDIR}/${F}")
+ set(DIRECTIVE "%dir ")
+ endif()
+
+ string(APPEND INSTALL_FILES "${DIRECTIVE}\"${F}\"\n")
+ endforeach()
+
+ if(REQUIRES_SYMLINK_RELOCATION_SCRIPT)
+ cpack_rpm_symlink_create_relocation_script("${PACKAGE_PREFIXES}")
+ endif()
+
+ set(RPM_SYMLINK_POSTINSTALL "${RPM_SYMLINK_POSTINSTALL}" PARENT_SCOPE)
+ set(CPACK_RPM_INSTALL_FILES "${INSTALL_FILES}" PARENT_SCOPE)
+endfunction()
+
+if(CMAKE_BINARY_DIR)
+ message(FATAL_ERROR "CPackRPM.cmake may only be used by CPack internally.")
+endif()
+
+if(NOT UNIX)
+ message(FATAL_ERROR "CPackRPM.cmake may only be used under UNIX.")
+endif()
+
+# We need to check if the binaries were compiled with debug symbols
+# because without them the package will be useless
+function(cpack_rpm_debugsymbol_check INSTALL_FILES WORKING_DIR)
+ if(NOT CPACK_BUILD_SOURCE_DIRS)
+ message(FATAL_ERROR "CPackRPM: CPACK_BUILD_SOURCE_DIRS variable is not set!"
+ " Required for debuginfo packaging. See documentation of"
+ " CPACK_RPM_DEBUGINFO_PACKAGE variable for details.")
+ endif()
+
+ # With objdump we should check the debug symbols
+ find_program(OBJDUMP_EXECUTABLE objdump)
+ if(NOT OBJDUMP_EXECUTABLE)
+ message(FATAL_ERROR "CPackRPM: objdump binary could not be found!"
+ " Required for debuginfo packaging. See documentation of"
+ " CPACK_RPM_DEBUGINFO_PACKAGE variable for details.")
+ endif()
+
+ # With debugedit we prepare source files list
+ find_program(DEBUGEDIT_EXECUTABLE debugedit "/usr/lib/rpm/")
+ if(NOT DEBUGEDIT_EXECUTABLE)
+ message(FATAL_ERROR "CPackRPM: debugedit binary could not be found!"
+ " Required for debuginfo packaging. See documentation of"
+ " CPACK_RPM_DEBUGINFO_PACKAGE variable for details.")
+ endif()
+
+ unset(mkdir_list_)
+ unset(cp_list_)
+ unset(additional_sources_)
+
+ foreach(F IN LISTS INSTALL_FILES)
+ if(IS_DIRECTORY "${WORKING_DIR}/${F}" OR IS_SYMLINK "${WORKING_DIR}/${F}")
+ continue()
+ endif()
+
+ execute_process(COMMAND "${OBJDUMP_EXECUTABLE}" -h ${WORKING_DIR}/${F}
+ WORKING_DIRECTORY "${CPACK_TOPLEVEL_DIRECTORY}"
+ RESULT_VARIABLE OBJDUMP_EXEC_RESULT
+ OUTPUT_VARIABLE OBJDUMP_OUT
+ ERROR_QUIET)
+ # Check if the given file is an executable or not
+ if(NOT OBJDUMP_EXEC_RESULT)
+ string(FIND "${OBJDUMP_OUT}" "debug" FIND_RESULT)
+ if(FIND_RESULT GREATER -1)
+ set(index_ 0)
+ foreach(source_dir_ IN LISTS CPACK_BUILD_SOURCE_DIRS)
+ string(LENGTH "${source_dir_}" source_dir_len_)
+ string(LENGTH "${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}/src_${index_}" debuginfo_dir_len)
+ if(source_dir_len_ LESS debuginfo_dir_len)
+ message(FATAL_ERROR "CPackRPM: source dir path '${source_dir_}' is"
+ " shorter than debuginfo sources dir path '${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}/src_${index_}'!"
+ " Source dir path must be longer than debuginfo sources dir path."
+ " Set CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX variable to a shorter value"
+ " or make source dir path longer."
+ " Required for debuginfo packaging. See documentation of"
+ " CPACK_RPM_DEBUGINFO_PACKAGE variable for details.")
+ endif()
+
+ file(REMOVE "${CPACK_RPM_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}/debugsources_add.list")
+ execute_process(COMMAND "${DEBUGEDIT_EXECUTABLE}" -b "${source_dir_}" -d "${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}/src_${index_}" -i -l "${CPACK_RPM_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}/debugsources_add.list" "${WORKING_DIR}/${F}"
+ RESULT_VARIABLE res_
+ OUTPUT_VARIABLE opt_
+ ERROR_VARIABLE err_
+ )
+
+ file(STRINGS
+ "${CPACK_RPM_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}/debugsources_add.list"
+ sources_)
+ list(REMOVE_DUPLICATES sources_)
+
+ foreach(source_ IN LISTS sources_)
+ if(EXISTS "${source_dir_}/${source_}" AND NOT IS_DIRECTORY "${source_dir_}/${source_}")
+ get_filename_component(path_part_ "${source_}" DIRECTORY)
+ list(APPEND mkdir_list_ "%{buildroot}${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}/src_${index_}/${path_part_}")
+ list(APPEND cp_list_ "cp \"${source_dir_}/${source_}\" \"%{buildroot}${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}/src_${index_}/${path_part_}\"")
+
+ list(APPEND additional_sources_ "${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}/src_${index_}/${source_}")
+ endif()
+ endforeach()
+
+ math(EXPR index_ "${index_} + 1")
+ endforeach()
+ else()
+ message(WARNING "CPackRPM: File: ${F} does not contain debug symbols. They will possibly be missing from debuginfo package!")
+ endif()
+
+ get_file_permissions("${WORKING_DIR}/${F}" permissions_)
+ if(NOT "USER_EXECUTE" IN_LIST permissions_ AND
+ NOT "GROUP_EXECUTE" IN_LIST permissions_ AND
+ NOT "WORLD_EXECUTE" IN_LIST permissions_)
+ if(CPACK_RPM_INSTALL_WITH_EXEC)
+ execute_process(COMMAND chmod a+x ${WORKING_DIR}/${F}
+ RESULT_VARIABLE res_
+ ERROR_VARIABLE err_
+ OUTPUT_QUIET)
+
+ if(res_)
+ message(FATAL_ERROR "CPackRPM: could not apply execute permissions "
+ "requested by CPACK_RPM_INSTALL_WITH_EXEC variable on "
+ "'${WORKING_DIR}/${F}'! Reason: '${err_}'")
+ endif()
+ else()
+ message(AUTHOR_WARNING "CPackRPM: File: ${WORKING_DIR}/${F} does not "
+ "have execute permissions. Debuginfo symbols will not be extracted"
+ "! Missing debuginfo may cause packaging failure. Consider setting "
+ "execute permissions or setting 'CPACK_RPM_INSTALL_WITH_EXEC' "
+ "variable.")
+ endif()
+ endif()
+ endif()
+ endforeach()
+
+ list(LENGTH mkdir_list_ len_)
+ if(len_)
+ list(REMOVE_DUPLICATES mkdir_list_)
+ unset(TMP_RPM_DEBUGINFO_INSTALL)
+ foreach(part_ IN LISTS mkdir_list_)
+ string(APPEND TMP_RPM_DEBUGINFO_INSTALL "mkdir -p \"${part_}\"\n")
+ endforeach()
+ endif()
+
+ list(LENGTH cp_list_ len_)
+ if(len_)
+ list(REMOVE_DUPLICATES cp_list_)
+ foreach(part_ IN LISTS cp_list_)
+ string(APPEND TMP_RPM_DEBUGINFO_INSTALL "${part_}\n")
+ endforeach()
+ endif()
+
+ if(NOT DEFINED CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS)
+ set(CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS /usr /usr/src /usr/src/debug)
+ if(CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS_ADDITION)
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: Adding ${CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS_ADDITION} to builtin omit list.")
+ endif()
+ list(APPEND CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS "${CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS_ADDITION}")
+ endif()
+ endif()
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS= ${CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS}")
+ endif()
+
+ list(LENGTH additional_sources_ len_)
+ if(len_)
+ list(REMOVE_DUPLICATES additional_sources_)
+ unset(additional_sources_all_)
+ foreach(source_ IN LISTS additional_sources_)
+ string(REPLACE "/" ";" split_source_ " ${source_}")
+ list(REMOVE_AT split_source_ 0)
+ unset(tmp_path_)
+ # Now generate all segments of the path
+ foreach(segment_ IN LISTS split_source_)
+ string(APPEND tmp_path_ "/${segment_}")
+ list(APPEND additional_sources_all_ "${tmp_path_}")
+ endforeach()
+ endforeach()
+
+ list(REMOVE_DUPLICATES additional_sources_all_)
+ list(REMOVE_ITEM additional_sources_all_
+ ${CPACK_RPM_DEBUGINFO_EXCLUDE_DIRS})
+
+ unset(TMP_DEBUGINFO_ADDITIONAL_SOURCES)
+ foreach(source_ IN LISTS additional_sources_all_)
+ string(APPEND TMP_DEBUGINFO_ADDITIONAL_SOURCES "${source_}\n")
+ endforeach()
+ endif()
+
+ set(TMP_RPM_DEBUGINFO_INSTALL "${TMP_RPM_DEBUGINFO_INSTALL}" PARENT_SCOPE)
+ set(TMP_DEBUGINFO_ADDITIONAL_SOURCES "${TMP_DEBUGINFO_ADDITIONAL_SOURCES}"
+ PARENT_SCOPE)
+endfunction()
+
+function(cpack_rpm_variable_fallback OUTPUT_VAR_NAME)
+ set(FALLBACK_VAR_NAMES ${ARGN})
+
+ foreach(variable_name IN LISTS FALLBACK_VAR_NAMES)
+ if(${variable_name})
+ set(${OUTPUT_VAR_NAME} "${${variable_name}}" PARENT_SCOPE)
+ break()
+ endif()
+ endforeach()
+endfunction()
+
+function(cpack_rpm_generate_package)
+ # rpmbuild is the basic command for building RPM package
+ # it may be a simple (symbolic) link to rpm command.
+ find_program(RPMBUILD_EXECUTABLE rpmbuild)
+
+ # Check version of the rpmbuild tool this would be easier to
+ # track bugs with users and CPackRPM debug mode.
+ # We may use RPM version in order to check for available version dependent features
+ if(RPMBUILD_EXECUTABLE)
+ execute_process(COMMAND ${RPMBUILD_EXECUTABLE} --version
+ OUTPUT_VARIABLE _TMP_VERSION
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ string(REGEX REPLACE "^.* " ""
+ RPMBUILD_EXECUTABLE_VERSION
+ ${_TMP_VERSION})
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: rpmbuild version is <${RPMBUILD_EXECUTABLE_VERSION}>")
+ endif()
+ endif()
+
+ if(NOT RPMBUILD_EXECUTABLE)
+ message(FATAL_ERROR "RPM package requires rpmbuild executable")
+ endif()
+
+ # Display lsb_release output if DEBUG mode enable
+ # This will help to diagnose problem with CPackRPM
+ # because we will know on which kind of Linux we are
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ find_program(LSB_RELEASE_EXECUTABLE lsb_release)
+ if(LSB_RELEASE_EXECUTABLE)
+ execute_process(COMMAND ${LSB_RELEASE_EXECUTABLE} -a
+ OUTPUT_VARIABLE _TMP_LSB_RELEASE_OUTPUT
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ string(REGEX REPLACE "\n" ", "
+ LSB_RELEASE_OUTPUT
+ ${_TMP_LSB_RELEASE_OUTPUT})
+ else ()
+ set(LSB_RELEASE_OUTPUT "lsb_release not installed/found!")
+ endif()
+ message("CPackRPM:Debug: LSB_RELEASE = ${LSB_RELEASE_OUTPUT}")
+ endif()
+
+ # We may use RPM version in the future in order
+ # to shut down warning about space in buildtree
+ # some recent RPM version should support space in different places.
+ # not checked [yet].
+ if(CPACK_TOPLEVEL_DIRECTORY MATCHES ".* .*")
+ message(FATAL_ERROR "${RPMBUILD_EXECUTABLE} can't handle paths with spaces, use a build directory without spaces for building RPMs.")
+ endif()
+
+ # If rpmbuild is found
+ # we try to discover alien since we may be on non RPM distro like Debian.
+ # In this case we may try to to use more advanced features
+ # like generating RPM directly from DEB using alien.
+ # FIXME feature not finished (yet)
+ find_program(ALIEN_EXECUTABLE alien)
+ if(ALIEN_EXECUTABLE)
+ message(STATUS "alien found, we may be on a Debian based distro.")
+ endif()
+
+ # Are we packaging components ?
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ string(TOUPPER ${CPACK_RPM_PACKAGE_COMPONENT} CPACK_RPM_PACKAGE_COMPONENT_UPPER)
+ endif()
+
+ set(WDIR "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}")
+
+ #
+ # Use user-defined RPM specific variables value
+ # or generate reasonable default value from
+ # CPACK_xxx generic values.
+ # The variables comes from the needed (mandatory or not)
+ # values found in the RPM specification file aka ".spec" file.
+ # The variables which may/should be defined are:
+ #
+
+ # CPACK_RPM_PACKAGE_SUMMARY (mandatory)
+
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ cpack_rpm_variable_fallback("CPACK_RPM_PACKAGE_SUMMARY"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_SUMMARY"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_PACKAGE_SUMMARY")
+ endif()
+
+ if(NOT CPACK_RPM_PACKAGE_SUMMARY)
+ if(CPACK_PACKAGE_DESCRIPTION_SUMMARY)
+ set(CPACK_RPM_PACKAGE_SUMMARY ${CPACK_PACKAGE_DESCRIPTION_SUMMARY})
+ else()
+ # if neither var is defined lets use the name as summary
+ string(TOLOWER "${CPACK_PACKAGE_NAME}" CPACK_RPM_PACKAGE_SUMMARY)
+ endif()
+ endif()
+
+ if(NOT CPACK_RPM_PACKAGE_URL AND CMAKE_PROJECT_HOMEPAGE_URL)
+ set(CPACK_RPM_PACKAGE_URL "${CMAKE_PROJECT_HOMEPAGE_URL}")
+ endif()
+
+ # CPACK_RPM_PACKAGE_NAME (mandatory)
+ if(NOT CPACK_RPM_PACKAGE_NAME)
+ string(TOLOWER "${CPACK_PACKAGE_NAME}" CPACK_RPM_PACKAGE_NAME)
+ endif()
+
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ string(TOUPPER "${CPACK_RPM_MAIN_COMPONENT}"
+ CPACK_RPM_MAIN_COMPONENT_UPPER)
+
+ if(NOT CPACK_RPM_MAIN_COMPONENT_UPPER STREQUAL CPACK_RPM_PACKAGE_COMPONENT_UPPER)
+ string(APPEND CPACK_RPM_PACKAGE_NAME "-${CPACK_RPM_PACKAGE_COMPONENT}")
+
+ cpack_rpm_variable_fallback("CPACK_RPM_PACKAGE_NAME"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_NAME"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_PACKAGE_NAME")
+ endif()
+ endif()
+
+ # CPACK_RPM_PACKAGE_VERSION (mandatory)
+ if(NOT CPACK_RPM_PACKAGE_VERSION)
+ if(NOT CPACK_PACKAGE_VERSION)
+ message(FATAL_ERROR "RPM package requires a package version")
+ endif()
+ set(CPACK_RPM_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION})
+ endif()
+ # Replace '-' in version with '_'
+ # '-' character is an Illegal RPM version character
+ # it is illegal because it is used to separate
+ # RPM "Version" from RPM "Release"
+ string(REPLACE "-" "_" CPACK_RPM_PACKAGE_VERSION ${CPACK_RPM_PACKAGE_VERSION})
+
+ # CPACK_RPM_PACKAGE_ARCHITECTURE (mandatory)
+ if(NOT CPACK_RPM_PACKAGE_ARCHITECTURE)
+ execute_process(COMMAND uname "-m"
+ OUTPUT_VARIABLE CPACK_RPM_PACKAGE_ARCHITECTURE
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ else()
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: using user-specified build arch = ${CPACK_RPM_PACKAGE_ARCHITECTURE}")
+ endif()
+ endif()
+
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ cpack_rpm_variable_fallback("CPACK_RPM_PACKAGE_ARCHITECTURE"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_ARCHITECTURE"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_PACKAGE_ARCHITECTURE")
+
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: using component build arch = ${CPACK_RPM_PACKAGE_ARCHITECTURE}")
+ endif()
+ endif()
+
+ if(${CPACK_RPM_PACKAGE_ARCHITECTURE} STREQUAL "noarch")
+ set(TMP_RPM_BUILDARCH "Buildarch: ${CPACK_RPM_PACKAGE_ARCHITECTURE}")
+ else()
+ set(TMP_RPM_BUILDARCH "")
+ endif()
+
+ # CPACK_RPM_PACKAGE_RELEASE
+ # The RPM release is the numbering of the RPM package ITSELF
+ # this is the version of the PACKAGING and NOT the version
+ # of the CONTENT of the package.
+ # You may well need to generate a new RPM package release
+ # without changing the version of the packaged software.
+ # This is the case when the packaging is buggy (not) the software :=)
+ # If not set, 1 is a good candidate
+ if(NOT CPACK_RPM_PACKAGE_RELEASE)
+ set(CPACK_RPM_PACKAGE_RELEASE "1")
+ endif()
+
+ if(CPACK_RPM_PACKAGE_RELEASE_DIST)
+ string(APPEND CPACK_RPM_PACKAGE_RELEASE "%{?dist}")
+ endif()
+
+ # CPACK_RPM_PACKAGE_LICENSE
+ if(NOT CPACK_RPM_PACKAGE_LICENSE)
+ set(CPACK_RPM_PACKAGE_LICENSE "unknown")
+ endif()
+
+ # CPACK_RPM_PACKAGE_GROUP
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ cpack_rpm_variable_fallback("CPACK_RPM_PACKAGE_GROUP"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_GROUP"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_PACKAGE_GROUP")
+ endif()
+
+ if(NOT CPACK_RPM_PACKAGE_GROUP)
+ set(CPACK_RPM_PACKAGE_GROUP "unknown")
+ endif()
+
+ # CPACK_RPM_PACKAGE_VENDOR
+ if(NOT CPACK_RPM_PACKAGE_VENDOR)
+ if(CPACK_PACKAGE_VENDOR)
+ set(CPACK_RPM_PACKAGE_VENDOR "${CPACK_PACKAGE_VENDOR}")
+ else()
+ set(CPACK_RPM_PACKAGE_VENDOR "unknown")
+ endif()
+ endif()
+
+ # CPACK_RPM_PACKAGE_SOURCE
+ # The name of the source tarball in case we generate a source RPM
+
+ # CPACK_RPM_PACKAGE_DESCRIPTION
+ # The variable content may be either
+ # - explicitly given by the user or
+ # - filled with the content of CPACK_PACKAGE_DESCRIPTION_FILE
+ # if it is defined
+ # - set to a default value
+ #
+
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ cpack_rpm_variable_fallback("CPACK_RPM_PACKAGE_DESCRIPTION"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_DESCRIPTION"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_PACKAGE_DESCRIPTION"
+ "CPACK_COMPONENT_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_DESCRIPTION")
+ endif()
+
+ if(NOT CPACK_RPM_PACKAGE_DESCRIPTION)
+ if(CPACK_PACKAGE_DESCRIPTION_FILE)
+ file(READ ${CPACK_PACKAGE_DESCRIPTION_FILE} CPACK_RPM_PACKAGE_DESCRIPTION)
+ else ()
+ set(CPACK_RPM_PACKAGE_DESCRIPTION "no package description available")
+ endif ()
+ endif ()
+
+ # CPACK_RPM_COMPRESSION_TYPE
+ #
+ if (CPACK_RPM_COMPRESSION_TYPE)
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: User Specified RPM compression type: ${CPACK_RPM_COMPRESSION_TYPE}")
+ endif()
+ if(CPACK_RPM_COMPRESSION_TYPE STREQUAL "lzma")
+ set(CPACK_RPM_COMPRESSION_TYPE_TMP "%define _binary_payload w9.lzdio")
+ endif()
+ if(CPACK_RPM_COMPRESSION_TYPE STREQUAL "xz")
+ set(CPACK_RPM_COMPRESSION_TYPE_TMP "%define _binary_payload w7.xzdio")
+ endif()
+ if(CPACK_RPM_COMPRESSION_TYPE STREQUAL "bzip2")
+ set(CPACK_RPM_COMPRESSION_TYPE_TMP "%define _binary_payload w9.bzdio")
+ endif()
+ if(CPACK_RPM_COMPRESSION_TYPE STREQUAL "gzip")
+ set(CPACK_RPM_COMPRESSION_TYPE_TMP "%define _binary_payload w9.gzdio")
+ endif()
+ else()
+ set(CPACK_RPM_COMPRESSION_TYPE_TMP "")
+ endif()
+
+ if(NOT CPACK_RPM_PACKAGE_SOURCES)
+ if(CPACK_PACKAGE_RELOCATABLE OR CPACK_RPM_PACKAGE_RELOCATABLE)
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: Trying to build a relocatable package")
+ endif()
+ if(CPACK_SET_DESTDIR AND (NOT CPACK_SET_DESTDIR STREQUAL "I_ON"))
+ message("CPackRPM:Warning: CPACK_SET_DESTDIR is set (=${CPACK_SET_DESTDIR}) while requesting a relocatable package (CPACK_RPM_PACKAGE_RELOCATABLE is set): this is not supported, the package won't be relocatable.")
+ set(CPACK_RPM_PACKAGE_RELOCATABLE FALSE)
+ else()
+ set(CPACK_RPM_PACKAGE_PREFIX ${CPACK_PACKAGING_INSTALL_PREFIX}) # kept for back compatibility (provided external RPM spec files)
+ cpack_rpm_prepare_relocation_paths()
+ set(CPACK_RPM_PACKAGE_RELOCATABLE TRUE)
+ endif()
+ endif()
+ else()
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ message(FATAL_ERROR "CPACK_RPM_PACKAGE_SOURCES parameter can not be used"
+ " in combination with CPACK_RPM_PACKAGE_COMPONENT parameter!")
+ endif()
+
+ set(CPACK_RPM_PACKAGE_RELOCATABLE FALSE) # disable relocatable option if building source RPM
+ endif()
+
+ execute_process(
+ COMMAND "${RPMBUILD_EXECUTABLE}" --querytags
+ OUTPUT_VARIABLE RPMBUILD_TAG_LIST
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ string(REPLACE "\n" ";" RPMBUILD_TAG_LIST "${RPMBUILD_TAG_LIST}")
+
+ 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()
+
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ cpack_rpm_variable_fallback("CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_PACKAGE_${_RPM_SPEC_HEADER}"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_PACKAGE_${_RPM_SPEC_HEADER}")
+ endif()
+
+ if(DEFINED CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER})
+ # Prefix can be replaced by Prefixes but the old version still works so we'll ignore it for now
+ # Requires* is a special case because it gets transformed to Requires(pre/post/preun/postun)
+ # Auto* is a special case because the tags can not be queried by querytags rpmbuild flag
+ set(special_case_tags_ PREFIX REQUIRES_PRE REQUIRES_POST REQUIRES_PREUN REQUIRES_POSTUN AUTOPROV AUTOREQ AUTOREQPROV)
+ if(NOT _RPM_SPEC_HEADER IN_LIST RPMBUILD_TAG_LIST AND NOT _RPM_SPEC_HEADER IN_LIST special_case_tags_)
+ message(AUTHOR_WARNING "CPackRPM:Warning: ${_RPM_SPEC_HEADER} not "
+ "supported in provided rpmbuild. Tag will not be used.")
+ continue()
+ endif()
+
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: using CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}")
+ endif()
+
+ set(CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}_TMP ${CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}})
+ endif()
+
+ # Treat the RPM Spec keyword iff it has been properly defined
+ if(DEFINED CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}_TMP)
+ # Transform NAME --> Name e.g. PROVIDES --> Provides
+ # The Upper-case first letter and lowercase tail is the
+ # appropriate value required in the final RPM spec file.
+ string(SUBSTRING ${_RPM_SPEC_HEADER} 1 -1 _PACKAGE_HEADER_TAIL)
+ string(TOLOWER "${_PACKAGE_HEADER_TAIL}" _PACKAGE_HEADER_TAIL)
+ string(SUBSTRING ${_RPM_SPEC_HEADER} 0 1 _PACKAGE_HEADER_NAME)
+ string(APPEND _PACKAGE_HEADER_NAME "${_PACKAGE_HEADER_TAIL}")
+ # The following keywords require parentheses around the "pre" or "post" suffix in the final RPM spec file.
+ set(SCRIPTS_REQUIREMENTS_LIST REQUIRES_PRE REQUIRES_POST REQUIRES_PREUN REQUIRES_POSTUN)
+ list(FIND SCRIPTS_REQUIREMENTS_LIST ${_RPM_SPEC_HEADER} IS_SCRIPTS_REQUIREMENT_FOUND)
+ if(NOT ${IS_SCRIPTS_REQUIREMENT_FOUND} EQUAL -1)
+ string(REPLACE "_" "(" _PACKAGE_HEADER_NAME "${_PACKAGE_HEADER_NAME}")
+ string(APPEND _PACKAGE_HEADER_NAME ")")
+ endif()
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: User defined ${_PACKAGE_HEADER_NAME}:\n ${CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}_TMP}")
+ endif()
+ set(TMP_RPM_${_RPM_SPEC_HEADER} "${_PACKAGE_HEADER_NAME}: ${CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}_TMP}")
+ unset(CPACK_RPM_PACKAGE_${_RPM_SPEC_HEADER}_TMP)
+ endif()
+ endforeach()
+
+ # CPACK_RPM_SPEC_INSTALL_POST
+ # May be used to define a RPM post intallation script
+ # for example setting it to "/bin/true" may prevent
+ # rpmbuild from stripping binaries.
+ if(CPACK_RPM_SPEC_INSTALL_POST)
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: User defined CPACK_RPM_SPEC_INSTALL_POST = ${CPACK_RPM_SPEC_INSTALL_POST}")
+ endif()
+ set(TMP_RPM_SPEC_INSTALL_POST "%define __spec_install_post ${CPACK_RPM_SPEC_INSTALL_POST}")
+ endif()
+
+ # CPACK_RPM_POST_INSTALL_SCRIPT_FILE (or CPACK_RPM_<COMPONENT>_POST_INSTALL_SCRIPT_FILE)
+ # CPACK_RPM_POST_UNINSTALL_SCRIPT_FILE (or CPACK_RPM_<COMPONENT>_POST_UNINSTALL_SCRIPT_FILE)
+ # May be used to embed a post (un)installation script in the spec file.
+ # The referred script file(s) will be read and directly
+ # put after the %post or %postun section
+ # ----------------------------------------------------------------
+ # CPACK_RPM_PRE_INSTALL_SCRIPT_FILE (or CPACK_RPM_<COMPONENT>_PRE_INSTALL_SCRIPT_FILE)
+ # CPACK_RPM_PRE_UNINSTALL_SCRIPT_FILE (or CPACK_RPM_<COMPONENT>_PRE_UNINSTALL_SCRIPT_FILE)
+ # May be used to embed a pre (un)installation script in the spec file.
+ # The referred script file(s) will be read and directly
+ # put after the %pre or %preun section
+ foreach(RPM_SCRIPT_FILE_TYPE_ "INSTALL" "UNINSTALL")
+ foreach(RPM_SCRIPT_FILE_TIME_ "PRE" "POST")
+ set("CPACK_RPM_${RPM_SCRIPT_FILE_TIME_}_${RPM_SCRIPT_FILE_TYPE_}_READ_FILE"
+ "${CPACK_RPM_${RPM_SCRIPT_FILE_TIME_}_${RPM_SCRIPT_FILE_TYPE_}_SCRIPT_FILE}")
+
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ cpack_rpm_variable_fallback("CPACK_RPM_${RPM_SCRIPT_FILE_TIME_}_${RPM_SCRIPT_FILE_TYPE_}_READ_FILE"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_${RPM_SCRIPT_FILE_TIME_}_${RPM_SCRIPT_FILE_TYPE_}_SCRIPT_FILE"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_${RPM_SCRIPT_FILE_TIME_}_${RPM_SCRIPT_FILE_TYPE_}_SCRIPT_FILE")
+ endif()
+
+ # Handle file if it has been specified
+ if(CPACK_RPM_${RPM_SCRIPT_FILE_TIME_}_${RPM_SCRIPT_FILE_TYPE_}_READ_FILE)
+ if(EXISTS ${CPACK_RPM_${RPM_SCRIPT_FILE_TIME_}_${RPM_SCRIPT_FILE_TYPE_}_READ_FILE})
+ file(READ ${CPACK_RPM_${RPM_SCRIPT_FILE_TIME_}_${RPM_SCRIPT_FILE_TYPE_}_READ_FILE}
+ "CPACK_RPM_SPEC_${RPM_SCRIPT_FILE_TIME_}${RPM_SCRIPT_FILE_TYPE_}")
+ else()
+ message("CPackRPM:Warning: CPACK_RPM_${RPM_SCRIPT_FILE_TIME_}_${RPM_SCRIPT_FILE_TYPE_}_SCRIPT_FILE <${CPACK_RPM_${RPM_SCRIPT_FILE_TIME_}_${RPM_SCRIPT_FILE_TYPE_}_READ_FILE}> does not exists - ignoring")
+ endif()
+ else()
+ # reset SPEC var value if no file has been specified
+ # (either globally or component-wise)
+ set("CPACK_RPM_SPEC_${RPM_SCRIPT_FILE_TIME_}${RPM_SCRIPT_FILE_TYPE_}" "")
+ endif()
+ endforeach()
+ endforeach()
+
+ # CPACK_RPM_CHANGELOG_FILE
+ # May be used to embed a changelog in the spec file.
+ # The referred file will be read and directly put after the %changelog section
+ if(CPACK_RPM_CHANGELOG_FILE)
+ if(EXISTS ${CPACK_RPM_CHANGELOG_FILE})
+ file(READ ${CPACK_RPM_CHANGELOG_FILE} CPACK_RPM_SPEC_CHANGELOG)
+ else()
+ message(SEND_ERROR "CPackRPM:Warning: CPACK_RPM_CHANGELOG_FILE <${CPACK_RPM_CHANGELOG_FILE}> does not exists - ignoring")
+ endif()
+ else()
+ set(CPACK_RPM_SPEC_CHANGELOG "* Sun Jul 4 2010 Eric Noulard <eric.noulard@gmail.com> - ${CPACK_RPM_PACKAGE_VERSION}-${CPACK_RPM_PACKAGE_RELEASE}\n Generated by CPack RPM (no Changelog file were provided)")
+ endif()
+
+ # CPACK_RPM_SPEC_MORE_DEFINE
+ # This is a generated spec rpm file spaceholder
+ if(CPACK_RPM_SPEC_MORE_DEFINE)
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: User defined more define spec line specified:\n ${CPACK_RPM_SPEC_MORE_DEFINE}")
+ endif()
+ endif()
+
+ # Now we may create the RPM build tree structure
+ set(CPACK_RPM_ROOTDIR "${CPACK_TOPLEVEL_DIRECTORY}")
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: Using CPACK_RPM_ROOTDIR=${CPACK_RPM_ROOTDIR}")
+ endif()
+ # Prepare RPM build tree
+ file(MAKE_DIRECTORY ${CPACK_RPM_ROOTDIR})
+ file(MAKE_DIRECTORY ${CPACK_RPM_ROOTDIR}/tmp)
+ file(MAKE_DIRECTORY ${CPACK_RPM_ROOTDIR}/BUILD)
+ file(MAKE_DIRECTORY ${CPACK_RPM_ROOTDIR}/RPMS)
+ file(MAKE_DIRECTORY ${CPACK_RPM_ROOTDIR}/SOURCES)
+ file(MAKE_DIRECTORY ${CPACK_RPM_ROOTDIR}/SPECS)
+ file(MAKE_DIRECTORY ${CPACK_RPM_ROOTDIR}/SRPMS)
+
+ # it seems rpmbuild can't handle spaces in the path
+ # neither escaping (as below) nor putting quotes around the path seem to help
+ #string(REGEX REPLACE " " "\\\\ " CPACK_RPM_DIRECTORY "${CPACK_TOPLEVEL_DIRECTORY}")
+ set(CPACK_RPM_DIRECTORY "${CPACK_TOPLEVEL_DIRECTORY}")
+
+ cpack_rpm_prepare_content_list()
+
+ # In component case, put CPACK_ABSOLUTE_DESTINATION_FILES_<COMPONENT>
+ # into CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL
+ # otherwise, put CPACK_ABSOLUTE_DESTINATION_FILES
+ # This must be done BEFORE the CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL handling
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ if(CPACK_ABSOLUTE_DESTINATION_FILES)
+ cpack_rpm_variable_fallback("COMPONENT_FILES_TAG"
+ "CPACK_ABSOLUTE_DESTINATION_FILES_${CPACK_RPM_PACKAGE_COMPONENT}"
+ "CPACK_ABSOLUTE_DESTINATION_FILES_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}")
+ set(CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL "${${COMPONENT_FILES_TAG}}")
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: Handling Absolute Destination Files: <${CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL}>")
+ message("CPackRPM:Debug: in component = ${CPACK_RPM_PACKAGE_COMPONENT}")
+ endif()
+ endif()
+ else()
+ if(CPACK_ABSOLUTE_DESTINATION_FILES)
+ set(CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL "${CPACK_ABSOLUTE_DESTINATION_FILES}")
+ endif()
+ endif()
+
+ # In component case, set CPACK_RPM_USER_FILELIST_INTERNAL with CPACK_RPM_<COMPONENT>_USER_FILELIST.
+ set(CPACK_RPM_USER_FILELIST_INTERNAL "")
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ cpack_rpm_variable_fallback("CPACK_RPM_USER_FILELIST_INTERNAL"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_USER_FILELIST"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_USER_FILELIST")
+
+ if(CPACK_RPM_PACKAGE_DEBUG AND CPACK_RPM_USER_FILELIST_INTERNAL)
+ message("CPackRPM:Debug: Handling User Filelist: <${CPACK_RPM_USER_FILELIST_INTERNAL}>")
+ message("CPackRPM:Debug: in component = ${CPACK_RPM_PACKAGE_COMPONENT}")
+ endif()
+ elseif(CPACK_RPM_USER_FILELIST)
+ set(CPACK_RPM_USER_FILELIST_INTERNAL "${CPACK_RPM_USER_FILELIST}")
+ endif()
+
+ # Handle user specified file line list in CPACK_RPM_USER_FILELIST_INTERNAL
+ # Remove those files from CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL
+ # or CPACK_RPM_INSTALL_FILES,
+ # hence it must be done before these auto-generated lists are processed.
+ if(CPACK_RPM_USER_FILELIST_INTERNAL)
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: Handling User Filelist: <${CPACK_RPM_USER_FILELIST_INTERNAL}>")
+ endif()
+
+ # Create CMake list from CPACK_RPM_INSTALL_FILES
+ string(STRIP "${CPACK_RPM_INSTALL_FILES}" CPACK_RPM_INSTALL_FILES_LIST)
+ string(REPLACE "\n" ";" CPACK_RPM_INSTALL_FILES_LIST
+ "${CPACK_RPM_INSTALL_FILES_LIST}")
+ string(REPLACE "\"" "" CPACK_RPM_INSTALL_FILES_LIST
+ "${CPACK_RPM_INSTALL_FILES_LIST}")
+
+ set(CPACK_RPM_USER_INSTALL_FILES "")
+ foreach(F IN LISTS CPACK_RPM_USER_FILELIST_INTERNAL)
+ string(REGEX REPLACE "%[A-Za-z]+(\\([^()]*\\))? " "" F_PATH ${F})
+ string(REGEX MATCH "(%[A-Za-z]+(\\([^()]*\\))? )*" F_PREFIX ${F})
+ string(STRIP ${F_PREFIX} F_PREFIX)
+
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: F_PREFIX=<${F_PREFIX}>, F_PATH=<${F_PATH}>")
+ endif()
+ if(F_PREFIX)
+ string(APPEND F_PREFIX " ")
+ endif()
+ # Rebuild the user list file
+ string(APPEND CPACK_RPM_USER_INSTALL_FILES "${F_PREFIX}\"${F_PATH}\"\n")
+
+ # Remove from CPACK_RPM_INSTALL_FILES and CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL
+ list(REMOVE_ITEM CPACK_RPM_INSTALL_FILES_LIST ${F_PATH})
+ # ABSOLUTE destination files list may not exists at all
+ if (CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL)
+ list(REMOVE_ITEM CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL ${F_PATH})
+ endif()
+ endforeach()
+
+ # Rebuild CPACK_RPM_INSTALL_FILES
+ set(CPACK_RPM_INSTALL_FILES "")
+ foreach(F IN LISTS CPACK_RPM_INSTALL_FILES_LIST)
+ string(APPEND CPACK_RPM_INSTALL_FILES "\"${F}\"\n")
+ endforeach()
+ else()
+ set(CPACK_RPM_USER_INSTALL_FILES "")
+ endif()
+
+ if (CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL)
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: Handling Absolute Destination Files: ${CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL}")
+ endif()
+ # Remove trailing space
+ string(STRIP "${CPACK_RPM_INSTALL_FILES}" CPACK_RPM_INSTALL_FILES_LIST)
+ # Transform endline separated - string into CMake List
+ string(REPLACE "\n" ";" CPACK_RPM_INSTALL_FILES_LIST "${CPACK_RPM_INSTALL_FILES_LIST}")
+ # Remove unnecessary quotes
+ string(REPLACE "\"" "" CPACK_RPM_INSTALL_FILES_LIST "${CPACK_RPM_INSTALL_FILES_LIST}")
+ # Remove ABSOLUTE install file from INSTALL FILE LIST
+ list(REMOVE_ITEM CPACK_RPM_INSTALL_FILES_LIST ${CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL})
+ # Rebuild INSTALL_FILES
+ set(CPACK_RPM_INSTALL_FILES "")
+ foreach(F IN LISTS CPACK_RPM_INSTALL_FILES_LIST)
+ string(APPEND CPACK_RPM_INSTALL_FILES "\"${F}\"\n")
+ endforeach()
+ # Build ABSOLUTE_INSTALL_FILES
+ set(CPACK_RPM_ABSOLUTE_INSTALL_FILES "")
+ foreach(F IN LISTS CPACK_ABSOLUTE_DESTINATION_FILES_INTERNAL)
+ string(APPEND CPACK_RPM_ABSOLUTE_INSTALL_FILES "%config \"${F}\"\n")
+ endforeach()
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: CPACK_RPM_ABSOLUTE_INSTALL_FILES=${CPACK_RPM_ABSOLUTE_INSTALL_FILES}")
+ message("CPackRPM:Debug: CPACK_RPM_INSTALL_FILES=${CPACK_RPM_INSTALL_FILES}")
+ endif()
+ else()
+ # reset vars in order to avoid leakage of value(s) from one component to another
+ set(CPACK_RPM_ABSOLUTE_INSTALL_FILES "")
+ endif()
+
+ cpack_rpm_variable_fallback("CPACK_RPM_DEBUGINFO_PACKAGE"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_DEBUGINFO_PACKAGE"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_DEBUGINFO_PACKAGE"
+ "CPACK_RPM_DEBUGINFO_PACKAGE")
+ if(CPACK_RPM_DEBUGINFO_PACKAGE OR (CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE AND NOT GENERATE_SPEC_PARTS))
+ cpack_rpm_variable_fallback("CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_BUILD_SOURCE_DIRS_PREFIX"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_BUILD_SOURCE_DIRS_PREFIX"
+ "CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX")
+ if(NOT CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX)
+ set(CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX "/usr/src/debug/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}")
+ endif()
+
+ # handle cases where path contains extra slashes (e.g. /a//b/ instead of
+ # /a/b)
+ get_filename_component(CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX
+ "${CPACK_RPM_BUILD_SOURCE_DIRS_PREFIX}" ABSOLUTE)
+
+ if(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE AND GENERATE_SPEC_PARTS)
+ file(WRITE "${CPACK_RPM_ROOTDIR}/SPECS/${CPACK_RPM_PACKAGE_COMPONENT}.files"
+ "${CPACK_RPM_INSTALL_FILES}")
+ else()
+ if(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE AND CPACK_RPM_PACKAGE_COMPONENT)
+ # this part is only required by components packaging - with monolithic
+ # packages we can be certain that there are no other components present
+ # so CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE is a noop
+ if(CPACK_RPM_DEBUGINFO_PACKAGE)
+ # only add current package files to debuginfo list if debuginfo
+ # generation is enabled for current package
+ string(STRIP "${CPACK_RPM_INSTALL_FILES}" install_files_)
+ string(REPLACE "\n" ";" install_files_ "${install_files_}")
+ string(REPLACE "\"" "" install_files_ "${install_files_}")
+ else()
+ unset(install_files_)
+ endif()
+
+ file(GLOB files_ "${CPACK_RPM_DIRECTORY}/SPECS/*.files")
+
+ foreach(f_ IN LISTS files_)
+ file(READ "${f_}" tmp_)
+ string(APPEND install_files_ ";${tmp_}")
+ endforeach()
+
+ # if there were other components/groups so we need to move files from them
+ # to current component otherwise those files won't be found
+ file(GLOB components_ LIST_DIRECTORIES true RELATIVE
+ "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}"
+ "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}/*")
+ foreach(component_ IN LISTS components_)
+ string(TOUPPER "${component_}" component_dir_upper_)
+ if(component_dir_upper_ STREQUAL CPACK_RPM_PACKAGE_COMPONENT_UPPER)
+ # skip current component
+ continue()
+ endif()
+
+ file(GLOB_RECURSE files_for_move_ LIST_DIRECTORIES false RELATIVE
+ "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}/${component_}"
+ "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}/${component_}/*")
+
+ foreach(f_ IN LISTS files_for_move_)
+ get_filename_component(dir_path_ "${f_}" DIRECTORY)
+ set(src_file_
+ "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}/${component_}/${f_}")
+
+ # check that we are not overriding an existing file that doesn't
+ # match the file that we want to copy
+ if(EXISTS "${src_file_}" AND EXISTS "${WDIR}/${f_}")
+ execute_process(
+ COMMAND ${CMAKE_COMMAND} -E compare_files "${src_file_}" "${WDIR}/${f_}"
+ RESULT_VARIABLE res_
+ )
+ if(res_)
+ message(FATAL_ERROR "CPackRPM:Error: File on path '${WDIR}/${f_}'"
+ " already exists but is a different than the one in component"
+ " '${component_}'! Packages will not be generated.")
+ endif()
+ endif()
+
+ file(MAKE_DIRECTORY "${WDIR}/${dir_path_}")
+ file(RENAME "${src_file_}"
+ "${WDIR}/${f_}")
+ endforeach()
+ endforeach()
+
+ cpack_rpm_debugsymbol_check("${install_files_}" "${WDIR}")
+ else()
+ string(STRIP "${CPACK_RPM_INSTALL_FILES}" install_files_)
+ string(REPLACE "\n" ";" install_files_ "${install_files_}")
+ string(REPLACE "\"" "" install_files_ "${install_files_}")
+
+ cpack_rpm_debugsymbol_check("${install_files_}" "${WDIR}")
+ endif()
+
+ if(TMP_DEBUGINFO_ADDITIONAL_SOURCES)
+ set(TMP_RPM_DEBUGINFO "
+# Modified version of %%debug_package macro
+# defined in /usr/lib/rpm/macros as that one
+# can't handle injection of extra source files.
+%ifnarch noarch
+%global __debug_package 1
+%package debuginfo
+Summary: Debug information for package %{name}
+Group: Development/Debug
+AutoReqProv: 0
+%description debuginfo
+This package provides debug information for package %{name}.
+Debug information is useful when developing applications that use this
+package or when debugging this package.
+%files debuginfo -f debugfiles.list
+%defattr(-,root,root)
+${TMP_DEBUGINFO_ADDITIONAL_SOURCES}
+%endif
+")
+ elseif(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE)
+ message(AUTHOR_WARNING "CPackRPM:Warning: debuginfo package was requested"
+ " but will not be generated as no source files were found!")
+ else()
+ message(AUTHOR_WARNING "CPackRPM:Warning: debuginfo package was requested"
+ " but will not be generated as no source files were found! Component: '"
+ "${CPACK_RPM_PACKAGE_COMPONENT}'.")
+ endif()
+ endif()
+ endif()
+
+ # Prepare install files
+ cpack_rpm_prepare_install_files(
+ "${CPACK_RPM_INSTALL_FILES}"
+ "${WDIR}"
+ "${RPM_USED_PACKAGE_PREFIXES}"
+ "${CPACK_RPM_PACKAGE_RELOCATABLE}"
+ )
+
+ # set default user and group
+ foreach(_PERM_TYPE "USER" "GROUP")
+ if(CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_DEFAULT_${_PERM_TYPE})
+ set(TMP_DEFAULT_${_PERM_TYPE} "${CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_DEFAULT_${_PERM_TYPE}}")
+ elseif(CPACK_RPM_DEFAULT_${_PERM_TYPE})
+ set(TMP_DEFAULT_${_PERM_TYPE} "${CPACK_RPM_DEFAULT_${_PERM_TYPE}}")
+ else()
+ set(TMP_DEFAULT_${_PERM_TYPE} "root")
+ endif()
+ endforeach()
+
+ # set default file and dir permissions
+ foreach(_PERM_TYPE "FILE" "DIR")
+ if(CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_DEFAULT_${_PERM_TYPE}_PERMISSIONS)
+ get_unix_permissions_octal_notation("CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_DEFAULT_${_PERM_TYPE}_PERMISSIONS" "TMP_DEFAULT_${_PERM_TYPE}_PERMISSIONS")
+ set(_PERMISSIONS_VAR "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_DEFAULT_${_PERM_TYPE}_PERMISSIONS")
+ elseif(CPACK_RPM_DEFAULT_${_PERM_TYPE}_PERMISSIONS)
+ get_unix_permissions_octal_notation("CPACK_RPM_DEFAULT_${_PERM_TYPE}_PERMISSIONS" "TMP_DEFAULT_${_PERM_TYPE}_PERMISSIONS")
+ set(_PERMISSIONS_VAR "CPACK_RPM_DEFAULT_${_PERM_TYPE}_PERMISSIONS")
+ else()
+ set(TMP_DEFAULT_${_PERM_TYPE}_PERMISSIONS "-")
+ endif()
+ endforeach()
+
+ # The name of the final spec file to be used by rpmbuild
+ set(CPACK_RPM_BINARY_SPECFILE "${CPACK_RPM_ROOTDIR}/SPECS/${CPACK_RPM_PACKAGE_NAME}.spec")
+
+ # Print out some debug information if we were asked for that
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: CPACK_TOPLEVEL_DIRECTORY = ${CPACK_TOPLEVEL_DIRECTORY}")
+ message("CPackRPM:Debug: CPACK_TOPLEVEL_TAG = ${CPACK_TOPLEVEL_TAG}")
+ message("CPackRPM:Debug: CPACK_TEMPORARY_DIRECTORY = ${CPACK_TEMPORARY_DIRECTORY}")
+ message("CPackRPM:Debug: CPACK_OUTPUT_FILE_NAME = ${CPACK_OUTPUT_FILE_NAME}")
+ message("CPackRPM:Debug: CPACK_OUTPUT_FILE_PATH = ${CPACK_OUTPUT_FILE_PATH}")
+ message("CPackRPM:Debug: CPACK_PACKAGE_FILE_NAME = ${CPACK_PACKAGE_FILE_NAME}")
+ message("CPackRPM:Debug: CPACK_RPM_BINARY_SPECFILE = ${CPACK_RPM_BINARY_SPECFILE}")
+ message("CPackRPM:Debug: CPACK_PACKAGE_INSTALL_DIRECTORY = ${CPACK_PACKAGE_INSTALL_DIRECTORY}")
+ message("CPackRPM:Debug: CPACK_TEMPORARY_PACKAGE_FILE_NAME = ${CPACK_TEMPORARY_PACKAGE_FILE_NAME}")
+ endif()
+
+ #
+ # USER generated/provided spec file handling.
+ #
+
+ # We can have a component specific spec file.
+ if(CPACK_RPM_PACKAGE_COMPONENT)
+ cpack_rpm_variable_fallback("CPACK_RPM_USER_BINARY_SPECFILE"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_USER_BINARY_SPECFILE"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_USER_BINARY_SPECFILE")
+ endif()
+
+ cpack_rpm_variable_fallback("CPACK_RPM_FILE_NAME"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_FILE_NAME"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_FILE_NAME"
+ "CPACK_RPM_FILE_NAME")
+ if(NOT CPACK_RPM_FILE_NAME STREQUAL "RPM-DEFAULT")
+ if(CPACK_RPM_FILE_NAME)
+ if(NOT CPACK_RPM_FILE_NAME MATCHES ".*\\.rpm")
+ message(FATAL_ERROR "'${CPACK_RPM_FILE_NAME}' is not a valid RPM package file name as it must end with '.rpm'!")
+ endif()
+ else()
+ # old file name format for back compatibility
+ string(TOUPPER "${CPACK_RPM_MAIN_COMPONENT}"
+ CPACK_RPM_MAIN_COMPONENT_UPPER)
+
+ if(CPACK_RPM_MAIN_COMPONENT_UPPER STREQUAL CPACK_RPM_PACKAGE_COMPONENT_UPPER)
+ # this is the main component so ignore the component filename part
+ set(CPACK_RPM_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}.rpm")
+ else()
+ set(CPACK_RPM_FILE_NAME "${CPACK_OUTPUT_FILE_NAME}")
+ endif()
+ endif()
+ # else example:
+ #set(CPACK_RPM_FILE_NAME "${CPACK_RPM_PACKAGE_NAME}-${CPACK_RPM_PACKAGE_VERSION}-${CPACK_RPM_PACKAGE_RELEASE}-${CPACK_RPM_PACKAGE_ARCHITECTURE}.rpm")
+
+ if(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE AND GENERATE_SPEC_PARTS)
+ string(TOLOWER "${CPACK_RPM_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}.*\\.rpm" expected_filename_)
+
+ file(WRITE "${CPACK_RPM_ROOTDIR}/SPECS/${CPACK_RPM_PACKAGE_COMPONENT}.rpm_name"
+ "${expected_filename_};${CPACK_RPM_FILE_NAME}")
+ elseif(NOT CPACK_RPM_DEBUGINFO_PACKAGE)
+ set(FILE_NAME_DEFINE "%define _rpmfilename ${CPACK_RPM_FILE_NAME}")
+ endif()
+ endif()
+
+ if(CPACK_RPM_PACKAGE_SOURCES) # source rpm
+ set(archive_name_ "${CPACK_RPM_PACKAGE_NAME}-${CPACK_RPM_PACKAGE_VERSION}")
+
+ execute_process(
+ COMMAND ${CMAKE_COMMAND} -E tar "cfvz" "${CPACK_RPM_DIRECTORY}/SOURCES/${archive_name_}.tar.gz" "${CPACK_PACKAGE_FILE_NAME}"
+ WORKING_DIRECTORY ${CPACK_RPM_DIRECTORY}
+ )
+ set(TMP_RPM_SOURCE "Source: ${archive_name_}.tar.gz")
+
+ if(CPACK_RPM_BUILDREQUIRES)
+ set(TMP_RPM_BUILD_REQUIRES "BuildRequires: ${CPACK_RPM_BUILDREQUIRES}")
+ endif()
+
+ # Disable debuginfo packages - srpm generates invalid packages due to
+ # releasing control to cpack to generate binary packages.
+ # Note however that this doesn't prevent cpack to generate debuginfo
+ # packages when run from srpm with --rebuild.
+ set(TMP_RPM_DISABLE_DEBUGINFO "%define debug_package %{nil}")
+
+ if(NOT CPACK_RPM_SOURCE_PKG_PACKAGING_INSTALL_PREFIX)
+ set(CPACK_RPM_SOURCE_PKG_PACKAGING_INSTALL_PREFIX "/")
+ endif()
+
+ set(TMP_RPM_BUILD
+ "
+%build
+mkdir cpack_rpm_build_dir
+cd cpack_rpm_build_dir
+'${CMAKE_COMMAND}' ${CPACK_RPM_SOURCE_PKG_BUILD_PARAMS} -DCPACK_PACKAGING_INSTALL_PREFIX=${CPACK_RPM_SOURCE_PKG_PACKAGING_INSTALL_PREFIX} ../${CPACK_PACKAGE_FILE_NAME}
+make %{?_smp_mflags}" # %{?_smp_mflags} -> -j option
+ )
+ set(TMP_RPM_INSTALL
+ "
+cd cpack_rpm_build_dir
+cpack -G RPM
+mv *.rpm %_rpmdir"
+ )
+ set(TMP_RPM_PREP "%setup -c")
+
+ set(RPMBUILD_FLAGS "-bs")
+
+ file(WRITE ${CPACK_RPM_BINARY_SPECFILE}.in
+ "# 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\@
+Version: \@CPACK_RPM_PACKAGE_VERSION\@
+Release: \@CPACK_RPM_PACKAGE_RELEASE\@
+License: \@CPACK_RPM_PACKAGE_LICENSE\@
+Group: \@CPACK_RPM_PACKAGE_GROUP\@
+Vendor: \@CPACK_RPM_PACKAGE_VENDOR\@
+
+\@TMP_RPM_SOURCE\@
+\@TMP_RPM_BUILD_REQUIRES\@
+\@TMP_RPM_BUILDARCH\@
+\@TMP_RPM_PREFIXES\@
+
+\@TMP_RPM_DISABLE_DEBUGINFO\@
+
+%define _rpmdir %_topdir/RPMS
+%define _srcrpmdir %_topdir/SRPMS
+\@FILE_NAME_DEFINE\@
+%define _unpackaged_files_terminate_build 0
+\@TMP_RPM_SPEC_INSTALL_POST\@
+\@CPACK_RPM_SPEC_MORE_DEFINE\@
+\@CPACK_RPM_COMPRESSION_TYPE_TMP\@
+
+%description
+\@CPACK_RPM_PACKAGE_DESCRIPTION\@
+
+# This is a shortcutted spec file generated by CMake RPM generator
+# we skip _install step because CPack does that for us.
+# We do only save CPack installed tree in _prepr
+# and then restore it in build.
+%prep
+\@TMP_RPM_PREP\@
+
+\@TMP_RPM_BUILD\@
+
+#p build
+
+%install
+\@TMP_RPM_INSTALL\@
+
+%clean
+
+%changelog
+\@CPACK_RPM_SPEC_CHANGELOG\@
+"
+ )
+
+ elseif(GENERATE_SPEC_PARTS) # binary rpm with single debuginfo package
+ file(WRITE ${CPACK_RPM_BINARY_SPECFILE}.in
+ "# -*- rpm-spec -*-
+%package -n \@CPACK_RPM_PACKAGE_NAME\@
+Summary: \@CPACK_RPM_PACKAGE_SUMMARY\@
+Version: \@CPACK_RPM_PACKAGE_VERSION\@
+Release: \@CPACK_RPM_PACKAGE_RELEASE\@
+License: \@CPACK_RPM_PACKAGE_LICENSE\@
+Group: \@CPACK_RPM_PACKAGE_GROUP\@
+Vendor: \@CPACK_RPM_PACKAGE_VENDOR\@
+
+\@TMP_RPM_URL\@
+\@TMP_RPM_REQUIRES\@
+\@TMP_RPM_REQUIRES_PRE\@
+\@TMP_RPM_REQUIRES_POST\@
+\@TMP_RPM_REQUIRES_PREUN\@
+\@TMP_RPM_REQUIRES_POSTUN\@
+\@TMP_RPM_PROVIDES\@
+\@TMP_RPM_OBSOLETES\@
+\@TMP_RPM_CONFLICTS\@
+\@TMP_RPM_SUGGESTS\@
+\@TMP_RPM_AUTOPROV\@
+\@TMP_RPM_AUTOREQ\@
+\@TMP_RPM_AUTOREQPROV\@
+\@TMP_RPM_BUILDARCH\@
+\@TMP_RPM_PREFIXES\@
+\@TMP_RPM_EPOCH\@
+
+%description -n \@CPACK_RPM_PACKAGE_NAME\@
+\@CPACK_RPM_PACKAGE_DESCRIPTION\@
+
+%files -n \@CPACK_RPM_PACKAGE_NAME\@
+%defattr(\@TMP_DEFAULT_FILE_PERMISSIONS\@,\@TMP_DEFAULT_USER\@,\@TMP_DEFAULT_GROUP\@,\@TMP_DEFAULT_DIR_PERMISSIONS\@)
+\@CPACK_RPM_INSTALL_FILES\@
+\@CPACK_RPM_ABSOLUTE_INSTALL_FILES\@
+\@CPACK_RPM_USER_INSTALL_FILES\@
+"
+ )
+
+ else() # binary rpm
+ if(CPACK_RPM_DEBUGINFO_SINGLE_PACKAGE)
+ # find generated spec file and take its name
+ file(GLOB spec_files_ "${CPACK_RPM_DIRECTORY}/SPECS/*.spec")
+
+ foreach(f_ IN LISTS spec_files_)
+ file(READ "${f_}" tmp_)
+ string(APPEND TMP_OTHER_COMPONENTS "\n${tmp_}\n")
+ endforeach()
+ endif()
+
+ # We should generate a USER spec file template:
+ # - either because the user asked for it : CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE
+ # - or the user did not provide one : NOT CPACK_RPM_USER_BINARY_SPECFILE
+ set(RPMBUILD_FLAGS "-bb")
+ if(CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE OR NOT CPACK_RPM_USER_BINARY_SPECFILE)
+
+ file(WRITE ${CPACK_RPM_BINARY_SPECFILE}.in
+ "# 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\@
+Version: \@CPACK_RPM_PACKAGE_VERSION\@
+Release: \@CPACK_RPM_PACKAGE_RELEASE\@
+License: \@CPACK_RPM_PACKAGE_LICENSE\@
+Group: \@CPACK_RPM_PACKAGE_GROUP\@
+Vendor: \@CPACK_RPM_PACKAGE_VENDOR\@
+
+\@TMP_RPM_URL\@
+\@TMP_RPM_REQUIRES\@
+\@TMP_RPM_REQUIRES_PRE\@
+\@TMP_RPM_REQUIRES_POST\@
+\@TMP_RPM_REQUIRES_PREUN\@
+\@TMP_RPM_REQUIRES_POSTUN\@
+\@TMP_RPM_PROVIDES\@
+\@TMP_RPM_OBSOLETES\@
+\@TMP_RPM_CONFLICTS\@
+\@TMP_RPM_SUGGESTS\@
+\@TMP_RPM_AUTOPROV\@
+\@TMP_RPM_AUTOREQ\@
+\@TMP_RPM_AUTOREQPROV\@
+\@TMP_RPM_BUILDARCH\@
+\@TMP_RPM_PREFIXES\@
+\@TMP_RPM_EPOCH\@
+
+\@TMP_RPM_DEBUGINFO\@
+
+%define _rpmdir %_topdir/RPMS
+%define _srcrpmdir %_topdir/SRPMS
+\@FILE_NAME_DEFINE\@
+%define _unpackaged_files_terminate_build 0
+\@TMP_RPM_SPEC_INSTALL_POST\@
+\@CPACK_RPM_SPEC_MORE_DEFINE\@
+\@CPACK_RPM_COMPRESSION_TYPE_TMP\@
+
+%description
+\@CPACK_RPM_PACKAGE_DESCRIPTION\@
+
+# This is a shortcutted spec file generated by CMake RPM generator
+# we skip _install step because CPack does that for us.
+# We do only save CPack installed tree in _prepr
+# and then restore it in build.
+%prep
+mv $RPM_BUILD_ROOT %_topdir/tmpBBroot
+
+%install
+if [ -e $RPM_BUILD_ROOT ];
+then
+ rm -rf $RPM_BUILD_ROOT
+fi
+mv %_topdir/tmpBBroot $RPM_BUILD_ROOT
+
+\@TMP_RPM_DEBUGINFO_INSTALL\@
+
+%clean
+
+%post
+\@RPM_SYMLINK_POSTINSTALL\@
+\@CPACK_RPM_SPEC_POSTINSTALL\@
+
+%postun
+\@CPACK_RPM_SPEC_POSTUNINSTALL\@
+
+%pre
+\@CPACK_RPM_SPEC_PREINSTALL\@
+
+%preun
+\@CPACK_RPM_SPEC_PREUNINSTALL\@
+
+%files
+%defattr(\@TMP_DEFAULT_FILE_PERMISSIONS\@,\@TMP_DEFAULT_USER\@,\@TMP_DEFAULT_GROUP\@,\@TMP_DEFAULT_DIR_PERMISSIONS\@)
+\@CPACK_RPM_INSTALL_FILES\@
+\@CPACK_RPM_ABSOLUTE_INSTALL_FILES\@
+\@CPACK_RPM_USER_INSTALL_FILES\@
+
+%changelog
+\@CPACK_RPM_SPEC_CHANGELOG\@
+
+\@TMP_OTHER_COMPONENTS\@
+"
+ )
+ endif()
+
+ # Stop here if we were asked to only generate a template USER spec file
+ # The generated file may then be used as a template by user who wants
+ # to customize their own spec file.
+ if(CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE)
+ message(FATAL_ERROR "CPackRPM: STOP here Generated USER binary spec file template is: ${CPACK_RPM_BINARY_SPECFILE}.in")
+ endif()
+ endif()
+
+ # After that we may either use a user provided spec file
+ # or generate one using appropriate variables value.
+ if(CPACK_RPM_USER_BINARY_SPECFILE)
+ # User may have specified SPECFILE just use it
+ message("CPackRPM: Will use USER specified spec file: ${CPACK_RPM_USER_BINARY_SPECFILE}")
+ # The user provided file is processed for @var replacement
+ configure_file(${CPACK_RPM_USER_BINARY_SPECFILE} ${CPACK_RPM_BINARY_SPECFILE} @ONLY)
+ else()
+ # No User specified spec file, will use the generated spec file
+ message("CPackRPM: Will use GENERATED spec file: ${CPACK_RPM_BINARY_SPECFILE}")
+ # Note the just created file is processed for @var replacement
+ configure_file(${CPACK_RPM_BINARY_SPECFILE}.in ${CPACK_RPM_BINARY_SPECFILE} @ONLY)
+ endif()
+
+ if(NOT GENERATE_SPEC_PARTS) # generate package
+ if(RPMBUILD_EXECUTABLE)
+ # Now call rpmbuild using the SPECFILE
+ execute_process(
+ COMMAND "${RPMBUILD_EXECUTABLE}" ${RPMBUILD_FLAGS}
+ --define "_topdir ${CPACK_RPM_DIRECTORY}"
+ --buildroot "%_topdir/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}"
+ --target "${CPACK_RPM_PACKAGE_ARCHITECTURE}"
+ "${CPACK_RPM_BINARY_SPECFILE}"
+ WORKING_DIRECTORY "${CPACK_TOPLEVEL_DIRECTORY}/${CPACK_PACKAGE_FILE_NAME}${CPACK_RPM_PACKAGE_COMPONENT_PART_PATH}"
+ RESULT_VARIABLE CPACK_RPMBUILD_EXEC_RESULT
+ ERROR_FILE "${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.err"
+ OUTPUT_FILE "${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.out")
+ if(CPACK_RPM_PACKAGE_DEBUG OR CPACK_RPMBUILD_EXEC_RESULT)
+ file(READ ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.err RPMBUILDERR)
+ file(READ ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.out RPMBUILDOUT)
+ message("CPackRPM:Debug: You may consult rpmbuild logs in: ")
+ message("CPackRPM:Debug: - ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.err")
+ message("CPackRPM:Debug: *** ${RPMBUILDERR} ***")
+ message("CPackRPM:Debug: - ${CPACK_TOPLEVEL_DIRECTORY}/rpmbuild${CPACK_RPM_PACKAGE_NAME}.out")
+ message("CPackRPM:Debug: *** ${RPMBUILDOUT} ***")
+ endif()
+ else()
+ if(ALIEN_EXECUTABLE)
+ message(FATAL_ERROR "RPM packaging through alien not done (yet)")
+ endif()
+ endif()
+
+ # find generated rpm files and take their names
+ file(GLOB_RECURSE GENERATED_FILES "${CPACK_RPM_DIRECTORY}/RPMS/*.rpm"
+ "${CPACK_RPM_DIRECTORY}/SRPMS/*.rpm")
+
+ if(NOT GENERATED_FILES)
+ message(FATAL_ERROR "RPM package was not generated! ${CPACK_RPM_DIRECTORY}")
+ endif()
+
+ unset(expected_filenames_)
+ unset(filenames_)
+ if(CPACK_RPM_DEBUGINFO_PACKAGE AND NOT CPACK_RPM_FILE_NAME STREQUAL "RPM-DEFAULT")
+ list(APPEND expected_filenames_
+ "${CPACK_RPM_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}.*\\.rpm")
+ list(APPEND filenames_ "${CPACK_RPM_FILE_NAME}")
+ endif()
+
+ if(CPACK_RPM_DEBUGINFO_PACKAGE)
+ cpack_rpm_variable_fallback("CPACK_RPM_DEBUGINFO_FILE_NAME"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT}_DEBUGINFO_FILE_NAME"
+ "CPACK_RPM_${CPACK_RPM_PACKAGE_COMPONENT_UPPER}_DEBUGINFO_FILE_NAME"
+ "CPACK_RPM_DEBUGINFO_FILE_NAME")
+
+ if(CPACK_RPM_DEBUGINFO_FILE_NAME AND
+ NOT CPACK_RPM_DEBUGINFO_FILE_NAME STREQUAL "RPM-DEFAULT")
+ list(APPEND expected_filenames_
+ "${CPACK_RPM_PACKAGE_NAME}-debuginfo-${CPACK_PACKAGE_VERSION}.*\\.rpm")
+ string(REPLACE "@cpack_component@" "${CPACK_RPM_PACKAGE_COMPONENT}"
+ CPACK_RPM_DEBUGINFO_FILE_NAME "${CPACK_RPM_DEBUGINFO_FILE_NAME}")
+ list(APPEND filenames_ "${CPACK_RPM_DEBUGINFO_FILE_NAME}")
+ endif()
+ endif()
+
+ # check if other files have to be renamed
+ file(GLOB rename_files_ "${CPACK_RPM_DIRECTORY}/SPECS/*.rpm_name")
+ if(rename_files_)
+ foreach(f_ IN LISTS rename_files_)
+ file(READ "${f_}" tmp_)
+ list(GET tmp_ 0 efn_)
+ list(APPEND expected_filenames_ "${efn_}")
+ list(GET tmp_ 1 fn_)
+ list(APPEND filenames_ "${fn_}")
+ endforeach()
+ endif()
+
+ if(expected_filenames_)
+ foreach(F IN LISTS GENERATED_FILES)
+ unset(matched_)
+ foreach(expected_ IN LISTS expected_filenames_)
+ if(F MATCHES ".*/${expected_}")
+ list(FIND expected_filenames_ "${expected_}" idx_)
+ list(GET filenames_ ${idx_} filename_)
+ get_filename_component(FILE_PATH "${F}" DIRECTORY)
+ file(RENAME "${F}" "${FILE_PATH}/${filename_}")
+ list(APPEND new_files_list_ "${FILE_PATH}/${filename_}")
+ set(matched_ "YES")
+
+ break()
+ endif()
+ endforeach()
+
+ if(NOT matched_)
+ list(APPEND new_files_list_ "${F}")
+ endif()
+ endforeach()
+
+ set(GENERATED_FILES "${new_files_list_}")
+ endif()
+ endif()
+
+ set(GEN_CPACK_OUTPUT_FILES "${GENERATED_FILES}" PARENT_SCOPE)
+
+ if(CPACK_RPM_PACKAGE_DEBUG)
+ message("CPackRPM:Debug: GEN_CPACK_OUTPUT_FILES = ${GENERATED_FILES}")
+ endif()
+endfunction()
+
+cpack_rpm_generate_package()
+
+cmake_policy(POP)
diff --git a/Modules/Internal/CPack/CPackWIX.cmake b/Modules/Internal/CPack/CPackWIX.cmake
new file mode 100644
index 000000000..d1875f23c
--- /dev/null
+++ b/Modules/Internal/CPack/CPackWIX.cmake
@@ -0,0 +1,20 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+if(NOT CPACK_WIX_ROOT)
+ string(REPLACE "\\" "/" CPACK_WIX_ROOT "$ENV{WIX}")
+endif()
+
+find_program(CPACK_WIX_CANDLE_EXECUTABLE candle
+ PATHS "${CPACK_WIX_ROOT}" PATH_SUFFIXES "bin")
+
+if(NOT CPACK_WIX_CANDLE_EXECUTABLE)
+ message(FATAL_ERROR "Could not find the WiX candle executable.")
+endif()
+
+find_program(CPACK_WIX_LIGHT_EXECUTABLE light
+ PATHS "${CPACK_WIX_ROOT}" PATH_SUFFIXES "bin")
+
+if(NOT CPACK_WIX_LIGHT_EXECUTABLE)
+ message(FATAL_ERROR "Could not find the WiX light executable.")
+endif()
diff --git a/Modules/Internal/CPack/CPackZIP.cmake b/Modules/Internal/CPack/CPackZIP.cmake
new file mode 100644
index 000000000..f619de400
--- /dev/null
+++ b/Modules/Internal/CPack/CPackZIP.cmake
@@ -0,0 +1,30 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+
+if(CMAKE_BINARY_DIR)
+ message(FATAL_ERROR "CPackZIP.cmake may only be used by CPack internally.")
+endif()
+
+find_program(ZIP_EXECUTABLE wzzip PATHS "$ENV{ProgramFiles}/WinZip")
+if(ZIP_EXECUTABLE)
+ set(CPACK_ZIP_COMMAND "\"${ZIP_EXECUTABLE}\" -P \"<ARCHIVE>\" @<FILELIST>")
+ set(CPACK_ZIP_NEED_QUOTES TRUE)
+endif()
+
+if(NOT ZIP_EXECUTABLE)
+ find_program(ZIP_EXECUTABLE 7z PATHS "$ENV{ProgramFiles}/7-Zip")
+ if(ZIP_EXECUTABLE)
+ set(CPACK_ZIP_COMMAND "\"${ZIP_EXECUTABLE}\" a -tzip \"<ARCHIVE>\" @<FILELIST>")
+ set(CPACK_ZIP_NEED_QUOTES TRUE)
+ endif()
+endif()
+
+if(NOT ZIP_EXECUTABLE)
+ find_package(Cygwin)
+ find_program(ZIP_EXECUTABLE zip PATHS "${CYGWIN_INSTALL_PATH}/bin")
+ if(ZIP_EXECUTABLE)
+ set(CPACK_ZIP_COMMAND "\"${ZIP_EXECUTABLE}\" -r \"<ARCHIVE>\" . -i@<FILELIST>")
+ set(CPACK_ZIP_NEED_QUOTES FALSE)
+ endif()
+endif()
diff --git a/Modules/Platform/AIX-XLClang-C.cmake b/Modules/Platform/AIX-XLClang-C.cmake
new file mode 100644
index 000000000..f0bedc5d8
--- /dev/null
+++ b/Modules/Platform/AIX-XLClang-C.cmake
@@ -0,0 +1,2 @@
+include(Platform/AIX-XLClang)
+__aix_compiler_xlclang(C)
diff --git a/Modules/Platform/AIX-XLClang-CXX.cmake b/Modules/Platform/AIX-XLClang-CXX.cmake
new file mode 100644
index 000000000..cceb5769c
--- /dev/null
+++ b/Modules/Platform/AIX-XLClang-CXX.cmake
@@ -0,0 +1,2 @@
+include(Platform/AIX-XLClang)
+__aix_compiler_xlclang(CXX)
diff --git a/Modules/Platform/AIX-XLClang.cmake b/Modules/Platform/AIX-XLClang.cmake
new file mode 100644
index 000000000..c9320950e
--- /dev/null
+++ b/Modules/Platform/AIX-XLClang.cmake
@@ -0,0 +1,15 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+
+# This module is shared by multiple languages; use include blocker.
+if(__AIX_COMPILER_XLCLANG)
+ return()
+endif()
+set(__AIX_COMPILER_XLCLANG 1)
+
+include(Platform/AIX-XL)
+
+macro(__aix_compiler_xlclang lang)
+ __aix_compiler_xl(${lang})
+endmacro()
diff --git a/Modules/Platform/Apple-Absoft-Fortran.cmake b/Modules/Platform/Apple-Absoft-Fortran.cmake
new file mode 100644
index 000000000..8caa2026c
--- /dev/null
+++ b/Modules/Platform/Apple-Absoft-Fortran.cmake
@@ -0,0 +1,7 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+set(CMAKE_Fortran_VERBOSE_FLAG "-X -v") # Runs gcc under the hood.
+
+set(CMAKE_Fortran_OSX_COMPATIBILITY_VERSION_FLAG "-compatibility_version ")
+set(CMAKE_Fortran_OSX_CURRENT_VERSION_FLAG "-current_version ")
diff --git a/Modules/Platform/Apple-AppleClang-C.cmake b/Modules/Platform/Apple-AppleClang-C.cmake
new file mode 100644
index 000000000..f45ccf413
--- /dev/null
+++ b/Modules/Platform/Apple-AppleClang-C.cmake
@@ -0,0 +1,6 @@
+include(Platform/Apple-Clang-C)
+if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 4.2)
+ set(CMAKE_C_SYSTEM_FRAMEWORK_SEARCH_FLAG "-iframework ")
+else()
+ unset(CMAKE_C_SYSTEM_FRAMEWORK_SEARCH_FLAG)
+endif()
diff --git a/Modules/Platform/Apple-AppleClang-CXX.cmake b/Modules/Platform/Apple-AppleClang-CXX.cmake
new file mode 100644
index 000000000..1128204cf
--- /dev/null
+++ b/Modules/Platform/Apple-AppleClang-CXX.cmake
@@ -0,0 +1,6 @@
+include(Platform/Apple-Clang-CXX)
+if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.2)
+ set(CMAKE_CXX_SYSTEM_FRAMEWORK_SEARCH_FLAG "-iframework ")
+else()
+ unset(CMAKE_CXX_SYSTEM_FRAMEWORK_SEARCH_FLAG)
+endif()
diff --git a/Modules/Platform/Apple-Clang-C.cmake b/Modules/Platform/Apple-Clang-C.cmake
new file mode 100644
index 000000000..4d0dc8294
--- /dev/null
+++ b/Modules/Platform/Apple-Clang-C.cmake
@@ -0,0 +1,2 @@
+include(Platform/Apple-Clang)
+__apple_compiler_clang(C)
diff --git a/Modules/Platform/Apple-Clang-CXX.cmake b/Modules/Platform/Apple-Clang-CXX.cmake
new file mode 100644
index 000000000..6c1ddc104
--- /dev/null
+++ b/Modules/Platform/Apple-Clang-CXX.cmake
@@ -0,0 +1,2 @@
+include(Platform/Apple-Clang)
+__apple_compiler_clang(CXX)
diff --git a/Modules/Platform/Apple-Clang.cmake b/Modules/Platform/Apple-Clang.cmake
new file mode 100644
index 000000000..0681bfb05
--- /dev/null
+++ b/Modules/Platform/Apple-Clang.cmake
@@ -0,0 +1,32 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+
+# This module is shared by multiple languages; use include blocker.
+include_guard()
+
+macro(__apple_compiler_clang lang)
+ set(CMAKE_${lang}_VERBOSE_FLAG "-v -Wl,-v") # also tell linker to print verbose output
+ set(CMAKE_SHARED_LIBRARY_CREATE_${lang}_FLAGS "-dynamiclib -Wl,-headerpad_max_install_names")
+ set(CMAKE_SHARED_MODULE_CREATE_${lang}_FLAGS "-bundle -Wl,-headerpad_max_install_names")
+ set(CMAKE_${lang}_SYSROOT_FLAG "-isysroot")
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG "-mmacosx-version-min=")
+ if(NOT CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 3.2)
+ set(CMAKE_${lang}_SYSTEM_FRAMEWORK_SEARCH_FLAG "-iframework ")
+ endif()
+ if(_CMAKE_OSX_SYSROOT_PATH MATCHES "/iPhoneOS")
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG "-miphoneos-version-min=")
+ elseif(_CMAKE_OSX_SYSROOT_PATH MATCHES "/iPhoneSimulator")
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG "-mios-simulator-version-min=")
+ elseif(_CMAKE_OSX_SYSROOT_PATH MATCHES "/AppleTVOS")
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG "-mtvos-version-min=")
+ elseif(_CMAKE_OSX_SYSROOT_PATH MATCHES "/AppleTVSimulator")
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG "-mtvos-simulator-version-min=")
+ elseif(_CMAKE_OSX_SYSROOT_PATH MATCHES "/WatchOS")
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG "-mwatchos-version-min=")
+ elseif(_CMAKE_OSX_SYSROOT_PATH MATCHES "/WatchSimulator")
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG "-mwatchos-simulator-version-min=")
+ else()
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG "-mmacosx-version-min=")
+ endif()
+endmacro()
diff --git a/Modules/Platform/Apple-GNU-C.cmake b/Modules/Platform/Apple-GNU-C.cmake
new file mode 100644
index 000000000..5481c99d8
--- /dev/null
+++ b/Modules/Platform/Apple-GNU-C.cmake
@@ -0,0 +1,4 @@
+include(Platform/Apple-GNU)
+__apple_compiler_gnu(C)
+cmake_gnu_set_sysroot_flag(C)
+cmake_gnu_set_osx_deployment_target_flag(C)
diff --git a/Modules/Platform/Apple-GNU-CXX.cmake b/Modules/Platform/Apple-GNU-CXX.cmake
new file mode 100644
index 000000000..727f72641
--- /dev/null
+++ b/Modules/Platform/Apple-GNU-CXX.cmake
@@ -0,0 +1,4 @@
+include(Platform/Apple-GNU)
+__apple_compiler_gnu(CXX)
+cmake_gnu_set_sysroot_flag(CXX)
+cmake_gnu_set_osx_deployment_target_flag(CXX)
diff --git a/Modules/Platform/Apple-GNU-Fortran.cmake b/Modules/Platform/Apple-GNU-Fortran.cmake
new file mode 100644
index 000000000..2f53603cb
--- /dev/null
+++ b/Modules/Platform/Apple-GNU-Fortran.cmake
@@ -0,0 +1,10 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+include(Platform/Apple-GNU)
+__apple_compiler_gnu(Fortran)
+cmake_gnu_set_sysroot_flag(Fortran)
+cmake_gnu_set_osx_deployment_target_flag(Fortran)
+
+set(CMAKE_Fortran_OSX_COMPATIBILITY_VERSION_FLAG "-compatibility_version ")
+set(CMAKE_Fortran_OSX_CURRENT_VERSION_FLAG "-current_version ")
diff --git a/Modules/Platform/Apple-GNU.cmake b/Modules/Platform/Apple-GNU.cmake
new file mode 100644
index 000000000..0eb816831
--- /dev/null
+++ b/Modules/Platform/Apple-GNU.cmake
@@ -0,0 +1,57 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+
+# This module is shared by multiple languages; use include blocker.
+include_guard()
+
+macro(__apple_compiler_gnu lang)
+ set(CMAKE_${lang}_VERBOSE_FLAG "-v -Wl,-v") # also tell linker to print verbose output
+ # GNU does not have -shared on OS X
+ set(CMAKE_SHARED_LIBRARY_CREATE_${lang}_FLAGS "-dynamiclib -Wl,-headerpad_max_install_names")
+ set(CMAKE_SHARED_MODULE_CREATE_${lang}_FLAGS "-bundle -Wl,-headerpad_max_install_names")
+
+ if(NOT CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 4.3)
+ set(CMAKE_${lang}_SYSTEM_FRAMEWORK_SEARCH_FLAG "-iframework ")
+ endif()
+endmacro()
+
+macro(cmake_gnu_set_sysroot_flag lang)
+ if(NOT DEFINED CMAKE_${lang}_SYSROOT_FLAG)
+ set(_doc "${lang} compiler has -isysroot")
+ message(STATUS "Checking whether ${_doc}")
+ execute_process(
+ COMMAND ${CMAKE_${lang}_COMPILER} "-v" "--help"
+ OUTPUT_VARIABLE _gcc_help
+ ERROR_VARIABLE _gcc_help
+ )
+ if("${_gcc_help}" MATCHES "isysroot")
+ message(STATUS "Checking whether ${_doc} - yes")
+ set(CMAKE_${lang}_SYSROOT_FLAG "-isysroot")
+ else()
+ message(STATUS "Checking whether ${_doc} - no")
+ set(CMAKE_${lang}_SYSROOT_FLAG "")
+ endif()
+ set(CMAKE_${lang}_SYSROOT_FLAG_CODE "set(CMAKE_${lang}_SYSROOT_FLAG \"${CMAKE_${lang}_SYSROOT_FLAG}\")")
+ endif()
+endmacro()
+
+macro(cmake_gnu_set_osx_deployment_target_flag lang)
+ if(NOT DEFINED CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG)
+ set(_doc "${lang} compiler supports OSX deployment target flag")
+ message(STATUS "Checking whether ${_doc}")
+ execute_process(
+ COMMAND ${CMAKE_${lang}_COMPILER} "-v" "--help"
+ OUTPUT_VARIABLE _gcc_help
+ ERROR_VARIABLE _gcc_help
+ )
+ if("${_gcc_help}" MATCHES "macosx-version-min")
+ message(STATUS "Checking whether ${_doc} - yes")
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG "-mmacosx-version-min=")
+ else()
+ message(STATUS "Checking whether ${_doc} - no")
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG "")
+ endif()
+ set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG_CODE "set(CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG \"${CMAKE_${lang}_OSX_DEPLOYMENT_TARGET_FLAG}\")")
+ endif()
+endmacro()
diff --git a/Modules/Platform/Apple-Intel-C.cmake b/Modules/Platform/Apple-Intel-C.cmake
new file mode 100644
index 000000000..95bb270d3
--- /dev/null
+++ b/Modules/Platform/Apple-Intel-C.cmake
@@ -0,0 +1,2 @@
+include(Platform/Apple-Intel)
+__apple_compiler_intel(C)
diff --git a/Modules/Platform/Apple-Intel-CXX.cmake b/Modules/Platform/Apple-Intel-CXX.cmake
new file mode 100644
index 000000000..b87e512df
--- /dev/null
+++ b/Modules/Platform/Apple-Intel-CXX.cmake
@@ -0,0 +1,2 @@
+include(Platform/Apple-Intel)
+__apple_compiler_intel(CXX)
diff --git a/Modules/Platform/Apple-Intel-Fortran.cmake b/Modules/Platform/Apple-Intel-Fortran.cmake
new file mode 100644
index 000000000..e54e23762
--- /dev/null
+++ b/Modules/Platform/Apple-Intel-Fortran.cmake
@@ -0,0 +1,8 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+include(Platform/Apple-Intel)
+__apple_compiler_intel(Fortran)
+
+set(CMAKE_Fortran_OSX_COMPATIBILITY_VERSION_FLAG "-compatibility_version ")
+set(CMAKE_Fortran_OSX_CURRENT_VERSION_FLAG "-current_version ")
diff --git a/Modules/Platform/Apple-Intel.cmake b/Modules/Platform/Apple-Intel.cmake
new file mode 100644
index 000000000..a854be996
--- /dev/null
+++ b/Modules/Platform/Apple-Intel.cmake
@@ -0,0 +1,19 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+
+# This module is shared by multiple languages; use include blocker.
+include_guard()
+
+macro(__apple_compiler_intel lang)
+ set(CMAKE_${lang}_VERBOSE_FLAG "-v -Wl,-v") # also tell linker to print verbose output
+ set(CMAKE_SHARED_LIBRARY_CREATE_${lang}_FLAGS "-dynamiclib -Wl,-headerpad_max_install_names")
+ set(CMAKE_SHARED_MODULE_CREATE_${lang}_FLAGS "-bundle -Wl,-headerpad_max_install_names")
+
+ set(CMAKE_${lang}_LINKER_WRAPPER_FLAG "-Wl,")
+ set(CMAKE_${lang}_LINKER_WRAPPER_FLAG_SEP ",")
+
+ if(NOT CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 12.0)
+ set(CMAKE_${lang}_COMPILE_OPTIONS_VISIBILITY "-fvisibility=")
+ endif()
+endmacro()
diff --git a/Modules/Platform/Apple-NAG-Fortran.cmake b/Modules/Platform/Apple-NAG-Fortran.cmake
new file mode 100644
index 000000000..8d3e741c1
--- /dev/null
+++ b/Modules/Platform/Apple-NAG-Fortran.cmake
@@ -0,0 +1,15 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+set(CMAKE_Fortran_VERBOSE_FLAG "-Wl,-v") # Runs gcc under the hood.
+
+# Need -fpp explicitly on case-insensitive filesystem.
+set(CMAKE_Fortran_COMPILE_OBJECT
+ "<CMAKE_Fortran_COMPILER> -fpp -o <OBJECT> <DEFINES> <INCLUDES> <FLAGS> -c <SOURCE>")
+
+set(CMAKE_Fortran_OSX_COMPATIBILITY_VERSION_FLAG "-Wl,-compatibility_version -Wl,")
+set(CMAKE_Fortran_OSX_CURRENT_VERSION_FLAG "-Wl,-current_version -Wl,")
+set(CMAKE_SHARED_LIBRARY_CREATE_Fortran_FLAGS "-Wl,-shared")
+set(CMAKE_SHARED_LIBRARY_SONAME_Fortran_FLAG "-Wl,-install_name -Wl,")
+set(CMAKE_Fortran_CREATE_SHARED_LIBRARY
+ "<CMAKE_Fortran_COMPILER> <LANGUAGE_COMPILE_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_Fortran_FLAGS> <LINK_FLAGS> -o <TARGET> <SONAME_FLAG><TARGET_INSTALLNAME_DIR><TARGET_SONAME> <OBJECTS> <LINK_LIBRARIES>")
diff --git a/Modules/Platform/Apple-NVIDIA-CUDA.cmake b/Modules/Platform/Apple-NVIDIA-CUDA.cmake
new file mode 100644
index 000000000..bec394839
--- /dev/null
+++ b/Modules/Platform/Apple-NVIDIA-CUDA.cmake
@@ -0,0 +1,19 @@
+include(Platform/Darwin)
+
+set(__IMPLICT_LINKS )
+foreach(dir ${CMAKE_CUDA_HOST_IMPLICIT_LINK_DIRECTORIES})
+ string(APPEND __IMPLICT_LINKS " -L\"${dir}\"")
+endforeach()
+foreach(lib ${CMAKE_CUDA_HOST_IMPLICIT_LINK_LIBRARIES})
+ if(${lib} MATCHES "/")
+ string(APPEND __IMPLICT_LINKS " \"${lib}\"")
+ else()
+ string(APPEND __IMPLICT_LINKS " -l${lib}")
+ endif()
+endforeach()
+
+set(CMAKE_SHARED_LIBRARY_CREATE_CUDA_FLAGS "-shared -Wl,-headerpad_max_install_names")
+set(CMAKE_SHARED_MODULE_CREATE_CUDA_FLAGS "-shared -Wl,-headerpad_max_install_names")
+
+set(CMAKE_CUDA_CREATE_SHARED_LIBRARY "<CMAKE_CUDA_HOST_LINK_LAUNCHER> <CMAKE_SHARED_LIBRARY_CUDA_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CUDA_FLAGS> -o <TARGET> <SONAME_FLAG> <TARGET_INSTALLNAME_DIR><TARGET_SONAME> <OBJECTS> <LINK_LIBRARIES>${__IMPLICT_LINKS}")
+set(CMAKE_CUDA_CREATE_SHARED_MODULE "<CMAKE_CUDA_HOST_LINK_LAUNCHER> <CMAKE_SHARED_LIBRARY_CUDA_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CUDA_FLAGS> -o <TARGET> <OBJECTS> <LINK_LIBRARIES>${__IMPLICT_LINKS}")
diff --git a/Modules/Platform/Apple-PGI-C.cmake b/Modules/Platform/Apple-PGI-C.cmake
new file mode 100644
index 000000000..1e117247b
--- /dev/null
+++ b/Modules/Platform/Apple-PGI-C.cmake
@@ -0,0 +1,2 @@
+include(Platform/Apple-PGI)
+__apple_compiler_pgi(C)
diff --git a/Modules/Platform/Apple-PGI-CXX.cmake b/Modules/Platform/Apple-PGI-CXX.cmake
new file mode 100644
index 000000000..aa5daf7dd
--- /dev/null
+++ b/Modules/Platform/Apple-PGI-CXX.cmake
@@ -0,0 +1,2 @@
+include(Platform/Apple-PGI)
+__apple_compiler_pgi(CXX)
diff --git a/Modules/Platform/Apple-PGI-Fortran.cmake b/Modules/Platform/Apple-PGI-Fortran.cmake
new file mode 100644
index 000000000..1e3e4b1a7
--- /dev/null
+++ b/Modules/Platform/Apple-PGI-Fortran.cmake
@@ -0,0 +1,2 @@
+include(Platform/Apple-PGI)
+__apple_compiler_pgi(Fortran)
diff --git a/Modules/Platform/Apple-PGI.cmake b/Modules/Platform/Apple-PGI.cmake
new file mode 100644
index 000000000..8d343b7d1
--- /dev/null
+++ b/Modules/Platform/Apple-PGI.cmake
@@ -0,0 +1,11 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+# This module is shared by multiple languages; use include blocker.
+include_guard()
+
+macro(__apple_compiler_pgi lang)
+ set(CMAKE_${lang}_OSX_COMPATIBILITY_VERSION_FLAG "-Wl,-compatibility_version,")
+ set(CMAKE_${lang}_OSX_CURRENT_VERSION_FLAG "-Wl,-current_version,")
+ set(CMAKE_SHARED_LIBRARY_SONAME_${lang}_FLAG "-Wl,-install_name")
+endmacro()
diff --git a/Modules/Platform/Apple-VisualAge-C.cmake b/Modules/Platform/Apple-VisualAge-C.cmake
new file mode 100644
index 000000000..7fa603231
--- /dev/null
+++ b/Modules/Platform/Apple-VisualAge-C.cmake
@@ -0,0 +1 @@
+include(Platform/Apple-XL-C)
diff --git a/Modules/Platform/Apple-VisualAge-CXX.cmake b/Modules/Platform/Apple-VisualAge-CXX.cmake
new file mode 100644
index 000000000..12dd34740
--- /dev/null
+++ b/Modules/Platform/Apple-VisualAge-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Apple-XL-CXX)
diff --git a/Modules/Platform/Apple-XL-C.cmake b/Modules/Platform/Apple-XL-C.cmake
new file mode 100644
index 000000000..2aeb132d1
--- /dev/null
+++ b/Modules/Platform/Apple-XL-C.cmake
@@ -0,0 +1,8 @@
+set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "-qmkshrobj")
+set(CMAKE_SHARED_MODULE_CREATE_C_FLAGS "-bundle")
+
+# Enable shared library versioning.
+set(CMAKE_SHARED_LIBRARY_SONAME_C_FLAG "-Wl,-install_name")
+
+# -qhalt=e = Halt on error messages (rather than just severe errors)
+string(APPEND CMAKE_C_FLAGS_INIT " -qhalt=e")
diff --git a/Modules/Platform/Apple-XL-CXX.cmake b/Modules/Platform/Apple-XL-CXX.cmake
new file mode 100644
index 000000000..f8e1906a8
--- /dev/null
+++ b/Modules/Platform/Apple-XL-CXX.cmake
@@ -0,0 +1,8 @@
+set(CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS "-qmkshrobj")
+set(CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS "-bundle")
+
+# Enable shared library versioning.
+set(CMAKE_SHARED_LIBRARY_SONAME_CXX_FLAG "-Wl,-install_name")
+
+# -qhalt=e = Halt on error messages (rather than just severe errors)
+string(APPEND CMAKE_C_FLAGS_INIT " -qhalt=e")
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-Determine.cmake b/Modules/Platform/GHS-MULTI-Determine.cmake
new file mode 100644
index 000000000..349d90657
--- /dev/null
+++ b/Modules/Platform/GHS-MULTI-Determine.cmake
@@ -0,0 +1,56 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#Setup Green Hills MULTI specific compilation information
+
+if(CMAKE_HOST_UNIX)
+ set(GHS_OS_ROOT "/usr/ghs" CACHE PATH "GHS platform OS search root directory")
+else()
+ set(GHS_OS_ROOT "C:/ghs" CACHE PATH "GHS platform OS search root directory")
+endif()
+mark_as_advanced(GHS_OS_ROOT)
+
+set(GHS_OS_DIR "NOTFOUND" CACHE PATH "GHS platform OS directory")
+mark_as_advanced(GHS_OS_DIR)
+
+set(GHS_OS_DIR_OPTION "-os_dir " CACHE STRING "GHS compiler OS option")
+mark_as_advanced(GHS_OS_DIR_OPTION)
+
+#set GHS_OS_DIR if not set by user
+if(NOT GHS_OS_DIR)
+ if(EXISTS ${GHS_OS_ROOT})
+
+ #get all directories in root directory
+ FILE(GLOB GHS_CANDIDATE_OS_DIRS
+ LIST_DIRECTORIES true RELATIVE ${GHS_OS_ROOT} ${GHS_OS_ROOT}/*)
+ FILE(GLOB GHS_CANDIDATE_OS_FILES
+ LIST_DIRECTORIES false RELATIVE ${GHS_OS_ROOT} ${GHS_OS_ROOT}/*)
+ if(GHS_CANDIDATE_OS_FILES)
+ list(REMOVE_ITEM GHS_CANDIDATE_OS_DIRS ${GHS_CANDIDATE_OS_FILES})
+ endif ()
+
+ #filter based on platform name
+ if(GHS_TARGET_PLATFORM MATCHES "integrity")
+ list(FILTER GHS_CANDIDATE_OS_DIRS INCLUDE REGEX "int[0-9][0-9][0-9][0-9a-z]")
+ else() #fall-back for standalone
+ unset(GHS_CANDIDATE_OS_DIRS)
+ set(GHS_OS_DIR "IGNORE")
+ endif()
+
+ if(GHS_CANDIDATE_OS_DIRS)
+ list(SORT GHS_CANDIDATE_OS_DIRS)
+ list(GET GHS_CANDIDATE_OS_DIRS -1 GHS_OS_DIR)
+ string(CONCAT GHS_OS_DIR ${GHS_OS_ROOT} "/" ${GHS_OS_DIR})
+ endif()
+
+ #update cache with new value
+ set(GHS_OS_DIR "${GHS_OS_DIR}" CACHE PATH "GHS platform OS directory" FORCE)
+ endif()
+endif()
+
+set(GHS_BSP_NAME "IGNORE" CACHE STRING "BSP name")
+
+set(GHS_CUSTOMIZATION "" CACHE FILEPATH "optional GHS customization")
+mark_as_advanced(GHS_CUSTOMIZATION)
+set(GHS_GPJ_MACROS "" CACHE STRING "optional GHS macros generated in the .gpjs for legacy reasons")
+mark_as_advanced(GHS_GPJ_MACROS)
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-Flang-Fortran.cmake b/Modules/Platform/Windows-Flang-Fortran.cmake
new file mode 100644
index 000000000..c4420f7cd
--- /dev/null
+++ b/Modules/Platform/Windows-Flang-Fortran.cmake
@@ -0,0 +1,8 @@
+include(Platform/Windows-MSVC)
+__windows_compiler_msvc(Fortran)
+set(CMAKE_Fortran_COMPILE_OBJECT "<CMAKE_Fortran_COMPILER> ${_COMPILE_Fortran} <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT> -c <SOURCE>")
+
+set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreaded -Xclang --dependent-lib=libcmt)
+set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDLL -Xclang --dependent-lib=msvcrt)
+set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDebug -Xclang --dependent-lib=libcmtd)
+set(CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDebugDLL -Xclang --dependent-lib=msvcrtd)
diff --git a/Modules/Platform/WindowsPhone-Clang-C.cmake b/Modules/Platform/WindowsPhone-Clang-C.cmake
new file mode 100644
index 000000000..6e38572cd
--- /dev/null
+++ b/Modules/Platform/WindowsPhone-Clang-C.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-Clang-C)
diff --git a/Modules/Platform/WindowsPhone-Clang-CXX.cmake b/Modules/Platform/WindowsPhone-Clang-CXX.cmake
new file mode 100644
index 000000000..bf47978c4
--- /dev/null
+++ b/Modules/Platform/WindowsPhone-Clang-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-Clang-CXX)
diff --git a/Modules/Platform/WindowsPhone-GNU-C.cmake b/Modules/Platform/WindowsPhone-GNU-C.cmake
new file mode 100644
index 000000000..ff6acd56d
--- /dev/null
+++ b/Modules/Platform/WindowsPhone-GNU-C.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-GNU-C)
diff --git a/Modules/Platform/WindowsPhone-GNU-CXX.cmake b/Modules/Platform/WindowsPhone-GNU-CXX.cmake
new file mode 100644
index 000000000..6adab6af3
--- /dev/null
+++ b/Modules/Platform/WindowsPhone-GNU-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-GNU-CXX)
diff --git a/Modules/Platform/WindowsStore-Clang-C.cmake b/Modules/Platform/WindowsStore-Clang-C.cmake
new file mode 100644
index 000000000..6e38572cd
--- /dev/null
+++ b/Modules/Platform/WindowsStore-Clang-C.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-Clang-C)
diff --git a/Modules/Platform/WindowsStore-Clang-CXX.cmake b/Modules/Platform/WindowsStore-Clang-CXX.cmake
new file mode 100644
index 000000000..bf47978c4
--- /dev/null
+++ b/Modules/Platform/WindowsStore-Clang-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-Clang-CXX)
diff --git a/Modules/Platform/WindowsStore-GNU-C.cmake b/Modules/Platform/WindowsStore-GNU-C.cmake
new file mode 100644
index 000000000..ff6acd56d
--- /dev/null
+++ b/Modules/Platform/WindowsStore-GNU-C.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-GNU-C)
diff --git a/Modules/Platform/WindowsStore-GNU-CXX.cmake b/Modules/Platform/WindowsStore-GNU-CXX.cmake
new file mode 100644
index 000000000..6adab6af3
--- /dev/null
+++ b/Modules/Platform/WindowsStore-GNU-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Windows-GNU-CXX)
diff --git a/Modules/Platform/iOS-Determine-CXX.cmake b/Modules/Platform/iOS-Determine-CXX.cmake
new file mode 100644
index 000000000..ac80fa62d
--- /dev/null
+++ b/Modules/Platform/iOS-Determine-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Darwin-Determine-CXX)
diff --git a/Modules/Platform/iOS-Initialize.cmake b/Modules/Platform/iOS-Initialize.cmake
new file mode 100644
index 000000000..301ca4cbd
--- /dev/null
+++ b/Modules/Platform/iOS-Initialize.cmake
@@ -0,0 +1,9 @@
+include(Platform/Darwin-Initialize)
+
+if(NOT _CMAKE_OSX_SYSROOT_PATH MATCHES "/iPhone(OS|Simulator)")
+ message(FATAL_ERROR "${CMAKE_OSX_SYSROOT} is not an iOS SDK")
+endif()
+
+set(IOS 1)
+
+set(_CMAKE_FEATURE_DETECTION_TARGET_TYPE STATIC_LIBRARY)
diff --git a/Modules/Platform/iOS.cmake b/Modules/Platform/iOS.cmake
new file mode 100644
index 000000000..850ddc241
--- /dev/null
+++ b/Modules/Platform/iOS.cmake
@@ -0,0 +1 @@
+include(Platform/Darwin)
diff --git a/Modules/Platform/tvOS-Determine-CXX.cmake b/Modules/Platform/tvOS-Determine-CXX.cmake
new file mode 100644
index 000000000..ac80fa62d
--- /dev/null
+++ b/Modules/Platform/tvOS-Determine-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Darwin-Determine-CXX)
diff --git a/Modules/Platform/tvOS-Initialize.cmake b/Modules/Platform/tvOS-Initialize.cmake
new file mode 100644
index 000000000..6834c8031
--- /dev/null
+++ b/Modules/Platform/tvOS-Initialize.cmake
@@ -0,0 +1,7 @@
+include(Platform/Darwin-Initialize)
+
+if(NOT _CMAKE_OSX_SYSROOT_PATH MATCHES "/AppleTV(OS|Simulator)")
+ message(FATAL_ERROR "${CMAKE_OSX_SYSROOT} is not an tvOS SDK")
+endif()
+
+set(_CMAKE_FEATURE_DETECTION_TARGET_TYPE STATIC_LIBRARY)
diff --git a/Modules/Platform/tvOS.cmake b/Modules/Platform/tvOS.cmake
new file mode 100644
index 000000000..850ddc241
--- /dev/null
+++ b/Modules/Platform/tvOS.cmake
@@ -0,0 +1 @@
+include(Platform/Darwin)
diff --git a/Modules/Platform/watchOS-Determine-CXX.cmake b/Modules/Platform/watchOS-Determine-CXX.cmake
new file mode 100644
index 000000000..ac80fa62d
--- /dev/null
+++ b/Modules/Platform/watchOS-Determine-CXX.cmake
@@ -0,0 +1 @@
+include(Platform/Darwin-Determine-CXX)
diff --git a/Modules/Platform/watchOS-Initialize.cmake b/Modules/Platform/watchOS-Initialize.cmake
new file mode 100644
index 000000000..2f396d394
--- /dev/null
+++ b/Modules/Platform/watchOS-Initialize.cmake
@@ -0,0 +1,7 @@
+include(Platform/Darwin-Initialize)
+
+if(NOT _CMAKE_OSX_SYSROOT_PATH MATCHES "/Watch(OS|Simulator)")
+ message(FATAL_ERROR "${CMAKE_OSX_SYSROOT} is not an watchOS SDK")
+endif()
+
+set(_CMAKE_FEATURE_DETECTION_TARGET_TYPE STATIC_LIBRARY)
diff --git a/Modules/Platform/watchOS.cmake b/Modules/Platform/watchOS.cmake
new file mode 100644
index 000000000..850ddc241
--- /dev/null
+++ b/Modules/Platform/watchOS.cmake
@@ -0,0 +1 @@
+include(Platform/Darwin)
diff --git a/Modules/UseSWIG/ManageSupportFiles.cmake b/Modules/UseSWIG/ManageSupportFiles.cmake
new file mode 100644
index 000000000..4a03900b7
--- /dev/null
+++ b/Modules/UseSWIG/ManageSupportFiles.cmake
@@ -0,0 +1,31 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+
+if (ACTION STREQUAL "CLEAN")
+ # Collect current list of generated files
+ file (GLOB files LIST_DIRECTORIES FALSE RELATIVE "${SUPPORT_FILES_WORKING_DIRECTORY}" "${SUPPORT_FILES_WORKING_DIRECTORY}/*")
+
+ if (files)
+ # clean-up the output directory
+ ## compute full paths
+ list (TRANSFORM files PREPEND "${SUPPORT_FILES_OUTPUT_DIRECTORY}/")
+ ## remove generated files from the output directory
+ file (REMOVE ${files})
+
+ # clean-up working directory
+ file (REMOVE_RECURSE "${SUPPORT_FILES_WORKING_DIRECTORY}")
+ endif()
+
+ file (MAKE_DIRECTORY "${SUPPORT_FILES_WORKING_DIRECTORY}")
+endif()
+
+if (ACTION STREQUAL "COPY")
+ # Collect current list of generated files
+ file (GLOB files LIST_DIRECTORIES FALSE "${SUPPORT_FILES_WORKING_DIRECTORY}/*")
+
+ if (files)
+ # copy files to the output directory
+ file (COPY ${files} DESTINATION "${SUPPORT_FILES_OUTPUT_DIRECTORY}")
+ endif()
+endif()
diff --git a/Source/CMakeInstallSignTool.cmake.in b/Source/CMakeInstallSignTool.cmake.in
new file mode 100644
index 000000000..fca629c31
--- /dev/null
+++ b/Source/CMakeInstallSignTool.cmake.in
@@ -0,0 +1,51 @@
+# The signtool. Default to PATH.
+set(CMake_INSTALL_SIGNTOOL "@CMake_INSTALL_SIGNTOOL@")
+if(NOT CMake_INSTALL_SIGNTOOL)
+ set(CMake_INSTALL_SIGNTOOL signtool)
+endif()
+
+# Select a certificate by Subject Name. Default to automatic selection.
+set(CMake_INSTALL_SIGNTOOL_SUBJECT_NAME "@CMake_INSTALL_SIGNTOOL_SUBJECT_NAME@")
+if(CMake_INSTALL_SIGNTOOL_SUBJECT_NAME)
+ set(select_cert -n "${CMake_INSTALL_SIGNTOOL_SUBJECT_NAME}")
+else()
+ set(select_cert -a)
+endif()
+
+# Timestamp URL. Default to a common provider.
+set(CMake_INSTALL_SIGNTOOL_TIMESTAMP_URL "@CMake_INSTALL_SIGNTOOL_TIMESTAMP_URL@")
+if(NOT CMake_INSTALL_SIGNTOOL_TIMESTAMP_URL)
+ set(CMake_INSTALL_SIGNTOOL_TIMESTAMP_URL "http://timestamp.digicert.com")
+endif()
+
+# Glob files that need a signature.
+file(GLOB files "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/bin/*.exe")
+
+# Sign all files at once.
+if(files)
+ # Run the signtool through 'cmd /c' to enable password prompt popup.
+ # Some providers have trouble when signtool is invoked with SW_HIDE.
+ set(cmd cmd /c "${CMake_INSTALL_SIGNTOOL}" sign -v ${select_cert})
+
+ # Sign with SHA-1 for Windows 7 and below.
+ execute_process(
+ COMMAND ${cmd} -t "${CMake_INSTALL_SIGNTOOL_TIMESTAMP_URL}" ${files}
+ RESULT_VARIABLE result
+ ERROR_VARIABLE stderr
+ )
+ if(NOT result EQUAL 0)
+ string(REPLACE "\n" "\n " stderr " ${stderr}")
+ message(WARNING "signtool failed:\n${stderr}")
+ endif()
+
+ # Sign with SHA-256 for Windows 8 and above.
+ execute_process(
+ COMMAND ${cmd} -tr "${CMake_INSTALL_SIGNTOOL_TIMESTAMP_URL}" -fd sha256 -td sha256 -as ${files}
+ RESULT_VARIABLE result
+ ERROR_VARIABLE stderr
+ )
+ if(NOT result EQUAL 0)
+ string(REPLACE "\n" "\n " stderr " ${stderr}")
+ message(WARNING "signtool failed:\n${stderr}")
+ endif()
+endif()
diff --git a/Source/CMakeVersion.rc.in b/Source/CMakeVersion.rc.in
new file mode 100644
index 000000000..762d9bb62
--- /dev/null
+++ b/Source/CMakeVersion.rc.in
@@ -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. */
+
+1 VERSIONINFO
+FILEVERSION @CMake_RCVERSION@
+PRODUCTVERSION @CMake_RCVERSION@
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904E4"
+ BEGIN
+ VALUE "FileVersion", "@CMake_RCVERSION_STR@\0"
+ VALUE "ProductVersion", "@CMake_RCVERSION_STR@\0"
+ END
+ END
+
+ BLOCK "VarFileInfo"
+ BEGIN
+ /* The following line should only be modified for localized versions. */
+ /* It consists of any number of WORD,WORD pairs, with each pair */
+ /* describing a language,codepage combination supported by the file. */
+ /* */
+ /* For example, a file might have values "0x409,1252" indicating that it */
+ /* supports English language (0x409) in the Windows ANSI codepage (1252). */
+
+ VALUE "Translation", 0x409, 1252
+ END
+END
diff --git a/Source/CPack/WiX/cmCMakeToWixPath.cxx b/Source/CPack/WiX/cmCMakeToWixPath.cxx
new file mode 100644
index 000000000..b3889cf2e
--- /dev/null
+++ b/Source/CPack/WiX/cmCMakeToWixPath.cxx
@@ -0,0 +1,39 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmCMakeToWixPath.h"
+
+#include "cmSystemTools.h"
+
+#include <string>
+#include <vector>
+
+#ifdef __CYGWIN__
+# include <sys/cygwin.h>
+std::string CMakeToWixPath(const std::string& cygpath)
+{
+ std::vector<char> winpath_chars;
+ ssize_t winpath_size;
+
+ // Get the required buffer size.
+ winpath_size =
+ cygwin_conv_path(CCP_POSIX_TO_WIN_A, cygpath.c_str(), nullptr, 0);
+ if (winpath_size <= 0) {
+ return cygpath;
+ }
+
+ winpath_chars.assign(static_cast<size_t>(winpath_size) + 1, '\0');
+
+ winpath_size = cygwin_conv_path(CCP_POSIX_TO_WIN_A, cygpath.c_str(),
+ winpath_chars.data(), winpath_size);
+ if (winpath_size < 0) {
+ return cygpath;
+ }
+
+ return cmSystemTools::TrimWhitespace(winpath_chars.data());
+}
+#else
+std::string CMakeToWixPath(const std::string& path)
+{
+ return path;
+}
+#endif
diff --git a/Source/CPack/WiX/cmCMakeToWixPath.h b/Source/CPack/WiX/cmCMakeToWixPath.h
new file mode 100644
index 000000000..8bb9e0408
--- /dev/null
+++ b/Source/CPack/WiX/cmCMakeToWixPath.h
@@ -0,0 +1,12 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmCMakeToWixPath_h
+#define cmCMakeToWixPath_h
+
+#include "cmConfigure.h" //IWYU pragma: keep
+
+#include <string>
+
+std::string CMakeToWixPath(const std::string& cygpath);
+
+#endif // cmCMakeToWixPath_h
diff --git a/Source/CPack/cmCPackExternalGenerator.cxx b/Source/CPack/cmCPackExternalGenerator.cxx
new file mode 100644
index 000000000..9dc985331
--- /dev/null
+++ b/Source/CPack/cmCPackExternalGenerator.cxx
@@ -0,0 +1,323 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmCPackExternalGenerator.h"
+
+#include "cmAlgorithms.h"
+#include "cmCPackComponentGroup.h"
+#include "cmCPackLog.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+#include "cm_jsoncpp_value.h"
+#include "cm_jsoncpp_writer.h"
+
+#include "cmsys/FStream.hxx"
+
+#include <map>
+#include <utility>
+#include <vector>
+
+int cmCPackExternalGenerator::InitializeInternal()
+{
+ this->SetOption("CPACK_EXTERNAL_KNOWN_VERSIONS", "1.0");
+
+ if (!this->ReadListFile("Internal/CPack/CPackExternal.cmake")) {
+ cmCPackLogger(cmCPackLog::LOG_ERROR,
+ "Error while executing CPackExternal.cmake" << std::endl);
+ return 0;
+ }
+
+ std::string major = this->GetOption("CPACK_EXTERNAL_SELECTED_MAJOR");
+ if (major == "1") {
+ this->Generator = cm::make_unique<cmCPackExternalVersion1Generator>(this);
+ }
+
+ return this->Superclass::InitializeInternal();
+}
+
+int cmCPackExternalGenerator::PackageFiles()
+{
+ Json::StreamWriterBuilder builder;
+ builder["indentation"] = " ";
+
+ std::string filename = "package.json";
+ if (!this->packageFileNames.empty()) {
+ filename = this->packageFileNames[0];
+ }
+
+ cmsys::ofstream fout(filename.c_str());
+ std::unique_ptr<Json::StreamWriter> jout(builder.newStreamWriter());
+
+ Json::Value root(Json::objectValue);
+
+ if (!this->Generator->WriteToJSON(root)) {
+ return 0;
+ }
+
+ if (jout->write(root, &fout)) {
+ return 0;
+ }
+
+ const char* packageScript = this->GetOption("CPACK_EXTERNAL_PACKAGE_SCRIPT");
+ if (packageScript && *packageScript) {
+ if (!cmSystemTools::FileIsFullPath(packageScript)) {
+ cmCPackLogger(
+ cmCPackLog::LOG_ERROR,
+ "CPACK_EXTERNAL_PACKAGE_SCRIPT does not contain a full file path"
+ << std::endl);
+ return 0;
+ }
+
+ bool res = this->MakefileMap->ReadListFile(packageScript);
+
+ if (cmSystemTools::GetErrorOccuredFlag() || !res) {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+bool cmCPackExternalGenerator::SupportsComponentInstallation() const
+{
+ return true;
+}
+
+int cmCPackExternalGenerator::InstallProjectViaInstallCommands(
+ bool setDestDir, const std::string& tempInstallDirectory)
+{
+ if (this->StagingEnabled()) {
+ return cmCPackGenerator::InstallProjectViaInstallCommands(
+ setDestDir, tempInstallDirectory);
+ }
+
+ return 1;
+}
+
+int cmCPackExternalGenerator::InstallProjectViaInstallScript(
+ bool setDestDir, const std::string& tempInstallDirectory)
+{
+ if (this->StagingEnabled()) {
+ return cmCPackGenerator::InstallProjectViaInstallScript(
+ setDestDir, tempInstallDirectory);
+ }
+
+ return 1;
+}
+
+int cmCPackExternalGenerator::InstallProjectViaInstalledDirectories(
+ bool setDestDir, const std::string& tempInstallDirectory,
+ const mode_t* default_dir_mode)
+{
+ if (this->StagingEnabled()) {
+ return cmCPackGenerator::InstallProjectViaInstalledDirectories(
+ setDestDir, tempInstallDirectory, default_dir_mode);
+ }
+
+ return 1;
+}
+
+int cmCPackExternalGenerator::RunPreinstallTarget(
+ const std::string& installProjectName, const std::string& installDirectory,
+ cmGlobalGenerator* globalGenerator, const std::string& buildConfig)
+{
+ if (this->StagingEnabled()) {
+ return cmCPackGenerator::RunPreinstallTarget(
+ installProjectName, installDirectory, globalGenerator, buildConfig);
+ }
+
+ return 1;
+}
+
+int cmCPackExternalGenerator::InstallCMakeProject(
+ bool setDestDir, const std::string& installDirectory,
+ const std::string& baseTempInstallDirectory, const mode_t* default_dir_mode,
+ const std::string& component, bool componentInstall,
+ const std::string& installSubDirectory, const std::string& buildConfig,
+ std::string& absoluteDestFiles)
+{
+ if (this->StagingEnabled()) {
+ return cmCPackGenerator::InstallCMakeProject(
+ setDestDir, installDirectory, baseTempInstallDirectory, default_dir_mode,
+ component, componentInstall, installSubDirectory, buildConfig,
+ absoluteDestFiles);
+ }
+
+ return 1;
+}
+
+bool cmCPackExternalGenerator::StagingEnabled() const
+{
+ return !cmSystemTools::IsOff(
+ this->GetOption("CPACK_EXTERNAL_ENABLE_STAGING"));
+}
+
+cmCPackExternalGenerator::cmCPackExternalVersionGenerator::
+ cmCPackExternalVersionGenerator(cmCPackExternalGenerator* parent)
+ : Parent(parent)
+{
+}
+
+int cmCPackExternalGenerator::cmCPackExternalVersionGenerator::WriteVersion(
+ Json::Value& root)
+{
+ root["formatVersionMajor"] = this->GetVersionMajor();
+ root["formatVersionMinor"] = this->GetVersionMinor();
+
+ return 1;
+}
+
+int cmCPackExternalGenerator::cmCPackExternalVersionGenerator::WriteToJSON(
+ Json::Value& root)
+{
+ if (!this->WriteVersion(root)) {
+ return 0;
+ }
+
+ const char* packageName = this->Parent->GetOption("CPACK_PACKAGE_NAME");
+ if (packageName) {
+ root["packageName"] = packageName;
+ }
+
+ const char* packageVersion =
+ this->Parent->GetOption("CPACK_PACKAGE_VERSION");
+ if (packageVersion) {
+ root["packageVersion"] = packageVersion;
+ }
+
+ const char* packageDescriptionFile =
+ this->Parent->GetOption("CPACK_PACKAGE_DESCRIPTION_FILE");
+ if (packageDescriptionFile) {
+ root["packageDescriptionFile"] = packageDescriptionFile;
+ }
+
+ const char* packageDescriptionSummary =
+ this->Parent->GetOption("CPACK_PACKAGE_DESCRIPTION_SUMMARY");
+ if (packageDescriptionSummary) {
+ root["packageDescriptionSummary"] = packageDescriptionSummary;
+ }
+
+ const char* buildConfigCstr = this->Parent->GetOption("CPACK_BUILD_CONFIG");
+ if (buildConfigCstr) {
+ root["buildConfig"] = buildConfigCstr;
+ }
+
+ const char* defaultDirectoryPermissions =
+ this->Parent->GetOption("CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS");
+ if (defaultDirectoryPermissions && *defaultDirectoryPermissions) {
+ root["defaultDirectoryPermissions"] = defaultDirectoryPermissions;
+ }
+ if (cmSystemTools::IsInternallyOn(
+ this->Parent->GetOption("CPACK_SET_DESTDIR"))) {
+ root["setDestdir"] = true;
+ root["packagingInstallPrefix"] =
+ this->Parent->GetOption("CPACK_PACKAGING_INSTALL_PREFIX");
+ } else {
+ root["setDestdir"] = false;
+ }
+
+ root["stripFiles"] =
+ !cmSystemTools::IsOff(this->Parent->GetOption("CPACK_STRIP_FILES"));
+ root["warnOnAbsoluteInstallDestination"] =
+ this->Parent->IsOn("CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION");
+ root["errorOnAbsoluteInstallDestination"] =
+ this->Parent->IsOn("CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION");
+
+ Json::Value& projects = root["projects"] = Json::Value(Json::arrayValue);
+ for (auto& project : this->Parent->CMakeProjects) {
+ Json::Value jsonProject(Json::objectValue);
+
+ jsonProject["projectName"] = project.ProjectName;
+ jsonProject["component"] = project.Component;
+ jsonProject["directory"] = project.Directory;
+ jsonProject["subDirectory"] = project.SubDirectory;
+
+ Json::Value& installationTypes = jsonProject["installationTypes"] =
+ Json::Value(Json::arrayValue);
+ for (auto& installationType : project.InstallationTypes) {
+ installationTypes.append(installationType->Name);
+ }
+
+ Json::Value& components = jsonProject["components"] =
+ Json::Value(Json::arrayValue);
+ for (auto& component : project.Components) {
+ components.append(component->Name);
+ }
+
+ projects.append(jsonProject);
+ }
+
+ Json::Value& installationTypes = root["installationTypes"] =
+ Json::Value(Json::objectValue);
+ for (auto& installationType : this->Parent->InstallationTypes) {
+ Json::Value& jsonInstallationType =
+ installationTypes[installationType.first] =
+ Json::Value(Json::objectValue);
+
+ jsonInstallationType["name"] = installationType.second.Name;
+ jsonInstallationType["displayName"] = installationType.second.DisplayName;
+ jsonInstallationType["index"] = installationType.second.Index;
+ }
+
+ Json::Value& components = root["components"] =
+ Json::Value(Json::objectValue);
+ for (auto& component : this->Parent->Components) {
+ Json::Value& jsonComponent = components[component.first] =
+ Json::Value(Json::objectValue);
+
+ jsonComponent["name"] = component.second.Name;
+ jsonComponent["displayName"] = component.second.DisplayName;
+ if (component.second.Group) {
+ jsonComponent["group"] = component.second.Group->Name;
+ }
+ jsonComponent["isRequired"] = component.second.IsRequired;
+ jsonComponent["isHidden"] = component.second.IsHidden;
+ jsonComponent["isDisabledByDefault"] =
+ component.second.IsDisabledByDefault;
+ jsonComponent["isDownloaded"] = component.second.IsDownloaded;
+ jsonComponent["description"] = component.second.Description;
+ jsonComponent["archiveFile"] = component.second.ArchiveFile;
+
+ Json::Value& cmpInstallationTypes = jsonComponent["installationTypes"] =
+ Json::Value(Json::arrayValue);
+ for (auto& installationType : component.second.InstallationTypes) {
+ cmpInstallationTypes.append(installationType->Name);
+ }
+
+ Json::Value& dependencies = jsonComponent["dependencies"] =
+ Json::Value(Json::arrayValue);
+ for (auto& dep : component.second.Dependencies) {
+ dependencies.append(dep->Name);
+ }
+ }
+
+ Json::Value& groups = root["componentGroups"] =
+ Json::Value(Json::objectValue);
+ for (auto& group : this->Parent->ComponentGroups) {
+ Json::Value& jsonGroup = groups[group.first] =
+ Json::Value(Json::objectValue);
+
+ jsonGroup["name"] = group.second.Name;
+ jsonGroup["displayName"] = group.second.DisplayName;
+ jsonGroup["description"] = group.second.Description;
+ jsonGroup["isBold"] = group.second.IsBold;
+ jsonGroup["isExpandedByDefault"] = group.second.IsExpandedByDefault;
+ if (group.second.ParentGroup) {
+ jsonGroup["parentGroup"] = group.second.ParentGroup->Name;
+ }
+
+ Json::Value& subgroups = jsonGroup["subgroups"] =
+ Json::Value(Json::arrayValue);
+ for (auto& subgroup : group.second.Subgroups) {
+ subgroups.append(subgroup->Name);
+ }
+
+ Json::Value& groupComponents = jsonGroup["components"] =
+ Json::Value(Json::arrayValue);
+ for (auto& component : group.second.Components) {
+ groupComponents.append(component->Name);
+ }
+ }
+
+ return 1;
+}
diff --git a/Source/CPack/cmCPackExternalGenerator.h b/Source/CPack/cmCPackExternalGenerator.h
new file mode 100644
index 000000000..176d6a9d9
--- /dev/null
+++ b/Source/CPack/cmCPackExternalGenerator.h
@@ -0,0 +1,89 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmCPackExternalGenerator_h
+#define cmCPackExternalGenerator_h
+
+#include "cmCPackGenerator.h"
+#include "cm_sys_stat.h"
+
+#include <memory>
+#include <string>
+
+class cmGlobalGenerator;
+namespace Json {
+class Value;
+}
+
+/** \class cmCPackExternalGenerator
+ * \brief A generator for CPack External packaging tools
+ */
+class cmCPackExternalGenerator : public cmCPackGenerator
+{
+public:
+ cmCPackTypeMacro(cmCPackExternalGenerator, cmCPackGenerator);
+
+ const char* GetOutputExtension() override { return ".json"; }
+
+protected:
+ int InitializeInternal() override;
+
+ int PackageFiles() override;
+
+ bool SupportsComponentInstallation() const override;
+
+ int InstallProjectViaInstallCommands(
+ bool setDestDir, const std::string& tempInstallDirectory) override;
+ int InstallProjectViaInstallScript(
+ bool setDestDir, const std::string& tempInstallDirectory) override;
+ int InstallProjectViaInstalledDirectories(
+ bool setDestDir, const std::string& tempInstallDirectory,
+ const mode_t* default_dir_mode) override;
+
+ int RunPreinstallTarget(const std::string& installProjectName,
+ const std::string& installDirectory,
+ cmGlobalGenerator* globalGenerator,
+ const std::string& buildConfig) override;
+ int InstallCMakeProject(bool setDestDir, const std::string& installDirectory,
+ const std::string& baseTempInstallDirectory,
+ const mode_t* default_dir_mode,
+ const std::string& component, bool componentInstall,
+ const std::string& installSubDirectory,
+ const std::string& buildConfig,
+ std::string& absoluteDestFiles) override;
+
+private:
+ bool StagingEnabled() const;
+
+ class cmCPackExternalVersionGenerator
+ {
+ public:
+ cmCPackExternalVersionGenerator(cmCPackExternalGenerator* parent);
+
+ virtual ~cmCPackExternalVersionGenerator() = default;
+
+ virtual int WriteToJSON(Json::Value& root);
+
+ protected:
+ virtual int GetVersionMajor() = 0;
+ virtual int GetVersionMinor() = 0;
+
+ int WriteVersion(Json::Value& root);
+
+ cmCPackExternalGenerator* Parent;
+ };
+
+ class cmCPackExternalVersion1Generator
+ : public cmCPackExternalVersionGenerator
+ {
+ public:
+ using cmCPackExternalVersionGenerator::cmCPackExternalVersionGenerator;
+
+ protected:
+ int GetVersionMajor() override { return 1; }
+ int GetVersionMinor() override { return 0; }
+ };
+
+ std::unique_ptr<cmCPackExternalVersionGenerator> Generator;
+};
+
+#endif
diff --git a/Source/CPack/cmCPackFreeBSDGenerator.cxx b/Source/CPack/cmCPackFreeBSDGenerator.cxx
new file mode 100644
index 000000000..9fdafa47b
--- /dev/null
+++ b/Source/CPack/cmCPackFreeBSDGenerator.cxx
@@ -0,0 +1,345 @@
+/* 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>
+#include <utility>
+
+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() = default;
+
+// 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 (char c : v.value) {
+ 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(std::string k)
+ : key(std::move(k))
+ {
+ }
+
+ virtual ~ManifestKey() = default;
+
+ // 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, std::string v)
+ : ManifestKey(k)
+ , value(std::move(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 (std::string const& e : v) {
+ (*this) << e;
+ }
+ return *this;
+ }
+
+ void write_value(cmGeneratedFileStream& s) const override
+ {
+ bool with_comma = false;
+
+ s << '[';
+ for (std::string const& elem : value) {
+ s << (with_comma ? ',' : ' ');
+ s << EscapeQuotes(elem);
+ 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 (std::string const& elem : value) {
+ s << " \"" << elem << R"(": {"origin": ")" << elem << "\"},\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();
+ }
+ 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.empty()) {
+ 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.empty()) {
+ 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;
+ return stat(filename.c_str(), &statbuf) < 0 ||
+ (statbuf.st_mode & S_IFMT) != S_IFREG;
+}
+
+// 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)
+{
+ s << "\"files\": {\n";
+ for (std::string const& file : files) {
+ s << " \"/" << cmSystemTools::RelativePath(toplevel, file) << "\": \""
+ << "<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("Internal/CPack/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);
+ 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::CollapseFullPath("../", toplevel);
+ pkg_create_from_manifest(output_dir.c_str(), ::TXZ, toplevel.c_str(),
+ manifestname.c_str(), nullptr);
+
+ std::string broken_suffix = std::string("-") +
+ var_lookup("CPACK_TOPLEVEL_TAG") + std::string(GetOutputExtension());
+ for (std::string& name : packageFileNames) {
+ cmCPackLogger(cmCPackLog::LOG_DEBUG, "Packagefile " << name << std::endl);
+ if (has_suffix(name, broken_suffix)) {
+ name.replace(name.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/cmCPackNuGetGenerator.cxx b/Source/CPack/cmCPackNuGetGenerator.cxx
new file mode 100644
index 000000000..76f06992b
--- /dev/null
+++ b/Source/CPack/cmCPackNuGetGenerator.cxx
@@ -0,0 +1,141 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmCPackNuGetGenerator.h"
+
+#include "cmAlgorithms.h"
+#include "cmCPackComponentGroup.h"
+#include "cmCPackLog.h"
+#include "cmSystemTools.h"
+
+#include <algorithm>
+#include <iterator>
+#include <map>
+#include <ostream>
+#include <string>
+#include <utility>
+#include <vector>
+
+bool cmCPackNuGetGenerator::SupportsComponentInstallation() const
+{
+ return IsOn("CPACK_NUGET_COMPONENT_INSTALL");
+}
+
+int cmCPackNuGetGenerator::PackageFiles()
+{
+ cmCPackLogger(cmCPackLog::LOG_DEBUG, "Toplevel: " << toplevel << std::endl);
+
+ /* Reset package file name list it will be populated after the
+ * `CPackNuGet.cmake` run */
+ packageFileNames.clear();
+
+ /* Are we in the component packaging case */
+ if (WantsComponentInstallation()) {
+ if (componentPackageMethod == ONE_PACKAGE) {
+ // CASE 1 : COMPONENT ALL-IN-ONE package
+ // Meaning that all per-component pre-installed files
+ // goes into the single package.
+ this->SetOption("CPACK_NUGET_ALL_IN_ONE", "TRUE");
+ SetupGroupComponentVariables(true);
+ } else {
+ // 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.
+ SetupGroupComponentVariables(componentPackageMethod ==
+ ONE_PACKAGE_PER_COMPONENT);
+ }
+ } else {
+ // CASE 3 : NON COMPONENT package.
+ this->SetOption("CPACK_NUGET_ORDINAL_MONOLITIC", "TRUE");
+ }
+
+ auto retval = this->ReadListFile("Internal/CPack/CPackNuGet.cmake");
+ if (retval) {
+ AddGeneratedPackageNames();
+ } else {
+ cmCPackLogger(cmCPackLog::LOG_ERROR,
+ "Error while execution CPackNuGet.cmake" << std::endl);
+ }
+
+ return retval;
+}
+
+void cmCPackNuGetGenerator::SetupGroupComponentVariables(bool ignoreGroup)
+{
+ // The default behavior is to have one package by component group
+ // unless CPACK_COMPONENTS_IGNORE_GROUP is specified.
+ if (!ignoreGroup) {
+ std::vector<std::string> groups;
+ for (auto const& compG : this->ComponentGroups) {
+ cmCPackLogger(cmCPackLog::LOG_VERBOSE,
+ "Packaging component group: " << compG.first << std::endl);
+ groups.push_back(compG.first);
+ auto compGUp =
+ cmSystemTools::UpperCase(cmSystemTools::MakeCidentifier(compG.first));
+
+ // Collect components for this group
+ std::vector<std::string> components;
+ std::transform(begin(compG.second.Components),
+ end(compG.second.Components),
+ std::back_inserter(components),
+ [](cmCPackComponent const* comp) { return comp->Name; });
+ this->SetOption("CPACK_NUGET_" + compGUp + "_GROUP_COMPONENTS",
+ cmJoin(components, ";").c_str());
+ }
+ if (!groups.empty()) {
+ this->SetOption("CPACK_NUGET_GROUPS", cmJoin(groups, ";").c_str());
+ }
+
+ // Handle Orphan components (components not belonging to any groups)
+ std::vector<std::string> components;
+ for (auto const& comp : this->Components) {
+ // Does the component belong to a group?
+ if (comp.second.Group == nullptr) {
+ cmCPackLogger(
+ cmCPackLog::LOG_VERBOSE,
+ "Component <"
+ << comp.second.Name
+ << "> does not belong to any group, package it separately."
+ << std::endl);
+ components.push_back(comp.first);
+ }
+ }
+ if (!components.empty()) {
+ this->SetOption("CPACK_NUGET_COMPONENTS",
+ cmJoin(components, ";").c_str());
+ }
+
+ } else {
+ std::vector<std::string> components;
+ components.reserve(this->Components.size());
+ std::transform(begin(this->Components), end(this->Components),
+ std::back_inserter(components),
+ [](std::pair<std::string, cmCPackComponent> const& comp) {
+ return comp.first;
+ });
+ this->SetOption("CPACK_NUGET_COMPONENTS", cmJoin(components, ";").c_str());
+ }
+}
+
+void cmCPackNuGetGenerator::AddGeneratedPackageNames()
+{
+ const char* const files_list = this->GetOption("GEN_CPACK_OUTPUT_FILES");
+ if (!files_list) {
+ cmCPackLogger(
+ cmCPackLog::LOG_ERROR,
+ "Error while execution CPackNuGet.cmake: No NuGet package has generated"
+ << std::endl);
+ return;
+ }
+ // add the generated packages to package file names list
+ std::string fileNames{ files_list };
+ const char sep = ';';
+ std::string::size_type pos1 = 0;
+ std::string::size_type pos2 = fileNames.find(sep, pos1 + 1);
+ while (pos2 != std::string::npos) {
+ packageFileNames.push_back(fileNames.substr(pos1, pos2 - pos1));
+ pos1 = pos2 + 1;
+ pos2 = fileNames.find(sep, pos1 + 1);
+ }
+ packageFileNames.push_back(fileNames.substr(pos1, pos2 - pos1));
+}
diff --git a/Source/CPack/cmCPackNuGetGenerator.h b/Source/CPack/cmCPackNuGetGenerator.h
new file mode 100644
index 000000000..a59db2d04
--- /dev/null
+++ b/Source/CPack/cmCPackNuGetGenerator.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 cmCPackNuGetGenerator_h
+#define cmCPackNuGetGenerator_h
+
+#include "cmCPackGenerator.h"
+
+/** \class cmCPackNuGetGenerator
+ * \brief A generator for RPM packages
+ */
+class cmCPackNuGetGenerator : public cmCPackGenerator
+{
+public:
+ cmCPackTypeMacro(cmCPackNuGetGenerator, cmCPackGenerator);
+
+ // NOTE In fact, it is possible to have NuGet not only for Windows...
+ // https://docs.microsoft.com/en-us/nuget/install-nuget-client-tools
+ static bool CanGenerate() { return true; }
+
+protected:
+ bool SupportsComponentInstallation() const override;
+ int PackageFiles() override;
+
+ const char* GetOutputExtension() override { return ".nupkg"; }
+ bool SupportsAbsoluteDestination() const override { return false; }
+ /**
+ * The method used to prepare variables when component
+ * install is used.
+ */
+ void SetupGroupComponentVariables(bool ignoreGroup);
+ /**
+ * Populate \c packageFileNames vector of built packages.
+ */
+ void AddGeneratedPackageNames();
+};
+
+#endif
diff --git a/Source/Checks/Curses.cmake b/Source/Checks/Curses.cmake
new file mode 100644
index 000000000..2942b666a
--- /dev/null
+++ b/Source/Checks/Curses.cmake
@@ -0,0 +1,41 @@
+message(STATUS "Checking for curses support")
+
+# Try compiling a simple project using curses.
+# Pass in any cache entries that the user may have set.
+set(CMakeCheckCurses_ARGS "")
+foreach(v
+ CURSES_INCLUDE_PATH
+ CURSES_CURSES_LIBRARY
+ CURSES_NCURSES_LIBRARY
+ CURSES_EXTRA_LIBRARY
+ CURSES_FORM_LIBRARY
+ )
+ if(${v})
+ list(APPEND CMakeCheckCurses_ARGS -D${v}=${${v}})
+ endif()
+endforeach()
+file(REMOVE_RECURSE "${CMake_BINARY_DIR}/Source/Checks/Curses-build")
+try_compile(CMakeCheckCurses_COMPILED
+ ${CMake_BINARY_DIR}/Source/Checks/Curses-build
+ ${CMake_SOURCE_DIR}/Source/Checks/Curses
+ CheckCurses # project name
+ CheckCurses # target name
+ CMAKE_FLAGS
+ "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS}"
+ ${CMakeCheckCurses_ARGS}
+ OUTPUT_VARIABLE CMakeCheckCurses_OUTPUT
+ )
+
+# Convert result from cache entry to normal variable.
+set(CMakeCheckCurses_COMPILED "${CMakeCheckCurses_COMPILED}")
+unset(CMakeCheckCurses_COMPILED CACHE)
+
+if(CMakeCheckCurses_COMPILED)
+ message(STATUS "Checking for curses support - Success")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+ "Checking for curses support passed with the following output:\n${CMakeCheckCurses_OUTPUT}\n\n")
+else()
+ message(STATUS "Checking for curses support - Failed")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+ "Checking for curses support failed with the following output:\n${CMakeCheckCurses_OUTPUT}\n\n")
+endif()
diff --git a/Source/Checks/Curses/CMakeLists.txt b/Source/Checks/Curses/CMakeLists.txt
new file mode 100644
index 000000000..17318a33b
--- /dev/null
+++ b/Source/Checks/Curses/CMakeLists.txt
@@ -0,0 +1,25 @@
+cmake_minimum_required(VERSION 3.1)
+if(POLICY CMP0060)
+ cmake_policy(SET CMP0060 NEW)
+endif()
+project(CheckCurses C)
+
+set(CURSES_NEED_NCURSES TRUE)
+find_package(Curses)
+if(NOT CURSES_FOUND)
+ return()
+endif()
+include_directories(${CURSES_INCLUDE_DIRS})
+add_executable(CheckCurses CheckCurses.c)
+target_link_libraries(CheckCurses ${CURSES_LIBRARIES})
+
+foreach(h
+ CURSES_HAVE_CURSES_H
+ CURSES_HAVE_NCURSES_H
+ CURSES_HAVE_NCURSES_NCURSES_H
+ CURSES_HAVE_NCURSES_CURSES_H
+ )
+ if(${h})
+ target_compile_definitions(CheckCurses PRIVATE ${h})
+ endif()
+endforeach()
diff --git a/Source/Checks/Curses/CheckCurses.c b/Source/Checks/Curses/CheckCurses.c
new file mode 100644
index 000000000..7d827e6bf
--- /dev/null
+++ b/Source/Checks/Curses/CheckCurses.c
@@ -0,0 +1,15 @@
+#if defined(CURSES_HAVE_NCURSES_H)
+# include <ncurses.h>
+#elif defined(CURSES_HAVE_NCURSES_NCURSES_H)
+# include <ncurses/ncurses.h>
+#elif defined(CURSES_HAVE_NCURSES_CURSES_H)
+# include <ncurses/curses.h>
+#else
+# include <curses.h>
+#endif
+
+int main()
+{
+ curses_version();
+ return 0;
+}
diff --git a/Source/Checks/cm_cxx14_check.cmake b/Source/Checks/cm_cxx14_check.cmake
new file mode 100644
index 000000000..38606b9c9
--- /dev/null
+++ b/Source/Checks/cm_cxx14_check.cmake
@@ -0,0 +1,36 @@
+set(CMake_CXX14_BROKEN 0)
+if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|PGI")
+ if(NOT CMAKE_CXX14_STANDARD_COMPILE_OPTION)
+ set(CMake_CXX14_WORKS 0)
+ endif()
+ if(NOT DEFINED CMake_CXX14_WORKS)
+ message(STATUS "Checking if compiler supports needed C++14 constructs")
+ try_compile(CMake_CXX14_WORKS
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_LIST_DIR}/cm_cxx14_check.cpp
+ CMAKE_FLAGS -DCMAKE_CXX_STANDARD=14
+ OUTPUT_VARIABLE OUTPUT
+ )
+ if(CMake_CXX14_WORKS AND "${OUTPUT}" MATCHES "error: no member named.*gets.*in the global namespace")
+ set_property(CACHE CMake_CXX14_WORKS PROPERTY VALUE 0)
+ endif()
+ if(CMake_CXX14_WORKS)
+ message(STATUS "Checking if compiler supports needed C++14 constructs - yes")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+ "Determining if compiler supports needed C++14 constructs passed with the following output:\n"
+ "${OUTPUT}\n"
+ "\n"
+ )
+ else()
+ message(STATUS "Checking if compiler supports needed C++14 constructs - no")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+ "Determining if compiler supports needed C++14 constructs failed with the following output:\n"
+ "${OUTPUT}\n"
+ "\n"
+ )
+ endif()
+ endif()
+ if(NOT CMake_CXX14_WORKS)
+ set(CMake_CXX14_BROKEN 1)
+ endif()
+endif()
diff --git a/Source/Checks/cm_cxx14_check.cpp b/Source/Checks/cm_cxx14_check.cpp
new file mode 100644
index 000000000..fff36c916
--- /dev/null
+++ b/Source/Checks/cm_cxx14_check.cpp
@@ -0,0 +1,15 @@
+#include <cstdio>
+#include <iterator>
+#include <memory>
+
+int main()
+{
+ int a[] = { 0, 1, 2 };
+ auto ai = std::cbegin(a);
+
+ int b[] = { 2, 1, 0 };
+ auto bi = std::cend(b);
+
+ std::unique_ptr<int> u(new int(0));
+ return *u + *ai + *(bi - 1);
+}
diff --git a/Source/Checks/cm_cxx17_check.cmake b/Source/Checks/cm_cxx17_check.cmake
new file mode 100644
index 000000000..4da2fd7ca
--- /dev/null
+++ b/Source/Checks/cm_cxx17_check.cmake
@@ -0,0 +1,36 @@
+set(CMake_CXX17_BROKEN 0)
+if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|PGI")
+ if(NOT CMAKE_CXX17_STANDARD_COMPILE_OPTION)
+ set(CMake_CXX17_WORKS 0)
+ endif()
+ if(NOT DEFINED CMake_CXX17_WORKS)
+ message(STATUS "Checking if compiler supports needed C++17 constructs")
+ try_compile(CMake_CXX17_WORKS
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_LIST_DIR}/cm_cxx17_check.cpp
+ CMAKE_FLAGS -DCMAKE_CXX_STANDARD=17
+ OUTPUT_VARIABLE OUTPUT
+ )
+ if(CMake_CXX17_WORKS AND "${OUTPUT}" MATCHES "error: no member named.*gets.*in the global namespace")
+ set_property(CACHE CMake_CXX17_WORKS PROPERTY VALUE 0)
+ endif()
+ if(CMake_CXX17_WORKS)
+ message(STATUS "Checking if compiler supports needed C++17 constructs - yes")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+ "Determining if compiler supports needed C++17 constructs passed with the following output:\n"
+ "${OUTPUT}\n"
+ "\n"
+ )
+ else()
+ message(STATUS "Checking if compiler supports needed C++17 constructs - no")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+ "Determining if compiler supports needed C++17 constructs failed with the following output:\n"
+ "${OUTPUT}\n"
+ "\n"
+ )
+ endif()
+ endif()
+ if(NOT CMake_CXX17_WORKS)
+ set(CMake_CXX17_BROKEN 1)
+ endif()
+endif()
diff --git a/Source/Checks/cm_cxx17_check.cpp b/Source/Checks/cm_cxx17_check.cpp
new file mode 100644
index 000000000..593d9b263
--- /dev/null
+++ b/Source/Checks/cm_cxx17_check.cpp
@@ -0,0 +1,31 @@
+#include <cstdio>
+#include <iterator>
+#include <memory>
+#include <unordered_map>
+
+#ifdef _MSC_VER
+# include <comdef.h>
+#endif
+
+int main()
+{
+ int a[] = { 0, 1, 2 };
+ auto ai = std::cbegin(a);
+
+ int b[] = { 2, 1, 0 };
+ auto bi = std::cend(b);
+
+ auto ci = std::size(a);
+
+ std::unique_ptr<int> u(new int(0));
+
+#ifdef _MSC_VER
+ // clang-cl has problems instantiating this constructor in C++17 mode
+ // error: indirection requires pointer operand ('const _GUID' invalid)
+ // return *_IID;
+ IUnknownPtr ptr{};
+ IDispatchPtr disp(ptr);
+#endif
+
+ return *u + *ai + *(bi - 1) + (3 - static_cast<int>(ci));
+}
diff --git a/Source/Modules/CheckCXXLinkerFlag.cmake b/Source/Modules/CheckCXXLinkerFlag.cmake
new file mode 100644
index 000000000..9ad2ad630
--- /dev/null
+++ b/Source/Modules/CheckCXXLinkerFlag.cmake
@@ -0,0 +1,25 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+include_guard(GLOBAL)
+include(CheckCXXSourceCompiles)
+include(CMakeCheckCompilerFlagCommonPatterns)
+
+function(check_cxx_linker_flag _flag _var)
+ set(CMAKE_REQUIRED_LIBRARIES "${_flag}")
+
+ # Normalize locale during test compilation.
+ set(_locale_vars LC_ALL LC_MESSAGES LANG)
+ foreach(v IN LISTS _locale_vars)
+ set(_locale_vars_saved_${v} "$ENV{${v}}")
+ set(ENV{${v}} C)
+ endforeach()
+ check_compiler_flag_common_patterns(_common_patterns)
+ check_cxx_source_compiles("int main() { return 0; }" ${_var}
+ ${_common_patterns}
+ )
+ foreach(v IN LISTS _locale_vars)
+ set(ENV{${v}} ${_locale_vars_saved_${v}})
+ endforeach()
+ set(${_var} "${${_var}}" PARENT_SCOPE)
+endfunction()
diff --git a/Source/Modules/FindLibUUID.cmake b/Source/Modules/FindLibUUID.cmake
new file mode 100644
index 000000000..17f11c1f5
--- /dev/null
+++ b/Source/Modules/FindLibUUID.cmake
@@ -0,0 +1,85 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindLibUUID
+------------
+
+Find LibUUID include directory and library.
+
+Imported Targets
+^^^^^^^^^^^^^^^^
+
+An :ref:`imported target <Imported targets>` named
+``LibUUID::LibUUID`` is provided if LibUUID has been found.
+
+Result Variables
+^^^^^^^^^^^^^^^^
+
+This module defines the following variables:
+
+``LibUUID_FOUND``
+ True if LibUUID was found, false otherwise.
+``LibUUID_INCLUDE_DIRS``
+ Include directories needed to include LibUUID headers.
+``LibUUID_LIBRARIES``
+ Libraries needed to link to LibUUID.
+
+Cache Variables
+^^^^^^^^^^^^^^^
+
+This module uses the following cache variables:
+
+``LibUUID_LIBRARY``
+ The location of the LibUUID library file.
+``LibUUID_INCLUDE_DIR``
+ The location of the LibUUID include directory containing ``uuid/uuid.h``.
+
+The cache variables should not be used by project code.
+They may be set by end users to point at LibUUID components.
+#]=======================================================================]
+
+#-----------------------------------------------------------------------------
+if(CYGWIN)
+ # Note: on current version of Cygwin, linking to libuuid.dll.a doesn't
+ # import the right symbols sometimes. Fix this by linking directly
+ # to the DLL that provides the symbols, instead.
+ set(old_suffixes ${CMAKE_FIND_LIBRARY_SUFFIXES})
+ set(CMAKE_FIND_LIBRARY_SUFFIXES .dll)
+ find_library(LibUUID_LIBRARY
+ NAMES cyguuid-1.dll
+ )
+ set(CMAKE_FIND_LIBRARY_SUFFIXES ${old_suffixes})
+else()
+ find_library(LibUUID_LIBRARY
+ NAMES uuid
+ )
+endif()
+mark_as_advanced(LibUUID_LIBRARY)
+
+find_path(LibUUID_INCLUDE_DIR
+ NAMES uuid/uuid.h
+ )
+mark_as_advanced(LibUUID_INCLUDE_DIR)
+
+#-----------------------------------------------------------------------------
+include(${CMAKE_CURRENT_LIST_DIR}/../../Modules/FindPackageHandleStandardArgs.cmake)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibUUID
+ FOUND_VAR LibUUID_FOUND
+ REQUIRED_VARS LibUUID_LIBRARY LibUUID_INCLUDE_DIR
+ )
+set(LIBUUID_FOUND ${LibUUID_FOUND})
+
+#-----------------------------------------------------------------------------
+# Provide documented result variables and targets.
+if(LibUUID_FOUND)
+ set(LibUUID_INCLUDE_DIRS ${LibUUID_INCLUDE_DIR})
+ set(LibUUID_LIBRARIES ${LibUUID_LIBRARY})
+ if(NOT TARGET LibUUID::LibUUID)
+ add_library(LibUUID::LibUUID UNKNOWN IMPORTED)
+ set_target_properties(LibUUID::LibUUID PROPERTIES
+ IMPORTED_LOCATION "${LibUUID_LIBRARY}"
+ INTERFACE_INCLUDE_DIRECTORIES "${LibUUID_INCLUDE_DIRS}"
+ )
+ endif()
+endif()
diff --git a/Source/Modules/OverrideC.cmake b/Source/Modules/OverrideC.cmake
new file mode 100644
index 000000000..f8299adb0
--- /dev/null
+++ b/Source/Modules/OverrideC.cmake
@@ -0,0 +1,3 @@
+if("${CMAKE_SYSTEM_NAME};${CMAKE_C_COMPILER_ID}" STREQUAL "AIX;GNU")
+ string(APPEND CMAKE_C_FLAGS_INIT " -pthread")
+endif()
diff --git a/Source/Modules/OverrideCXX.cmake b/Source/Modules/OverrideCXX.cmake
new file mode 100644
index 000000000..13689e2c5
--- /dev/null
+++ b/Source/Modules/OverrideCXX.cmake
@@ -0,0 +1,3 @@
+if("${CMAKE_SYSTEM_NAME};${CMAKE_CXX_COMPILER_ID}" STREQUAL "AIX;GNU")
+ string(APPEND CMAKE_CXX_FLAGS_INIT " -pthread")
+endif()
diff --git a/Source/cmAddCompileDefinitionsCommand.cxx b/Source/cmAddCompileDefinitionsCommand.cxx
new file mode 100644
index 000000000..04748192a
--- /dev/null
+++ b/Source/cmAddCompileDefinitionsCommand.cxx
@@ -0,0 +1,20 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmAddCompileDefinitionsCommand.h"
+
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
+bool cmAddCompileDefinitionsCommand::InitialPass(
+ std::vector<std::string> const& args, cmExecutionStatus&)
+{
+ if (args.empty()) {
+ return true;
+ }
+
+ for (std::string const& i : args) {
+ this->Makefile->AddCompileDefinition(i);
+ }
+ return true;
+}
diff --git a/Source/cmAddCompileDefinitionsCommand.h b/Source/cmAddCompileDefinitionsCommand.h
new file mode 100644
index 000000000..e985dca8f
--- /dev/null
+++ b/Source/cmAddCompileDefinitionsCommand.h
@@ -0,0 +1,31 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmAddCompileDefinitionsCommand_h
+#define cmAddCompileDefinitionsCommand_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+#include "cmCommand.h"
+
+class cmExecutionStatus;
+
+class cmAddCompileDefinitionsCommand : public cmCommand
+{
+public:
+ /**
+ * This is a virtual constructor for the command.
+ */
+ cmCommand* Clone() override { return new cmAddCompileDefinitionsCommand; }
+
+ /**
+ * 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/cmAddLinkOptionsCommand.cxx b/Source/cmAddLinkOptionsCommand.cxx
new file mode 100644
index 000000000..10ebd1284
--- /dev/null
+++ b/Source/cmAddLinkOptionsCommand.cxx
@@ -0,0 +1,20 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmAddLinkOptionsCommand.h"
+
+#include "cmMakefile.h"
+
+class cmExecutionStatus;
+
+bool cmAddLinkOptionsCommand::InitialPass(std::vector<std::string> const& args,
+ cmExecutionStatus&)
+{
+ if (args.empty()) {
+ return true;
+ }
+
+ for (std::string const& i : args) {
+ this->Makefile->AddLinkOption(i);
+ }
+ return true;
+}
diff --git a/Source/cmAddLinkOptionsCommand.h b/Source/cmAddLinkOptionsCommand.h
new file mode 100644
index 000000000..30fff0058
--- /dev/null
+++ b/Source/cmAddLinkOptionsCommand.h
@@ -0,0 +1,31 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmAddLinkOptionsCommand_h
+#define cmAddLinkOptionsCommand_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+#include "cmCommand.h"
+
+class cmExecutionStatus;
+
+class cmAddLinkOptionsCommand : public cmCommand
+{
+public:
+ /**
+ * This is a virtual constructor for the command.
+ */
+ cmCommand* Clone() override { return new cmAddLinkOptionsCommand; }
+
+ /**
+ * 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/cmAffinity.cxx b/Source/cmAffinity.cxx
new file mode 100644
index 000000000..09b029866
--- /dev/null
+++ b/Source/cmAffinity.cxx
@@ -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. */
+#include "cmAffinity.h"
+
+#include "cm_uv.h"
+
+#ifndef CMAKE_USE_SYSTEM_LIBUV
+# ifdef _WIN32
+# define CM_HAVE_CPU_AFFINITY
+# include <windows.h>
+# elif defined(__linux__) || defined(__FreeBSD__)
+# define CM_HAVE_CPU_AFFINITY
+# include <pthread.h>
+# include <sched.h>
+// On some platforms CPU_ZERO needs memset but sched.h forgets string.h
+# include <string.h> // IWYU pragma: keep
+# if defined(__FreeBSD__)
+# include <pthread_np.h>
+# include <sys/cpuset.h>
+# include <sys/param.h>
+# endif
+# if defined(__linux__)
+typedef cpu_set_t cm_cpuset_t;
+# else
+typedef cpuset_t cm_cpuset_t;
+# endif
+# endif
+#endif
+
+namespace cmAffinity {
+
+std::set<size_t> GetProcessorsAvailable()
+{
+ std::set<size_t> processorsAvailable;
+#ifdef CM_HAVE_CPU_AFFINITY
+ int cpumask_size = uv_cpumask_size();
+ if (cpumask_size > 0) {
+# ifdef _WIN32
+ DWORD_PTR procmask;
+ DWORD_PTR sysmask;
+ if (GetProcessAffinityMask(GetCurrentProcess(), &procmask, &sysmask) !=
+ 0) {
+ for (int i = 0; i < cpumask_size; ++i) {
+ if (procmask & (((DWORD_PTR)1) << i)) {
+ processorsAvailable.insert(i);
+ }
+ }
+ }
+# else
+ cm_cpuset_t cpuset;
+ CPU_ZERO(&cpuset); // NOLINT(clang-tidy)
+ if (pthread_getaffinity_np(pthread_self(), sizeof(cpuset), &cpuset) == 0) {
+ for (int i = 0; i < cpumask_size; ++i) {
+ if (CPU_ISSET(i, &cpuset)) {
+ processorsAvailable.insert(i);
+ }
+ }
+ }
+# endif
+ }
+#endif
+ return processorsAvailable;
+}
+}
diff --git a/Source/cmAffinity.h b/Source/cmAffinity.h
new file mode 100644
index 000000000..3775bae40
--- /dev/null
+++ b/Source/cmAffinity.h
@@ -0,0 +1,12 @@
+/* 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 <cstddef>
+#include <set>
+
+namespace cmAffinity {
+
+std::set<size_t> GetProcessorsAvailable();
+}
diff --git a/Source/cmArgumentParser.cxx b/Source/cmArgumentParser.cxx
new file mode 100644
index 000000000..751d117f4
--- /dev/null
+++ b/Source/cmArgumentParser.cxx
@@ -0,0 +1,93 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmArgumentParser.h"
+
+#include <algorithm>
+#include <type_traits>
+
+namespace ArgumentParser {
+
+auto ActionMap::Emplace(cm::string_view name, Action action)
+ -> std::pair<iterator, bool>
+{
+ auto const it =
+ std::lower_bound(this->begin(), this->end(), name,
+ [](value_type const& elem, cm::string_view const& k) {
+ return elem.first < k;
+ });
+ return (it != this->end() && it->first == name)
+ ? std::make_pair(it, false)
+ : std::make_pair(this->emplace(it, name, std::move(action)), true);
+}
+
+auto ActionMap::Find(cm::string_view name) const -> const_iterator
+{
+ auto const it =
+ std::lower_bound(this->begin(), this->end(), name,
+ [](value_type const& elem, cm::string_view const& k) {
+ return elem.first < k;
+ });
+ return (it != this->end() && it->first == name) ? it : this->end();
+}
+
+void Instance::Bind(bool& val)
+{
+ val = true;
+ this->CurrentString = nullptr;
+ this->CurrentList = nullptr;
+ this->ExpectValue = false;
+}
+
+void Instance::Bind(std::string& val)
+{
+ this->CurrentString = &val;
+ this->CurrentList = nullptr;
+ this->ExpectValue = true;
+}
+
+void Instance::Bind(StringList& val)
+{
+ this->CurrentString = nullptr;
+ this->CurrentList = &val;
+ this->ExpectValue = true;
+}
+
+void Instance::Bind(MultiStringList& val)
+{
+ this->CurrentString = nullptr;
+ this->CurrentList = (static_cast<void>(val.emplace_back()), &val.back());
+ this->ExpectValue = false;
+}
+
+void Instance::Consume(cm::string_view arg, void* result,
+ std::vector<std::string>* unparsedArguments,
+ std::vector<std::string>* keywordsMissingValue)
+{
+ auto const it = this->Bindings.Find(arg);
+ if (it != this->Bindings.end()) {
+ it->second(*this, result);
+ if (this->ExpectValue && keywordsMissingValue != nullptr) {
+ keywordsMissingValue->emplace_back(arg);
+ }
+ return;
+ }
+
+ if (this->CurrentString != nullptr) {
+ this->CurrentString->assign(std::string(arg));
+ this->CurrentString = nullptr;
+ this->CurrentList = nullptr;
+ } else if (this->CurrentList != nullptr) {
+ this->CurrentList->emplace_back(arg);
+ } else if (unparsedArguments != nullptr) {
+ unparsedArguments->emplace_back(arg);
+ }
+
+ if (this->ExpectValue) {
+ if (keywordsMissingValue != nullptr) {
+ keywordsMissingValue->pop_back();
+ }
+ this->ExpectValue = false;
+ }
+}
+
+} // namespace ArgumentParser
diff --git a/Source/cmArgumentParser.h b/Source/cmArgumentParser.h
new file mode 100644
index 000000000..6cfe94633
--- /dev/null
+++ b/Source/cmArgumentParser.h
@@ -0,0 +1,143 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmArgumentParser_h
+#define cmArgumentParser_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cm_static_string_view.hxx"
+#include "cm_string_view.hxx"
+
+#include <cassert>
+#include <functional>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace ArgumentParser {
+
+using StringList = std::vector<std::string>;
+using MultiStringList = std::vector<StringList>;
+
+class Instance;
+using Action = std::function<void(Instance&, void*)>;
+
+// using ActionMap = cm::flat_map<cm::string_view, Action>;
+class ActionMap : public std::vector<std::pair<cm::string_view, Action>>
+{
+public:
+ std::pair<iterator, bool> Emplace(cm::string_view name, Action action);
+ const_iterator Find(cm::string_view name) const;
+};
+
+class Instance
+{
+public:
+ Instance(ActionMap const& bindings)
+ : Bindings(bindings)
+ {
+ }
+
+ void Bind(bool& val);
+ void Bind(std::string& val);
+ void Bind(StringList& val);
+ void Bind(MultiStringList& val);
+
+ void Consume(cm::string_view arg, void* result,
+ std::vector<std::string>* unparsedArguments,
+ std::vector<std::string>* keywordsMissingValue);
+
+private:
+ ActionMap const& Bindings;
+ std::string* CurrentString = nullptr;
+ StringList* CurrentList = nullptr;
+ bool ExpectValue = false;
+};
+
+} // namespace ArgumentParser
+
+template <typename Result>
+class cmArgumentParser
+{
+public:
+ // I *think* this function could be made `constexpr` when the code is
+ // compiled as C++20. This would allow building a parser at compile time.
+ template <typename T>
+ cmArgumentParser& Bind(cm::static_string_view name, T Result::*member)
+ {
+ bool const inserted =
+ this->Bindings
+ .Emplace(name,
+ [member](ArgumentParser::Instance& instance, void* result) {
+ instance.Bind(static_cast<Result*>(result)->*member);
+ })
+ .second;
+ assert(inserted), (void)inserted;
+ return *this;
+ }
+
+ template <typename Range>
+ void Parse(Result& result, Range const& args,
+ std::vector<std::string>* unparsedArguments = nullptr,
+ std::vector<std::string>* keywordsMissingValue = nullptr) const
+ {
+ ArgumentParser::Instance instance(this->Bindings);
+ for (cm::string_view arg : args) {
+ instance.Consume(arg, &result, unparsedArguments, keywordsMissingValue);
+ }
+ }
+
+ template <typename Range>
+ Result Parse(Range const& args,
+ std::vector<std::string>* unparsedArguments = nullptr,
+ std::vector<std::string>* keywordsMissingValue = nullptr) const
+ {
+ Result result;
+ this->Parse(result, args, unparsedArguments, keywordsMissingValue);
+ return result;
+ }
+
+private:
+ ArgumentParser::ActionMap Bindings;
+};
+
+template <>
+class cmArgumentParser<void>
+{
+public:
+ template <typename T>
+ cmArgumentParser& Bind(cm::static_string_view name, T& ref)
+ {
+ bool const inserted = this->Bind(cm::string_view(name), ref);
+ assert(inserted), (void)inserted;
+ return *this;
+ }
+
+ template <typename Range>
+ void Parse(Range const& args,
+ std::vector<std::string>* unparsedArguments = nullptr,
+ std::vector<std::string>* keywordsMissingValue = nullptr) const
+ {
+ ArgumentParser::Instance instance(this->Bindings);
+ for (cm::string_view arg : args) {
+ instance.Consume(arg, nullptr, unparsedArguments, keywordsMissingValue);
+ }
+ }
+
+protected:
+ template <typename T>
+ bool Bind(cm::string_view name, T& ref)
+ {
+ return this->Bindings
+ .Emplace(name,
+ [&ref](ArgumentParser::Instance& instance, void*) {
+ instance.Bind(ref);
+ })
+ .second;
+ }
+
+private:
+ ArgumentParser::ActionMap Bindings;
+};
+
+#endif
diff --git a/Source/cmConnection.cxx b/Source/cmConnection.cxx
new file mode 100644
index 000000000..166426bfc
--- /dev/null
+++ b/Source/cmConnection.cxx
@@ -0,0 +1,163 @@
+/* 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 = static_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 = static_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.get());
+ 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), 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() = default;
+
+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.get()) {
+ this->WriteStream->data = nullptr;
+ }
+
+ WriteStream.reset();
+
+ return true;
+}
diff --git a/Source/cmConnection.h b/Source/cmConnection.h
new file mode 100644
index 000000000..092b91302
--- /dev/null
+++ b/Source/cmConnection.h
@@ -0,0 +1,136 @@
+/* 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 "cmUVHandlePtr.h"
+#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
+{
+public:
+ cmConnection() = default;
+
+ cmConnection(cmConnection const&) = delete;
+ cmConnection& operator=(cmConnection const&) = delete;
+
+ 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);
+
+ 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:
+ cm::uv_stream_ptr WriteStream;
+
+ 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/cmDuration.cxx b/Source/cmDuration.cxx
new file mode 100644
index 000000000..8ca5d8d12
--- /dev/null
+++ b/Source/cmDuration.cxx
@@ -0,0 +1,27 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#define CMDURATION_CPP
+#include "cmDuration.h"
+
+template <typename T>
+T cmDurationTo(const cmDuration& duration)
+{
+ /* This works because the comparison operators for duration rely on
+ * std::common_type.
+ * So for example duration<int>::max() gets promoted to a duration<double>,
+ * which can then be safely compared.
+ */
+ if (duration >= std::chrono::duration<T>::max()) {
+ return std::chrono::duration<T>::max().count();
+ }
+ if (duration <= std::chrono::duration<T>::min()) {
+ return std::chrono::duration<T>::min().count();
+ }
+ // Ensure number of seconds by defining ratio<1>
+ return std::chrono::duration_cast<std::chrono::duration<T, std::ratio<1>>>(
+ duration)
+ .count();
+}
+
+template int cmDurationTo<int>(const cmDuration&);
+template unsigned int cmDurationTo<unsigned int>(const cmDuration&);
diff --git a/Source/cmDuration.h b/Source/cmDuration.h
new file mode 100644
index 000000000..6df1455b4
--- /dev/null
+++ b/Source/cmDuration.h
@@ -0,0 +1,24 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#pragma once
+
+#include <chrono>
+#include <ratio>
+
+typedef std::chrono::duration<double, std::ratio<1>> cmDuration;
+
+/*
+ * This function will return number of seconds in the requested type T.
+ *
+ * A duration_cast from duration<double> to duration<T> will not yield what
+ * one might expect if the double representation does not fit into type T.
+ * This function aims to safely convert, by clamping the double value between
+ * the permissible valid values for T.
+ */
+template <typename T>
+T cmDurationTo(const cmDuration& duration);
+
+#ifndef CMDURATION_CPP
+extern template int cmDurationTo<int>(const cmDuration&);
+extern template unsigned int cmDurationTo<unsigned int>(const cmDuration&);
+#endif
diff --git a/Source/cmFSPermissions.cxx b/Source/cmFSPermissions.cxx
new file mode 100644
index 000000000..4015a5164
--- /dev/null
+++ b/Source/cmFSPermissions.cxx
@@ -0,0 +1,34 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmFSPermissions.h"
+
+bool cmFSPermissions::stringToModeT(std::string const& arg,
+ mode_t& permissions)
+{
+ if (arg == "OWNER_READ") {
+ permissions |= mode_owner_read;
+ } else if (arg == "OWNER_WRITE") {
+ permissions |= mode_owner_write;
+ } else if (arg == "OWNER_EXECUTE") {
+ permissions |= mode_owner_execute;
+ } else if (arg == "GROUP_READ") {
+ permissions |= mode_group_read;
+ } else if (arg == "GROUP_WRITE") {
+ permissions |= mode_group_write;
+ } else if (arg == "GROUP_EXECUTE") {
+ permissions |= mode_group_execute;
+ } else if (arg == "WORLD_READ") {
+ permissions |= mode_world_read;
+ } else if (arg == "WORLD_WRITE") {
+ permissions |= mode_world_write;
+ } else if (arg == "WORLD_EXECUTE") {
+ permissions |= mode_world_execute;
+ } else if (arg == "SETUID") {
+ permissions |= mode_setuid;
+ } else if (arg == "SETGID") {
+ permissions |= mode_setgid;
+ } else {
+ return false;
+ }
+ return true;
+}
diff --git a/Source/cmFSPermissions.h b/Source/cmFSPermissions.h
new file mode 100644
index 000000000..7a6e70866
--- /dev/null
+++ b/Source/cmFSPermissions.h
@@ -0,0 +1,45 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmFSPermissions_h
+#define cmFSPermissions_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cm_sys_stat.h"
+
+#include <string>
+
+namespace cmFSPermissions {
+
+// Table of permissions flags.
+#if defined(_WIN32) && !defined(__CYGWIN__)
+static const mode_t mode_owner_read = S_IREAD;
+static const mode_t mode_owner_write = S_IWRITE;
+static const mode_t mode_owner_execute = S_IEXEC;
+static const mode_t mode_group_read = 040;
+static const mode_t mode_group_write = 020;
+static const mode_t mode_group_execute = 010;
+static const mode_t mode_world_read = 04;
+static const mode_t mode_world_write = 02;
+static const mode_t mode_world_execute = 01;
+static const mode_t mode_setuid = 04000;
+static const mode_t mode_setgid = 02000;
+#else
+static const mode_t mode_owner_read = S_IRUSR;
+static const mode_t mode_owner_write = S_IWUSR;
+static const mode_t mode_owner_execute = S_IXUSR;
+static const mode_t mode_group_read = S_IRGRP;
+static const mode_t mode_group_write = S_IWGRP;
+static const mode_t mode_group_execute = S_IXGRP;
+static const mode_t mode_world_read = S_IROTH;
+static const mode_t mode_world_write = S_IWOTH;
+static const mode_t mode_world_execute = S_IXOTH;
+static const mode_t mode_setuid = S_ISUID;
+static const mode_t mode_setgid = S_ISGID;
+#endif
+
+bool stringToModeT(std::string const& arg, mode_t& permissions);
+
+} // ns
+
+#endif
diff --git a/Source/cmFileAPI.cxx b/Source/cmFileAPI.cxx
new file mode 100644
index 000000000..ba4266963
--- /dev/null
+++ b/Source/cmFileAPI.cxx
@@ -0,0 +1,835 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmFileAPI.h"
+
+#include "cmAlgorithms.h"
+#include "cmCryptoHash.h"
+#include "cmFileAPICMakeFiles.h"
+#include "cmFileAPICache.h"
+#include "cmFileAPICodemodel.h"
+#include "cmGlobalGenerator.h"
+#include "cmSystemTools.h"
+#include "cmTimestamp.h"
+#include "cmake.h"
+#include "cmsys/Directory.hxx"
+#include "cmsys/FStream.hxx"
+
+#include <algorithm>
+#include <cassert>
+#include <chrono>
+#include <ctime>
+#include <iomanip>
+#include <sstream>
+#include <utility>
+
+cmFileAPI::cmFileAPI(cmake* cm)
+ : CMakeInstance(cm)
+{
+ this->APIv1 =
+ this->CMakeInstance->GetHomeOutputDirectory() + "/.cmake/api/v1";
+
+ Json::CharReaderBuilder rbuilder;
+ rbuilder["collectComments"] = false;
+ rbuilder["failIfExtra"] = true;
+ rbuilder["rejectDupKeys"] = false;
+ rbuilder["strictRoot"] = true;
+ this->JsonReader =
+ std::unique_ptr<Json::CharReader>(rbuilder.newCharReader());
+
+ Json::StreamWriterBuilder wbuilder;
+ wbuilder["indentation"] = "\t";
+ this->JsonWriter =
+ std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
+}
+
+void cmFileAPI::ReadQueries()
+{
+ std::string const query_dir = this->APIv1 + "/query";
+ this->QueryExists = cmSystemTools::FileIsDirectory(query_dir);
+ if (!this->QueryExists) {
+ return;
+ }
+
+ // Load queries at the top level.
+ std::vector<std::string> queries = cmFileAPI::LoadDir(query_dir);
+
+ // Read the queries and save for later.
+ for (std::string& query : queries) {
+ if (cmHasLiteralPrefix(query, "client-")) {
+ this->ReadClient(query);
+ } else if (!cmFileAPI::ReadQuery(query, this->TopQuery.Known)) {
+ this->TopQuery.Unknown.push_back(std::move(query));
+ }
+ }
+}
+
+void cmFileAPI::WriteReplies()
+{
+ if (this->QueryExists) {
+ cmSystemTools::MakeDirectory(this->APIv1 + "/reply");
+ this->WriteJsonFile(this->BuildReplyIndex(), "index", ComputeSuffixTime);
+ }
+
+ this->RemoveOldReplyFiles();
+}
+
+std::vector<std::string> cmFileAPI::LoadDir(std::string const& dir)
+{
+ std::vector<std::string> files;
+ cmsys::Directory d;
+ d.Load(dir);
+ for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
+ std::string f = d.GetFile(i);
+ if (f != "." && f != "..") {
+ files.push_back(std::move(f));
+ }
+ }
+ std::sort(files.begin(), files.end());
+ return files;
+}
+
+void cmFileAPI::RemoveOldReplyFiles()
+{
+ std::string const reply_dir = this->APIv1 + "/reply";
+ std::vector<std::string> files = this->LoadDir(reply_dir);
+ for (std::string const& f : files) {
+ if (this->ReplyFiles.find(f) == this->ReplyFiles.end()) {
+ std::string file = reply_dir + "/" + f;
+ cmSystemTools::RemoveFile(file);
+ }
+ }
+}
+
+bool cmFileAPI::ReadJsonFile(std::string const& file, Json::Value& value,
+ std::string& error)
+{
+ std::vector<char> content;
+
+ cmsys::ifstream fin;
+ if (!cmSystemTools::FileIsDirectory(file)) {
+ fin.open(file.c_str(), std::ios::binary);
+ }
+ auto finEnd = fin.rdbuf()->pubseekoff(0, std::ios::end);
+ if (finEnd > 0) {
+ size_t finSize = finEnd;
+ try {
+ // Allocate a buffer to read the whole file.
+ content.resize(finSize);
+
+ // Now read the file from the beginning.
+ fin.seekg(0, std::ios::beg);
+ fin.read(content.data(), finSize);
+ } catch (...) {
+ fin.setstate(std::ios::failbit);
+ }
+ }
+ fin.close();
+ if (!fin) {
+ value = Json::Value();
+ error = "failed to read from file";
+ return false;
+ }
+
+ // Parse our buffer as json.
+ if (!this->JsonReader->parse(content.data(), content.data() + content.size(),
+ &value, &error)) {
+ value = Json::Value();
+ return false;
+ }
+
+ return true;
+}
+
+std::string cmFileAPI::WriteJsonFile(
+ Json::Value const& value, std::string const& prefix,
+ std::string (*computeSuffix)(std::string const&))
+{
+ std::string fileName;
+
+ // Write the json file with a temporary name.
+ std::string const& tmpFile = this->APIv1 + "/tmp.json";
+ cmsys::ofstream ftmp(tmpFile.c_str());
+ this->JsonWriter->write(value, &ftmp);
+ ftmp << "\n";
+ ftmp.close();
+ if (!ftmp) {
+ cmSystemTools::RemoveFile(tmpFile);
+ return fileName;
+ }
+
+ // Compute the final name for the file.
+ fileName = prefix + "-" + computeSuffix(tmpFile) + ".json";
+
+ // Create the destination.
+ std::string file = this->APIv1 + "/reply";
+ cmSystemTools::MakeDirectory(file);
+ file += "/";
+ file += fileName;
+
+ // If the final name already exists then assume it has proper content.
+ // Otherwise, atomically place the reply file at its final name
+ if (cmSystemTools::FileExists(file, true) ||
+ !cmSystemTools::RenameFile(tmpFile, file)) {
+ cmSystemTools::RemoveFile(tmpFile);
+ }
+
+ // Record this among files we have just written.
+ this->ReplyFiles.insert(fileName);
+
+ return fileName;
+}
+
+Json::Value cmFileAPI::MaybeJsonFile(Json::Value in, std::string const& prefix)
+{
+ Json::Value out;
+ if (in.isObject() || in.isArray()) {
+ out = Json::objectValue;
+ out["jsonFile"] = this->WriteJsonFile(in, prefix);
+ } else {
+ out = std::move(in);
+ }
+ return out;
+}
+
+std::string cmFileAPI::ComputeSuffixHash(std::string const& file)
+{
+ cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
+ std::string hash = hasher.HashFile(file);
+ hash.resize(20, '0');
+ return hash;
+}
+
+std::string cmFileAPI::ComputeSuffixTime(std::string const&)
+{
+ std::chrono::milliseconds ms =
+ std::chrono::duration_cast<std::chrono::milliseconds>(
+ std::chrono::system_clock::now().time_since_epoch());
+ std::chrono::seconds s =
+ std::chrono::duration_cast<std::chrono::seconds>(ms);
+
+ std::time_t ts = s.count();
+ std::size_t tms = ms.count() % 1000;
+
+ cmTimestamp cmts;
+ std::ostringstream ss;
+ ss << cmts.CreateTimestampFromTimeT(ts, "%Y-%m-%dT%H-%M-%S", true) << '-'
+ << std::setfill('0') << std::setw(4) << tms;
+ return ss.str();
+}
+
+bool cmFileAPI::ReadQuery(std::string const& query,
+ std::vector<Object>& objects)
+{
+ // Parse the "<kind>-" syntax.
+ std::string::size_type sep_pos = query.find('-');
+ if (sep_pos == std::string::npos) {
+ return false;
+ }
+ std::string kindName = query.substr(0, sep_pos);
+ std::string verStr = query.substr(sep_pos + 1);
+ if (kindName == ObjectKindName(ObjectKind::CodeModel)) {
+ Object o;
+ o.Kind = ObjectKind::CodeModel;
+ if (verStr == "v2") {
+ o.Version = 2;
+ } else {
+ return false;
+ }
+ objects.push_back(o);
+ return true;
+ }
+ if (kindName == ObjectKindName(ObjectKind::Cache)) {
+ Object o;
+ o.Kind = ObjectKind::Cache;
+ if (verStr == "v2") {
+ o.Version = 2;
+ } else {
+ return false;
+ }
+ objects.push_back(o);
+ return true;
+ }
+ if (kindName == ObjectKindName(ObjectKind::CMakeFiles)) {
+ Object o;
+ o.Kind = ObjectKind::CMakeFiles;
+ if (verStr == "v1") {
+ o.Version = 1;
+ } else {
+ return false;
+ }
+ objects.push_back(o);
+ return true;
+ }
+ if (kindName == ObjectKindName(ObjectKind::InternalTest)) {
+ Object o;
+ o.Kind = ObjectKind::InternalTest;
+ if (verStr == "v1") {
+ o.Version = 1;
+ } else if (verStr == "v2") {
+ o.Version = 2;
+ } else {
+ return false;
+ }
+ objects.push_back(o);
+ return true;
+ }
+ return false;
+}
+
+void cmFileAPI::ReadClient(std::string const& client)
+{
+ // Load queries for the client.
+ std::string clientDir = this->APIv1 + "/query/" + client;
+ std::vector<std::string> queries = this->LoadDir(clientDir);
+
+ // Read the queries and save for later.
+ ClientQuery& clientQuery = this->ClientQueries[client];
+ for (std::string& query : queries) {
+ if (query == "query.json") {
+ clientQuery.HaveQueryJson = true;
+ this->ReadClientQuery(client, clientQuery.QueryJson);
+ } else if (!this->ReadQuery(query, clientQuery.DirQuery.Known)) {
+ clientQuery.DirQuery.Unknown.push_back(std::move(query));
+ }
+ }
+}
+
+void cmFileAPI::ReadClientQuery(std::string const& client, ClientQueryJson& q)
+{
+ // Read the query.json file.
+ std::string queryFile = this->APIv1 + "/query/" + client + "/query.json";
+ Json::Value query;
+ if (!this->ReadJsonFile(queryFile, query, q.Error)) {
+ return;
+ }
+ if (!query.isObject()) {
+ q.Error = "query root is not an object";
+ return;
+ }
+
+ Json::Value const& clientValue = query["client"];
+ if (!clientValue.isNull()) {
+ q.ClientValue = clientValue;
+ }
+ q.RequestsValue = std::move(query["requests"]);
+ q.Requests = this->BuildClientRequests(q.RequestsValue);
+}
+
+Json::Value cmFileAPI::BuildReplyIndex()
+{
+ Json::Value index(Json::objectValue);
+
+ // Report information about this version of CMake.
+ index["cmake"] = this->BuildCMake();
+
+ // Reply to all queries that we loaded.
+ Json::Value& reply = index["reply"] = this->BuildReply(this->TopQuery);
+ for (auto const& client : this->ClientQueries) {
+ std::string const& clientName = client.first;
+ ClientQuery const& clientQuery = client.second;
+ reply[clientName] = this->BuildClientReply(clientQuery);
+ }
+
+ // Move our index of generated objects into its field.
+ Json::Value& objects = index["objects"] = Json::arrayValue;
+ for (auto& entry : this->ReplyIndexObjects) {
+ objects.append(std::move(entry.second)); // NOLINT(*)
+ }
+
+ return index;
+}
+
+Json::Value cmFileAPI::BuildCMake()
+{
+ Json::Value cmake = Json::objectValue;
+ cmake["version"] = this->CMakeInstance->ReportVersionJson();
+ Json::Value& cmake_paths = cmake["paths"] = Json::objectValue;
+ cmake_paths["cmake"] = cmSystemTools::GetCMakeCommand();
+ cmake_paths["ctest"] = cmSystemTools::GetCTestCommand();
+ cmake_paths["cpack"] = cmSystemTools::GetCPackCommand();
+ cmake_paths["root"] = cmSystemTools::GetCMakeRoot();
+ cmake["generator"] = this->CMakeInstance->GetGlobalGenerator()->GetJson();
+ return cmake;
+}
+
+Json::Value cmFileAPI::BuildReply(Query const& q)
+{
+ Json::Value reply = Json::objectValue;
+ for (Object const& o : q.Known) {
+ std::string const& name = ObjectName(o);
+ reply[name] = this->AddReplyIndexObject(o);
+ }
+
+ for (std::string const& name : q.Unknown) {
+ reply[name] = cmFileAPI::BuildReplyError("unknown query file");
+ }
+ return reply;
+}
+
+Json::Value cmFileAPI::BuildReplyError(std::string const& error)
+{
+ Json::Value e = Json::objectValue;
+ e["error"] = error;
+ return e;
+}
+
+Json::Value const& cmFileAPI::AddReplyIndexObject(Object const& o)
+{
+ Json::Value& indexEntry = this->ReplyIndexObjects[o];
+ if (!indexEntry.isNull()) {
+ // The reply object has already been generated.
+ return indexEntry;
+ }
+
+ // Generate this reply object.
+ Json::Value const& object = this->BuildObject(o);
+ assert(object.isObject());
+
+ // Populate this index entry.
+ indexEntry = Json::objectValue;
+ indexEntry["kind"] = object["kind"];
+ indexEntry["version"] = object["version"];
+ indexEntry["jsonFile"] = this->WriteJsonFile(object, ObjectName(o));
+ return indexEntry;
+}
+
+const char* cmFileAPI::ObjectKindName(ObjectKind kind)
+{
+ // Keep in sync with ObjectKind enum.
+ static const char* objectKindNames[] = {
+ "codemodel", //
+ "cache", //
+ "cmakeFiles", //
+ "__test" //
+ };
+ return objectKindNames[size_t(kind)];
+}
+
+std::string cmFileAPI::ObjectName(Object const& o)
+{
+ std::string name = ObjectKindName(o.Kind);
+ name += "-v";
+ name += std::to_string(o.Version);
+ return name;
+}
+
+Json::Value cmFileAPI::BuildVersion(unsigned int major, unsigned int minor)
+{
+ Json::Value version;
+ version["major"] = major;
+ version["minor"] = minor;
+ return version;
+}
+
+Json::Value cmFileAPI::BuildObject(Object const& object)
+{
+ Json::Value value;
+
+ switch (object.Kind) {
+ case ObjectKind::CodeModel:
+ value = this->BuildCodeModel(object);
+ break;
+ case ObjectKind::Cache:
+ value = this->BuildCache(object);
+ break;
+ case ObjectKind::CMakeFiles:
+ value = this->BuildCMakeFiles(object);
+ break;
+ case ObjectKind::InternalTest:
+ value = this->BuildInternalTest(object);
+ break;
+ }
+
+ return value;
+}
+
+cmFileAPI::ClientRequests cmFileAPI::BuildClientRequests(
+ Json::Value const& requests)
+{
+ ClientRequests result;
+ if (requests.isNull()) {
+ result.Error = "'requests' member missing";
+ return result;
+ }
+ if (!requests.isArray()) {
+ result.Error = "'requests' member is not an array";
+ return result;
+ }
+
+ result.reserve(requests.size());
+ for (Json::Value const& request : requests) {
+ result.emplace_back(this->BuildClientRequest(request));
+ }
+
+ return result;
+}
+
+cmFileAPI::ClientRequest cmFileAPI::BuildClientRequest(
+ Json::Value const& request)
+{
+ ClientRequest r;
+
+ if (!request.isObject()) {
+ r.Error = "request is not an object";
+ return r;
+ }
+
+ Json::Value const& kind = request["kind"];
+ if (kind.isNull()) {
+ r.Error = "'kind' member missing";
+ return r;
+ }
+ if (!kind.isString()) {
+ r.Error = "'kind' member is not a string";
+ return r;
+ }
+ std::string const& kindName = kind.asString();
+
+ if (kindName == this->ObjectKindName(ObjectKind::CodeModel)) {
+ r.Kind = ObjectKind::CodeModel;
+ } else if (kindName == this->ObjectKindName(ObjectKind::Cache)) {
+ r.Kind = ObjectKind::Cache;
+ } else if (kindName == this->ObjectKindName(ObjectKind::CMakeFiles)) {
+ r.Kind = ObjectKind::CMakeFiles;
+ } else if (kindName == this->ObjectKindName(ObjectKind::InternalTest)) {
+ r.Kind = ObjectKind::InternalTest;
+ } else {
+ r.Error = "unknown request kind '" + kindName + "'";
+ return r;
+ }
+
+ Json::Value const& version = request["version"];
+ if (version.isNull()) {
+ r.Error = "'version' member missing";
+ return r;
+ }
+ std::vector<RequestVersion> versions;
+ if (!cmFileAPI::ReadRequestVersions(version, versions, r.Error)) {
+ return r;
+ }
+
+ switch (r.Kind) {
+ case ObjectKind::CodeModel:
+ this->BuildClientRequestCodeModel(r, versions);
+ break;
+ case ObjectKind::Cache:
+ this->BuildClientRequestCache(r, versions);
+ break;
+ case ObjectKind::CMakeFiles:
+ this->BuildClientRequestCMakeFiles(r, versions);
+ break;
+ case ObjectKind::InternalTest:
+ this->BuildClientRequestInternalTest(r, versions);
+ break;
+ }
+
+ return r;
+}
+
+Json::Value cmFileAPI::BuildClientReply(ClientQuery const& q)
+{
+ Json::Value reply = this->BuildReply(q.DirQuery);
+
+ if (!q.HaveQueryJson) {
+ return reply;
+ }
+
+ Json::Value& reply_query_json = reply["query.json"];
+ ClientQueryJson const& qj = q.QueryJson;
+
+ if (!qj.Error.empty()) {
+ reply_query_json = this->BuildReplyError(qj.Error);
+ return reply;
+ }
+
+ if (!qj.ClientValue.isNull()) {
+ reply_query_json["client"] = qj.ClientValue;
+ }
+
+ if (!qj.RequestsValue.isNull()) {
+ reply_query_json["requests"] = qj.RequestsValue;
+ }
+
+ reply_query_json["responses"] = this->BuildClientReplyResponses(qj.Requests);
+
+ return reply;
+}
+
+Json::Value cmFileAPI::BuildClientReplyResponses(
+ ClientRequests const& requests)
+{
+ Json::Value responses;
+
+ if (!requests.Error.empty()) {
+ responses = this->BuildReplyError(requests.Error);
+ return responses;
+ }
+
+ responses = Json::arrayValue;
+ for (ClientRequest const& request : requests) {
+ responses.append(this->BuildClientReplyResponse(request));
+ }
+
+ return responses;
+}
+
+Json::Value cmFileAPI::BuildClientReplyResponse(ClientRequest const& request)
+{
+ Json::Value response;
+ if (!request.Error.empty()) {
+ response = this->BuildReplyError(request.Error);
+ return response;
+ }
+ response = this->AddReplyIndexObject(request);
+ return response;
+}
+
+bool cmFileAPI::ReadRequestVersions(Json::Value const& version,
+ std::vector<RequestVersion>& versions,
+ std::string& error)
+{
+ if (version.isArray()) {
+ for (Json::Value const& v : version) {
+ if (!ReadRequestVersion(v, /*inArray=*/true, versions, error)) {
+ return false;
+ }
+ }
+ } else {
+ if (!ReadRequestVersion(version, /*inArray=*/false, versions, error)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool cmFileAPI::ReadRequestVersion(Json::Value const& version, bool inArray,
+ std::vector<RequestVersion>& result,
+ std::string& error)
+{
+ if (version.isUInt()) {
+ RequestVersion v;
+ v.Major = version.asUInt();
+ result.push_back(v);
+ return true;
+ }
+
+ if (!version.isObject()) {
+ if (inArray) {
+ error = "'version' array entry is not a non-negative integer or object";
+ } else {
+ error =
+ "'version' member is not a non-negative integer, object, or array";
+ }
+ return false;
+ }
+
+ Json::Value const& major = version["major"];
+ if (major.isNull()) {
+ error = "'version' object 'major' member missing";
+ return false;
+ }
+ if (!major.isUInt()) {
+ error = "'version' object 'major' member is not a non-negative integer";
+ return false;
+ }
+
+ RequestVersion v;
+ v.Major = major.asUInt();
+
+ Json::Value const& minor = version["minor"];
+ if (minor.isUInt()) {
+ v.Minor = minor.asUInt();
+ } else if (!minor.isNull()) {
+ error = "'version' object 'minor' member is not a non-negative integer";
+ return false;
+ }
+
+ result.push_back(v);
+
+ return true;
+}
+
+std::string cmFileAPI::NoSupportedVersion(
+ std::vector<RequestVersion> const& versions)
+{
+ std::ostringstream msg;
+ msg << "no supported version specified";
+ if (!versions.empty()) {
+ msg << " among:";
+ for (RequestVersion const& v : versions) {
+ msg << " " << v.Major << "." << v.Minor;
+ }
+ }
+ return msg.str();
+}
+
+// The "codemodel" object kind.
+
+static unsigned int const CodeModelV2Minor = 0;
+
+void cmFileAPI::BuildClientRequestCodeModel(
+ ClientRequest& r, std::vector<RequestVersion> const& versions)
+{
+ // Select a known version from those requested.
+ for (RequestVersion const& v : versions) {
+ if ((v.Major == 2 && v.Minor <= CodeModelV2Minor)) {
+ r.Version = v.Major;
+ break;
+ }
+ }
+ if (!r.Version) {
+ r.Error = NoSupportedVersion(versions);
+ }
+}
+
+Json::Value cmFileAPI::BuildCodeModel(Object const& object)
+{
+ using namespace std::placeholders;
+ Json::Value codemodel = cmFileAPICodemodelDump(*this, object.Version);
+ codemodel["kind"] = this->ObjectKindName(object.Kind);
+
+ Json::Value& version = codemodel["version"];
+ if (object.Version == 2) {
+ version = BuildVersion(2, CodeModelV2Minor);
+ } else {
+ return codemodel; // should be unreachable
+ }
+
+ return codemodel;
+}
+
+// The "cache" object kind.
+
+static unsigned int const CacheV2Minor = 0;
+
+void cmFileAPI::BuildClientRequestCache(
+ ClientRequest& r, std::vector<RequestVersion> const& versions)
+{
+ // Select a known version from those requested.
+ for (RequestVersion const& v : versions) {
+ if ((v.Major == 2 && v.Minor <= CacheV2Minor)) {
+ r.Version = v.Major;
+ break;
+ }
+ }
+ if (!r.Version) {
+ r.Error = NoSupportedVersion(versions);
+ }
+}
+
+Json::Value cmFileAPI::BuildCache(Object const& object)
+{
+ using namespace std::placeholders;
+ Json::Value cache = cmFileAPICacheDump(*this, object.Version);
+ cache["kind"] = this->ObjectKindName(object.Kind);
+
+ Json::Value& version = cache["version"];
+ if (object.Version == 2) {
+ version = BuildVersion(2, CacheV2Minor);
+ } else {
+ return cache; // should be unreachable
+ }
+
+ return cache;
+}
+
+// The "cmakeFiles" object kind.
+
+static unsigned int const CMakeFilesV1Minor = 0;
+
+void cmFileAPI::BuildClientRequestCMakeFiles(
+ ClientRequest& r, std::vector<RequestVersion> const& versions)
+{
+ // Select a known version from those requested.
+ for (RequestVersion const& v : versions) {
+ if ((v.Major == 1 && v.Minor <= CMakeFilesV1Minor)) {
+ r.Version = v.Major;
+ break;
+ }
+ }
+ if (!r.Version) {
+ r.Error = NoSupportedVersion(versions);
+ }
+}
+
+Json::Value cmFileAPI::BuildCMakeFiles(Object const& object)
+{
+ using namespace std::placeholders;
+ Json::Value cmakeFiles = cmFileAPICMakeFilesDump(*this, object.Version);
+ cmakeFiles["kind"] = this->ObjectKindName(object.Kind);
+
+ Json::Value& version = cmakeFiles["version"];
+ if (object.Version == 1) {
+ version = BuildVersion(1, CMakeFilesV1Minor);
+ } else {
+ return cmakeFiles; // should be unreachable
+ }
+
+ return cmakeFiles;
+}
+
+// The "__test" object kind is for internal testing of CMake.
+
+static unsigned int const InternalTestV1Minor = 3;
+static unsigned int const InternalTestV2Minor = 0;
+
+void cmFileAPI::BuildClientRequestInternalTest(
+ ClientRequest& r, std::vector<RequestVersion> const& versions)
+{
+ // Select a known version from those requested.
+ for (RequestVersion const& v : versions) {
+ if ((v.Major == 1 && v.Minor <= InternalTestV1Minor) || //
+ (v.Major == 2 && v.Minor <= InternalTestV2Minor)) {
+ r.Version = v.Major;
+ break;
+ }
+ }
+ if (!r.Version) {
+ r.Error = NoSupportedVersion(versions);
+ }
+}
+
+Json::Value cmFileAPI::BuildInternalTest(Object const& object)
+{
+ Json::Value test = Json::objectValue;
+ test["kind"] = this->ObjectKindName(object.Kind);
+ Json::Value& version = test["version"];
+ if (object.Version == 2) {
+ version = BuildVersion(2, InternalTestV2Minor);
+ } else {
+ version = BuildVersion(1, InternalTestV1Minor);
+ }
+ return test;
+}
+
+Json::Value cmFileAPI::ReportCapabilities()
+{
+ Json::Value capabilities = Json::objectValue;
+ Json::Value& requests = capabilities["requests"] = Json::arrayValue;
+
+ {
+ Json::Value request = Json::objectValue;
+ request["kind"] = ObjectKindName(ObjectKind::CodeModel);
+ Json::Value& versions = request["version"] = Json::arrayValue;
+ versions.append(BuildVersion(2, CodeModelV2Minor));
+ requests.append(std::move(request)); // NOLINT(*)
+ }
+
+ {
+ Json::Value request = Json::objectValue;
+ request["kind"] = ObjectKindName(ObjectKind::Cache);
+ Json::Value& versions = request["version"] = Json::arrayValue;
+ versions.append(BuildVersion(2, CacheV2Minor));
+ requests.append(std::move(request)); // NOLINT(*)
+ }
+
+ {
+ Json::Value request = Json::objectValue;
+ request["kind"] = ObjectKindName(ObjectKind::CMakeFiles);
+ Json::Value& versions = request["version"] = Json::arrayValue;
+ versions.append(BuildVersion(1, CMakeFilesV1Minor));
+ requests.append(std::move(request)); // NOLINT(*)
+ }
+
+ return capabilities;
+}
diff --git a/Source/cmFileAPI.h b/Source/cmFileAPI.h
new file mode 100644
index 000000000..602efa8ed
--- /dev/null
+++ b/Source/cmFileAPI.h
@@ -0,0 +1,209 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmFileAPI_h
+#define cmFileAPI_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cm_jsoncpp_reader.h"
+#include "cm_jsoncpp_value.h"
+#include "cm_jsoncpp_writer.h"
+
+#include <map>
+#include <memory> // IWYU pragma: keep
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+class cmake;
+
+class cmFileAPI
+{
+public:
+ cmFileAPI(cmake* cm);
+
+ /** Read fileapi queries from disk. */
+ void ReadQueries();
+
+ /** Write fileapi replies to disk. */
+ void WriteReplies();
+
+ /** Get the "cmake" instance with which this was constructed. */
+ cmake* GetCMakeInstance() const { return this->CMakeInstance; }
+
+ /** Convert a JSON object or array into an object with a single
+ "jsonFile" member specifying a file named with the given prefix
+ and holding the original object. Other JSON types are unchanged. */
+ Json::Value MaybeJsonFile(Json::Value in, std::string const& prefix);
+
+ /** Report file-api capabilities for cmake -E capabilities. */
+ static Json::Value ReportCapabilities();
+
+private:
+ cmake* CMakeInstance;
+
+ /** The api/v1 directory location. */
+ std::string APIv1;
+
+ /** The set of files we have just written to the reply directory. */
+ std::unordered_set<std::string> ReplyFiles;
+
+ static std::vector<std::string> LoadDir(std::string const& dir);
+ void RemoveOldReplyFiles();
+
+ // Keep in sync with ObjectKindName.
+ enum class ObjectKind
+ {
+ CodeModel,
+ Cache,
+ CMakeFiles,
+ InternalTest
+ };
+
+ /** Identify one object kind and major version. */
+ struct Object
+ {
+ ObjectKind Kind;
+ unsigned long Version = 0;
+ friend bool operator<(Object const& l, Object const& r)
+ {
+ if (l.Kind != r.Kind) {
+ return l.Kind < r.Kind;
+ }
+ return l.Version < r.Version;
+ }
+ };
+
+ /** Represent content of a query directory. */
+ struct Query
+ {
+ /** Known object kind-version pairs. */
+ std::vector<Object> Known;
+ /** Unknown object kind names. */
+ std::vector<std::string> Unknown;
+ };
+
+ /** Represent one request in a client 'query.json'. */
+ struct ClientRequest : public Object
+ {
+ /** Empty if request is valid, else the error string. */
+ std::string Error;
+ };
+
+ /** Represent the "requests" in a client 'query.json'. */
+ struct ClientRequests : public std::vector<ClientRequest>
+ {
+ /** Empty if requests field is valid, else the error string. */
+ std::string Error;
+ };
+
+ /** Represent the content of a client query.json file. */
+ struct ClientQueryJson
+ {
+ /** The error string if parsing failed, else empty. */
+ std::string Error;
+
+ /** The 'query.json' object "client" member if it exists, else null. */
+ Json::Value ClientValue;
+
+ /** The 'query.json' object "requests" member if it exists, else null. */
+ Json::Value RequestsValue;
+
+ /** Requests extracted from 'query.json'. */
+ ClientRequests Requests;
+ };
+
+ /** Represent content of a client query directory. */
+ struct ClientQuery
+ {
+ /** The content of the client query directory except 'query.json'. */
+ Query DirQuery;
+
+ /** True if 'query.json' exists. */
+ bool HaveQueryJson = false;
+
+ /** The 'query.json' content. */
+ ClientQueryJson QueryJson;
+ };
+
+ /** Whether the top-level query directory exists at all. */
+ bool QueryExists = false;
+
+ /** The content of the top-level query directory. */
+ Query TopQuery;
+
+ /** The content of each "client-$client" query directory. */
+ std::map<std::string, ClientQuery> ClientQueries;
+
+ /** Reply index object generated for object kind/version.
+ This populates the "objects" field of the reply index. */
+ std::map<Object, Json::Value> ReplyIndexObjects;
+
+ std::unique_ptr<Json::CharReader> JsonReader;
+ std::unique_ptr<Json::StreamWriter> JsonWriter;
+
+ bool ReadJsonFile(std::string const& file, Json::Value& value,
+ std::string& error);
+
+ std::string WriteJsonFile(
+ Json::Value const& value, std::string const& prefix,
+ std::string (*computeSuffix)(std::string const&) = ComputeSuffixHash);
+ static std::string ComputeSuffixHash(std::string const&);
+ static std::string ComputeSuffixTime(std::string const&);
+
+ static bool ReadQuery(std::string const& query,
+ std::vector<Object>& objects);
+ void ReadClient(std::string const& client);
+ void ReadClientQuery(std::string const& client, ClientQueryJson& q);
+
+ Json::Value BuildReplyIndex();
+ Json::Value BuildCMake();
+ Json::Value BuildReply(Query const& q);
+ static Json::Value BuildReplyError(std::string const& error);
+ Json::Value const& AddReplyIndexObject(Object const& o);
+
+ static const char* ObjectKindName(ObjectKind kind);
+ static std::string ObjectName(Object const& o);
+
+ static Json::Value BuildVersion(unsigned int major, unsigned int minor);
+
+ Json::Value BuildObject(Object const& object);
+
+ ClientRequests BuildClientRequests(Json::Value const& requests);
+ ClientRequest BuildClientRequest(Json::Value const& request);
+ Json::Value BuildClientReply(ClientQuery const& q);
+ Json::Value BuildClientReplyResponses(ClientRequests const& requests);
+ Json::Value BuildClientReplyResponse(ClientRequest const& request);
+
+ struct RequestVersion
+ {
+ unsigned int Major = 0;
+ unsigned int Minor = 0;
+ };
+ static bool ReadRequestVersions(Json::Value const& version,
+ std::vector<RequestVersion>& versions,
+ std::string& error);
+ static bool ReadRequestVersion(Json::Value const& version, bool inArray,
+ std::vector<RequestVersion>& result,
+ std::string& error);
+ static std::string NoSupportedVersion(
+ std::vector<RequestVersion> const& versions);
+
+ void BuildClientRequestCodeModel(
+ ClientRequest& r, std::vector<RequestVersion> const& versions);
+ Json::Value BuildCodeModel(Object const& object);
+
+ void BuildClientRequestCache(ClientRequest& r,
+ std::vector<RequestVersion> const& versions);
+ Json::Value BuildCache(Object const& object);
+
+ void BuildClientRequestCMakeFiles(
+ ClientRequest& r, std::vector<RequestVersion> const& versions);
+ Json::Value BuildCMakeFiles(Object const& object);
+
+ void BuildClientRequestInternalTest(
+ ClientRequest& r, std::vector<RequestVersion> const& versions);
+ Json::Value BuildInternalTest(Object const& object);
+};
+
+#endif
diff --git a/Source/cmFileAPICMakeFiles.cxx b/Source/cmFileAPICMakeFiles.cxx
new file mode 100644
index 000000000..5590bc2b3
--- /dev/null
+++ b/Source/cmFileAPICMakeFiles.cxx
@@ -0,0 +1,114 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmFileAPICMakeFiles.h"
+
+#include "cmFileAPI.h"
+#include "cmGlobalGenerator.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+#include "cm_jsoncpp_value.h"
+
+#include <string>
+#include <vector>
+
+namespace {
+
+class CMakeFiles
+{
+ cmFileAPI& FileAPI;
+ unsigned long Version;
+ std::string CMakeModules;
+ std::string const& TopSource;
+ std::string const& TopBuild;
+ bool OutOfSource;
+
+ Json::Value DumpPaths();
+ Json::Value DumpInputs();
+ Json::Value DumpInput(std::string const& file);
+
+public:
+ CMakeFiles(cmFileAPI& fileAPI, unsigned long version);
+ Json::Value Dump();
+};
+
+CMakeFiles::CMakeFiles(cmFileAPI& fileAPI, unsigned long version)
+ : FileAPI(fileAPI)
+ , Version(version)
+ , CMakeModules(cmSystemTools::GetCMakeRoot() + "/Modules")
+ , TopSource(this->FileAPI.GetCMakeInstance()->GetHomeDirectory())
+ , TopBuild(this->FileAPI.GetCMakeInstance()->GetHomeOutputDirectory())
+ , OutOfSource(TopBuild != TopSource)
+{
+ static_cast<void>(this->Version);
+}
+
+Json::Value CMakeFiles::Dump()
+{
+ Json::Value cmakeFiles = Json::objectValue;
+ cmakeFiles["paths"] = this->DumpPaths();
+ cmakeFiles["inputs"] = DumpInputs();
+ return cmakeFiles;
+}
+
+Json::Value CMakeFiles::DumpPaths()
+{
+ Json::Value paths = Json::objectValue;
+ paths["source"] = this->TopSource;
+ paths["build"] = this->TopBuild;
+ return paths;
+}
+
+Json::Value CMakeFiles::DumpInputs()
+{
+ Json::Value inputs = Json::arrayValue;
+
+ cmGlobalGenerator* gg =
+ this->FileAPI.GetCMakeInstance()->GetGlobalGenerator();
+ for (cmLocalGenerator const* lg : gg->GetLocalGenerators()) {
+ cmMakefile const* mf = lg->GetMakefile();
+ for (std::string const& file : mf->GetListFiles()) {
+ inputs.append(this->DumpInput(file));
+ }
+ }
+
+ return inputs;
+}
+
+Json::Value CMakeFiles::DumpInput(std::string const& file)
+{
+ Json::Value input = Json::objectValue;
+
+ bool const isCMake = cmSystemTools::IsSubDirectory(file, this->CMakeModules);
+ if (isCMake) {
+ input["isCMake"] = true;
+ }
+
+ if (!cmSystemTools::IsSubDirectory(file, this->TopSource) &&
+ !cmSystemTools::IsSubDirectory(file, this->TopBuild)) {
+ input["isExternal"] = true;
+ }
+
+ if (this->OutOfSource &&
+ cmSystemTools::IsSubDirectory(file, this->TopBuild)) {
+ input["isGenerated"] = true;
+ }
+
+ std::string path = file;
+ if (!isCMake && cmSystemTools::IsSubDirectory(path, this->TopSource)) {
+ // Use a relative path within the source directory.
+ path = cmSystemTools::RelativePath(this->TopSource, path);
+ }
+ input["path"] = path;
+
+ return input;
+}
+}
+
+Json::Value cmFileAPICMakeFilesDump(cmFileAPI& fileAPI, unsigned long version)
+{
+ CMakeFiles cmakeFiles(fileAPI, version);
+ return cmakeFiles.Dump();
+}
diff --git a/Source/cmFileAPICMakeFiles.h b/Source/cmFileAPICMakeFiles.h
new file mode 100644
index 000000000..a851c32f4
--- /dev/null
+++ b/Source/cmFileAPICMakeFiles.h
@@ -0,0 +1,15 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmFileAPICMakeFiles_h
+#define cmFileAPICMakeFiles_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cm_jsoncpp_value.h"
+
+class cmFileAPI;
+
+extern Json::Value cmFileAPICMakeFilesDump(cmFileAPI& fileAPI,
+ unsigned long version);
+
+#endif
diff --git a/Source/cmFileAPICache.cxx b/Source/cmFileAPICache.cxx
new file mode 100644
index 000000000..f96bc90e5
--- /dev/null
+++ b/Source/cmFileAPICache.cxx
@@ -0,0 +1,106 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmFileAPICache.h"
+
+#include "cmFileAPI.h"
+#include "cmState.h"
+#include "cmake.h"
+
+#include "cm_jsoncpp_value.h"
+
+#include <algorithm>
+#include <string>
+#include <utility>
+#include <vector>
+
+namespace {
+
+class Cache
+{
+ cmFileAPI& FileAPI;
+ unsigned long Version;
+ cmState* State;
+
+ Json::Value DumpEntries();
+ Json::Value DumpEntry(std::string const& name);
+ Json::Value DumpEntryProperties(std::string const& name);
+ Json::Value DumpEntryProperty(std::string const& name,
+ std::string const& prop);
+
+public:
+ Cache(cmFileAPI& fileAPI, unsigned long version);
+ Json::Value Dump();
+};
+
+Cache::Cache(cmFileAPI& fileAPI, unsigned long version)
+ : FileAPI(fileAPI)
+ , Version(version)
+ , State(this->FileAPI.GetCMakeInstance()->GetState())
+{
+ static_cast<void>(this->Version);
+}
+
+Json::Value Cache::Dump()
+{
+ Json::Value cache = Json::objectValue;
+ cache["entries"] = DumpEntries();
+ return cache;
+}
+
+Json::Value Cache::DumpEntries()
+{
+ Json::Value entries = Json::arrayValue;
+
+ std::vector<std::string> names = this->State->GetCacheEntryKeys();
+ std::sort(names.begin(), names.end());
+
+ for (std::string const& name : names) {
+ entries.append(this->DumpEntry(name));
+ }
+
+ return entries;
+}
+
+Json::Value Cache::DumpEntry(std::string const& name)
+{
+ Json::Value entry = Json::objectValue;
+ entry["name"] = name;
+ entry["type"] =
+ cmState::CacheEntryTypeToString(this->State->GetCacheEntryType(name));
+ entry["value"] = this->State->GetCacheEntryValue(name);
+
+ Json::Value properties = this->DumpEntryProperties(name);
+ if (!properties.empty()) {
+ entry["properties"] = std::move(properties);
+ }
+
+ return entry;
+}
+
+Json::Value Cache::DumpEntryProperties(std::string const& name)
+{
+ Json::Value properties = Json::arrayValue;
+ std::vector<std::string> props =
+ this->State->GetCacheEntryPropertyList(name);
+ std::sort(props.begin(), props.end());
+ for (std::string const& prop : props) {
+ properties.append(this->DumpEntryProperty(name, prop));
+ }
+ return properties;
+}
+
+Json::Value Cache::DumpEntryProperty(std::string const& name,
+ std::string const& prop)
+{
+ Json::Value property = Json::objectValue;
+ property["name"] = prop;
+ property["value"] = this->State->GetCacheEntryProperty(name, prop);
+ return property;
+}
+}
+
+Json::Value cmFileAPICacheDump(cmFileAPI& fileAPI, unsigned long version)
+{
+ Cache cache(fileAPI, version);
+ return cache.Dump();
+}
diff --git a/Source/cmFileAPICache.h b/Source/cmFileAPICache.h
new file mode 100644
index 000000000..09d9e1ce9
--- /dev/null
+++ b/Source/cmFileAPICache.h
@@ -0,0 +1,15 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmFileAPICache_h
+#define cmFileAPICache_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cm_jsoncpp_value.h"
+
+class cmFileAPI;
+
+extern Json::Value cmFileAPICacheDump(cmFileAPI& fileAPI,
+ unsigned long version);
+
+#endif
diff --git a/Source/cmFileAPICodemodel.cxx b/Source/cmFileAPICodemodel.cxx
new file mode 100644
index 000000000..fecbf63ca
--- /dev/null
+++ b/Source/cmFileAPICodemodel.cxx
@@ -0,0 +1,1250 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmFileAPICodemodel.h"
+
+#include "cmAlgorithms.h"
+#include "cmCryptoHash.h"
+#include "cmFileAPI.h"
+#include "cmGeneratorExpression.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmInstallGenerator.h"
+#include "cmInstallSubdirectoryGenerator.h"
+#include "cmInstallTargetGenerator.h"
+#include "cmLinkLineComputer.h"
+#include "cmListFileCache.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmSourceFile.h"
+#include "cmSourceGroup.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmTargetDepend.h"
+#include "cmake.h"
+
+#include "cm_jsoncpp_value.h"
+
+#include <algorithm>
+#include <cassert>
+#include <map>
+#include <set>
+#include <string>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+namespace {
+
+class Codemodel
+{
+ cmFileAPI& FileAPI;
+ unsigned long Version;
+
+ Json::Value DumpPaths();
+ Json::Value DumpConfigurations();
+ Json::Value DumpConfiguration(std::string const& config);
+
+public:
+ Codemodel(cmFileAPI& fileAPI, unsigned long version);
+ Json::Value Dump();
+};
+
+class CodemodelConfig
+{
+ cmFileAPI& FileAPI;
+ unsigned long Version;
+ std::string const& Config;
+ std::string TopSource;
+ std::string TopBuild;
+
+ struct Directory
+ {
+ cmStateSnapshot Snapshot;
+ cmLocalGenerator const* LocalGenerator = nullptr;
+ Json::Value TargetIndexes = Json::arrayValue;
+ Json::ArrayIndex ProjectIndex;
+ bool HasInstallRule = false;
+ };
+ std::map<cmStateSnapshot, Json::ArrayIndex, cmStateSnapshot::StrictWeakOrder>
+ DirectoryMap;
+ std::vector<Directory> Directories;
+
+ struct Project
+ {
+ cmStateSnapshot Snapshot;
+ static const Json::ArrayIndex NoParentIndex =
+ static_cast<Json::ArrayIndex>(-1);
+ Json::ArrayIndex ParentIndex = NoParentIndex;
+ Json::Value ChildIndexes = Json::arrayValue;
+ Json::Value DirectoryIndexes = Json::arrayValue;
+ Json::Value TargetIndexes = Json::arrayValue;
+ };
+ std::map<cmStateSnapshot, Json::ArrayIndex, cmStateSnapshot::StrictWeakOrder>
+ ProjectMap;
+ std::vector<Project> Projects;
+
+ void ProcessDirectories();
+
+ Json::ArrayIndex GetDirectoryIndex(cmLocalGenerator const* lg);
+ Json::ArrayIndex GetDirectoryIndex(cmStateSnapshot s);
+
+ Json::ArrayIndex AddProject(cmStateSnapshot s);
+
+ Json::Value DumpTargets();
+ Json::Value DumpTarget(cmGeneratorTarget* gt, Json::ArrayIndex ti);
+
+ Json::Value DumpDirectories();
+ Json::Value DumpDirectory(Directory& d);
+
+ Json::Value DumpProjects();
+ Json::Value DumpProject(Project& p);
+
+ Json::Value DumpMinimumCMakeVersion(cmStateSnapshot s);
+
+public:
+ CodemodelConfig(cmFileAPI& fileAPI, unsigned long version,
+ std::string const& config);
+ Json::Value Dump();
+};
+
+std::string RelativeIfUnder(std::string const& top, std::string const& in)
+{
+ std::string out;
+ if (in == top) {
+ out = ".";
+ } else if (cmSystemTools::IsSubDirectory(in, top)) {
+ out = in.substr(top.size() + 1);
+ } else {
+ out = in;
+ }
+ return out;
+}
+
+std::string TargetId(cmGeneratorTarget const* gt, std::string const& topBuild)
+{
+ cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
+ std::string path = RelativeIfUnder(
+ topBuild, gt->GetLocalGenerator()->GetCurrentBinaryDirectory());
+ std::string hash = hasher.HashString(path);
+ hash.resize(20, '0');
+ return gt->GetName() + CMAKE_DIRECTORY_ID_SEP + hash;
+}
+
+class BacktraceData
+{
+ std::string TopSource;
+ std::unordered_map<std::string, Json::ArrayIndex> CommandMap;
+ std::unordered_map<std::string, Json::ArrayIndex> FileMap;
+ std::unordered_map<cmListFileContext const*, Json::ArrayIndex> NodeMap;
+ Json::Value Commands = Json::arrayValue;
+ Json::Value Files = Json::arrayValue;
+ Json::Value Nodes = Json::arrayValue;
+
+ Json::ArrayIndex AddCommand(std::string const& command)
+ {
+ auto i = this->CommandMap.find(command);
+ if (i == this->CommandMap.end()) {
+ auto cmdIndex = static_cast<Json::ArrayIndex>(this->Commands.size());
+ i = this->CommandMap.emplace(command, cmdIndex).first;
+ this->Commands.append(command);
+ }
+ return i->second;
+ }
+
+ Json::ArrayIndex AddFile(std::string const& file)
+ {
+ auto i = this->FileMap.find(file);
+ if (i == this->FileMap.end()) {
+ auto fileIndex = static_cast<Json::ArrayIndex>(this->Files.size());
+ i = this->FileMap.emplace(file, fileIndex).first;
+ this->Files.append(RelativeIfUnder(this->TopSource, file));
+ }
+ return i->second;
+ }
+
+public:
+ BacktraceData(std::string topSource);
+ bool Add(cmListFileBacktrace const& bt, Json::ArrayIndex& index);
+ Json::Value Dump();
+};
+
+BacktraceData::BacktraceData(std::string topSource)
+ : TopSource(std::move(topSource))
+{
+}
+
+bool BacktraceData::Add(cmListFileBacktrace const& bt, Json::ArrayIndex& index)
+{
+ if (bt.Empty()) {
+ return false;
+ }
+ cmListFileContext const* top = &bt.Top();
+ auto found = this->NodeMap.find(top);
+ if (found != this->NodeMap.end()) {
+ index = found->second;
+ return true;
+ }
+ Json::Value entry = Json::objectValue;
+ entry["file"] = this->AddFile(top->FilePath);
+ if (top->Line) {
+ entry["line"] = static_cast<int>(top->Line);
+ }
+ if (!top->Name.empty()) {
+ entry["command"] = this->AddCommand(top->Name);
+ }
+ Json::ArrayIndex parent;
+ if (this->Add(bt.Pop(), parent)) {
+ entry["parent"] = parent;
+ }
+ index = this->NodeMap[top] = this->Nodes.size();
+ this->Nodes.append(std::move(entry)); // NOLINT(*)
+ return true;
+}
+
+Json::Value BacktraceData::Dump()
+{
+ Json::Value backtraceGraph;
+ this->CommandMap.clear();
+ this->FileMap.clear();
+ this->NodeMap.clear();
+ backtraceGraph["commands"] = std::move(this->Commands);
+ backtraceGraph["files"] = std::move(this->Files);
+ backtraceGraph["nodes"] = std::move(this->Nodes);
+ return backtraceGraph;
+}
+
+struct CompileData
+{
+ struct IncludeEntry
+ {
+ BT<std::string> Path;
+ bool IsSystem = false;
+ IncludeEntry(BT<std::string> path, bool isSystem)
+ : Path(std::move(path))
+ , IsSystem(isSystem)
+ {
+ }
+ };
+
+ void SetDefines(std::set<BT<std::string>> const& defines);
+
+ std::string Language;
+ std::string Sysroot;
+ std::vector<BT<std::string>> Flags;
+ std::vector<BT<std::string>> Defines;
+ std::vector<IncludeEntry> Includes;
+};
+
+void CompileData::SetDefines(std::set<BT<std::string>> const& defines)
+{
+ this->Defines.reserve(defines.size());
+ for (BT<std::string> const& d : defines) {
+ this->Defines.push_back(d);
+ }
+}
+
+class Target
+{
+ cmGeneratorTarget* GT;
+ std::string const& Config;
+ std::string TopSource;
+ std::string TopBuild;
+ std::vector<cmSourceGroup> SourceGroupsLocal;
+ BacktraceData Backtraces;
+
+ std::map<std::string, CompileData> CompileDataMap;
+
+ std::unordered_map<cmSourceFile const*, Json::ArrayIndex> SourceMap;
+ Json::Value Sources = Json::arrayValue;
+
+ struct SourceGroup
+ {
+ std::string Name;
+ Json::Value SourceIndexes = Json::arrayValue;
+ };
+ std::unordered_map<cmSourceGroup const*, Json::ArrayIndex> SourceGroupsMap;
+ std::vector<SourceGroup> SourceGroups;
+
+ struct CompileGroup
+ {
+ std::map<Json::Value, Json::ArrayIndex>::iterator Entry;
+ Json::Value SourceIndexes = Json::arrayValue;
+ };
+ std::map<Json::Value, Json::ArrayIndex> CompileGroupMap;
+ std::vector<CompileGroup> CompileGroups;
+
+ void ProcessLanguages();
+ void ProcessLanguage(std::string const& lang);
+
+ Json::ArrayIndex AddSourceGroup(cmSourceGroup* sg, Json::ArrayIndex si);
+ CompileData BuildCompileData(cmSourceFile* sf);
+ Json::ArrayIndex AddSourceCompileGroup(cmSourceFile* sf,
+ Json::ArrayIndex si);
+ void AddBacktrace(Json::Value& object, cmListFileBacktrace const& bt);
+ Json::Value DumpPaths();
+ Json::Value DumpCompileData(CompileData cd);
+ Json::Value DumpInclude(CompileData::IncludeEntry const& inc);
+ Json::Value DumpDefine(BT<std::string> const& def);
+ Json::Value DumpSources();
+ Json::Value DumpSource(cmGeneratorTarget::SourceAndKind const& sk,
+ Json::ArrayIndex si);
+ Json::Value DumpSourceGroups();
+ Json::Value DumpSourceGroup(SourceGroup& sg);
+ Json::Value DumpCompileGroups();
+ Json::Value DumpCompileGroup(CompileGroup& cg);
+ Json::Value DumpSysroot(std::string const& path);
+ Json::Value DumpInstall();
+ Json::Value DumpInstallPrefix();
+ Json::Value DumpInstallDestinations();
+ Json::Value DumpInstallDestination(cmInstallTargetGenerator* itGen);
+ Json::Value DumpArtifacts();
+ Json::Value DumpLink();
+ Json::Value DumpArchive();
+ Json::Value DumpLinkCommandFragments();
+ Json::Value DumpCommandFragments(std::vector<BT<std::string>> const& frags);
+ Json::Value DumpCommandFragment(BT<std::string> const& frag,
+ std::string const& role = std::string());
+ Json::Value DumpDependencies();
+ Json::Value DumpDependency(cmTargetDepend const& td);
+ Json::Value DumpFolder();
+
+public:
+ Target(cmGeneratorTarget* gt, std::string const& config);
+ Json::Value Dump();
+};
+
+Codemodel::Codemodel(cmFileAPI& fileAPI, unsigned long version)
+ : FileAPI(fileAPI)
+ , Version(version)
+{
+}
+
+Json::Value Codemodel::Dump()
+{
+ Json::Value codemodel = Json::objectValue;
+
+ codemodel["paths"] = this->DumpPaths();
+ codemodel["configurations"] = this->DumpConfigurations();
+
+ return codemodel;
+}
+
+Json::Value Codemodel::DumpPaths()
+{
+ Json::Value paths = Json::objectValue;
+ paths["source"] = this->FileAPI.GetCMakeInstance()->GetHomeDirectory();
+ paths["build"] = this->FileAPI.GetCMakeInstance()->GetHomeOutputDirectory();
+ return paths;
+}
+
+Json::Value Codemodel::DumpConfigurations()
+{
+ std::vector<std::string> configs;
+ cmGlobalGenerator* gg =
+ this->FileAPI.GetCMakeInstance()->GetGlobalGenerator();
+ auto makefiles = gg->GetMakefiles();
+ if (!makefiles.empty()) {
+ makefiles[0]->GetConfigurations(configs);
+ if (configs.empty()) {
+ configs.emplace_back();
+ }
+ }
+ Json::Value configurations = Json::arrayValue;
+ for (std::string const& config : configs) {
+ configurations.append(this->DumpConfiguration(config));
+ }
+ return configurations;
+}
+
+Json::Value Codemodel::DumpConfiguration(std::string const& config)
+{
+ CodemodelConfig configuration(this->FileAPI, this->Version, config);
+ return configuration.Dump();
+}
+
+CodemodelConfig::CodemodelConfig(cmFileAPI& fileAPI, unsigned long version,
+ std::string const& config)
+ : FileAPI(fileAPI)
+ , Version(version)
+ , Config(config)
+ , TopSource(this->FileAPI.GetCMakeInstance()->GetHomeDirectory())
+ , TopBuild(this->FileAPI.GetCMakeInstance()->GetHomeOutputDirectory())
+{
+ static_cast<void>(this->Version);
+}
+
+Json::Value CodemodelConfig::Dump()
+{
+ Json::Value configuration = Json::objectValue;
+ configuration["name"] = this->Config;
+ this->ProcessDirectories();
+ configuration["targets"] = this->DumpTargets();
+ configuration["directories"] = this->DumpDirectories();
+ configuration["projects"] = this->DumpProjects();
+ return configuration;
+}
+
+void CodemodelConfig::ProcessDirectories()
+{
+ cmGlobalGenerator* gg =
+ this->FileAPI.GetCMakeInstance()->GetGlobalGenerator();
+ std::vector<cmLocalGenerator*> const& localGens = gg->GetLocalGenerators();
+
+ // Add directories in forward order to process parents before children.
+ this->Directories.reserve(localGens.size());
+ for (cmLocalGenerator* lg : localGens) {
+ auto directoryIndex =
+ static_cast<Json::ArrayIndex>(this->Directories.size());
+ this->Directories.emplace_back();
+ Directory& d = this->Directories[directoryIndex];
+ d.Snapshot = lg->GetStateSnapshot().GetBuildsystemDirectory();
+ d.LocalGenerator = lg;
+ this->DirectoryMap[d.Snapshot] = directoryIndex;
+
+ d.ProjectIndex = this->AddProject(d.Snapshot);
+ this->Projects[d.ProjectIndex].DirectoryIndexes.append(directoryIndex);
+ }
+
+ // Update directories in reverse order to process children before parents.
+ for (auto di = this->Directories.rbegin(); di != this->Directories.rend();
+ ++di) {
+ Directory& d = *di;
+
+ // Accumulate the presence of install rules on the way up.
+ for (auto gen : d.LocalGenerator->GetMakefile()->GetInstallGenerators()) {
+ if (!dynamic_cast<cmInstallSubdirectoryGenerator*>(gen)) {
+ d.HasInstallRule = true;
+ break;
+ }
+ }
+ if (!d.HasInstallRule) {
+ for (cmStateSnapshot const& child : d.Snapshot.GetChildren()) {
+ cmStateSnapshot childDir = child.GetBuildsystemDirectory();
+ Json::ArrayIndex const childIndex = this->GetDirectoryIndex(childDir);
+ if (this->Directories[childIndex].HasInstallRule) {
+ d.HasInstallRule = true;
+ break;
+ }
+ }
+ }
+ }
+}
+
+Json::ArrayIndex CodemodelConfig::GetDirectoryIndex(cmLocalGenerator const* lg)
+{
+ return this->GetDirectoryIndex(
+ lg->GetStateSnapshot().GetBuildsystemDirectory());
+}
+
+Json::ArrayIndex CodemodelConfig::GetDirectoryIndex(cmStateSnapshot s)
+{
+ auto i = this->DirectoryMap.find(s);
+ assert(i != this->DirectoryMap.end());
+ return i->second;
+}
+
+Json::ArrayIndex CodemodelConfig::AddProject(cmStateSnapshot s)
+{
+ cmStateSnapshot ps = s.GetBuildsystemDirectoryParent();
+ if (ps.IsValid() && ps.GetProjectName() == s.GetProjectName()) {
+ // This directory is part of its parent directory project.
+ Json::ArrayIndex const parentDirIndex = this->GetDirectoryIndex(ps);
+ return this->Directories[parentDirIndex].ProjectIndex;
+ }
+
+ // This directory starts a new project.
+ auto projectIndex = static_cast<Json::ArrayIndex>(this->Projects.size());
+ this->Projects.emplace_back();
+ Project& p = this->Projects[projectIndex];
+ p.Snapshot = s;
+ this->ProjectMap[s] = projectIndex;
+ if (ps.IsValid()) {
+ Json::ArrayIndex const parentDirIndex = this->GetDirectoryIndex(ps);
+ p.ParentIndex = this->Directories[parentDirIndex].ProjectIndex;
+ this->Projects[p.ParentIndex].ChildIndexes.append(projectIndex);
+ }
+ return projectIndex;
+}
+
+Json::Value CodemodelConfig::DumpTargets()
+{
+ Json::Value targets = Json::arrayValue;
+
+ std::vector<cmGeneratorTarget*> targetList;
+ cmGlobalGenerator* gg =
+ this->FileAPI.GetCMakeInstance()->GetGlobalGenerator();
+ for (cmLocalGenerator const* lg : gg->GetLocalGenerators()) {
+ cmAppend(targetList, lg->GetGeneratorTargets());
+ }
+ std::sort(targetList.begin(), targetList.end(),
+ [](cmGeneratorTarget* l, cmGeneratorTarget* r) {
+ return l->GetName() < r->GetName();
+ });
+
+ for (cmGeneratorTarget* gt : targetList) {
+ if (gt->GetType() == cmStateEnums::GLOBAL_TARGET ||
+ gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ continue;
+ }
+
+ targets.append(this->DumpTarget(gt, targets.size()));
+ }
+
+ return targets;
+}
+
+Json::Value CodemodelConfig::DumpTarget(cmGeneratorTarget* gt,
+ Json::ArrayIndex ti)
+{
+ Target t(gt, this->Config);
+ std::string prefix = "target-" + gt->GetName();
+ for (char& c : prefix) {
+ // CMP0037 OLD behavior allows slashes in target names. Remove them.
+ if (c == '/' || c == '\\') {
+ c = '_';
+ }
+ }
+ if (!this->Config.empty()) {
+ prefix += "-" + this->Config;
+ }
+ Json::Value target = this->FileAPI.MaybeJsonFile(t.Dump(), prefix);
+ target["name"] = gt->GetName();
+ target["id"] = TargetId(gt, this->TopBuild);
+
+ // Cross-reference directory containing target.
+ Json::ArrayIndex di = this->GetDirectoryIndex(gt->GetLocalGenerator());
+ target["directoryIndex"] = di;
+ this->Directories[di].TargetIndexes.append(ti);
+
+ // Cross-reference project containing target.
+ Json::ArrayIndex pi = this->Directories[di].ProjectIndex;
+ target["projectIndex"] = pi;
+ this->Projects[pi].TargetIndexes.append(ti);
+
+ return target;
+}
+
+Json::Value CodemodelConfig::DumpDirectories()
+{
+ Json::Value directories = Json::arrayValue;
+ for (Directory& d : this->Directories) {
+ directories.append(this->DumpDirectory(d));
+ }
+ return directories;
+}
+
+Json::Value CodemodelConfig::DumpDirectory(Directory& d)
+{
+ Json::Value directory = Json::objectValue;
+
+ std::string sourceDir = d.Snapshot.GetDirectory().GetCurrentSource();
+ directory["source"] = RelativeIfUnder(this->TopSource, sourceDir);
+
+ std::string buildDir = d.Snapshot.GetDirectory().GetCurrentBinary();
+ directory["build"] = RelativeIfUnder(this->TopBuild, buildDir);
+
+ cmStateSnapshot parentDir = d.Snapshot.GetBuildsystemDirectoryParent();
+ if (parentDir.IsValid()) {
+ directory["parentIndex"] = this->GetDirectoryIndex(parentDir);
+ }
+
+ Json::Value childIndexes = Json::arrayValue;
+ for (cmStateSnapshot const& child : d.Snapshot.GetChildren()) {
+ childIndexes.append(
+ this->GetDirectoryIndex(child.GetBuildsystemDirectory()));
+ }
+ if (!childIndexes.empty()) {
+ directory["childIndexes"] = std::move(childIndexes);
+ }
+
+ directory["projectIndex"] = d.ProjectIndex;
+
+ if (!d.TargetIndexes.empty()) {
+ directory["targetIndexes"] = std::move(d.TargetIndexes);
+ }
+
+ Json::Value minimumCMakeVersion = this->DumpMinimumCMakeVersion(d.Snapshot);
+ if (!minimumCMakeVersion.isNull()) {
+ directory["minimumCMakeVersion"] = std::move(minimumCMakeVersion);
+ }
+
+ if (d.HasInstallRule) {
+ directory["hasInstallRule"] = true;
+ }
+
+ return directory;
+}
+
+Json::Value CodemodelConfig::DumpProjects()
+{
+ Json::Value projects = Json::arrayValue;
+ for (Project& p : this->Projects) {
+ projects.append(this->DumpProject(p));
+ }
+ return projects;
+}
+
+Json::Value CodemodelConfig::DumpProject(Project& p)
+{
+ Json::Value project = Json::objectValue;
+
+ project["name"] = p.Snapshot.GetProjectName();
+
+ if (p.ParentIndex != Project::NoParentIndex) {
+ project["parentIndex"] = p.ParentIndex;
+ }
+
+ if (!p.ChildIndexes.empty()) {
+ project["childIndexes"] = std::move(p.ChildIndexes);
+ }
+
+ project["directoryIndexes"] = std::move(p.DirectoryIndexes);
+
+ if (!p.TargetIndexes.empty()) {
+ project["targetIndexes"] = std::move(p.TargetIndexes);
+ }
+
+ return project;
+}
+
+Json::Value CodemodelConfig::DumpMinimumCMakeVersion(cmStateSnapshot s)
+{
+ Json::Value minimumCMakeVersion;
+ if (std::string const* def =
+ s.GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
+ minimumCMakeVersion = Json::objectValue;
+ minimumCMakeVersion["string"] = *def;
+ }
+ return minimumCMakeVersion;
+}
+
+Target::Target(cmGeneratorTarget* gt, std::string const& config)
+ : GT(gt)
+ , Config(config)
+ , TopSource(gt->GetGlobalGenerator()->GetCMakeInstance()->GetHomeDirectory())
+ , TopBuild(
+ gt->GetGlobalGenerator()->GetCMakeInstance()->GetHomeOutputDirectory())
+ , SourceGroupsLocal(this->GT->Makefile->GetSourceGroups())
+ , Backtraces(this->TopSource)
+{
+}
+
+Json::Value Target::Dump()
+{
+ Json::Value target = Json::objectValue;
+
+ cmStateEnums::TargetType const type = this->GT->GetType();
+
+ target["name"] = this->GT->GetName();
+ target["type"] = cmState::GetTargetTypeName(type);
+ target["id"] = TargetId(this->GT, this->TopBuild);
+ target["paths"] = this->DumpPaths();
+ if (this->GT->Target->GetIsGeneratorProvided()) {
+ target["isGeneratorProvided"] = true;
+ }
+
+ this->AddBacktrace(target, this->GT->GetBacktrace());
+
+ if (this->GT->Target->GetHaveInstallRule()) {
+ target["install"] = this->DumpInstall();
+ }
+
+ if (this->GT->HaveWellDefinedOutputFiles()) {
+ Json::Value artifacts = this->DumpArtifacts();
+ if (!artifacts.empty()) {
+ target["artifacts"] = std::move(artifacts);
+ }
+ }
+
+ if (type == cmStateEnums::EXECUTABLE ||
+ type == cmStateEnums::SHARED_LIBRARY ||
+ type == cmStateEnums::MODULE_LIBRARY) {
+ target["nameOnDisk"] = this->GT->GetFullName(this->Config);
+ target["link"] = this->DumpLink();
+ } else if (type == cmStateEnums::STATIC_LIBRARY) {
+ target["nameOnDisk"] = this->GT->GetFullName(this->Config);
+ target["archive"] = this->DumpArchive();
+ }
+
+ Json::Value dependencies = this->DumpDependencies();
+ if (!dependencies.empty()) {
+ target["dependencies"] = dependencies;
+ }
+
+ {
+ this->ProcessLanguages();
+
+ target["sources"] = this->DumpSources();
+
+ Json::Value folder = this->DumpFolder();
+ if (!folder.isNull()) {
+ target["folder"] = std::move(folder);
+ }
+
+ Json::Value sourceGroups = this->DumpSourceGroups();
+ if (!sourceGroups.empty()) {
+ target["sourceGroups"] = std::move(sourceGroups);
+ }
+
+ Json::Value compileGroups = this->DumpCompileGroups();
+ if (!compileGroups.empty()) {
+ target["compileGroups"] = std::move(compileGroups);
+ }
+ }
+
+ target["backtraceGraph"] = this->Backtraces.Dump();
+
+ return target;
+}
+
+void Target::ProcessLanguages()
+{
+ std::set<std::string> languages;
+ this->GT->GetLanguages(languages, this->Config);
+ for (std::string const& lang : languages) {
+ this->ProcessLanguage(lang);
+ }
+}
+
+void Target::ProcessLanguage(std::string const& lang)
+{
+ CompileData& cd = this->CompileDataMap[lang];
+ cd.Language = lang;
+ if (const char* sysrootCompile =
+ this->GT->Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE")) {
+ cd.Sysroot = sysrootCompile;
+ } else if (const char* sysroot =
+ this->GT->Makefile->GetDefinition("CMAKE_SYSROOT")) {
+ cd.Sysroot = sysroot;
+ }
+ cmLocalGenerator* lg = this->GT->GetLocalGenerator();
+ {
+ // FIXME: Add flags from end section of ExpandRuleVariable,
+ // which may need to be factored out.
+ std::string flags;
+ lg->GetTargetCompileFlags(this->GT, this->Config, lang, flags);
+ cd.Flags.emplace_back(std::move(flags), cmListFileBacktrace());
+ }
+ std::set<BT<std::string>> defines =
+ lg->GetTargetDefines(this->GT, this->Config, lang);
+ cd.SetDefines(defines);
+ std::vector<BT<std::string>> includePathList =
+ lg->GetIncludeDirectories(this->GT, lang, this->Config);
+ for (BT<std::string> const& i : includePathList) {
+ cd.Includes.emplace_back(
+ i, this->GT->IsSystemIncludeDirectory(i.Value, this->Config, lang));
+ }
+}
+
+Json::ArrayIndex Target::AddSourceGroup(cmSourceGroup* sg, Json::ArrayIndex si)
+{
+ std::unordered_map<cmSourceGroup const*, Json::ArrayIndex>::iterator i =
+ this->SourceGroupsMap.find(sg);
+ if (i == this->SourceGroupsMap.end()) {
+ auto sgIndex = static_cast<Json::ArrayIndex>(this->SourceGroups.size());
+ i = this->SourceGroupsMap.emplace(sg, sgIndex).first;
+ SourceGroup g;
+ g.Name = sg->GetFullName();
+ this->SourceGroups.push_back(std::move(g));
+ }
+ this->SourceGroups[i->second].SourceIndexes.append(si);
+ return i->second;
+}
+
+CompileData Target::BuildCompileData(cmSourceFile* sf)
+{
+ CompileData fd;
+
+ fd.Language = sf->GetLanguage();
+ if (fd.Language.empty()) {
+ return fd;
+ }
+ CompileData const& cd = this->CompileDataMap.at(fd.Language);
+
+ fd.Sysroot = cd.Sysroot;
+
+ cmLocalGenerator* lg = this->GT->GetLocalGenerator();
+ cmGeneratorExpressionInterpreter genexInterpreter(lg, this->Config, this->GT,
+ fd.Language);
+
+ fd.Flags = cd.Flags;
+ const std::string COMPILE_FLAGS("COMPILE_FLAGS");
+ if (const char* cflags = sf->GetProperty(COMPILE_FLAGS)) {
+ std::string flags = genexInterpreter.Evaluate(cflags, COMPILE_FLAGS);
+ fd.Flags.emplace_back(std::move(flags), cmListFileBacktrace());
+ }
+ const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
+ if (const char* coptions = sf->GetProperty(COMPILE_OPTIONS)) {
+ std::string flags;
+ lg->AppendCompileOptions(
+ flags, genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS));
+ fd.Flags.emplace_back(std::move(flags), cmListFileBacktrace());
+ }
+
+ // Add include directories from source file properties.
+ {
+ std::vector<std::string> includes;
+ const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
+ if (const char* cincludes = sf->GetProperty(INCLUDE_DIRECTORIES)) {
+ const std::string& evaluatedIncludes =
+ genexInterpreter.Evaluate(cincludes, INCLUDE_DIRECTORIES);
+ lg->AppendIncludeDirectories(includes, evaluatedIncludes, *sf);
+
+ for (std::string const& include : includes) {
+ bool const isSystemInclude = this->GT->IsSystemIncludeDirectory(
+ include, this->Config, fd.Language);
+ fd.Includes.emplace_back(include, isSystemInclude);
+ }
+ }
+ }
+ fd.Includes.insert(fd.Includes.end(), cd.Includes.begin(),
+ cd.Includes.end());
+
+ const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
+ std::set<std::string> fileDefines;
+ if (const char* defs = sf->GetProperty(COMPILE_DEFINITIONS)) {
+ lg->AppendDefines(fileDefines,
+ genexInterpreter.Evaluate(defs, COMPILE_DEFINITIONS));
+ }
+
+ const std::string defPropName =
+ "COMPILE_DEFINITIONS_" + cmSystemTools::UpperCase(this->Config);
+ if (const char* config_defs = sf->GetProperty(defPropName)) {
+ lg->AppendDefines(
+ fileDefines,
+ genexInterpreter.Evaluate(config_defs, COMPILE_DEFINITIONS));
+ }
+
+ std::set<BT<std::string>> defines;
+ defines.insert(fileDefines.begin(), fileDefines.end());
+ defines.insert(cd.Defines.begin(), cd.Defines.end());
+
+ fd.SetDefines(defines);
+
+ return fd;
+}
+
+Json::ArrayIndex Target::AddSourceCompileGroup(cmSourceFile* sf,
+ Json::ArrayIndex si)
+{
+ Json::Value compileDataJson =
+ this->DumpCompileData(this->BuildCompileData(sf));
+ std::map<Json::Value, Json::ArrayIndex>::iterator i =
+ this->CompileGroupMap.find(compileDataJson);
+ if (i == this->CompileGroupMap.end()) {
+ Json::ArrayIndex cgIndex =
+ static_cast<Json::ArrayIndex>(this->CompileGroups.size());
+ i =
+ this->CompileGroupMap.emplace(std::move(compileDataJson), cgIndex).first;
+ CompileGroup g;
+ g.Entry = i;
+ this->CompileGroups.push_back(std::move(g));
+ }
+ this->CompileGroups[i->second].SourceIndexes.append(si);
+ return i->second;
+}
+
+void Target::AddBacktrace(Json::Value& object, cmListFileBacktrace const& bt)
+{
+ Json::ArrayIndex backtrace;
+ if (this->Backtraces.Add(bt, backtrace)) {
+ object["backtrace"] = backtrace;
+ }
+}
+
+Json::Value Target::DumpPaths()
+{
+ Json::Value paths = Json::objectValue;
+ cmLocalGenerator* lg = this->GT->GetLocalGenerator();
+
+ std::string const& sourceDir = lg->GetCurrentSourceDirectory();
+ paths["source"] = RelativeIfUnder(this->TopSource, sourceDir);
+
+ std::string const& buildDir = lg->GetCurrentBinaryDirectory();
+ paths["build"] = RelativeIfUnder(this->TopBuild, buildDir);
+
+ return paths;
+}
+
+Json::Value Target::DumpSources()
+{
+ Json::Value sources = Json::arrayValue;
+ cmGeneratorTarget::KindedSources const& kinded =
+ this->GT->GetKindedSources(this->Config);
+ for (cmGeneratorTarget::SourceAndKind const& sk : kinded.Sources) {
+ sources.append(this->DumpSource(sk, sources.size()));
+ }
+ return sources;
+}
+
+Json::Value Target::DumpSource(cmGeneratorTarget::SourceAndKind const& sk,
+ Json::ArrayIndex si)
+{
+ Json::Value source = Json::objectValue;
+
+ std::string const path = sk.Source.Value->GetFullPath();
+ source["path"] = RelativeIfUnder(this->TopSource, path);
+ if (sk.Source.Value->GetIsGenerated()) {
+ source["isGenerated"] = true;
+ }
+ this->AddBacktrace(source, sk.Source.Backtrace);
+
+ if (cmSourceGroup* sg =
+ this->GT->Makefile->FindSourceGroup(path, this->SourceGroupsLocal)) {
+ source["sourceGroupIndex"] = this->AddSourceGroup(sg, si);
+ }
+
+ switch (sk.Kind) {
+ case cmGeneratorTarget::SourceKindObjectSource: {
+ source["compileGroupIndex"] =
+ this->AddSourceCompileGroup(sk.Source.Value, si);
+ } break;
+ case cmGeneratorTarget::SourceKindAppManifest:
+ case cmGeneratorTarget::SourceKindCertificate:
+ case cmGeneratorTarget::SourceKindCustomCommand:
+ case cmGeneratorTarget::SourceKindExternalObject:
+ case cmGeneratorTarget::SourceKindExtra:
+ case cmGeneratorTarget::SourceKindHeader:
+ case cmGeneratorTarget::SourceKindIDL:
+ case cmGeneratorTarget::SourceKindManifest:
+ case cmGeneratorTarget::SourceKindModuleDefinition:
+ case cmGeneratorTarget::SourceKindResx:
+ case cmGeneratorTarget::SourceKindXaml:
+ break;
+ }
+
+ return source;
+}
+
+Json::Value Target::DumpCompileData(CompileData cd)
+{
+ Json::Value result = Json::objectValue;
+
+ if (!cd.Language.empty()) {
+ result["language"] = cd.Language;
+ }
+ if (!cd.Sysroot.empty()) {
+ result["sysroot"] = this->DumpSysroot(cd.Sysroot);
+ }
+ if (!cd.Flags.empty()) {
+ result["compileCommandFragments"] = this->DumpCommandFragments(cd.Flags);
+ }
+ if (!cd.Includes.empty()) {
+ Json::Value includes = Json::arrayValue;
+ for (auto const& i : cd.Includes) {
+ includes.append(this->DumpInclude(i));
+ }
+ result["includes"] = includes;
+ }
+ if (!cd.Defines.empty()) {
+ Json::Value defines = Json::arrayValue;
+ for (BT<std::string> const& d : cd.Defines) {
+ defines.append(this->DumpDefine(d));
+ }
+ result["defines"] = std::move(defines);
+ }
+
+ return result;
+}
+
+Json::Value Target::DumpInclude(CompileData::IncludeEntry const& inc)
+{
+ Json::Value include = Json::objectValue;
+ include["path"] = inc.Path.Value;
+ if (inc.IsSystem) {
+ include["isSystem"] = true;
+ }
+ this->AddBacktrace(include, inc.Path.Backtrace);
+ return include;
+}
+
+Json::Value Target::DumpDefine(BT<std::string> const& def)
+{
+ Json::Value define = Json::objectValue;
+ define["define"] = def.Value;
+ this->AddBacktrace(define, def.Backtrace);
+ return define;
+}
+
+Json::Value Target::DumpSourceGroups()
+{
+ Json::Value sourceGroups = Json::arrayValue;
+ for (auto& sg : this->SourceGroups) {
+ sourceGroups.append(this->DumpSourceGroup(sg));
+ }
+ return sourceGroups;
+}
+
+Json::Value Target::DumpSourceGroup(SourceGroup& sg)
+{
+ Json::Value group = Json::objectValue;
+ group["name"] = sg.Name;
+ group["sourceIndexes"] = std::move(sg.SourceIndexes);
+ return group;
+}
+
+Json::Value Target::DumpCompileGroups()
+{
+ Json::Value compileGroups = Json::arrayValue;
+ for (auto& cg : this->CompileGroups) {
+ compileGroups.append(this->DumpCompileGroup(cg));
+ }
+ return compileGroups;
+}
+
+Json::Value Target::DumpCompileGroup(CompileGroup& cg)
+{
+ Json::Value group = cg.Entry->first;
+ group["sourceIndexes"] = std::move(cg.SourceIndexes);
+ return group;
+}
+
+Json::Value Target::DumpSysroot(std::string const& path)
+{
+ Json::Value sysroot = Json::objectValue;
+ sysroot["path"] = path;
+ return sysroot;
+}
+
+Json::Value Target::DumpInstall()
+{
+ Json::Value install = Json::objectValue;
+ install["prefix"] = this->DumpInstallPrefix();
+ install["destinations"] = this->DumpInstallDestinations();
+ return install;
+}
+
+Json::Value Target::DumpInstallPrefix()
+{
+ Json::Value prefix = Json::objectValue;
+ std::string p =
+ this->GT->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
+ cmSystemTools::ConvertToUnixSlashes(p);
+ prefix["path"] = p;
+ return prefix;
+}
+
+Json::Value Target::DumpInstallDestinations()
+{
+ Json::Value destinations = Json::arrayValue;
+ auto installGens = this->GT->Target->GetInstallGenerators();
+ for (auto itGen : installGens) {
+ destinations.append(this->DumpInstallDestination(itGen));
+ }
+ return destinations;
+}
+
+Json::Value Target::DumpInstallDestination(cmInstallTargetGenerator* itGen)
+{
+ Json::Value destination = Json::objectValue;
+ destination["path"] = itGen->GetDestination(this->Config);
+ this->AddBacktrace(destination, itGen->GetBacktrace());
+ return destination;
+}
+
+Json::Value Target::DumpArtifacts()
+{
+ Json::Value artifacts = Json::arrayValue;
+
+ // Object libraries have only object files as artifacts.
+ if (this->GT->GetType() == cmStateEnums::OBJECT_LIBRARY) {
+ if (!this->GT->GetGlobalGenerator()->HasKnownObjectFileLocation(nullptr)) {
+ return artifacts;
+ }
+ std::vector<cmSourceFile const*> objectSources;
+ this->GT->GetObjectSources(objectSources, this->Config);
+ std::string const obj_dir = this->GT->GetObjectDirectory(this->Config);
+ for (cmSourceFile const* sf : objectSources) {
+ const std::string& obj = this->GT->GetObjectName(sf);
+ Json::Value artifact = Json::objectValue;
+ artifact["path"] = RelativeIfUnder(this->TopBuild, obj_dir + obj);
+ artifacts.append(std::move(artifact)); // NOLINT(*)
+ }
+ return artifacts;
+ }
+
+ // Other target types always have a "main" artifact.
+ {
+ Json::Value artifact = Json::objectValue;
+ artifact["path"] =
+ RelativeIfUnder(this->TopBuild,
+ this->GT->GetFullPath(
+ this->Config, cmStateEnums::RuntimeBinaryArtifact));
+ artifacts.append(std::move(artifact)); // NOLINT(*)
+ }
+
+ // Add Windows-specific artifacts produced by the linker.
+ if (this->GT->IsDLLPlatform() &&
+ this->GT->GetType() != cmStateEnums::STATIC_LIBRARY) {
+ if (this->GT->GetType() == cmStateEnums::SHARED_LIBRARY ||
+ this->GT->IsExecutableWithExports()) {
+ Json::Value artifact = Json::objectValue;
+ artifact["path"] =
+ RelativeIfUnder(this->TopBuild,
+ this->GT->GetFullPath(
+ this->Config, cmStateEnums::ImportLibraryArtifact));
+ artifacts.append(std::move(artifact)); // NOLINT(*)
+ }
+ cmGeneratorTarget::OutputInfo const* output =
+ this->GT->GetOutputInfo(this->Config);
+ if (output && !output->PdbDir.empty()) {
+ Json::Value artifact = Json::objectValue;
+ artifact["path"] = RelativeIfUnder(this->TopBuild,
+ output->PdbDir + '/' +
+ this->GT->GetPDBName(this->Config));
+ artifacts.append(std::move(artifact)); // NOLINT(*)
+ }
+ }
+ return artifacts;
+}
+
+Json::Value Target::DumpLink()
+{
+ Json::Value link = Json::objectValue;
+ std::string lang = this->GT->GetLinkerLanguage(this->Config);
+ link["language"] = lang;
+ {
+ Json::Value commandFragments = this->DumpLinkCommandFragments();
+ if (!commandFragments.empty()) {
+ link["commandFragments"] = std::move(commandFragments);
+ }
+ }
+ if (const char* sysrootLink =
+ this->GT->Makefile->GetDefinition("CMAKE_SYSROOT_LINK")) {
+ link["sysroot"] = this->DumpSysroot(sysrootLink);
+ } else if (const char* sysroot =
+ this->GT->Makefile->GetDefinition("CMAKE_SYSROOT")) {
+ link["sysroot"] = this->DumpSysroot(sysroot);
+ }
+ if (this->GT->IsIPOEnabled(lang, this->Config)) {
+ link["lto"] = true;
+ }
+ return link;
+}
+
+Json::Value Target::DumpArchive()
+{
+ Json::Value archive = Json::objectValue;
+ {
+ // The "link" fragments not relevant to static libraries are empty.
+ Json::Value commandFragments = this->DumpLinkCommandFragments();
+ if (!commandFragments.empty()) {
+ archive["commandFragments"] = std::move(commandFragments);
+ }
+ }
+ std::string lang = this->GT->GetLinkerLanguage(this->Config);
+ if (this->GT->IsIPOEnabled(lang, this->Config)) {
+ archive["lto"] = true;
+ }
+ return archive;
+}
+
+Json::Value Target::DumpLinkCommandFragments()
+{
+ Json::Value linkFragments = Json::arrayValue;
+
+ std::string linkLanguageFlags;
+ std::string linkFlags;
+ std::string frameworkPath;
+ std::string linkPath;
+ std::string linkLibs;
+ cmLocalGenerator* lg = this->GT->GetLocalGenerator();
+ cmLinkLineComputer linkLineComputer(lg,
+ lg->GetStateSnapshot().GetDirectory());
+ lg->GetTargetFlags(&linkLineComputer, this->Config, linkLibs,
+ linkLanguageFlags, linkFlags, frameworkPath, linkPath,
+ this->GT);
+ linkLanguageFlags = cmSystemTools::TrimWhitespace(linkLanguageFlags);
+ linkFlags = cmSystemTools::TrimWhitespace(linkFlags);
+ frameworkPath = cmSystemTools::TrimWhitespace(frameworkPath);
+ linkPath = cmSystemTools::TrimWhitespace(linkPath);
+ linkLibs = cmSystemTools::TrimWhitespace(linkLibs);
+
+ if (!linkLanguageFlags.empty()) {
+ linkFragments.append(
+ this->DumpCommandFragment(std::move(linkLanguageFlags), "flags"));
+ }
+
+ if (!linkFlags.empty()) {
+ linkFragments.append(
+ this->DumpCommandFragment(std::move(linkFlags), "flags"));
+ }
+
+ if (!frameworkPath.empty()) {
+ linkFragments.append(
+ this->DumpCommandFragment(std::move(frameworkPath), "frameworkPath"));
+ }
+
+ if (!linkPath.empty()) {
+ linkFragments.append(
+ this->DumpCommandFragment(std::move(linkPath), "libraryPath"));
+ }
+
+ if (!linkLibs.empty()) {
+ linkFragments.append(
+ this->DumpCommandFragment(std::move(linkLibs), "libraries"));
+ }
+
+ return linkFragments;
+}
+
+Json::Value Target::DumpCommandFragments(
+ std::vector<BT<std::string>> const& frags)
+{
+ Json::Value commandFragments = Json::arrayValue;
+ for (BT<std::string> const& f : frags) {
+ commandFragments.append(this->DumpCommandFragment(f));
+ }
+ return commandFragments;
+}
+
+Json::Value Target::DumpCommandFragment(BT<std::string> const& frag,
+ std::string const& role)
+{
+ Json::Value fragment = Json::objectValue;
+ fragment["fragment"] = frag.Value;
+ if (!role.empty()) {
+ fragment["role"] = role;
+ }
+ this->AddBacktrace(fragment, frag.Backtrace);
+ return fragment;
+}
+
+Json::Value Target::DumpDependencies()
+{
+ Json::Value dependencies = Json::arrayValue;
+ cmGlobalGenerator* gg = this->GT->GetGlobalGenerator();
+ for (cmTargetDepend const& td : gg->GetTargetDirectDepends(this->GT)) {
+ dependencies.append(this->DumpDependency(td));
+ }
+ return dependencies;
+}
+
+Json::Value Target::DumpDependency(cmTargetDepend const& td)
+{
+ Json::Value dependency = Json::objectValue;
+ dependency["id"] = TargetId(td, this->TopBuild);
+ this->AddBacktrace(dependency, td.GetBacktrace());
+ return dependency;
+}
+
+Json::Value Target::DumpFolder()
+{
+ Json::Value folder;
+ if (const char* f = this->GT->GetProperty("FOLDER")) {
+ folder = Json::objectValue;
+ folder["name"] = f;
+ }
+ return folder;
+}
+}
+
+Json::Value cmFileAPICodemodelDump(cmFileAPI& fileAPI, unsigned long version)
+{
+ Codemodel codemodel(fileAPI, version);
+ return codemodel.Dump();
+}
diff --git a/Source/cmFileAPICodemodel.h b/Source/cmFileAPICodemodel.h
new file mode 100644
index 000000000..ffbd92863
--- /dev/null
+++ b/Source/cmFileAPICodemodel.h
@@ -0,0 +1,15 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmFileAPICodemodel_h
+#define cmFileAPICodemodel_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cm_jsoncpp_value.h"
+
+class cmFileAPI;
+
+extern Json::Value cmFileAPICodemodelDump(cmFileAPI& fileAPI,
+ unsigned long version);
+
+#endif
diff --git a/Source/cmFileCopier.cxx b/Source/cmFileCopier.cxx
new file mode 100644
index 000000000..49e8cd5b3
--- /dev/null
+++ b/Source/cmFileCopier.cxx
@@ -0,0 +1,713 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#include "cmFileCopier.h"
+
+#include "cmFSPermissions.h"
+#include "cmFileCommand.h"
+#include "cmFileTimes.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+#include "cmsys/Directory.hxx"
+#include "cmsys/Glob.hxx"
+
+#ifdef _WIN32
+# include "cmsys/FStream.hxx"
+#endif
+
+#include <sstream>
+#include <string.h>
+
+using namespace cmFSPermissions;
+
+cmFileCopier::cmFileCopier(cmFileCommand* command, const char* name)
+ : FileCommand(command)
+ , Makefile(command->GetMakefile())
+ , Name(name)
+ , Always(false)
+ , MatchlessFiles(true)
+ , FilePermissions(0)
+ , DirPermissions(0)
+ , CurrentMatchRule(nullptr)
+ , UseGivenPermissionsFile(false)
+ , UseGivenPermissionsDir(false)
+ , UseSourcePermissions(true)
+ , FollowSymlinkChain(false)
+ , Doing(DoingNone)
+{
+}
+
+cmFileCopier::~cmFileCopier() = default;
+
+cmFileCopier::MatchProperties cmFileCopier::CollectMatchProperties(
+ const std::string& file)
+{
+ // Match rules are case-insensitive on some platforms.
+#if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
+ const std::string file_to_match = cmSystemTools::LowerCase(file);
+#else
+ const std::string& file_to_match = file;
+#endif
+
+ // Collect properties from all matching rules.
+ bool matched = false;
+ MatchProperties result;
+ for (MatchRule& mr : this->MatchRules) {
+ if (mr.Regex.find(file_to_match)) {
+ matched = true;
+ result.Exclude |= mr.Properties.Exclude;
+ result.Permissions |= mr.Properties.Permissions;
+ }
+ }
+ if (!matched && !this->MatchlessFiles) {
+ result.Exclude = !cmSystemTools::FileIsDirectory(file);
+ }
+ return result;
+}
+
+bool cmFileCopier::SetPermissions(const std::string& toFile,
+ mode_t permissions)
+{
+ if (permissions) {
+#ifdef WIN32
+ if (Makefile->IsOn("CMAKE_CROSSCOMPILING")) {
+ // Store the mode in an NTFS alternate stream.
+ std::string mode_t_adt_filename = toFile + ":cmake_mode_t";
+
+ // Writing to an NTFS alternate stream changes the modification
+ // time, so we need to save and restore its original value.
+ cmFileTimes file_time_orig(toFile);
+ {
+ cmsys::ofstream permissionStream(mode_t_adt_filename.c_str());
+ if (permissionStream) {
+ permissionStream << std::oct << permissions << std::endl;
+ }
+ permissionStream.close();
+ }
+ file_time_orig.Store(toFile);
+ }
+#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;
+}
+
+// Translate an argument to a permissions bit.
+bool cmFileCopier::CheckPermissions(std::string const& arg,
+ mode_t& permissions)
+{
+ if (!cmFSPermissions::stringToModeT(arg, permissions)) {
+ std::ostringstream e;
+ e << this->Name << " given invalid permission \"" << arg << "\".";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+ return true;
+}
+
+std::string const& cmFileCopier::ToName(std::string const& fromName)
+{
+ return fromName;
+}
+
+bool cmFileCopier::ReportMissing(const std::string& fromFile)
+{
+ // The input file does not exist and installation is not optional.
+ std::ostringstream e;
+ e << this->Name << " cannot find \"" << fromFile << "\".";
+ this->FileCommand->SetError(e.str());
+ return false;
+}
+
+void cmFileCopier::NotBeforeMatch(std::string const& arg)
+{
+ std::ostringstream e;
+ e << "option " << arg << " may not appear before PATTERN or REGEX.";
+ this->FileCommand->SetError(e.str());
+ this->Doing = DoingError;
+}
+
+void cmFileCopier::NotAfterMatch(std::string const& arg)
+{
+ std::ostringstream e;
+ e << "option " << arg << " may not appear after PATTERN or REGEX.";
+ this->FileCommand->SetError(e.str());
+ this->Doing = DoingError;
+}
+
+void cmFileCopier::DefaultFilePermissions()
+{
+ // Use read/write permissions.
+ this->FilePermissions = 0;
+ this->FilePermissions |= mode_owner_read;
+ this->FilePermissions |= mode_owner_write;
+ this->FilePermissions |= mode_group_read;
+ this->FilePermissions |= mode_world_read;
+}
+
+void cmFileCopier::DefaultDirectoryPermissions()
+{
+ // Use read/write/executable permissions.
+ this->DirPermissions = 0;
+ this->DirPermissions |= mode_owner_read;
+ this->DirPermissions |= mode_owner_write;
+ this->DirPermissions |= mode_owner_execute;
+ this->DirPermissions |= mode_group_read;
+ this->DirPermissions |= mode_group_execute;
+ this->DirPermissions |= mode_world_read;
+ this->DirPermissions |= mode_world_execute;
+}
+
+bool cmFileCopier::GetDefaultDirectoryPermissions(mode_t** mode)
+{
+ // check if default dir creation permissions were set
+ const char* default_dir_install_permissions = this->Makefile->GetDefinition(
+ "CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS");
+ if (default_dir_install_permissions && *default_dir_install_permissions) {
+ std::vector<std::string> items;
+ cmSystemTools::ExpandListArgument(default_dir_install_permissions, items);
+ for (const auto& arg : items) {
+ if (!this->CheckPermissions(arg, **mode)) {
+ std::ostringstream e;
+ e << this->FileCommand->GetError()
+ << " Set with CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS "
+ "variable.";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+ }
+ } else {
+ *mode = nullptr;
+ }
+
+ return true;
+}
+
+bool cmFileCopier::Parse(std::vector<std::string> const& args)
+{
+ this->Doing = DoingFiles;
+ for (unsigned int i = 1; i < args.size(); ++i) {
+ // Check this argument.
+ if (!this->CheckKeyword(args[i]) && !this->CheckValue(args[i])) {
+ std::ostringstream e;
+ e << "called with unknown argument \"" << args[i] << "\".";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+
+ // Quit if an argument is invalid.
+ if (this->Doing == DoingError) {
+ return false;
+ }
+ }
+
+ // Require a destination.
+ if (this->Destination.empty()) {
+ std::ostringstream e;
+ e << this->Name << " given no DESTINATION";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+
+ // If file permissions were not specified set default permissions.
+ if (!this->UseGivenPermissionsFile && !this->UseSourcePermissions) {
+ this->DefaultFilePermissions();
+ }
+
+ // If directory permissions were not specified set default permissions.
+ if (!this->UseGivenPermissionsDir && !this->UseSourcePermissions) {
+ this->DefaultDirectoryPermissions();
+ }
+
+ return true;
+}
+
+bool cmFileCopier::CheckKeyword(std::string const& arg)
+{
+ if (arg == "DESTINATION") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingDestination;
+ }
+ } else if (arg == "FILES_FROM_DIR") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingFilesFromDir;
+ }
+ } else if (arg == "PATTERN") {
+ this->Doing = DoingPattern;
+ } else if (arg == "REGEX") {
+ this->Doing = DoingRegex;
+ } else if (arg == "FOLLOW_SYMLINK_CHAIN") {
+ this->FollowSymlinkChain = true;
+ this->Doing = DoingNone;
+ } else if (arg == "EXCLUDE") {
+ // Add this property to the current match rule.
+ if (this->CurrentMatchRule) {
+ this->CurrentMatchRule->Properties.Exclude = true;
+ this->Doing = DoingNone;
+ } else {
+ this->NotBeforeMatch(arg);
+ }
+ } else if (arg == "PERMISSIONS") {
+ if (this->CurrentMatchRule) {
+ this->Doing = DoingPermissionsMatch;
+ } else {
+ this->NotBeforeMatch(arg);
+ }
+ } else if (arg == "FILE_PERMISSIONS") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingPermissionsFile;
+ this->UseGivenPermissionsFile = true;
+ }
+ } else if (arg == "DIRECTORY_PERMISSIONS") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingPermissionsDir;
+ this->UseGivenPermissionsDir = true;
+ }
+ } else if (arg == "USE_SOURCE_PERMISSIONS") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingNone;
+ this->UseSourcePermissions = true;
+ }
+ } else if (arg == "NO_SOURCE_PERMISSIONS") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingNone;
+ this->UseSourcePermissions = false;
+ }
+ } else if (arg == "FILES_MATCHING") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingNone;
+ this->MatchlessFiles = false;
+ }
+ } else {
+ return false;
+ }
+ return true;
+}
+
+bool cmFileCopier::CheckValue(std::string const& arg)
+{
+ switch (this->Doing) {
+ case DoingFiles:
+ this->Files.push_back(arg);
+ break;
+ case DoingDestination:
+ if (arg.empty() || cmSystemTools::FileIsFullPath(arg)) {
+ this->Destination = arg;
+ } else {
+ this->Destination = this->Makefile->GetCurrentBinaryDirectory();
+ this->Destination += "/" + arg;
+ }
+ this->Doing = DoingNone;
+ break;
+ case DoingFilesFromDir:
+ if (cmSystemTools::FileIsFullPath(arg)) {
+ this->FilesFromDir = arg;
+ } else {
+ this->FilesFromDir = this->Makefile->GetCurrentSourceDirectory();
+ this->FilesFromDir += "/" + arg;
+ }
+ cmSystemTools::ConvertToUnixSlashes(this->FilesFromDir);
+ this->Doing = DoingNone;
+ break;
+ case DoingPattern: {
+ // Convert the pattern to a regular expression. Require a
+ // leading slash and trailing end-of-string in the matched
+ // string to make sure the pattern matches only whole file
+ // names.
+ std::string regex = "/";
+ regex += cmsys::Glob::PatternToRegex(arg, false);
+ regex += "$";
+ this->MatchRules.emplace_back(regex);
+ this->CurrentMatchRule = &*(this->MatchRules.end() - 1);
+ if (this->CurrentMatchRule->Regex.is_valid()) {
+ this->Doing = DoingNone;
+ } else {
+ std::ostringstream e;
+ e << "could not compile PATTERN \"" << arg << "\".";
+ this->FileCommand->SetError(e.str());
+ this->Doing = DoingError;
+ }
+ } break;
+ case DoingRegex:
+ this->MatchRules.emplace_back(arg);
+ this->CurrentMatchRule = &*(this->MatchRules.end() - 1);
+ if (this->CurrentMatchRule->Regex.is_valid()) {
+ this->Doing = DoingNone;
+ } else {
+ std::ostringstream e;
+ e << "could not compile REGEX \"" << arg << "\".";
+ this->FileCommand->SetError(e.str());
+ this->Doing = DoingError;
+ }
+ break;
+ case DoingPermissionsFile:
+ if (!this->CheckPermissions(arg, this->FilePermissions)) {
+ this->Doing = DoingError;
+ }
+ break;
+ case DoingPermissionsDir:
+ if (!this->CheckPermissions(arg, this->DirPermissions)) {
+ this->Doing = DoingError;
+ }
+ break;
+ case DoingPermissionsMatch:
+ if (!this->CheckPermissions(
+ arg, this->CurrentMatchRule->Properties.Permissions)) {
+ this->Doing = DoingError;
+ }
+ break;
+ default:
+ return false;
+ }
+ return true;
+}
+
+bool cmFileCopier::Run(std::vector<std::string> const& args)
+{
+ if (!this->Parse(args)) {
+ return false;
+ }
+
+ for (std::string const& f : this->Files) {
+ std::string file;
+ if (!f.empty() && !cmSystemTools::FileIsFullPath(f)) {
+ if (!this->FilesFromDir.empty()) {
+ file = this->FilesFromDir;
+ } else {
+ file = this->Makefile->GetCurrentSourceDirectory();
+ }
+ file += "/";
+ 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 = f;
+ }
+
+ // Split the input file into its directory and name components.
+ std::vector<std::string> fromPathComponents;
+ cmSystemTools::SplitPath(file, fromPathComponents);
+ std::string fromName = *(fromPathComponents.end() - 1);
+ std::string fromDir = cmSystemTools::JoinPath(
+ fromPathComponents.begin(), fromPathComponents.end() - 1);
+
+ // Compute the full path to the destination file.
+ std::string toFile = this->Destination;
+ if (!this->FilesFromDir.empty()) {
+ std::string dir = cmSystemTools::GetFilenamePath(f);
+ if (!dir.empty()) {
+ toFile += "/";
+ toFile += dir;
+ }
+ }
+ std::string const& toName = this->ToName(fromName);
+ if (!toName.empty()) {
+ toFile += "/";
+ toFile += toName;
+ }
+
+ // Construct the full path to the source file. The file name may
+ // have been changed above.
+ std::string fromFile = fromDir;
+ if (!fromName.empty()) {
+ fromFile += "/";
+ fromFile += fromName;
+ }
+
+ if (!this->Install(fromFile, toFile)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool cmFileCopier::Install(const std::string& fromFile,
+ const std::string& toFile)
+{
+ if (fromFile.empty()) {
+ std::ostringstream e;
+ e << "INSTALL encountered an empty string input file name.";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+
+ // Collect any properties matching this file name.
+ MatchProperties match_properties = this->CollectMatchProperties(fromFile);
+
+ // Skip the file if it is excluded.
+ if (match_properties.Exclude) {
+ return true;
+ }
+
+ if (cmSystemTools::SameFile(fromFile, toFile)) {
+ return true;
+ }
+
+ std::string newFromFile = fromFile;
+ std::string newToFile = toFile;
+
+ if (this->FollowSymlinkChain &&
+ !this->InstallSymlinkChain(newFromFile, newToFile)) {
+ return false;
+ }
+
+ if (cmSystemTools::FileIsSymlink(newFromFile)) {
+ return this->InstallSymlink(newFromFile, newToFile);
+ }
+ if (cmSystemTools::FileIsDirectory(newFromFile)) {
+ return this->InstallDirectory(newFromFile, newToFile, match_properties);
+ }
+ if (cmSystemTools::FileExists(newFromFile)) {
+ return this->InstallFile(newFromFile, newToFile, match_properties);
+ }
+ return this->ReportMissing(newFromFile);
+}
+
+bool cmFileCopier::InstallSymlinkChain(std::string& fromFile,
+ std::string& toFile)
+{
+ std::string newFromFile;
+ std::string toFilePath = cmSystemTools::GetFilenamePath(toFile);
+ while (cmSystemTools::ReadSymlink(fromFile, newFromFile)) {
+ if (!cmSystemTools::FileIsFullPath(newFromFile)) {
+ std::string fromFilePath = cmSystemTools::GetFilenamePath(fromFile);
+ newFromFile = fromFilePath + "/" + newFromFile;
+ }
+
+ std::string symlinkTarget = cmSystemTools::GetFilenameName(newFromFile);
+
+ bool copy = true;
+ if (!this->Always) {
+ std::string oldSymlinkTarget;
+ if (cmSystemTools::ReadSymlink(toFile, oldSymlinkTarget)) {
+ if (symlinkTarget == oldSymlinkTarget) {
+ copy = false;
+ }
+ }
+ }
+
+ this->ReportCopy(toFile, TypeLink, copy);
+
+ if (copy) {
+ cmSystemTools::RemoveFile(toFile);
+ cmSystemTools::MakeDirectory(toFilePath);
+
+ if (!cmSystemTools::CreateSymlink(symlinkTarget, toFile)) {
+ std::ostringstream e;
+ e << this->Name << " cannot create symlink \"" << toFile << "\".";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+ }
+
+ fromFile = newFromFile;
+ toFile = toFilePath + "/" + symlinkTarget;
+ }
+
+ return true;
+}
+
+bool cmFileCopier::InstallSymlink(const std::string& fromFile,
+ const std::string& toFile)
+{
+ // Read the original symlink.
+ std::string symlinkTarget;
+ if (!cmSystemTools::ReadSymlink(fromFile, symlinkTarget)) {
+ std::ostringstream e;
+ e << this->Name << " cannot read symlink \"" << fromFile
+ << "\" to duplicate at \"" << toFile << "\".";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+
+ // Compare the symlink value to that at the destination if not
+ // always installing.
+ bool copy = true;
+ if (!this->Always) {
+ std::string oldSymlinkTarget;
+ if (cmSystemTools::ReadSymlink(toFile, oldSymlinkTarget)) {
+ if (symlinkTarget == oldSymlinkTarget) {
+ copy = false;
+ }
+ }
+ }
+
+ // Inform the user about this file installation.
+ this->ReportCopy(toFile, TypeLink, copy);
+
+ if (copy) {
+ // Remove the destination file so we can always create the symlink.
+ cmSystemTools::RemoveFile(toFile);
+
+ // Create destination directory if it doesn't exist
+ cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(toFile));
+
+ // Create the symlink.
+ if (!cmSystemTools::CreateSymlink(symlinkTarget, toFile)) {
+ std::ostringstream e;
+ e << this->Name << " cannot duplicate symlink \"" << fromFile
+ << "\" at \"" << toFile << "\".";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool cmFileCopier::InstallFile(const std::string& fromFile,
+ const std::string& toFile,
+ MatchProperties match_properties)
+{
+ // Determine whether we will copy the file.
+ bool copy = true;
+ if (!this->Always) {
+ // If both files exist with the same time do not copy.
+ if (!this->FileTimes.DifferS(fromFile, toFile)) {
+ copy = false;
+ }
+ }
+
+ // Inform the user about this file installation.
+ this->ReportCopy(toFile, TypeFile, copy);
+
+ // Copy the file.
+ if (copy && !cmSystemTools::CopyAFile(fromFile, toFile, true)) {
+ std::ostringstream e;
+ e << this->Name << " cannot copy file \"" << fromFile << "\" to \""
+ << toFile << "\".";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+
+ // Set the file modification time of the destination file.
+ if (copy && !this->Always) {
+ // Add write permission so we can set the file time.
+ // Permissions are set unconditionally below anyway.
+ mode_t perm = 0;
+ if (cmSystemTools::GetPermissions(toFile, perm)) {
+ cmSystemTools::SetPermissions(toFile, perm | mode_owner_write);
+ }
+ if (!cmFileTimes::Copy(fromFile, toFile)) {
+ std::ostringstream e;
+ e << this->Name << " cannot set modification time on \"" << toFile
+ << "\"";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+ }
+
+ // Set permissions of the destination file.
+ mode_t permissions =
+ (match_properties.Permissions ? match_properties.Permissions
+ : this->FilePermissions);
+ if (!permissions) {
+ // No permissions were explicitly provided but the user requested
+ // that the source file permissions be used.
+ cmSystemTools::GetPermissions(fromFile, permissions);
+ }
+ return this->SetPermissions(toFile, permissions);
+}
+
+bool cmFileCopier::InstallDirectory(const std::string& source,
+ const std::string& destination,
+ MatchProperties match_properties)
+{
+ // Inform the user about this directory installation.
+ this->ReportCopy(destination, TypeDir,
+ !cmSystemTools::FileIsDirectory(destination));
+
+ // check if default dir creation permissions were set
+ mode_t default_dir_mode_v = 0;
+ mode_t* default_dir_mode = &default_dir_mode_v;
+ if (!this->GetDefaultDirectoryPermissions(&default_dir_mode)) {
+ return false;
+ }
+
+ // Make sure the destination directory exists.
+ if (!cmSystemTools::MakeDirectory(destination, default_dir_mode)) {
+ std::ostringstream e;
+ e << this->Name << " cannot make directory \"" << destination
+ << "\": " << cmSystemTools::GetLastSystemError();
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+
+ // Compute the requested permissions for the destination directory.
+ mode_t permissions =
+ (match_properties.Permissions ? match_properties.Permissions
+ : this->DirPermissions);
+ if (!permissions) {
+ // No permissions were explicitly provided but the user requested
+ // that the source directory permissions be used.
+ cmSystemTools::GetPermissions(source, permissions);
+ }
+
+ // Compute the set of permissions required on this directory to
+ // recursively install files and subdirectories safely.
+ mode_t required_permissions =
+ mode_owner_read | mode_owner_write | mode_owner_execute;
+
+ // If the required permissions are specified it is safe to set the
+ // final permissions now. Otherwise we must add the required
+ // permissions temporarily during file installation.
+ mode_t permissions_before = 0;
+ mode_t permissions_after = 0;
+ if ((permissions & required_permissions) == required_permissions) {
+ permissions_before = permissions;
+ } else {
+ permissions_before = permissions | required_permissions;
+ permissions_after = permissions;
+ }
+
+ // Set the required permissions of the destination directory.
+ if (!this->SetPermissions(destination, permissions_before)) {
+ return false;
+ }
+
+ // Load the directory contents to traverse it recursively.
+ cmsys::Directory dir;
+ if (!source.empty()) {
+ dir.Load(source);
+ }
+ unsigned long numFiles = static_cast<unsigned long>(dir.GetNumberOfFiles());
+ for (unsigned long fileNum = 0; fileNum < numFiles; ++fileNum) {
+ if (!(strcmp(dir.GetFile(fileNum), ".") == 0 ||
+ strcmp(dir.GetFile(fileNum), "..") == 0)) {
+ std::string fromPath = source;
+ fromPath += "/";
+ fromPath += dir.GetFile(fileNum);
+ std::string toPath = destination;
+ toPath += "/";
+ toPath += dir.GetFile(fileNum);
+ if (!this->Install(fromPath, toPath)) {
+ return false;
+ }
+ }
+ }
+
+ // Set the requested permissions of the destination directory.
+ return this->SetPermissions(destination, permissions_after);
+}
diff --git a/Source/cmFileCopier.h b/Source/cmFileCopier.h
new file mode 100644
index 000000000..a79a60b90
--- /dev/null
+++ b/Source/cmFileCopier.h
@@ -0,0 +1,122 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmFileCopier_h
+#define cmFileCopier_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cmFileTimeCache.h"
+#include "cm_sys_stat.h"
+#include "cmsys/RegularExpression.hxx"
+
+#include <string>
+#include <vector>
+
+class cmFileCommand;
+class cmMakefile;
+
+// File installation helper class.
+struct cmFileCopier
+{
+ cmFileCopier(cmFileCommand* command, const char* name = "COPY");
+ virtual ~cmFileCopier();
+
+ bool Run(std::vector<std::string> const& args);
+
+protected:
+ cmFileCommand* FileCommand;
+ cmMakefile* Makefile;
+ const char* Name;
+ bool Always;
+ cmFileTimeCache FileTimes;
+
+ // Whether to install a file not matching any expression.
+ bool MatchlessFiles;
+
+ // Permissions for files and directories installed by this object.
+ mode_t FilePermissions;
+ mode_t DirPermissions;
+
+ // Properties set by pattern and regex match rules.
+ struct MatchProperties
+ {
+ bool Exclude = false;
+ mode_t Permissions = 0;
+ };
+ struct MatchRule
+ {
+ cmsys::RegularExpression Regex;
+ MatchProperties Properties;
+ std::string RegexString;
+ MatchRule(std::string const& regex)
+ : Regex(regex)
+ , RegexString(regex)
+ {
+ }
+ };
+ std::vector<MatchRule> MatchRules;
+
+ // Get the properties from rules matching this input file.
+ MatchProperties CollectMatchProperties(const std::string& file);
+
+ bool SetPermissions(const std::string& toFile, mode_t permissions);
+
+ // Translate an argument to a permissions bit.
+ bool CheckPermissions(std::string const& arg, mode_t& permissions);
+
+ bool InstallSymlinkChain(std::string& fromFile, std::string& toFile);
+ bool InstallSymlink(const std::string& fromFile, const std::string& toFile);
+ bool InstallFile(const std::string& fromFile, const std::string& toFile,
+ MatchProperties match_properties);
+ bool InstallDirectory(const std::string& source,
+ const std::string& destination,
+ MatchProperties match_properties);
+ virtual bool Install(const std::string& fromFile, const std::string& toFile);
+ virtual std::string const& ToName(std::string const& fromName);
+
+ enum Type
+ {
+ TypeFile,
+ TypeDir,
+ TypeLink
+ };
+ virtual void ReportCopy(const std::string&, Type, bool) {}
+ virtual bool ReportMissing(const std::string& fromFile);
+
+ MatchRule* CurrentMatchRule;
+ bool UseGivenPermissionsFile;
+ bool UseGivenPermissionsDir;
+ bool UseSourcePermissions;
+ bool FollowSymlinkChain;
+ std::string Destination;
+ std::string FilesFromDir;
+ std::vector<std::string> Files;
+ int Doing;
+
+ virtual bool Parse(std::vector<std::string> const& args);
+ enum
+ {
+ DoingNone,
+ DoingError,
+ DoingDestination,
+ DoingFilesFromDir,
+ DoingFiles,
+ DoingPattern,
+ DoingRegex,
+ DoingPermissionsFile,
+ DoingPermissionsDir,
+ DoingPermissionsMatch,
+ DoingLast1
+ };
+ virtual bool CheckKeyword(std::string const& arg);
+ virtual bool CheckValue(std::string const& arg);
+
+ void NotBeforeMatch(std::string const& arg);
+ void NotAfterMatch(std::string const& arg);
+ virtual void DefaultFilePermissions();
+ virtual void DefaultDirectoryPermissions();
+
+ bool GetDefaultDirectoryPermissions(mode_t** mode);
+};
+
+#endif
diff --git a/Source/cmFileInstaller.cxx b/Source/cmFileInstaller.cxx
new file mode 100644
index 000000000..d4f76fd86
--- /dev/null
+++ b/Source/cmFileInstaller.cxx
@@ -0,0 +1,350 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#include "cmFileInstaller.h"
+
+#include "cmFSPermissions.h"
+#include "cmFileCommand.h"
+#include "cmMakefile.h"
+#include "cmSystemTools.h"
+
+#include "cm_sys_stat.h"
+
+#include <sstream>
+
+using namespace cmFSPermissions;
+
+cmFileInstaller::cmFileInstaller(cmFileCommand* command)
+ : cmFileCopier(command, "INSTALL")
+ , InstallType(cmInstallType_FILES)
+ , Optional(false)
+ , MessageAlways(false)
+ , MessageLazy(false)
+ , MessageNever(false)
+ , DestDirLength(0)
+{
+ // Installation does not use source permissions by default.
+ this->UseSourcePermissions = false;
+ // Check whether to copy files always or only if they have changed.
+ std::string install_always;
+ if (cmSystemTools::GetEnv("CMAKE_INSTALL_ALWAYS", install_always)) {
+ this->Always = cmSystemTools::IsOn(install_always);
+ }
+ // Get the current manifest.
+ this->Manifest =
+ this->Makefile->GetSafeDefinition("CMAKE_INSTALL_MANIFEST_FILES");
+}
+cmFileInstaller::~cmFileInstaller()
+{
+ // Save the updated install manifest.
+ this->Makefile->AddDefinition("CMAKE_INSTALL_MANIFEST_FILES",
+ this->Manifest.c_str());
+}
+
+void cmFileInstaller::ManifestAppend(std::string const& file)
+{
+ if (!this->Manifest.empty()) {
+ this->Manifest += ";";
+ }
+ this->Manifest += file.substr(this->DestDirLength);
+}
+
+std::string const& cmFileInstaller::ToName(std::string const& fromName)
+{
+ return this->Rename.empty() ? fromName : this->Rename;
+}
+
+void cmFileInstaller::ReportCopy(const std::string& toFile, Type type,
+ bool copy)
+{
+ if (!this->MessageNever && (copy || !this->MessageLazy)) {
+ std::string message = (copy ? "Installing: " : "Up-to-date: ");
+ message += toFile;
+ this->Makefile->DisplayStatus(message, -1);
+ }
+ if (type != TypeDir) {
+ // Add the file to the manifest.
+ this->ManifestAppend(toFile);
+ }
+}
+bool cmFileInstaller::ReportMissing(const std::string& fromFile)
+{
+ return (this->Optional || this->cmFileCopier::ReportMissing(fromFile));
+}
+bool cmFileInstaller::Install(const std::string& fromFile,
+ const std::string& toFile)
+{
+ // Support installing from empty source to make a directory.
+ if (this->InstallType == cmInstallType_DIRECTORY && fromFile.empty()) {
+ return this->InstallDirectory(fromFile, toFile, MatchProperties());
+ }
+ return this->cmFileCopier::Install(fromFile, toFile);
+}
+
+void cmFileInstaller::DefaultFilePermissions()
+{
+ this->cmFileCopier::DefaultFilePermissions();
+ // Add execute permissions based on the target type.
+ switch (this->InstallType) {
+ case cmInstallType_SHARED_LIBRARY:
+ case cmInstallType_MODULE_LIBRARY:
+ if (this->Makefile->IsOn("CMAKE_INSTALL_SO_NO_EXE")) {
+ break;
+ }
+ CM_FALLTHROUGH;
+ case cmInstallType_EXECUTABLE:
+ case cmInstallType_PROGRAMS:
+ this->FilePermissions |= mode_owner_execute;
+ this->FilePermissions |= mode_group_execute;
+ this->FilePermissions |= mode_world_execute;
+ break;
+ default:
+ break;
+ }
+}
+
+bool cmFileInstaller::Parse(std::vector<std::string> const& args)
+{
+ if (!this->cmFileCopier::Parse(args)) {
+ return false;
+ }
+
+ if (!this->Rename.empty()) {
+ if (!this->FilesFromDir.empty()) {
+ this->FileCommand->SetError("INSTALL option RENAME may not be "
+ "combined with FILES_FROM_DIR.");
+ return false;
+ }
+ if (this->InstallType != cmInstallType_FILES &&
+ this->InstallType != cmInstallType_PROGRAMS) {
+ this->FileCommand->SetError("INSTALL option RENAME may be used "
+ "only with FILES or PROGRAMS.");
+ return false;
+ }
+ if (this->Files.size() > 1) {
+ this->FileCommand->SetError("INSTALL option RENAME may be used "
+ "only with one file.");
+ return false;
+ }
+ }
+
+ if (!this->HandleInstallDestination()) {
+ return false;
+ }
+
+ if (((this->MessageAlways ? 1 : 0) + (this->MessageLazy ? 1 : 0) +
+ (this->MessageNever ? 1 : 0)) > 1) {
+ this->FileCommand->SetError("INSTALL options MESSAGE_ALWAYS, "
+ "MESSAGE_LAZY, and MESSAGE_NEVER "
+ "are mutually exclusive.");
+ return false;
+ }
+
+ return true;
+}
+
+bool cmFileInstaller::CheckKeyword(std::string const& arg)
+{
+ if (arg == "TYPE") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingType;
+ }
+ } else if (arg == "FILES") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingFiles;
+ }
+ } else if (arg == "RENAME") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingRename;
+ }
+ } else if (arg == "OPTIONAL") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingNone;
+ this->Optional = true;
+ }
+ } else if (arg == "MESSAGE_ALWAYS") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingNone;
+ this->MessageAlways = true;
+ }
+ } else if (arg == "MESSAGE_LAZY") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingNone;
+ this->MessageLazy = true;
+ }
+ } else if (arg == "MESSAGE_NEVER") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ this->Doing = DoingNone;
+ this->MessageNever = true;
+ }
+ } else if (arg == "PERMISSIONS") {
+ if (this->CurrentMatchRule) {
+ this->Doing = DoingPermissionsMatch;
+ } else {
+ // file(INSTALL) aliases PERMISSIONS to FILE_PERMISSIONS
+ this->Doing = DoingPermissionsFile;
+ this->UseGivenPermissionsFile = true;
+ }
+ } else if (arg == "DIR_PERMISSIONS") {
+ if (this->CurrentMatchRule) {
+ this->NotAfterMatch(arg);
+ } else {
+ // file(INSTALL) aliases DIR_PERMISSIONS to DIRECTORY_PERMISSIONS
+ this->Doing = DoingPermissionsDir;
+ this->UseGivenPermissionsDir = true;
+ }
+ } else if (arg == "COMPONENTS" || arg == "CONFIGURATIONS" ||
+ arg == "PROPERTIES") {
+ std::ostringstream e;
+ e << "INSTALL called with old-style " << arg << " argument. "
+ << "This script was generated with an older version of CMake. "
+ << "Re-run this cmake version on your build tree.";
+ this->FileCommand->SetError(e.str());
+ this->Doing = DoingError;
+ } else {
+ return this->cmFileCopier::CheckKeyword(arg);
+ }
+ return true;
+}
+
+bool cmFileInstaller::CheckValue(std::string const& arg)
+{
+ switch (this->Doing) {
+ case DoingType:
+ if (!this->GetTargetTypeFromString(arg)) {
+ this->Doing = DoingError;
+ }
+ break;
+ case DoingRename:
+ this->Rename = arg;
+ break;
+ default:
+ return this->cmFileCopier::CheckValue(arg);
+ }
+ return true;
+}
+
+bool cmFileInstaller::GetTargetTypeFromString(const std::string& stype)
+{
+ if (stype == "EXECUTABLE") {
+ this->InstallType = cmInstallType_EXECUTABLE;
+ } else if (stype == "FILE") {
+ this->InstallType = cmInstallType_FILES;
+ } else if (stype == "PROGRAM") {
+ this->InstallType = cmInstallType_PROGRAMS;
+ } else if (stype == "STATIC_LIBRARY") {
+ this->InstallType = cmInstallType_STATIC_LIBRARY;
+ } else if (stype == "SHARED_LIBRARY") {
+ this->InstallType = cmInstallType_SHARED_LIBRARY;
+ } else if (stype == "MODULE") {
+ this->InstallType = cmInstallType_MODULE_LIBRARY;
+ } else if (stype == "DIRECTORY") {
+ this->InstallType = cmInstallType_DIRECTORY;
+ } else {
+ std::ostringstream e;
+ e << "Option TYPE given unknown value \"" << stype << "\".";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
+ return true;
+}
+
+bool cmFileInstaller::HandleInstallDestination()
+{
+ std::string& destination = this->Destination;
+
+ // allow for / to be a valid destination
+ if (destination.size() < 2 && destination != "/") {
+ this->FileCommand->SetError("called with inappropriate arguments. "
+ "No DESTINATION provided or .");
+ return false;
+ }
+
+ std::string sdestdir;
+ if (cmSystemTools::GetEnv("DESTDIR", sdestdir) && !sdestdir.empty()) {
+ cmSystemTools::ConvertToUnixSlashes(sdestdir);
+ char ch1 = destination[0];
+ char ch2 = destination[1];
+ char ch3 = 0;
+ if (destination.size() > 2) {
+ ch3 = destination[2];
+ }
+ int skip = 0;
+ if (ch1 != '/') {
+ int relative = 0;
+ if (((ch1 >= 'a' && ch1 <= 'z') || (ch1 >= 'A' && ch1 <= 'Z')) &&
+ ch2 == ':') {
+ // Assume windows
+ // let's do some destdir magic:
+ skip = 2;
+ if (ch3 != '/') {
+ relative = 1;
+ }
+ } else {
+ relative = 1;
+ }
+ if (relative) {
+ // This is relative path on unix or windows. Since we are doing
+ // destdir, this case does not make sense.
+ this->FileCommand->SetError(
+ "called with relative DESTINATION. This "
+ "does not make sense when using DESTDIR. Specify "
+ "absolute path or remove DESTDIR environment variable.");
+ return false;
+ }
+ } else {
+ if (ch2 == '/') {
+ // looks like a network path.
+ std::string message =
+ "called with network path DESTINATION. This "
+ "does not make sense when using DESTDIR. Specify local "
+ "absolute path or remove DESTDIR environment variable."
+ "\nDESTINATION=\n";
+ message += destination;
+ this->FileCommand->SetError(message);
+ return false;
+ }
+ }
+ destination = sdestdir + destination.substr(skip);
+ this->DestDirLength = int(sdestdir.size());
+ }
+
+ // check if default dir creation permissions were set
+ mode_t default_dir_mode_v = 0;
+ mode_t* default_dir_mode = &default_dir_mode_v;
+ if (!this->GetDefaultDirectoryPermissions(&default_dir_mode)) {
+ return false;
+ }
+
+ if (this->InstallType != cmInstallType_DIRECTORY) {
+ if (!cmSystemTools::FileExists(destination)) {
+ if (!cmSystemTools::MakeDirectory(destination, default_dir_mode)) {
+ std::string errstring = "cannot create directory: " + destination +
+ ". Maybe need administrative privileges.";
+ this->FileCommand->SetError(errstring);
+ return false;
+ }
+ }
+ if (!cmSystemTools::FileIsDirectory(destination)) {
+ std::string errstring =
+ "INSTALL destination: " + destination + " is not a directory.";
+ this->FileCommand->SetError(errstring);
+ return false;
+ }
+ }
+ return true;
+}
diff --git a/Source/cmFileInstaller.h b/Source/cmFileInstaller.h
new file mode 100644
index 000000000..312529aa8
--- /dev/null
+++ b/Source/cmFileInstaller.h
@@ -0,0 +1,55 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmFileInstaller_h
+#define cmFileInstaller_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cmFileCopier.h"
+
+#include "cmInstallType.h"
+
+#include <string>
+#include <vector>
+
+class cmFileCommand;
+
+struct cmFileInstaller : public cmFileCopier
+{
+ cmFileInstaller(cmFileCommand* command);
+ ~cmFileInstaller() override;
+
+protected:
+ cmInstallType InstallType;
+ bool Optional;
+ bool MessageAlways;
+ bool MessageLazy;
+ bool MessageNever;
+ int DestDirLength;
+ std::string Rename;
+
+ std::string Manifest;
+ void ManifestAppend(std::string const& file);
+
+ std::string const& ToName(std::string const& fromName) override;
+
+ void ReportCopy(const std::string& toFile, Type type, bool copy) override;
+ bool ReportMissing(const std::string& fromFile) override;
+ bool Install(const std::string& fromFile,
+ const std::string& toFile) override;
+
+ bool Parse(std::vector<std::string> const& args) override;
+ enum
+ {
+ DoingType = DoingLast1,
+ DoingRename,
+ DoingLast2
+ };
+ bool CheckKeyword(std::string const& arg) override;
+ bool CheckValue(std::string const& arg) override;
+ void DefaultFilePermissions() override;
+ bool GetTargetTypeFromString(const std::string& stype);
+ bool HandleInstallDestination();
+};
+
+#endif
diff --git a/Source/cmFileTime.cxx b/Source/cmFileTime.cxx
new file mode 100644
index 000000000..253457ff2
--- /dev/null
+++ b/Source/cmFileTime.cxx
@@ -0,0 +1,49 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmFileTime.h"
+
+#include <string>
+#include <time.h>
+
+// Use a platform-specific API to get file times efficiently.
+#if !defined(_WIN32) || defined(__CYGWIN__)
+# include "cm_sys_stat.h"
+#else
+# include "cmsys/Encoding.hxx"
+# include <windows.h>
+#endif
+
+bool cmFileTime::Load(std::string const& fileName)
+{
+#if !defined(_WIN32) || defined(__CYGWIN__)
+ // POSIX version. Use the stat function.
+ struct stat fst;
+ if (::stat(fileName.c_str(), &fst) != 0) {
+ return false;
+ }
+# if CMake_STAT_HAS_ST_MTIM
+ // Nanosecond resolution
+ this->NS = fst.st_mtim.tv_sec * NsPerS + fst.st_mtim.tv_nsec;
+# elif CMake_STAT_HAS_ST_MTIMESPEC
+ // Nanosecond resolution
+ this->NS = fst.st_mtimespec.tv_sec * NsPerS + fst.st_mtimespec.tv_nsec;
+# else
+ // Second resolution
+ this->NS = fst.st_mtime * NsPerS;
+# endif
+#else
+ // Windows version. Get the modification time from extended file attributes.
+ WIN32_FILE_ATTRIBUTE_DATA fdata;
+ if (!GetFileAttributesExW(cmsys::Encoding::ToWide(fileName).c_str(),
+ GetFileExInfoStandard, &fdata)) {
+ return false;
+ }
+
+ // Copy the file time to the output location.
+ this->NS = (static_cast<NSC>(fdata.ftLastWriteTime.dwHighDateTime) << 32) |
+ static_cast<NSC>(fdata.ftLastWriteTime.dwLowDateTime);
+ // The file time resolution is 100 ns.
+ this->NS *= 100;
+#endif
+ return true;
+}
diff --git a/Source/cmFileTime.h b/Source/cmFileTime.h
new file mode 100644
index 000000000..d4de4e033
--- /dev/null
+++ b/Source/cmFileTime.h
@@ -0,0 +1,130 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmFileTime_h
+#define cmFileTime_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <string>
+
+/** \class cmFileTime
+ * \brief Abstract file modification time with support for comparison with
+ * other file modification times.
+ */
+class cmFileTime
+{
+public:
+ typedef long long NSC;
+ static constexpr NSC NsPerS = 1000000000;
+
+ cmFileTime() = default;
+ ~cmFileTime() = default;
+
+ /**
+ * @brief Loads the file time of fileName from the file system
+ * @return true on success
+ */
+ bool Load(std::string const& fileName);
+
+ /**
+ * @brief Return true if this is older than ftm
+ */
+ bool Older(cmFileTime const& ftm) const { return (this->NS - ftm.NS) < 0; }
+
+ /**
+ * @brief Return true if this is newer than ftm
+ */
+ bool Newer(cmFileTime const& ftm) const { return (ftm.NS - this->NS) < 0; }
+
+ /**
+ * @brief Return true if this is the same as ftm
+ */
+ bool Equal(cmFileTime const& ftm) const { return this->NS == ftm.NS; }
+
+ /**
+ * @brief Return true if this is not the same as ftm
+ */
+ bool Differ(cmFileTime const& ftm) const { return this->NS != ftm.NS; }
+
+ /**
+ * @brief Compare file modification times.
+ * @return -1, 0, +1 for this older, same, or newer than ftm.
+ */
+ int Compare(cmFileTime const& ftm) const
+ {
+ NSC const diff = this->NS - ftm.NS;
+ if (diff == 0) {
+ return 0;
+ }
+ return (diff < 0) ? -1 : 1;
+ }
+
+ // -- Comparison in second resolution
+
+ /**
+ * @brief Return true if this is at least a second older than ftm
+ */
+ bool OlderS(cmFileTime const& ftm) const
+ {
+ return (ftm.NS - this->NS) >= cmFileTime::NsPerS;
+ }
+
+ /**
+ * @brief Return true if this is at least a second newer than ftm
+ */
+ bool NewerS(cmFileTime const& ftm) const
+ {
+ return (this->NS - ftm.NS) >= cmFileTime::NsPerS;
+ }
+
+ /**
+ * @brief Return true if this is within the same second as ftm
+ */
+ bool EqualS(cmFileTime const& ftm) const
+ {
+ NSC diff = this->NS - ftm.NS;
+ if (diff < 0) {
+ diff = -diff;
+ }
+ return (diff < cmFileTime::NsPerS);
+ }
+
+ /**
+ * @brief Return true if this is older or newer than ftm by at least a second
+ */
+ bool DifferS(cmFileTime const& ftm) const
+ {
+ NSC diff = this->NS - ftm.NS;
+ if (diff < 0) {
+ diff = -diff;
+ }
+ return (diff >= cmFileTime::NsPerS);
+ }
+
+ /**
+ * @brief Compare file modification times.
+ * @return -1: this at least a second older, 0: this within the same second
+ * as ftm, +1: this at least a second newer than ftm.
+ */
+ int CompareS(cmFileTime const& ftm) const
+ {
+ NSC const diff = this->NS - ftm.NS;
+ if (diff <= -cmFileTime::NsPerS) {
+ return -1;
+ }
+ if (diff >= cmFileTime::NsPerS) {
+ return 1;
+ }
+ return 0;
+ }
+
+ /**
+ * @brief The file modification time in nanoseconds
+ */
+ NSC GetNS() const { return this->NS; }
+
+private:
+ NSC NS = 0;
+};
+
+#endif
diff --git a/Source/cmFileTimeCache.cxx b/Source/cmFileTimeCache.cxx
new file mode 100644
index 000000000..24d6bf6e1
--- /dev/null
+++ b/Source/cmFileTimeCache.cxx
@@ -0,0 +1,62 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmFileTimeCache.h"
+
+#include <string>
+#include <unordered_map>
+#include <utility>
+
+cmFileTimeCache::cmFileTimeCache() = default;
+
+cmFileTimeCache::~cmFileTimeCache() = default;
+
+bool cmFileTimeCache::Load(std::string const& fileName, cmFileTime& fileTime)
+{
+ // Use the stored time if available.
+ {
+ auto fit = this->Cache.find(fileName);
+ if (fit != this->Cache.end()) {
+ fileTime = fit->second;
+ return true;
+ }
+ }
+ // Read file time from OS
+ if (!fileTime.Load(fileName)) {
+ return false;
+ }
+ // Store file time in cache
+ this->Cache[fileName] = fileTime;
+ return true;
+}
+
+bool cmFileTimeCache::Remove(std::string const& fileName)
+{
+ return (this->Cache.erase(fileName) != 0);
+}
+
+bool cmFileTimeCache::Compare(std::string const& f1, std::string const& f2,
+ int* result)
+{
+ // Get the modification time for each file.
+ cmFileTime ft1, ft2;
+ if (this->Load(f1, ft1) && this->Load(f2, ft2)) {
+ // Compare the two modification times.
+ *result = ft1.Compare(ft2);
+ return true;
+ }
+ // No comparison available. Default to the same time.
+ *result = 0;
+ return false;
+}
+
+bool cmFileTimeCache::DifferS(std::string const& f1, std::string const& f2)
+{
+ // Get the modification time for each file.
+ cmFileTime ft1, ft2;
+ if (this->Load(f1, ft1) && this->Load(f2, ft2)) {
+ // Compare the two modification times.
+ return ft1.DifferS(ft2);
+ }
+ // No comparison available. Default to different times.
+ return true;
+}
diff --git a/Source/cmFileTimeCache.h b/Source/cmFileTimeCache.h
new file mode 100644
index 000000000..4f1a3a253
--- /dev/null
+++ b/Source/cmFileTimeCache.h
@@ -0,0 +1,56 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmFileTimeCache_h
+#define cmFileTimeCache_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cmFileTime.h" // IWYU pragma: keep
+#include <string>
+#include <unordered_map>
+
+/** \class cmFileTimeCache
+ * \brief Caches file modification times in an internal map for fast lookups.
+ */
+class cmFileTimeCache
+{
+public:
+ cmFileTimeCache();
+ ~cmFileTimeCache();
+
+ cmFileTimeCache(const cmFileTimeCache&) = delete;
+ cmFileTimeCache& operator=(const cmFileTimeCache&) = delete;
+
+ /**
+ * @brief Loads the file time from the cache or the file system.
+ * @return true on success
+ */
+ bool Load(std::string const& fileName, cmFileTime& fileTime);
+
+ /**
+ * @brief Removes a file time from the cache
+ * @return true if the file was found in the cache and removed
+ */
+ bool Remove(std::string const& fileName);
+
+ /**
+ * @brief Compare file modification times.
+ * @return true for successful comparison and false for error.
+ *
+ * When true is returned, result has -1, 0, +1 for
+ * f1 older, same, or newer than f2.
+ */
+ bool Compare(std::string const& f1, std::string const& f2, int* result);
+
+ /**
+ * @brief Compare file modification times.
+ * @return true unless both files exist and have modification times less
+ * than 1 second apart.
+ */
+ bool DifferS(std::string const& f1, std::string const& f2);
+
+private:
+ std::unordered_map<std::string, cmFileTime> Cache;
+};
+
+#endif
diff --git a/Source/cmFileTimes.cxx b/Source/cmFileTimes.cxx
new file mode 100644
index 000000000..fd4f6797f
--- /dev/null
+++ b/Source/cmFileTimes.cxx
@@ -0,0 +1,127 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmFileTimes.h"
+
+#include "cmAlgorithms.h"
+#include "cm_sys_stat.h"
+
+#include <utility>
+
+#if defined(_WIN32)
+# include "cmSystemTools.h"
+# include <windows.h>
+#else
+# include <utime.h>
+#endif
+
+#if defined(_WIN32) && \
+ (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__MINGW32__))
+# include <io.h>
+#endif
+
+#ifdef _WIN32
+class cmFileTimes::WindowsHandle
+{
+public:
+ WindowsHandle(HANDLE h)
+ : handle_(h)
+ {
+ }
+ ~WindowsHandle()
+ {
+ if (this->handle_ != INVALID_HANDLE_VALUE) {
+ CloseHandle(this->handle_);
+ }
+ }
+ explicit operator bool() const
+ {
+ return this->handle_ != INVALID_HANDLE_VALUE;
+ }
+ bool operator!() const { return this->handle_ == INVALID_HANDLE_VALUE; }
+ operator HANDLE() const { return this->handle_; }
+
+private:
+ HANDLE handle_;
+};
+#endif
+
+class cmFileTimes::Times
+{
+public:
+#if defined(_WIN32) && !defined(__CYGWIN__)
+ FILETIME timeCreation;
+ FILETIME timeLastAccess;
+ FILETIME timeLastWrite;
+#else
+ struct utimbuf timeBuf;
+#endif
+};
+
+cmFileTimes::cmFileTimes() = default;
+cmFileTimes::cmFileTimes(std::string const& fileName)
+{
+ Load(fileName);
+}
+cmFileTimes::~cmFileTimes() = default;
+
+bool cmFileTimes::Load(std::string const& fileName)
+{
+ std::unique_ptr<Times> ptr;
+ if (IsValid()) {
+ // Invalidate this and re-use times
+ ptr.swap(this->times);
+ } else {
+ ptr = cm::make_unique<Times>();
+ }
+
+#if defined(_WIN32) && !defined(__CYGWIN__)
+ cmFileTimes::WindowsHandle handle =
+ CreateFileW(cmSystemTools::ConvertToWindowsExtendedPath(fileName).c_str(),
+ GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING,
+ FILE_FLAG_BACKUP_SEMANTICS, 0);
+ if (!handle) {
+ return false;
+ }
+ if (!GetFileTime(handle, &ptr->timeCreation, &ptr->timeLastAccess,
+ &ptr->timeLastWrite)) {
+ return false;
+ }
+#else
+ struct stat st;
+ if (stat(fileName.c_str(), &st) < 0) {
+ return false;
+ }
+ ptr->timeBuf.actime = st.st_atime;
+ ptr->timeBuf.modtime = st.st_mtime;
+#endif
+ // Accept times
+ this->times = std::move(ptr);
+ return true;
+}
+
+bool cmFileTimes::Store(std::string const& fileName) const
+{
+ if (!IsValid()) {
+ return false;
+ }
+
+#if defined(_WIN32) && !defined(__CYGWIN__)
+ cmFileTimes::WindowsHandle handle = CreateFileW(
+ cmSystemTools::ConvertToWindowsExtendedPath(fileName).c_str(),
+ FILE_WRITE_ATTRIBUTES, 0, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
+ if (!handle) {
+ return false;
+ }
+ return SetFileTime(handle, &this->times->timeCreation,
+ &this->times->timeLastAccess,
+ &this->times->timeLastWrite) != 0;
+#else
+ return utime(fileName.c_str(), &this->times->timeBuf) >= 0;
+#endif
+}
+
+bool cmFileTimes::Copy(std::string const& fromFile, std::string const& toFile)
+{
+ cmFileTimes fileTimes;
+ return (fileTimes.Load(fromFile) && fileTimes.Store(toFile));
+}
diff --git a/Source/cmFileTimes.h b/Source/cmFileTimes.h
new file mode 100644
index 000000000..cbf0fe20a
--- /dev/null
+++ b/Source/cmFileTimes.h
@@ -0,0 +1,40 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmFileTimes_h
+#define cmFileTimes_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <memory> // IWYU pragma: keep
+#include <string>
+
+/** \class cmFileTimes
+ * \brief Loads and stores file times.
+ */
+class cmFileTimes
+{
+public:
+ cmFileTimes();
+ //! Calls Load()
+ cmFileTimes(std::string const& fileName);
+ ~cmFileTimes();
+
+ //! @return true, if file times were loaded successfully
+ bool IsValid() const { return (times != nullptr); }
+ //! Try to load the file times from @a fileName and @return IsValid()
+ bool Load(std::string const& fileName);
+ //! Stores the file times at @a fileName (if IsValid())
+ bool Store(std::string const& fileName) const;
+
+ //! Copies the file times of @a fromFile to @a toFile
+ static bool Copy(std::string const& fromFile, std::string const& toFile);
+
+private:
+#ifdef _WIN32
+ class WindowsHandle;
+#endif
+ class Times;
+ std::unique_ptr<Times> times;
+};
+
+#endif
diff --git a/Source/cmGetPipes.cxx b/Source/cmGetPipes.cxx
new file mode 100644
index 000000000..ad323f7ee
--- /dev/null
+++ b/Source/cmGetPipes.cxx
@@ -0,0 +1,48 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmGetPipes.h"
+
+#include "cm_uv.h"
+
+#include <fcntl.h>
+
+#if defined(_WIN32) && !defined(__CYGWIN__)
+# include <io.h>
+
+int cmGetPipes(int* fds)
+{
+ SECURITY_ATTRIBUTES attr;
+ HANDLE readh, writeh;
+ attr.nLength = sizeof(attr);
+ attr.lpSecurityDescriptor = nullptr;
+ attr.bInheritHandle = FALSE;
+ if (!CreatePipe(&readh, &writeh, &attr, 0))
+ return uv_translate_sys_error(GetLastError());
+ fds[0] = _open_osfhandle((intptr_t)readh, 0);
+ fds[1] = _open_osfhandle((intptr_t)writeh, 0);
+ if (fds[0] == -1 || fds[1] == -1) {
+ CloseHandle(readh);
+ CloseHandle(writeh);
+ return uv_translate_sys_error(GetLastError());
+ }
+ return 0;
+}
+#else
+# include <errno.h>
+# include <unistd.h>
+
+int cmGetPipes(int* fds)
+{
+ if (pipe(fds) == -1) {
+ return uv_translate_sys_error(errno);
+ }
+
+ if (fcntl(fds[0], F_SETFD, FD_CLOEXEC) == -1 ||
+ fcntl(fds[1], F_SETFD, FD_CLOEXEC) == -1) {
+ close(fds[0]);
+ close(fds[1]);
+ return uv_translate_sys_error(errno);
+ }
+ return 0;
+}
+#endif
diff --git a/Source/cmGetPipes.h b/Source/cmGetPipes.h
new file mode 100644
index 000000000..2a46b51b3
--- /dev/null
+++ b/Source/cmGetPipes.h
@@ -0,0 +1,8 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmGetPipes_h
+#define cmGetPipes_h
+
+int cmGetPipes(int* fds);
+
+#endif
diff --git a/Source/cmGlobVerificationManager.cxx b/Source/cmGlobVerificationManager.cxx
new file mode 100644
index 000000000..9fb417098
--- /dev/null
+++ b/Source/cmGlobVerificationManager.cxx
@@ -0,0 +1,178 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmGlobVerificationManager.h"
+
+#include "cmsys/FStream.hxx"
+#include <sstream>
+
+#include "cmGeneratedFileStream.h"
+#include "cmListFileCache.h"
+#include "cmSystemTools.h"
+#include "cmVersion.h"
+
+bool cmGlobVerificationManager::SaveVerificationScript(const std::string& path)
+{
+ if (this->Cache.empty()) {
+ return true;
+ }
+
+ std::string scriptFile = path;
+ scriptFile += "/CMakeFiles";
+ std::string stampFile = scriptFile;
+ cmSystemTools::MakeDirectory(scriptFile);
+ scriptFile += "/VerifyGlobs.cmake";
+ stampFile += "/cmake.verify_globs";
+ cmGeneratedFileStream verifyScriptFile(scriptFile);
+ verifyScriptFile.SetCopyIfDifferent(true);
+ if (!verifyScriptFile) {
+ cmSystemTools::Error("Unable to open verification script file for save. " +
+ scriptFile);
+ cmSystemTools::ReportLastSystemError("");
+ return false;
+ }
+
+ verifyScriptFile << std::boolalpha;
+ verifyScriptFile << "# CMAKE generated file: DO NOT EDIT!\n"
+ << "# Generated by CMake Version "
+ << cmVersion::GetMajorVersion() << "."
+ << cmVersion::GetMinorVersion() << "\n";
+
+ for (auto const& i : this->Cache) {
+ CacheEntryKey k = std::get<0>(i);
+ CacheEntryValue v = std::get<1>(i);
+
+ if (!v.Initialized) {
+ continue;
+ }
+
+ verifyScriptFile << "\n";
+
+ for (auto const& bt : v.Backtraces) {
+ verifyScriptFile << "# " << std::get<0>(bt);
+ std::get<1>(bt).PrintTitle(verifyScriptFile);
+ verifyScriptFile << "\n";
+ }
+
+ k.PrintGlobCommand(verifyScriptFile, "NEW_GLOB");
+ verifyScriptFile << "\n";
+
+ verifyScriptFile << "set(OLD_GLOB\n";
+ for (const std::string& file : v.Files) {
+ verifyScriptFile << " \"" << file << "\"\n";
+ }
+ verifyScriptFile << " )\n";
+
+ verifyScriptFile << "if(NOT \"${NEW_GLOB}\" STREQUAL \"${OLD_GLOB}\")\n"
+ << " message(\"-- GLOB mismatch!\")\n"
+ << " file(TOUCH_NOCREATE \"" << stampFile << "\")\n"
+ << "endif()\n";
+ }
+ verifyScriptFile.Close();
+
+ cmsys::ofstream verifyStampFile(stampFile.c_str());
+ if (!verifyStampFile) {
+ cmSystemTools::Error("Unable to open verification stamp file for write. " +
+ stampFile);
+ return false;
+ }
+ verifyStampFile << "# This file is generated by CMake for checking of the "
+ "VerifyGlobs.cmake file\n";
+ this->VerifyScript = scriptFile;
+ this->VerifyStamp = stampFile;
+ return true;
+}
+
+bool cmGlobVerificationManager::DoWriteVerifyTarget() const
+{
+ return !this->VerifyScript.empty() && !this->VerifyStamp.empty();
+}
+
+bool cmGlobVerificationManager::CacheEntryKey::operator<(
+ const CacheEntryKey& r) const
+{
+ if (this->Recurse < r.Recurse) {
+ return true;
+ }
+ if (this->Recurse > r.Recurse) {
+ return false;
+ }
+ if (this->ListDirectories < r.ListDirectories) {
+ return true;
+ }
+ if (this->ListDirectories > r.ListDirectories) {
+ return false;
+ }
+ if (this->FollowSymlinks < r.FollowSymlinks) {
+ return true;
+ }
+ if (this->FollowSymlinks > r.FollowSymlinks) {
+ return false;
+ }
+ if (this->Relative < r.Relative) {
+ return true;
+ }
+ if (this->Relative > r.Relative) {
+ return false;
+ }
+ if (this->Expression < r.Expression) {
+ return true;
+ }
+ if (this->Expression > r.Expression) {
+ return false;
+ }
+ return false;
+}
+
+void cmGlobVerificationManager::CacheEntryKey::PrintGlobCommand(
+ std::ostream& out, const std::string& cmdVar)
+{
+ out << "file(GLOB" << (this->Recurse ? "_RECURSE " : " ");
+ out << cmdVar << " ";
+ if (this->Recurse && this->FollowSymlinks) {
+ out << "FOLLOW_SYMLINKS ";
+ }
+ out << "LIST_DIRECTORIES " << this->ListDirectories << " ";
+ if (!this->Relative.empty()) {
+ out << "RELATIVE \"" << this->Relative << "\" ";
+ }
+ out << "\"" << this->Expression << "\")";
+}
+
+void cmGlobVerificationManager::AddCacheEntry(
+ const bool recurse, const bool listDirectories, const bool followSymlinks,
+ const std::string& relative, const std::string& expression,
+ const std::vector<std::string>& files, const std::string& variable,
+ const cmListFileBacktrace& backtrace)
+{
+ CacheEntryKey key = CacheEntryKey(recurse, listDirectories, followSymlinks,
+ relative, expression);
+ CacheEntryValue& value = this->Cache[key];
+ if (!value.Initialized) {
+ value.Files = files;
+ value.Initialized = true;
+ value.Backtraces.emplace_back(variable, backtrace);
+ } else if (value.Initialized && value.Files != files) {
+ std::ostringstream message;
+ message << std::boolalpha;
+ message << "The glob expression\n";
+ key.PrintGlobCommand(message, variable);
+ backtrace.PrintTitle(message);
+ message << "\nwas already present in the glob cache but the directory\n"
+ "contents have changed during the configuration run.\n";
+ message << "Matching glob expressions:";
+ for (auto const& bt : value.Backtraces) {
+ message << "\n " << std::get<0>(bt);
+ std::get<1>(bt).PrintTitle(message);
+ }
+ cmSystemTools::Error(message.str());
+ } else {
+ value.Backtraces.emplace_back(variable, backtrace);
+ }
+}
+
+void cmGlobVerificationManager::Reset()
+{
+ this->Cache.clear();
+ this->VerifyScript.clear();
+ this->VerifyStamp.clear();
+}
diff --git a/Source/cmGlobVerificationManager.h b/Source/cmGlobVerificationManager.h
new file mode 100644
index 000000000..48606d3f3
--- /dev/null
+++ b/Source/cmGlobVerificationManager.h
@@ -0,0 +1,85 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmGlobVerificationManager_h
+#define cmGlobVerificationManager_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cmListFileCache.h"
+
+#include <iosfwd>
+#include <map>
+#include <string>
+#include <utility>
+#include <vector>
+
+/** \class cmGlobVerificationManager
+ * \brief Class for expressing build-time dependencies on glob expressions.
+ *
+ * Generates a CMake script which verifies glob outputs during prebuild.
+ *
+ */
+class cmGlobVerificationManager
+{
+protected:
+ //! Save verification script for given makefile.
+ //! Saves to output <path>/<CMakeFilesDirectory>/VerifyGlobs.cmake
+ bool SaveVerificationScript(const std::string& path);
+
+ //! Add an entry into the glob cache
+ void AddCacheEntry(bool recurse, bool listDirectories, bool followSymlinks,
+ const std::string& relative,
+ const std::string& expression,
+ const std::vector<std::string>& files,
+ const std::string& variable,
+ const cmListFileBacktrace& bt);
+
+ //! Clear the glob cache for state reset.
+ void Reset();
+
+ //! Check targets should be written in generated build system.
+ bool DoWriteVerifyTarget() const;
+
+ //! Get the paths to the generated script and stamp files
+ std::string const& GetVerifyScript() const { return this->VerifyScript; }
+ std::string const& GetVerifyStamp() const { return this->VerifyStamp; }
+
+private:
+ struct CacheEntryKey
+ {
+ const bool Recurse;
+ const bool ListDirectories;
+ const bool FollowSymlinks;
+ const std::string Relative;
+ const std::string Expression;
+ CacheEntryKey(const bool rec, const bool l, const bool s, std::string rel,
+ std::string e)
+ : Recurse(rec)
+ , ListDirectories(l)
+ , FollowSymlinks(s)
+ , Relative(std::move(rel))
+ , Expression(std::move(e))
+ {
+ }
+ bool operator<(const CacheEntryKey& r) const;
+ void PrintGlobCommand(std::ostream& out, const std::string& cmdVar);
+ };
+
+ struct CacheEntryValue
+ {
+ bool Initialized = false;
+ std::vector<std::string> Files;
+ std::vector<std::pair<std::string, cmListFileBacktrace>> Backtraces;
+ };
+
+ typedef std::map<CacheEntryKey, CacheEntryValue> CacheEntryMap;
+ CacheEntryMap Cache;
+ std::string VerifyScript;
+ std::string VerifyStamp;
+
+ // Only cmState should be able to add cache values.
+ // cmGlobVerificationManager should never be used directly.
+ friend class cmState; // allow access to add cache values
+};
+
+#endif
diff --git a/Source/cmGlobalVisualStudioVersionedGenerator.cxx b/Source/cmGlobalVisualStudioVersionedGenerator.cxx
new file mode 100644
index 000000000..66a57eb10
--- /dev/null
+++ b/Source/cmGlobalVisualStudioVersionedGenerator.cxx
@@ -0,0 +1,519 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmGlobalVisualStudioVersionedGenerator.h"
+
+#include "cmAlgorithms.h"
+#include "cmDocumentationEntry.h"
+#include "cmLocalVisualStudio10Generator.h"
+#include "cmMakefile.h"
+#include "cmVSSetupHelper.h"
+#include "cmake.h"
+
+#if defined(_M_ARM64)
+# define HOST_PLATFORM_NAME "ARM64"
+# define HOST_TOOLS_ARCH ""
+#elif defined(_M_ARM)
+# define HOST_PLATFORM_NAME "ARM"
+# define HOST_TOOLS_ARCH ""
+#elif defined(_M_IA64)
+# define HOST_PLATFORM_NAME "Itanium"
+# define HOST_TOOLS_ARCH ""
+#elif defined(_WIN64)
+# define HOST_PLATFORM_NAME "x64"
+# define HOST_TOOLS_ARCH "x64"
+#else
+static bool VSIsWow64()
+{
+ BOOL isWow64 = false;
+ return IsWow64Process(GetCurrentProcess(), &isWow64) && isWow64;
+}
+#endif
+
+static std::string VSHostPlatformName()
+{
+#ifdef HOST_PLATFORM_NAME
+ return HOST_PLATFORM_NAME;
+#else
+ if (VSIsWow64()) {
+ return "x64";
+ } else {
+ return "Win32";
+ }
+#endif
+}
+
+static std::string VSHostArchitecture()
+{
+#ifdef HOST_TOOLS_ARCH
+ return HOST_TOOLS_ARCH;
+#else
+ if (VSIsWow64()) {
+ return "x64";
+ } else {
+ return "x86";
+ }
+#endif
+}
+
+static unsigned int VSVersionToMajor(
+ cmGlobalVisualStudioGenerator::VSVersion v)
+{
+ switch (v) {
+ case cmGlobalVisualStudioGenerator::VS9:
+ return 9;
+ case cmGlobalVisualStudioGenerator::VS10:
+ return 10;
+ case cmGlobalVisualStudioGenerator::VS11:
+ return 11;
+ case cmGlobalVisualStudioGenerator::VS12:
+ return 12;
+ case cmGlobalVisualStudioGenerator::VS14:
+ return 14;
+ case cmGlobalVisualStudioGenerator::VS15:
+ return 15;
+ case cmGlobalVisualStudioGenerator::VS16:
+ return 16;
+ }
+ return 0;
+}
+
+static const char* VSVersionToToolset(
+ cmGlobalVisualStudioGenerator::VSVersion v)
+{
+ switch (v) {
+ case cmGlobalVisualStudioGenerator::VS9:
+ return "v90";
+ case cmGlobalVisualStudioGenerator::VS10:
+ return "v100";
+ case cmGlobalVisualStudioGenerator::VS11:
+ return "v110";
+ case cmGlobalVisualStudioGenerator::VS12:
+ return "v120";
+ case cmGlobalVisualStudioGenerator::VS14:
+ return "v140";
+ case cmGlobalVisualStudioGenerator::VS15:
+ return "v141";
+ case cmGlobalVisualStudioGenerator::VS16:
+ return "v142";
+ }
+ return "";
+}
+
+static const char vs15generatorName[] = "Visual Studio 15 2017";
+
+// Map generator name without year to name with year.
+static const char* cmVS15GenName(const std::string& name, std::string& genName)
+{
+ if (strncmp(name.c_str(), vs15generatorName,
+ sizeof(vs15generatorName) - 6) != 0) {
+ return 0;
+ }
+ const char* p = name.c_str() + sizeof(vs15generatorName) - 6;
+ if (cmHasLiteralPrefix(p, " 2017")) {
+ p += 5;
+ }
+ genName = std::string(vs15generatorName) + p;
+ return p;
+}
+
+class cmGlobalVisualStudioVersionedGenerator::Factory15
+ : public cmGlobalGeneratorFactory
+{
+public:
+ cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+ cmake* cm) const override
+ {
+ std::string genName;
+ const char* p = cmVS15GenName(name, genName);
+ if (!p) {
+ return 0;
+ }
+ if (!*p) {
+ return new cmGlobalVisualStudioVersionedGenerator(
+ cmGlobalVisualStudioGenerator::VS15, cm, genName, "");
+ }
+ if (*p++ != ' ') {
+ return 0;
+ }
+ if (strcmp(p, "Win64") == 0) {
+ return new cmGlobalVisualStudioVersionedGenerator(
+ cmGlobalVisualStudioGenerator::VS15, cm, genName, "x64");
+ }
+ if (strcmp(p, "ARM") == 0) {
+ return new cmGlobalVisualStudioVersionedGenerator(
+ cmGlobalVisualStudioGenerator::VS15, cm, genName, "ARM");
+ }
+ return 0;
+ }
+
+ void GetDocumentation(cmDocumentationEntry& entry) const override
+ {
+ entry.Name = std::string(vs15generatorName) + " [arch]";
+ entry.Brief = "Generates Visual Studio 2017 project files. "
+ "Optional [arch] can be \"Win64\" or \"ARM\".";
+ }
+
+ std::vector<std::string> GetGeneratorNames() const override
+ {
+ std::vector<std::string> names;
+ names.push_back(vs15generatorName);
+ return names;
+ }
+
+ std::vector<std::string> GetGeneratorNamesWithPlatform() const override
+ {
+ std::vector<std::string> names;
+ names.push_back(vs15generatorName + std::string(" ARM"));
+ names.push_back(vs15generatorName + std::string(" Win64"));
+ return names;
+ }
+
+ bool SupportsToolset() const override { return true; }
+ bool SupportsPlatform() const override { return true; }
+
+ std::vector<std::string> GetKnownPlatforms() const override
+ {
+ std::vector<std::string> platforms;
+ platforms.emplace_back("x64");
+ platforms.emplace_back("Win32");
+ platforms.emplace_back("ARM");
+ platforms.emplace_back("ARM64");
+ return platforms;
+ }
+
+ std::string GetDefaultPlatformName() const override { return "Win32"; }
+};
+
+cmGlobalGeneratorFactory*
+cmGlobalVisualStudioVersionedGenerator::NewFactory15()
+{
+ return new Factory15;
+}
+
+static const char vs16generatorName[] = "Visual Studio 16 2019";
+
+// Map generator name without year to name with year.
+static const char* cmVS16GenName(const std::string& name, std::string& genName)
+{
+ if (strncmp(name.c_str(), vs16generatorName,
+ sizeof(vs16generatorName) - 6) != 0) {
+ return 0;
+ }
+ const char* p = name.c_str() + sizeof(vs16generatorName) - 6;
+ if (cmHasLiteralPrefix(p, " 2019")) {
+ p += 5;
+ }
+ genName = std::string(vs16generatorName) + p;
+ return p;
+}
+
+class cmGlobalVisualStudioVersionedGenerator::Factory16
+ : public cmGlobalGeneratorFactory
+{
+public:
+ cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
+ cmake* cm) const override
+ {
+ std::string genName;
+ const char* p = cmVS16GenName(name, genName);
+ if (!p) {
+ return 0;
+ }
+ if (!*p) {
+ return new cmGlobalVisualStudioVersionedGenerator(
+ cmGlobalVisualStudioGenerator::VS16, cm, genName, "");
+ }
+ return 0;
+ }
+
+ void GetDocumentation(cmDocumentationEntry& entry) const override
+ {
+ entry.Name = std::string(vs16generatorName);
+ entry.Brief = "Generates Visual Studio 2019 project files. "
+ "Use -A option to specify architecture.";
+ }
+
+ std::vector<std::string> GetGeneratorNames() const override
+ {
+ std::vector<std::string> names;
+ names.push_back(vs16generatorName);
+ return names;
+ }
+
+ std::vector<std::string> GetGeneratorNamesWithPlatform() const override
+ {
+ return std::vector<std::string>();
+ }
+
+ bool SupportsToolset() const override { return true; }
+ bool SupportsPlatform() const override { return true; }
+
+ std::vector<std::string> GetKnownPlatforms() const override
+ {
+ std::vector<std::string> platforms;
+ platforms.emplace_back("x64");
+ platforms.emplace_back("Win32");
+ platforms.emplace_back("ARM");
+ platforms.emplace_back("ARM64");
+ return platforms;
+ }
+
+ std::string GetDefaultPlatformName() const override
+ {
+ return VSHostPlatformName();
+ }
+};
+
+cmGlobalGeneratorFactory*
+cmGlobalVisualStudioVersionedGenerator::NewFactory16()
+{
+ return new Factory16;
+}
+
+cmGlobalVisualStudioVersionedGenerator::cmGlobalVisualStudioVersionedGenerator(
+ VSVersion version, cmake* cm, const std::string& name,
+ std::string const& platformInGeneratorName)
+ : cmGlobalVisualStudio14Generator(cm, name, platformInGeneratorName)
+ , vsSetupAPIHelper(VSVersionToMajor(version))
+{
+ this->Version = version;
+ this->ExpressEdition = false;
+ this->DefaultPlatformToolset = VSVersionToToolset(this->Version);
+ this->DefaultCLFlagTableName = VSVersionToToolset(this->Version);
+ this->DefaultCSharpFlagTableName = VSVersionToToolset(this->Version);
+ this->DefaultLinkFlagTableName = VSVersionToToolset(this->Version);
+ if (this->Version >= cmGlobalVisualStudioGenerator::VS16) {
+ this->DefaultPlatformName = VSHostPlatformName();
+ this->DefaultPlatformToolsetHostArchitecture = VSHostArchitecture();
+ }
+}
+
+bool cmGlobalVisualStudioVersionedGenerator::MatchesGeneratorName(
+ const std::string& name) const
+{
+ std::string genName;
+ switch (this->Version) {
+ case cmGlobalVisualStudioGenerator::VS9:
+ case cmGlobalVisualStudioGenerator::VS10:
+ case cmGlobalVisualStudioGenerator::VS11:
+ case cmGlobalVisualStudioGenerator::VS12:
+ case cmGlobalVisualStudioGenerator::VS14:
+ break;
+ case cmGlobalVisualStudioGenerator::VS15:
+ if (cmVS15GenName(name, genName)) {
+ return genName == this->GetName();
+ }
+ break;
+ case cmGlobalVisualStudioGenerator::VS16:
+ if (cmVS16GenName(name, genName)) {
+ return genName == this->GetName();
+ }
+ break;
+ }
+ return false;
+}
+
+bool cmGlobalVisualStudioVersionedGenerator::SetGeneratorInstance(
+ std::string const& i, cmMakefile* mf)
+{
+ if (!i.empty()) {
+ if (!this->vsSetupAPIHelper.SetVSInstance(i)) {
+ std::ostringstream e;
+ /* clang-format off */
+ e <<
+ "Generator\n"
+ " " << this->GetName() << "\n"
+ "could not find specified instance of Visual Studio:\n"
+ " " << i;
+ /* clang-format on */
+ mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
+ return false;
+ }
+ }
+
+ std::string vsInstance;
+ if (!this->vsSetupAPIHelper.GetVSInstanceInfo(vsInstance)) {
+ std::ostringstream e;
+ /* clang-format off */
+ e <<
+ "Generator\n"
+ " " << this->GetName() << "\n"
+ "could not find any instance of Visual Studio.\n";
+ /* clang-format on */
+ mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
+ return false;
+ }
+
+ // Save the selected instance persistently.
+ std::string genInstance = mf->GetSafeDefinition("CMAKE_GENERATOR_INSTANCE");
+ if (vsInstance != genInstance) {
+ this->CMakeInstance->AddCacheEntry(
+ "CMAKE_GENERATOR_INSTANCE", vsInstance.c_str(),
+ "Generator instance identifier.", cmStateEnums::INTERNAL);
+ }
+
+ return true;
+}
+
+bool cmGlobalVisualStudioVersionedGenerator::GetVSInstance(
+ std::string& dir) const
+{
+ return vsSetupAPIHelper.GetVSInstanceInfo(dir);
+}
+
+bool cmGlobalVisualStudioVersionedGenerator::IsDefaultToolset(
+ const std::string& version) const
+{
+ if (version.empty()) {
+ return true;
+ }
+
+ std::string vcToolsetVersion;
+ if (this->vsSetupAPIHelper.GetVCToolsetVersion(vcToolsetVersion)) {
+
+ cmsys::RegularExpression regex("[0-9][0-9]\\.[0-9]+");
+ if (regex.find(version) && regex.find(vcToolsetVersion)) {
+ const auto majorMinorEnd = vcToolsetVersion.find('.', 3);
+ const auto majorMinor = vcToolsetVersion.substr(0, majorMinorEnd);
+ return version == majorMinor;
+ }
+ }
+
+ return false;
+}
+
+std::string cmGlobalVisualStudioVersionedGenerator::GetAuxiliaryToolset() const
+{
+ const char* version = this->GetPlatformToolsetVersion();
+ if (version) {
+ std::string instancePath;
+ GetVSInstance(instancePath);
+ std::string toolsetDir = instancePath + "/VC/Auxiliary/Build";
+ char sep = '/';
+ if (cmSystemTools::VersionCompareGreaterEq(version, "14.20")) {
+ std::string toolsetDot = toolsetDir + "." + version +
+ "/Microsoft.VCToolsVersion." + version + ".props";
+ if (cmSystemTools::PathExists(toolsetDot)) {
+ sep = '.';
+ }
+ }
+ std::string toolsetPath = toolsetDir + sep + version +
+ "/Microsoft.VCToolsVersion." + version + ".props";
+ cmSystemTools::ConvertToUnixSlashes(toolsetPath);
+ return toolsetPath;
+ }
+ return {};
+}
+
+bool cmGlobalVisualStudioVersionedGenerator::InitializeWindows(cmMakefile* mf)
+{
+ // If the Win 8.1 SDK is installed then we can select a SDK matching
+ // the target Windows version.
+ if (this->IsWin81SDKInstalled()) {
+ // VS 2019 does not default to 8.1 so specify it explicitly when needed.
+ if (this->Version >= cmGlobalVisualStudioGenerator::VS16 &&
+ !cmSystemTools::VersionCompareGreater(this->SystemVersion, "8.1")) {
+ this->SetWindowsTargetPlatformVersion("8.1", mf);
+ return true;
+ }
+ return cmGlobalVisualStudio14Generator::InitializeWindows(mf);
+ }
+ // Otherwise we must choose a Win 10 SDK even if we are not targeting
+ // Windows 10.
+ return this->SelectWindows10SDK(mf, false);
+}
+
+bool cmGlobalVisualStudioVersionedGenerator::SelectWindowsStoreToolset(
+ std::string& toolset) const
+{
+ if (cmHasLiteralPrefix(this->SystemVersion, "10.0")) {
+ if (this->IsWindowsStoreToolsetInstalled() &&
+ this->IsWindowsDesktopToolsetInstalled()) {
+ toolset = VSVersionToToolset(this->Version);
+ return true;
+ } else {
+ return false;
+ }
+ }
+ return this->cmGlobalVisualStudio14Generator::SelectWindowsStoreToolset(
+ toolset);
+}
+
+bool cmGlobalVisualStudioVersionedGenerator::IsWindowsDesktopToolsetInstalled()
+ const
+{
+ return vsSetupAPIHelper.IsVSInstalled();
+}
+
+bool cmGlobalVisualStudioVersionedGenerator::IsWindowsStoreToolsetInstalled()
+ const
+{
+ return vsSetupAPIHelper.IsWin10SDKInstalled();
+}
+
+bool cmGlobalVisualStudioVersionedGenerator::IsWin81SDKInstalled() const
+{
+ // Does the VS installer tool know about one?
+ if (vsSetupAPIHelper.IsWin81SDKInstalled()) {
+ return true;
+ }
+
+ // Does the registry know about one (e.g. from VS 2015)?
+ std::string win81Root;
+ if (cmSystemTools::ReadRegistryValue(
+ "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\"
+ "Windows Kits\\Installed Roots;KitsRoot81",
+ win81Root, cmSystemTools::KeyWOW64_32) ||
+ cmSystemTools::ReadRegistryValue(
+ "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\"
+ "Windows Kits\\Installed Roots;KitsRoot81",
+ win81Root, cmSystemTools::KeyWOW64_32)) {
+ return cmSystemTools::FileExists(win81Root + "/include/um/windows.h",
+ true);
+ }
+ return false;
+}
+
+std::string cmGlobalVisualStudioVersionedGenerator::GetWindows10SDKMaxVersion()
+ const
+{
+ return std::string();
+}
+
+std::string cmGlobalVisualStudioVersionedGenerator::FindMSBuildCommand()
+{
+ std::string msbuild;
+
+ // Ask Visual Studio Installer tool.
+ std::string vs;
+ if (vsSetupAPIHelper.GetVSInstanceInfo(vs)) {
+ msbuild = vs + "/MSBuild/Current/Bin/MSBuild.exe";
+ if (cmSystemTools::FileExists(msbuild)) {
+ return msbuild;
+ }
+ msbuild = vs + "/MSBuild/15.0/Bin/MSBuild.exe";
+ if (cmSystemTools::FileExists(msbuild)) {
+ return msbuild;
+ }
+ }
+
+ msbuild = "MSBuild.exe";
+ return msbuild;
+}
+
+std::string cmGlobalVisualStudioVersionedGenerator::FindDevEnvCommand()
+{
+ std::string devenv;
+
+ // Ask Visual Studio Installer tool.
+ std::string vs;
+ if (vsSetupAPIHelper.GetVSInstanceInfo(vs)) {
+ devenv = vs + "/Common7/IDE/devenv.com";
+ if (cmSystemTools::FileExists(devenv)) {
+ return devenv;
+ }
+ }
+
+ devenv = "devenv.com";
+ return devenv;
+}
diff --git a/Source/cmGlobalVisualStudioVersionedGenerator.h b/Source/cmGlobalVisualStudioVersionedGenerator.h
new file mode 100644
index 000000000..466816ba8
--- /dev/null
+++ b/Source/cmGlobalVisualStudioVersionedGenerator.h
@@ -0,0 +1,65 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmGlobalVisualStudioVersionedGenerator_h
+#define cmGlobalVisualStudioVersionedGenerator_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <iosfwd>
+#include <string>
+
+#include "cmGlobalVisualStudio14Generator.h"
+#include "cmVSSetupHelper.h"
+
+class cmGlobalGeneratorFactory;
+class cmake;
+
+/** \class cmGlobalVisualStudioVersionedGenerator */
+class cmGlobalVisualStudioVersionedGenerator
+ : public cmGlobalVisualStudio14Generator
+{
+public:
+ static cmGlobalGeneratorFactory* NewFactory15();
+ static cmGlobalGeneratorFactory* NewFactory16();
+
+ bool MatchesGeneratorName(const std::string& name) const override;
+
+ bool SetGeneratorInstance(std::string const& i, cmMakefile* mf) override;
+
+ bool GetVSInstance(std::string& dir) const;
+
+ bool IsDefaultToolset(const std::string& version) const override;
+ std::string GetAuxiliaryToolset() const override;
+
+protected:
+ cmGlobalVisualStudioVersionedGenerator(
+ VSVersion version, cmake* cm, const std::string& name,
+ std::string const& platformInGeneratorName);
+
+ bool InitializeWindows(cmMakefile* mf) override;
+ bool SelectWindowsStoreToolset(std::string& toolset) const override;
+
+ // Used to verify that the Desktop toolset for the current generator is
+ // installed on the machine.
+ bool IsWindowsDesktopToolsetInstalled() const override;
+
+ // These aren't virtual because we need to check if the selected version
+ // of the toolset is installed
+ bool IsWindowsStoreToolsetInstalled() const;
+
+ // Check for a Win 8 SDK known to the registry or VS installer tool.
+ bool IsWin81SDKInstalled() const;
+
+ std::string GetWindows10SDKMaxVersion() const override;
+
+ std::string FindMSBuildCommand() override;
+ std::string FindDevEnvCommand() override;
+
+private:
+ class Factory15;
+ friend class Factory15;
+ class Factory16;
+ friend class Factory16;
+ mutable cmVSSetupAPIHelper vsSetupAPIHelper;
+};
+#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/cmInstallSubdirectoryGenerator.cxx b/Source/cmInstallSubdirectoryGenerator.cxx
new file mode 100644
index 000000000..1c0512ce5
--- /dev/null
+++ b/Source/cmInstallSubdirectoryGenerator.cxx
@@ -0,0 +1,76 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmInstallSubdirectoryGenerator.h"
+
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmPolicies.h"
+#include "cmScriptGenerator.h"
+#include "cmSystemTools.h"
+
+#include <sstream>
+#include <vector>
+
+cmInstallSubdirectoryGenerator::cmInstallSubdirectoryGenerator(
+ cmMakefile* makefile, const char* binaryDirectory, bool excludeFromAll)
+ : cmInstallGenerator(nullptr, std::vector<std::string>(), nullptr,
+ MessageDefault, excludeFromAll)
+ , Makefile(makefile)
+ , BinaryDirectory(binaryDirectory)
+{
+}
+
+cmInstallSubdirectoryGenerator::~cmInstallSubdirectoryGenerator() = default;
+
+bool cmInstallSubdirectoryGenerator::HaveInstall()
+{
+ for (auto generator : this->Makefile->GetInstallGenerators()) {
+ if (generator->HaveInstall()) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+void cmInstallSubdirectoryGenerator::CheckCMP0082(
+ bool& haveSubdirectoryInstall, bool& /*unused*/)
+{
+ if (this->HaveInstall()) {
+ haveSubdirectoryInstall = true;
+ }
+}
+
+bool cmInstallSubdirectoryGenerator::Compute(cmLocalGenerator* lg)
+{
+ this->LocalGenerator = lg;
+ return true;
+}
+
+void cmInstallSubdirectoryGenerator::GenerateScript(std::ostream& os)
+{
+ if (!this->ExcludeFromAll) {
+ cmPolicies::PolicyStatus status =
+ this->LocalGenerator->GetPolicyStatus(cmPolicies::CMP0082);
+ switch (status) {
+ case cmPolicies::WARN:
+ case cmPolicies::OLD:
+ // OLD behavior is handled in cmLocalGenerator::GenerateInstallRules()
+ break;
+
+ case cmPolicies::NEW:
+ case cmPolicies::REQUIRED_IF_USED:
+ case cmPolicies::REQUIRED_ALWAYS: {
+ Indent indent;
+ std::string odir = this->BinaryDirectory;
+ cmSystemTools::ConvertToUnixSlashes(odir);
+ os << indent << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n"
+ << indent.Next()
+ << "# Include the install script for the subdirectory.\n"
+ << indent.Next() << "include(\"" << odir
+ << "/cmake_install.cmake\")\n"
+ << indent << "endif()\n\n";
+ } break;
+ }
+ }
+}
diff --git a/Source/cmInstallSubdirectoryGenerator.h b/Source/cmInstallSubdirectoryGenerator.h
new file mode 100644
index 000000000..22759d948
--- /dev/null
+++ b/Source/cmInstallSubdirectoryGenerator.h
@@ -0,0 +1,41 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmInstallSubdirectoryGenerator_h
+#define cmInstallSubdirectoryGenerator_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cmInstallGenerator.h"
+
+#include <iosfwd>
+#include <string>
+
+class cmLocalGenerator;
+class cmMakefile;
+
+/** \class cmInstallSubdirectoryGenerator
+ * \brief Generate target installation rules.
+ */
+class cmInstallSubdirectoryGenerator : public cmInstallGenerator
+{
+public:
+ cmInstallSubdirectoryGenerator(cmMakefile* makefile,
+ const char* binaryDirectory,
+ bool excludeFromAll);
+ ~cmInstallSubdirectoryGenerator() override;
+
+ bool HaveInstall() override;
+ void CheckCMP0082(bool& haveSubdirectoryInstall,
+ bool& haveInstallAfterSubdirectory) override;
+
+ bool Compute(cmLocalGenerator* lg) override;
+
+protected:
+ void GenerateScript(std::ostream& os) override;
+
+ cmMakefile* Makefile;
+ std::string BinaryDirectory;
+ cmLocalGenerator* LocalGenerator;
+};
+
+#endif
diff --git a/Source/cmJsonObjectDictionary.h b/Source/cmJsonObjectDictionary.h
new file mode 100644
index 000000000..8a2b52995
--- /dev/null
+++ b/Source/cmJsonObjectDictionary.h
@@ -0,0 +1,45 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#pragma once
+
+#include <string>
+
+// Vocabulary:
+
+static const std::string kARTIFACTS_KEY = "artifacts";
+static const std::string kBUILD_DIRECTORY_KEY = "buildDirectory";
+static const std::string kCOMPILE_FLAGS_KEY = "compileFlags";
+static const std::string kCONFIGURATIONS_KEY = "configurations";
+static const std::string kDEFINES_KEY = "defines";
+static const std::string kFILE_GROUPS_KEY = "fileGroups";
+static const std::string kFRAMEWORK_PATH_KEY = "frameworkPath";
+static const std::string kFULL_NAME_KEY = "fullName";
+static const std::string kINCLUDE_PATH_KEY = "includePath";
+static const std::string kIS_CMAKE_KEY = "isCMake";
+static const std::string kIS_GENERATED_KEY = "isGenerated";
+static const std::string kIS_SYSTEM_KEY = "isSystem";
+static const std::string kIS_TEMPORARY_KEY = "isTemporary";
+static const std::string kKEY_KEY = "key";
+static const std::string kLANGUAGE_KEY = "language";
+static const std::string kLINKER_LANGUAGE_KEY = "linkerLanguage";
+static const std::string kLINK_FLAGS_KEY = "linkFlags";
+static const std::string kLINK_LANGUAGE_FLAGS_KEY = "linkLanguageFlags";
+static const std::string kLINK_LIBRARIES_KEY = "linkLibraries";
+static const std::string kLINK_PATH_KEY = "linkPath";
+static const std::string kNAME_KEY = "name";
+static const std::string kPATH_KEY = "path";
+static const std::string kPROJECTS_KEY = "projects";
+static const std::string kPROPERTIES_KEY = "properties";
+static const std::string kSOURCE_DIRECTORY_KEY = "sourceDirectory";
+static const std::string kSOURCES_KEY = "sources";
+static const std::string kSYSROOT_KEY = "sysroot";
+static const std::string kTARGETS_KEY = "targets";
+static const std::string kTYPE_KEY = "type";
+static const std::string kVALUE_KEY = "value";
+static const std::string kHAS_INSTALL_RULE = "hasInstallRule";
+static const std::string kINSTALL_PATHS = "installPaths";
+static const std::string kCTEST_NAME = "ctestName";
+static const std::string kCTEST_COMMAND = "ctestCommand";
+static const std::string kCTEST_INFO = "ctestInfo";
+static const std::string kMINIMUM_CMAKE_VERSION = "minimumCMakeVersion";
+static const std::string kIS_GENERATOR_PROVIDED_KEY = "isGeneratorProvided";
diff --git a/Source/cmJsonObjects.cxx b/Source/cmJsonObjects.cxx
new file mode 100644
index 000000000..636a8e1c2
--- /dev/null
+++ b/Source/cmJsonObjects.cxx
@@ -0,0 +1,693 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmJsonObjects.h" // IWYU pragma: keep
+
+#include "cmAlgorithms.h"
+#include "cmGeneratorExpression.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmInstallGenerator.h"
+#include "cmInstallSubdirectoryGenerator.h"
+#include "cmInstallTargetGenerator.h"
+#include "cmJsonObjectDictionary.h"
+#include "cmJsonObjects.h"
+#include "cmLinkLineComputer.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmProperty.h"
+#include "cmPropertyMap.h"
+#include "cmSourceFile.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmTest.h"
+#include "cmake.h"
+
+#include <algorithm>
+#include <cassert>
+#include <cstddef>
+#include <functional>
+#include <limits>
+#include <map>
+#include <set>
+#include <string>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+namespace {
+
+std::vector<std::string> getConfigurations(const cmake* cm)
+{
+ std::vector<std::string> configurations;
+ auto makefiles = cm->GetGlobalGenerator()->GetMakefiles();
+ if (makefiles.empty()) {
+ return configurations;
+ }
+
+ makefiles[0]->GetConfigurations(configurations);
+ if (configurations.empty()) {
+ configurations.emplace_back();
+ }
+ return configurations;
+}
+
+bool hasString(const Json::Value& v, const std::string& s)
+{
+ return !v.isNull() &&
+ std::any_of(v.begin(), v.end(),
+ [s](const Json::Value& i) { return i.asString() == s; });
+}
+
+template <class T>
+Json::Value fromStringList(const T& in)
+{
+ Json::Value result = Json::arrayValue;
+ for (std::string const& i : in) {
+ result.append(i);
+ }
+ return result;
+}
+
+} // namespace
+
+void cmGetCMakeInputs(const cmGlobalGenerator* gg,
+ const std::string& sourceDir,
+ const std::string& buildDir,
+ std::vector<std::string>* internalFiles,
+ std::vector<std::string>* explicitFiles,
+ std::vector<std::string>* tmpFiles)
+{
+ const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot() + '/';
+ std::vector<cmMakefile*> const& makefiles = gg->GetMakefiles();
+ for (cmMakefile const* mf : makefiles) {
+ for (std::string const& lf : mf->GetListFiles()) {
+
+ const std::string startOfFile = lf.substr(0, cmakeRootDir.size());
+ const bool isInternal = (startOfFile == cmakeRootDir);
+ const bool isTemporary = !isInternal && (lf.find(buildDir + '/') == 0);
+
+ std::string toAdd = lf;
+ if (!sourceDir.empty()) {
+ const std::string& relative =
+ cmSystemTools::RelativePath(sourceDir, lf);
+ if (toAdd.size() > relative.size()) {
+ toAdd = relative;
+ }
+ }
+
+ if (isInternal) {
+ if (internalFiles) {
+ internalFiles->push_back(std::move(toAdd));
+ }
+ } else {
+ if (isTemporary) {
+ if (tmpFiles) {
+ tmpFiles->push_back(std::move(toAdd));
+ }
+ } else {
+ if (explicitFiles) {
+ explicitFiles->push_back(std::move(toAdd));
+ }
+ }
+ }
+ }
+ }
+}
+
+Json::Value cmDumpCMakeInputs(const cmake* cm)
+{
+ const cmGlobalGenerator* gg = cm->GetGlobalGenerator();
+ const std::string& buildDir = cm->GetHomeOutputDirectory();
+ const std::string& sourceDir = cm->GetHomeDirectory();
+
+ std::vector<std::string> internalFiles;
+ std::vector<std::string> explicitFiles;
+ std::vector<std::string> tmpFiles;
+ cmGetCMakeInputs(gg, sourceDir, buildDir, &internalFiles, &explicitFiles,
+ &tmpFiles);
+
+ Json::Value array = Json::arrayValue;
+
+ Json::Value tmp = Json::objectValue;
+ tmp[kIS_CMAKE_KEY] = true;
+ tmp[kIS_TEMPORARY_KEY] = false;
+ tmp[kSOURCES_KEY] = fromStringList(internalFiles);
+ array.append(tmp);
+
+ tmp = Json::objectValue;
+ tmp[kIS_CMAKE_KEY] = false;
+ tmp[kIS_TEMPORARY_KEY] = false;
+ tmp[kSOURCES_KEY] = fromStringList(explicitFiles);
+ array.append(tmp);
+
+ tmp = Json::objectValue;
+ tmp[kIS_CMAKE_KEY] = false;
+ tmp[kIS_TEMPORARY_KEY] = true;
+ tmp[kSOURCES_KEY] = fromStringList(tmpFiles);
+ array.append(tmp);
+
+ return array;
+}
+
+class LanguageData
+{
+public:
+ bool operator==(const LanguageData& other) const;
+
+ void SetDefines(const std::set<std::string>& defines);
+
+ bool IsGenerated = false;
+ std::string Language;
+ std::string Flags;
+ std::vector<std::string> Defines;
+ std::vector<std::pair<std::string, bool>> IncludePathList;
+};
+
+bool LanguageData::operator==(const LanguageData& other) const
+{
+ return Language == other.Language && Defines == other.Defines &&
+ Flags == other.Flags && IncludePathList == other.IncludePathList &&
+ IsGenerated == other.IsGenerated;
+}
+
+void LanguageData::SetDefines(const std::set<std::string>& defines)
+{
+ std::vector<std::string> result;
+ result.reserve(defines.size());
+ for (std::string const& i : defines) {
+ result.push_back(i);
+ }
+ std::sort(result.begin(), result.end());
+ Defines = std::move(result);
+}
+
+namespace std {
+
+template <>
+struct hash<LanguageData>
+{
+ std::size_t operator()(const LanguageData& in) const
+ {
+ using std::hash;
+ size_t result =
+ hash<std::string>()(in.Language) ^ hash<std::string>()(in.Flags);
+ for (auto const& i : in.IncludePathList) {
+ result = result ^
+ (hash<std::string>()(i.first) ^
+ (i.second ? std::numeric_limits<size_t>::max() : 0));
+ }
+ for (auto const& i : in.Defines) {
+ result = result ^ hash<std::string>()(i);
+ }
+ result =
+ result ^ (in.IsGenerated ? std::numeric_limits<size_t>::max() : 0);
+ return result;
+ }
+};
+
+} // namespace std
+
+static Json::Value DumpSourceFileGroup(const LanguageData& data,
+ const std::vector<std::string>& files,
+ const std::string& baseDir)
+{
+ Json::Value result = Json::objectValue;
+
+ if (!data.Language.empty()) {
+ result[kLANGUAGE_KEY] = data.Language;
+ if (!data.Flags.empty()) {
+ result[kCOMPILE_FLAGS_KEY] = data.Flags;
+ }
+ if (!data.IncludePathList.empty()) {
+ Json::Value includes = Json::arrayValue;
+ for (auto const& i : data.IncludePathList) {
+ Json::Value tmp = Json::objectValue;
+ tmp[kPATH_KEY] = i.first;
+ if (i.second) {
+ tmp[kIS_SYSTEM_KEY] = i.second;
+ }
+ includes.append(tmp);
+ }
+ result[kINCLUDE_PATH_KEY] = includes;
+ }
+ if (!data.Defines.empty()) {
+ result[kDEFINES_KEY] = fromStringList(data.Defines);
+ }
+ }
+
+ result[kIS_GENERATED_KEY] = data.IsGenerated;
+
+ Json::Value sourcesValue = Json::arrayValue;
+ for (auto const& i : files) {
+ const std::string relPath = cmSystemTools::RelativePath(baseDir, i);
+ sourcesValue.append(relPath.size() < i.size() ? relPath : i);
+ }
+
+ result[kSOURCES_KEY] = sourcesValue;
+ return result;
+}
+
+static Json::Value DumpSourceFilesList(
+ cmGeneratorTarget* target, const std::string& config,
+ const std::map<std::string, LanguageData>& languageDataMap)
+{
+ // Collect sourcefile groups:
+
+ std::vector<cmSourceFile*> files;
+ target->GetSourceFiles(files, config);
+
+ std::unordered_map<LanguageData, std::vector<std::string>> fileGroups;
+ for (cmSourceFile* file : files) {
+ LanguageData fileData;
+ fileData.Language = file->GetLanguage();
+ if (!fileData.Language.empty()) {
+ const LanguageData& ld = languageDataMap.at(fileData.Language);
+ cmLocalGenerator* lg = target->GetLocalGenerator();
+ cmGeneratorExpressionInterpreter genexInterpreter(lg, config, target,
+ fileData.Language);
+
+ std::string compileFlags = ld.Flags;
+ const std::string COMPILE_FLAGS("COMPILE_FLAGS");
+ if (const char* cflags = file->GetProperty(COMPILE_FLAGS)) {
+ lg->AppendFlags(compileFlags,
+ genexInterpreter.Evaluate(cflags, COMPILE_FLAGS));
+ }
+ const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
+ if (const char* coptions = file->GetProperty(COMPILE_OPTIONS)) {
+ lg->AppendCompileOptions(
+ compileFlags, genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS));
+ }
+ fileData.Flags = compileFlags;
+
+ // Add include directories from source file properties.
+ std::vector<std::string> includes;
+
+ const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
+ if (const char* cincludes = file->GetProperty(INCLUDE_DIRECTORIES)) {
+ const std::string& evaluatedIncludes =
+ genexInterpreter.Evaluate(cincludes, INCLUDE_DIRECTORIES);
+ lg->AppendIncludeDirectories(includes, evaluatedIncludes, *file);
+
+ for (const auto& include : includes) {
+ fileData.IncludePathList.emplace_back(
+ include,
+ target->IsSystemIncludeDirectory(include, config,
+ fileData.Language));
+ }
+ }
+
+ fileData.IncludePathList.insert(fileData.IncludePathList.end(),
+ ld.IncludePathList.begin(),
+ ld.IncludePathList.end());
+
+ const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
+ std::set<std::string> defines;
+ if (const char* defs = file->GetProperty(COMPILE_DEFINITIONS)) {
+ lg->AppendDefines(
+ defines, genexInterpreter.Evaluate(defs, COMPILE_DEFINITIONS));
+ }
+
+ const std::string defPropName =
+ "COMPILE_DEFINITIONS_" + cmSystemTools::UpperCase(config);
+ if (const char* config_defs = file->GetProperty(defPropName)) {
+ lg->AppendDefines(
+ defines,
+ genexInterpreter.Evaluate(config_defs, COMPILE_DEFINITIONS));
+ }
+
+ defines.insert(ld.Defines.begin(), ld.Defines.end());
+
+ fileData.SetDefines(defines);
+ }
+
+ fileData.IsGenerated = file->GetIsGenerated();
+ std::vector<std::string>& groupFileList = fileGroups[fileData];
+ groupFileList.push_back(file->GetFullPath());
+ }
+
+ const std::string& baseDir = target->Makefile->GetCurrentSourceDirectory();
+ Json::Value result = Json::arrayValue;
+ for (auto const& it : fileGroups) {
+ Json::Value group = DumpSourceFileGroup(it.first, it.second, baseDir);
+ if (!group.isNull()) {
+ result.append(group);
+ }
+ }
+
+ return result;
+}
+
+static Json::Value DumpCTestInfo(cmLocalGenerator* lg, cmTest* testInfo,
+ const std::string& config)
+{
+ Json::Value result = Json::objectValue;
+ result[kCTEST_NAME] = testInfo->GetName();
+
+ // Concat command entries together. After the first should be the arguments
+ // for the command
+ std::string command;
+ for (auto const& cmd : testInfo->GetCommand()) {
+ command.append(cmd);
+ command.append(" ");
+ }
+
+ // Remove any config specific variables from the output.
+ cmGeneratorExpression ge;
+ auto cge = ge.Parse(command);
+ const std::string& processed = cge->Evaluate(lg, config);
+ result[kCTEST_COMMAND] = processed;
+
+ // Build up the list of properties that may have been specified
+ Json::Value properties = Json::arrayValue;
+ for (auto& prop : testInfo->GetProperties()) {
+ Json::Value entry = Json::objectValue;
+ entry[kKEY_KEY] = prop.first;
+
+ // Remove config variables from the value too.
+ auto cge_value = ge.Parse(prop.second.GetValue());
+ const std::string& processed_value = cge_value->Evaluate(lg, config);
+ entry[kVALUE_KEY] = processed_value;
+ properties.append(entry);
+ }
+ result[kPROPERTIES_KEY] = properties;
+
+ return result;
+}
+
+static void DumpMakefileTests(cmLocalGenerator* lg, const std::string& config,
+ Json::Value* result)
+{
+ auto mf = lg->GetMakefile();
+ std::vector<cmTest*> tests;
+ mf->GetTests(config, tests);
+ for (auto test : tests) {
+ Json::Value tmp = DumpCTestInfo(lg, test, config);
+ if (!tmp.isNull()) {
+ result->append(tmp);
+ }
+ }
+}
+
+static Json::Value DumpCTestProjectList(const cmake* cm,
+ std::string const& config)
+{
+ Json::Value result = Json::arrayValue;
+
+ auto globalGen = cm->GetGlobalGenerator();
+
+ for (const auto& projectIt : globalGen->GetProjectMap()) {
+ Json::Value pObj = Json::objectValue;
+ pObj[kNAME_KEY] = projectIt.first;
+
+ Json::Value tests = Json::arrayValue;
+
+ // Gather tests for every generator
+ for (const auto& lg : projectIt.second) {
+ // Make sure they're generated.
+ lg->GenerateTestFiles();
+ DumpMakefileTests(lg, config, &tests);
+ }
+
+ pObj[kCTEST_INFO] = tests;
+
+ result.append(pObj);
+ }
+
+ return result;
+}
+
+static Json::Value DumpCTestConfiguration(const cmake* cm,
+ const std::string& config)
+{
+ Json::Value result = Json::objectValue;
+ result[kNAME_KEY] = config;
+
+ result[kPROJECTS_KEY] = DumpCTestProjectList(cm, config);
+
+ return result;
+}
+
+static Json::Value DumpCTestConfigurationsList(const cmake* cm)
+{
+ Json::Value result = Json::arrayValue;
+
+ for (const std::string& c : getConfigurations(cm)) {
+ result.append(DumpCTestConfiguration(cm, c));
+ }
+
+ return result;
+}
+
+Json::Value cmDumpCTestInfo(const cmake* cm)
+{
+ Json::Value result = Json::objectValue;
+ result[kCONFIGURATIONS_KEY] = DumpCTestConfigurationsList(cm);
+ return result;
+}
+
+static Json::Value DumpTarget(cmGeneratorTarget* target,
+ const std::string& config)
+{
+ cmLocalGenerator* lg = target->GetLocalGenerator();
+
+ const cmStateEnums::TargetType type = target->GetType();
+ const std::string typeName = cmState::GetTargetTypeName(type);
+
+ Json::Value ttl = Json::arrayValue;
+ ttl.append("EXECUTABLE");
+ ttl.append("STATIC_LIBRARY");
+ ttl.append("SHARED_LIBRARY");
+ ttl.append("MODULE_LIBRARY");
+ ttl.append("OBJECT_LIBRARY");
+ ttl.append("UTILITY");
+ ttl.append("INTERFACE_LIBRARY");
+
+ if (!hasString(ttl, typeName) || target->IsImported()) {
+ return Json::Value();
+ }
+
+ Json::Value result = Json::objectValue;
+ result[kNAME_KEY] = target->GetName();
+ result[kIS_GENERATOR_PROVIDED_KEY] =
+ target->Target->GetIsGeneratorProvided();
+ result[kTYPE_KEY] = typeName;
+ result[kSOURCE_DIRECTORY_KEY] = lg->GetCurrentSourceDirectory();
+ result[kBUILD_DIRECTORY_KEY] = lg->GetCurrentBinaryDirectory();
+
+ if (type == cmStateEnums::INTERFACE_LIBRARY) {
+ return result;
+ }
+
+ result[kFULL_NAME_KEY] = target->GetFullName(config);
+
+ if (target->Target->GetHaveInstallRule()) {
+ result[kHAS_INSTALL_RULE] = true;
+
+ Json::Value installPaths = Json::arrayValue;
+ auto targetGenerators = target->Makefile->GetInstallGenerators();
+ for (auto installGenerator : targetGenerators) {
+ auto installTargetGenerator =
+ dynamic_cast<cmInstallTargetGenerator*>(installGenerator);
+ if (installTargetGenerator != nullptr &&
+ installTargetGenerator->GetTarget()->Target == target->Target) {
+ auto dest = installTargetGenerator->GetDestination(config);
+
+ std::string installPath;
+ if (!dest.empty() && cmSystemTools::FileIsFullPath(dest)) {
+ installPath = dest;
+ } else {
+ std::string installPrefix =
+ target->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
+ installPath = installPrefix + '/' + dest;
+ }
+
+ installPaths.append(installPath);
+ }
+ }
+
+ result[kINSTALL_PATHS] = installPaths;
+ }
+
+ if (target->HaveWellDefinedOutputFiles()) {
+ Json::Value artifacts = Json::arrayValue;
+ artifacts.append(
+ target->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact));
+ if (target->IsDLLPlatform()) {
+ artifacts.append(
+ target->GetFullPath(config, cmStateEnums::ImportLibraryArtifact));
+ const cmGeneratorTarget::OutputInfo* output =
+ target->GetOutputInfo(config);
+ if (output && !output->PdbDir.empty()) {
+ artifacts.append(output->PdbDir + '/' + target->GetPDBName(config));
+ }
+ }
+ result[kARTIFACTS_KEY] = artifacts;
+
+ result[kLINKER_LANGUAGE_KEY] = target->GetLinkerLanguage(config);
+
+ std::string linkLibs;
+ std::string linkFlags;
+ std::string linkLanguageFlags;
+ std::string frameworkPath;
+ std::string linkPath;
+ cmLinkLineComputer linkLineComputer(lg,
+ lg->GetStateSnapshot().GetDirectory());
+ lg->GetTargetFlags(&linkLineComputer, config, linkLibs, linkLanguageFlags,
+ linkFlags, frameworkPath, linkPath, target);
+
+ linkLibs = cmSystemTools::TrimWhitespace(linkLibs);
+ linkFlags = cmSystemTools::TrimWhitespace(linkFlags);
+ linkLanguageFlags = cmSystemTools::TrimWhitespace(linkLanguageFlags);
+ frameworkPath = cmSystemTools::TrimWhitespace(frameworkPath);
+ linkPath = cmSystemTools::TrimWhitespace(linkPath);
+
+ if (!cmSystemTools::TrimWhitespace(linkLibs).empty()) {
+ result[kLINK_LIBRARIES_KEY] = linkLibs;
+ }
+ if (!cmSystemTools::TrimWhitespace(linkFlags).empty()) {
+ result[kLINK_FLAGS_KEY] = linkFlags;
+ }
+ if (!cmSystemTools::TrimWhitespace(linkLanguageFlags).empty()) {
+ result[kLINK_LANGUAGE_FLAGS_KEY] = linkLanguageFlags;
+ }
+ if (!frameworkPath.empty()) {
+ result[kFRAMEWORK_PATH_KEY] = frameworkPath;
+ }
+ if (!linkPath.empty()) {
+ result[kLINK_PATH_KEY] = linkPath;
+ }
+ const std::string sysroot =
+ lg->GetMakefile()->GetSafeDefinition("CMAKE_SYSROOT");
+ if (!sysroot.empty()) {
+ result[kSYSROOT_KEY] = sysroot;
+ }
+ }
+
+ std::set<std::string> languages;
+ target->GetLanguages(languages, config);
+ std::map<std::string, LanguageData> languageDataMap;
+
+ for (std::string const& lang : languages) {
+ LanguageData& ld = languageDataMap[lang];
+ ld.Language = lang;
+ lg->GetTargetCompileFlags(target, config, lang, ld.Flags);
+ std::set<std::string> defines;
+ lg->GetTargetDefines(target, config, lang, defines);
+ ld.SetDefines(defines);
+ std::vector<std::string> includePathList;
+ lg->GetIncludeDirectories(includePathList, target, lang, config);
+ for (std::string const& i : includePathList) {
+ ld.IncludePathList.emplace_back(
+ i, target->IsSystemIncludeDirectory(i, config, lang));
+ }
+ }
+
+ Json::Value sourceGroupsValue =
+ DumpSourceFilesList(target, config, languageDataMap);
+ if (!sourceGroupsValue.empty()) {
+ result[kFILE_GROUPS_KEY] = sourceGroupsValue;
+ }
+
+ return result;
+}
+
+static Json::Value DumpTargetsList(
+ const std::vector<cmLocalGenerator*>& generators, const std::string& config)
+{
+ Json::Value result = Json::arrayValue;
+
+ std::vector<cmGeneratorTarget*> targetList;
+ for (auto const& lgIt : generators) {
+ cmAppend(targetList, lgIt->GetGeneratorTargets());
+ }
+ std::sort(targetList.begin(), targetList.end());
+
+ for (cmGeneratorTarget* target : targetList) {
+ Json::Value tmp = DumpTarget(target, config);
+ if (!tmp.isNull()) {
+ result.append(tmp);
+ }
+ }
+
+ return result;
+}
+
+static Json::Value DumpProjectList(const cmake* cm, std::string const& config)
+{
+ Json::Value result = Json::arrayValue;
+
+ auto globalGen = cm->GetGlobalGenerator();
+
+ for (auto const& projectIt : globalGen->GetProjectMap()) {
+ Json::Value pObj = Json::objectValue;
+ pObj[kNAME_KEY] = projectIt.first;
+
+ // All Projects must have at least one local generator
+ assert(!projectIt.second.empty());
+ const cmLocalGenerator* lg = projectIt.second.at(0);
+
+ // Project structure information:
+ const cmMakefile* mf = lg->GetMakefile();
+ auto minVersion = mf->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION");
+ pObj[kMINIMUM_CMAKE_VERSION] = minVersion ? minVersion : "";
+ pObj[kSOURCE_DIRECTORY_KEY] = mf->GetCurrentSourceDirectory();
+ pObj[kBUILD_DIRECTORY_KEY] = mf->GetCurrentBinaryDirectory();
+ pObj[kTARGETS_KEY] = DumpTargetsList(projectIt.second, config);
+
+ // For a project-level install rule it might be defined in any of its
+ // associated generators.
+ bool hasInstallRule = false;
+ for (const auto generator : projectIt.second) {
+ for (const auto installGen :
+ generator->GetMakefile()->GetInstallGenerators()) {
+ if (!dynamic_cast<cmInstallSubdirectoryGenerator*>(installGen)) {
+ hasInstallRule = true;
+ break;
+ }
+ }
+
+ if (hasInstallRule) {
+ break;
+ }
+ }
+
+ pObj[kHAS_INSTALL_RULE] = hasInstallRule;
+
+ result.append(pObj);
+ }
+
+ return result;
+}
+
+static Json::Value DumpConfiguration(const cmake* cm,
+ const std::string& config)
+{
+ Json::Value result = Json::objectValue;
+ result[kNAME_KEY] = config;
+
+ result[kPROJECTS_KEY] = DumpProjectList(cm, config);
+
+ return result;
+}
+
+static Json::Value DumpConfigurationsList(const cmake* cm)
+{
+ Json::Value result = Json::arrayValue;
+
+ for (std::string const& c : getConfigurations(cm)) {
+ result.append(DumpConfiguration(cm, c));
+ }
+
+ return result;
+}
+
+Json::Value cmDumpCodeModel(const cmake* cm)
+{
+ Json::Value result = Json::objectValue;
+ result[kCONFIGURATIONS_KEY] = DumpConfigurationsList(cm);
+ return result;
+}
diff --git a/Source/cmJsonObjects.h b/Source/cmJsonObjects.h
new file mode 100644
index 000000000..cd4da94f4
--- /dev/null
+++ b/Source/cmJsonObjects.h
@@ -0,0 +1,27 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmJsonObjects_h
+#define cmJsonObjects_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cm_jsoncpp_value.h"
+
+#include <string>
+#include <vector>
+
+class cmake;
+class cmGlobalGenerator;
+
+extern void cmGetCMakeInputs(const cmGlobalGenerator* gg,
+ const std::string& sourceDir,
+ const std::string& buildDir,
+ std::vector<std::string>* internalFiles,
+ std::vector<std::string>* explicitFiles,
+ std::vector<std::string>* tmpFiles);
+
+extern Json::Value cmDumpCodeModel(const cmake* cm);
+extern Json::Value cmDumpCTestInfo(const cmake* cm);
+extern Json::Value cmDumpCMakeInputs(const cmake* cm);
+
+#endif
diff --git a/Source/cmLinkItem.cxx b/Source/cmLinkItem.cxx
new file mode 100644
index 000000000..9b03ad011
--- /dev/null
+++ b/Source/cmLinkItem.cxx
@@ -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. */
+#include "cmLinkItem.h"
+
+#include "cmGeneratorTarget.h"
+
+#include <utility> // IWYU pragma: keep
+
+cmLinkItem::cmLinkItem() = default;
+
+cmLinkItem::cmLinkItem(std::string n, cmListFileBacktrace bt)
+ : String(std::move(n))
+ , Backtrace(std::move(bt))
+{
+}
+
+cmLinkItem::cmLinkItem(cmGeneratorTarget const* t, cmListFileBacktrace bt)
+ : Target(t)
+ , Backtrace(std::move(bt))
+{
+}
+
+std::string const& cmLinkItem::AsStr() const
+{
+ return this->Target ? this->Target->GetName() : this->String;
+}
+
+bool operator<(cmLinkItem const& l, cmLinkItem const& r)
+{
+ // Order among targets.
+ if (l.Target && r.Target) {
+ return l.Target < r.Target;
+ }
+ // Order targets before strings.
+ if (l.Target) {
+ return true;
+ }
+ if (r.Target) {
+ return false;
+ }
+ // Order among strings.
+ return l.String < r.String;
+}
+
+bool operator==(cmLinkItem const& l, cmLinkItem const& r)
+{
+ return l.Target == r.Target && l.String == r.String;
+}
+
+std::ostream& operator<<(std::ostream& os, cmLinkItem const& item)
+{
+ return os << item.AsStr();
+}
+
+cmLinkImplItem::cmLinkImplItem()
+ : cmLinkItem()
+{
+}
+
+cmLinkImplItem::cmLinkImplItem(cmLinkItem item, bool fromGenex)
+ : cmLinkItem(std::move(item))
+ , FromGenex(fromGenex)
+{
+}
diff --git a/Source/cmMessageType.h b/Source/cmMessageType.h
new file mode 100644
index 000000000..b57b86bee
--- /dev/null
+++ b/Source/cmMessageType.h
@@ -0,0 +1,21 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmMessageType_h
+#define cmMessageType_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+enum class MessageType
+{
+ AUTHOR_WARNING,
+ AUTHOR_ERROR,
+ FATAL_ERROR,
+ INTERNAL_ERROR,
+ MESSAGE,
+ WARNING,
+ LOG,
+ DEPRECATION_ERROR,
+ DEPRECATION_WARNING
+};
+
+#endif
diff --git a/Source/cmNinjaLinkLineDeviceComputer.cxx b/Source/cmNinjaLinkLineDeviceComputer.cxx
new file mode 100644
index 000000000..84c1b37d3
--- /dev/null
+++ b/Source/cmNinjaLinkLineDeviceComputer.cxx
@@ -0,0 +1,20 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#include "cmNinjaLinkLineDeviceComputer.h"
+
+#include "cmGlobalNinjaGenerator.h"
+
+cmNinjaLinkLineDeviceComputer::cmNinjaLinkLineDeviceComputer(
+ cmOutputConverter* outputConverter, cmStateDirectory const& stateDir,
+ cmGlobalNinjaGenerator const* gg)
+ : cmLinkLineDeviceComputer(outputConverter, stateDir)
+ , GG(gg)
+{
+}
+
+std::string cmNinjaLinkLineDeviceComputer::ConvertToLinkReference(
+ std::string const& lib) const
+{
+ return GG->ConvertToNinjaPath(lib);
+}
diff --git a/Source/cmNinjaLinkLineDeviceComputer.h b/Source/cmNinjaLinkLineDeviceComputer.h
new file mode 100644
index 000000000..84ced5b35
--- /dev/null
+++ b/Source/cmNinjaLinkLineDeviceComputer.h
@@ -0,0 +1,34 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#ifndef cmNinjaLinkLineDeviceComputer_h
+#define cmNinjaLinkLineDeviceComputer_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <string>
+
+#include "cmLinkLineDeviceComputer.h"
+
+class cmGlobalNinjaGenerator;
+class cmOutputConverter;
+class cmStateDirectory;
+
+class cmNinjaLinkLineDeviceComputer : public cmLinkLineDeviceComputer
+{
+public:
+ cmNinjaLinkLineDeviceComputer(cmOutputConverter* outputConverter,
+ cmStateDirectory const& stateDir,
+ cmGlobalNinjaGenerator const* gg);
+
+ cmNinjaLinkLineDeviceComputer(cmNinjaLinkLineDeviceComputer const&) = delete;
+ cmNinjaLinkLineDeviceComputer& operator=(
+ cmNinjaLinkLineDeviceComputer const&) = delete;
+
+ std::string ConvertToLinkReference(std::string const& input) const override;
+
+private:
+ cmGlobalNinjaGenerator const* GG;
+};
+
+#endif
diff --git a/Source/cmPipeConnection.cxx b/Source/cmPipeConnection.cxx
new file mode 100644
index 000000000..1eede13e0
--- /dev/null
+++ b/Source/cmPipeConnection.cxx
@@ -0,0 +1,71 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmPipeConnection.h"
+
+#include <utility>
+
+#include "cmServer.h"
+
+cmPipeConnection::cmPipeConnection(std::string name,
+ cmConnectionBufferStrategy* bufferStrategy)
+ : cmEventBasedConnection(bufferStrategy)
+ , PipeName(std::move(name))
+{
+}
+
+void cmPipeConnection::Connect(uv_stream_t* server)
+{
+ if (this->WriteStream.get()) {
+ // Accept and close all pipes but the first:
+ cm::uv_pipe_ptr rejectPipe;
+
+ rejectPipe.init(*this->Server->GetLoop(), 0);
+ uv_accept(server, rejectPipe);
+
+ return;
+ }
+
+ cm::uv_pipe_ptr ClientPipe;
+ ClientPipe.init(*this->Server->GetLoop(), 0,
+ static_cast<cmEventBasedConnection*>(this));
+
+ if (uv_accept(server, ClientPipe) != 0) {
+ return;
+ }
+
+ uv_read_start(ClientPipe, on_alloc_buffer, on_read);
+ WriteStream = std::move(ClientPipe);
+ Server->OnConnected(this);
+}
+
+bool cmPipeConnection::OnServeStart(std::string* errorMessage)
+{
+ this->ServerPipe.init(*this->Server->GetLoop(), 0,
+ 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;
+ }
+
+ if ((r = uv_listen(this->ServerPipe, 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->WriteStream.get()) {
+ this->WriteStream->data = nullptr;
+ }
+
+ this->ServerPipe.reset();
+
+ return cmEventBasedConnection::OnConnectionShuttingDown();
+}
diff --git a/Source/cmPipeConnection.h b/Source/cmPipeConnection.h
new file mode 100644
index 000000000..e67f15c57
--- /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 "cmUVHandlePtr.h"
+#include <string>
+
+#include "cmConnection.h"
+#include "cm_uv.h"
+
+class cmPipeConnection : public cmEventBasedConnection
+{
+public:
+ cmPipeConnection(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;
+ cm::uv_pipe_ptr ServerPipe;
+};
diff --git a/Source/cmQtAutoGen.cxx b/Source/cmQtAutoGen.cxx
new file mode 100644
index 000000000..3683eddda
--- /dev/null
+++ b/Source/cmQtAutoGen.cxx
@@ -0,0 +1,410 @@
+/* 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 "cmDuration.h"
+#include "cmProcessOutput.h"
+#include "cmSystemTools.h"
+#include "cmsys/FStream.hxx"
+#include "cmsys/RegularExpression.hxx"
+
+#include <algorithm>
+#include <array>
+#include <sstream>
+#include <utility>
+
+// - 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
+ cmAppend(baseOpts, extraOpts);
+}
+
+// - Class definitions
+
+unsigned int const cmQtAutoGen::ParallelMax = 64;
+std::string const cmQtAutoGen::ListSep = "<<<S>>>";
+
+std::string const& cmQtAutoGen::GeneratorName(GenT genType)
+{
+ static const std::string AutoGen("AutoGen");
+ static const std::string AutoMoc("AutoMoc");
+ static const std::string AutoUic("AutoUic");
+ static const std::string AutoRcc("AutoRcc");
+
+ switch (genType) {
+ case GenT::GEN:
+ return AutoGen;
+ case GenT::MOC:
+ return AutoMoc;
+ case GenT::UIC:
+ return AutoUic;
+ case GenT::RCC:
+ return AutoRcc;
+ }
+ return AutoGen;
+}
+
+std::string const& cmQtAutoGen::GeneratorNameUpper(GenT genType)
+{
+ static const std::string AUTOGEN("AUTOGEN");
+ static const std::string AUTOMOC("AUTOMOC");
+ static const std::string AUTOUIC("AUTOUIC");
+ static const std::string AUTORCC("AUTORCC");
+
+ switch (genType) {
+ case GenT::GEN:
+ return AUTOGEN;
+ case GenT::MOC:
+ return AUTOMOC;
+ case GenT::UIC:
+ return AUTOUIC;
+ case GenT::RCC:
+ return AUTORCC;
+ }
+ return AUTOGEN;
+}
+
+std::string cmQtAutoGen::Tools(bool moc, bool uic, bool rcc)
+{
+ std::string res;
+ std::vector<std::string> lst;
+ if (moc) {
+ lst.emplace_back("AUTOMOC");
+ }
+ if (uic) {
+ lst.emplace_back("AUTOUIC");
+ }
+ if (rcc) {
+ lst.emplace_back("AUTORCC");
+ }
+ switch (lst.size()) {
+ case 1:
+ res += lst.at(0);
+ break;
+ case 2:
+ res += lst.at(0);
+ res += " and ";
+ res += lst.at(1);
+ break;
+ case 3:
+ res += lst.at(0);
+ res += ", ";
+ res += lst.at(1);
+ res += " and ";
+ res += lst.at(2);
+ break;
+ default:
+ break;
+ }
+ return res;
+}
+
+std::string cmQtAutoGen::Quoted(std::string const& text)
+{
+ const std::array<std::pair<const char*, const char*>, 9> replaces = {
+ { { "\\", "\\\\" },
+ { "\"", "\\\"" },
+ { "\a", "\\a" },
+ { "\b", "\\b" },
+ { "\f", "\\f" },
+ { "\n", "\\n" },
+ { "\r", "\\r" },
+ { "\t", "\\t" },
+ { "\v", "\\v" } }
+ };
+
+ std::string res = text;
+ for (auto const& pair : replaces) {
+ cmSystemTools::ReplaceString(res, pair.first, pair.second);
+ }
+ res = '"' + res;
+ res += '"';
+ return res;
+}
+
+std::string cmQtAutoGen::QuotedCommand(std::vector<std::string> const& command)
+{
+ std::string res;
+ for (std::string const& item : command) {
+ if (!res.empty()) {
+ res.push_back(' ');
+ }
+ std::string const cesc = cmQtAutoGen::Quoted(item);
+ if (item.empty() || (cesc.size() > (item.size() + 2)) ||
+ (cesc.find(' ') != std::string::npos)) {
+ res += cesc;
+ } else {
+ res += item;
+ }
+ }
+ return res;
+}
+
+std::string cmQtAutoGen::SubDirPrefix(std::string const& filename)
+{
+ std::string::size_type slash_pos = filename.rfind('/');
+ if (slash_pos == std::string::npos) {
+ return std::string();
+ }
+ return filename.substr(0, slash_pos + 1);
+}
+
+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);
+}
+
+static void RccListParseContent(std::string const& content,
+ std::vector<std::string>& files)
+{
+ cmsys::RegularExpression fileMatchRegex("(<file[^<]+)");
+ cmsys::RegularExpression fileReplaceRegex("(^<file[^>]*>)");
+
+ const char* contentChars = content.c_str();
+ while (fileMatchRegex.find(contentChars)) {
+ std::string const qrcEntry = fileMatchRegex.match(1);
+ contentChars += qrcEntry.size();
+ {
+ fileReplaceRegex.find(qrcEntry);
+ std::string const tag = fileReplaceRegex.match(1);
+ files.push_back(qrcEntry.substr(tag.size()));
+ }
+ }
+}
+
+static bool RccListParseOutput(std::string const& rccStdOut,
+ std::string const& rccStdErr,
+ std::vector<std::string>& files,
+ std::string& error)
+{
+ // Lambda to strip CR characters
+ auto StripCR = [](std::string& line) {
+ std::string::size_type cr = line.find('\r');
+ if (cr != std::string::npos) {
+ line = line.substr(0, cr);
+ }
+ };
+
+ // Parse rcc std output
+ {
+ std::istringstream ostr(rccStdOut);
+ std::string oline;
+ while (std::getline(ostr, oline)) {
+ StripCR(oline);
+ if (!oline.empty()) {
+ files.push_back(oline);
+ }
+ }
+ }
+ // Parse rcc error output
+ {
+ std::istringstream estr(rccStdErr);
+ std::string eline;
+ while (std::getline(estr, eline)) {
+ StripCR(eline);
+ if (cmHasLiteralPrefix(eline, "RCC: Error in")) {
+ static std::string const searchString = "Cannot find file '";
+
+ std::string::size_type pos = eline.find(searchString);
+ if (pos == std::string::npos) {
+ error = "rcc lists unparsable output:\n";
+ error += cmQtAutoGen::Quoted(eline);
+ error += "\n";
+ return false;
+ }
+ pos += searchString.length();
+ std::string::size_type sz = eline.size() - pos - 1;
+ files.push_back(eline.substr(pos, sz));
+ }
+ }
+ }
+
+ return true;
+}
+
+cmQtAutoGen::RccLister::RccLister() = default;
+
+cmQtAutoGen::RccLister::RccLister(std::string rccExecutable,
+ std::vector<std::string> listOptions)
+ : RccExcutable_(std::move(rccExecutable))
+ , ListOptions_(std::move(listOptions))
+{
+}
+
+bool cmQtAutoGen::RccLister::list(std::string const& qrcFile,
+ std::vector<std::string>& files,
+ std::string& error, bool verbose) const
+{
+ error.clear();
+
+ if (!cmSystemTools::FileExists(qrcFile, true)) {
+ error = "The resource file ";
+ error += Quoted(qrcFile);
+ error += " does not exist.";
+ return false;
+ }
+
+ // Run rcc list command in the directory of the qrc file with the pathless
+ // qrc file name argument. This way rcc prints relative paths.
+ // This avoids issues on Windows when the qrc file is in a path that
+ // contains non-ASCII characters.
+ std::string const fileDir = cmSystemTools::GetFilenamePath(qrcFile);
+
+ if (!this->RccExcutable_.empty() &&
+ cmSystemTools::FileExists(this->RccExcutable_, true) &&
+ !this->ListOptions_.empty()) {
+
+ bool result = false;
+ int retVal = 0;
+ std::string rccStdOut;
+ std::string rccStdErr;
+ {
+ std::vector<std::string> cmd;
+ cmd.emplace_back(this->RccExcutable_);
+ cmAppend(cmd, this->ListOptions_);
+ cmd.emplace_back(cmSystemTools::GetFilenameName(qrcFile));
+
+ // Log command
+ if (verbose) {
+ std::string msg = "Running command:\n";
+ msg += QuotedCommand(cmd);
+ msg += '\n';
+ cmSystemTools::Stdout(msg);
+ }
+
+ result = cmSystemTools::RunSingleCommand(
+ cmd, &rccStdOut, &rccStdErr, &retVal, fileDir.c_str(),
+ cmSystemTools::OUTPUT_NONE, cmDuration::zero(), cmProcessOutput::Auto);
+ }
+ if (!result || retVal) {
+ error = "The rcc list process failed for ";
+ error += Quoted(qrcFile);
+ error += "\n";
+ if (!rccStdOut.empty()) {
+ error += rccStdOut;
+ error += "\n";
+ }
+ if (!rccStdErr.empty()) {
+ error += rccStdErr;
+ error += "\n";
+ }
+ return false;
+ }
+ if (!RccListParseOutput(rccStdOut, rccStdErr, files, error)) {
+ return false;
+ }
+ } else {
+ // We can't use rcc for the file listing.
+ // Read the qrc file content into string and parse it.
+ {
+ std::string qrcContents;
+ {
+ cmsys::ifstream ifs(qrcFile.c_str());
+ if (ifs) {
+ std::ostringstream osst;
+ osst << ifs.rdbuf();
+ qrcContents = osst.str();
+ } else {
+ error = "The resource file ";
+ error += Quoted(qrcFile);
+ error += " is not readable\n";
+ return false;
+ }
+ }
+ // Parse string content
+ RccListParseContent(qrcContents, files);
+ }
+ }
+
+ // Convert relative paths to absolute paths
+ for (std::string& entry : files) {
+ entry = cmSystemTools::CollapseFullPath(entry, fileDir);
+ }
+ return true;
+}
diff --git a/Source/cmQtAutoGen.h b/Source/cmQtAutoGen.h
new file mode 100644
index 000000000..9c5212952
--- /dev/null
+++ b/Source/cmQtAutoGen.h
@@ -0,0 +1,138 @@
+/* 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 <memory> // IWYU pragma: keep
+#include <string>
+#include <vector>
+
+/** \class cmQtAutoGen
+ * \brief Common base class for QtAutoGen classes
+ */
+class cmQtAutoGen
+{
+public:
+ /// @brief Integer version
+ struct IntegerVersion
+ {
+ unsigned int Major = 0;
+ unsigned int Minor = 0;
+
+ IntegerVersion() = default;
+ IntegerVersion(unsigned int major, unsigned int minor)
+ : Major(major)
+ , Minor(minor)
+ {
+ }
+
+ bool operator>(IntegerVersion const version)
+ {
+ return (this->Major > version.Major) ||
+ ((this->Major == version.Major) && (this->Minor > version.Minor));
+ }
+
+ bool operator>=(IntegerVersion const version)
+ {
+ return (this->Major > version.Major) ||
+ ((this->Major == version.Major) && (this->Minor >= version.Minor));
+ }
+ };
+
+ class CompilerFeatures
+ {
+ public:
+ bool Evaluated = false;
+ std::string HelpOutput;
+ std::vector<std::string> ListOptions;
+ };
+ typedef std::shared_ptr<CompilerFeatures> CompilerFeaturesHandle;
+
+ /// @brief AutoGen generator type
+ enum class GenT
+ {
+ GEN, // AUTOGEN
+ MOC, // AUTOMOC
+ UIC, // AUTOUIC
+ RCC // AUTORCC
+ };
+
+ /// @brief Nested lists separator
+ static std::string const ListSep;
+ /// @brief Maximum number of parallel threads/processes in a generator
+ static unsigned int const ParallelMax;
+
+public:
+ /// @brief Returns the generator name
+ static std::string const& GeneratorName(GenT genType);
+ /// @brief Returns the generator name in upper case
+ static std::string const& GeneratorNameUpper(GenT genType);
+
+ /// @brief Returns a string with the requested tool names
+ static std::string Tools(bool moc, bool uic, bool rcc);
+
+ /// @brief Returns the string escaped and enclosed in quotes
+ static std::string Quoted(std::string const& text);
+
+ static std::string QuotedCommand(std::vector<std::string> const& command);
+
+ /// @brief Returns the parent directory of the file with a "/" suffix
+ static std::string SubDirPrefix(std::string const& filename);
+
+ /// @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);
+
+ /** @class RccLister
+ * @brief Lists files in qrc resource files
+ */
+ class RccLister
+ {
+ public:
+ RccLister();
+ RccLister(std::string rccExecutable, std::vector<std::string> listOptions);
+
+ //! The rcc executable
+ std::string const& RccExcutable() const { return RccExcutable_; }
+ void SetRccExecutable(std::string const& rccExecutable)
+ {
+ RccExcutable_ = rccExecutable;
+ }
+
+ //! The rcc executable list options
+ std::vector<std::string> const& ListOptions() const
+ {
+ return ListOptions_;
+ }
+ void SetListOptions(std::vector<std::string> const& listOptions)
+ {
+ ListOptions_ = listOptions;
+ }
+
+ /**
+ * @brief Lists a files in the qrcFile
+ * @arg files The file names are appended to this list
+ * @arg error contains the error message when the function fails
+ */
+ bool list(std::string const& qrcFile, std::vector<std::string>& files,
+ std::string& error, bool verbose = false) const;
+
+ private:
+ std::string RccExcutable_;
+ std::vector<std::string> ListOptions_;
+ };
+};
+
+#endif
diff --git a/Source/cmQtAutoGenGlobalInitializer.cxx b/Source/cmQtAutoGenGlobalInitializer.cxx
new file mode 100644
index 000000000..ef8a56b3b
--- /dev/null
+++ b/Source/cmQtAutoGenGlobalInitializer.cxx
@@ -0,0 +1,303 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmQtAutoGenGlobalInitializer.h"
+#include "cmQtAutoGen.h"
+#include "cmQtAutoGenInitializer.h"
+
+#include "cmAlgorithms.h"
+#include "cmCustomCommandLines.h"
+#include "cmDuration.h"
+#include "cmGeneratorTarget.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmMessageType.h"
+#include "cmProcessOutput.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+
+#include <memory>
+#include <utility>
+
+cmQtAutoGenGlobalInitializer::Keywords::Keywords()
+ : AUTOMOC("AUTOMOC")
+ , AUTOUIC("AUTOUIC")
+ , AUTORCC("AUTORCC")
+ , AUTOMOC_EXECUTABLE("AUTOMOC_EXECUTABLE")
+ , AUTOUIC_EXECUTABLE("AUTOUIC_EXECUTABLE")
+ , AUTORCC_EXECUTABLE("AUTORCC_EXECUTABLE")
+ , SKIP_AUTOGEN("SKIP_AUTOGEN")
+ , SKIP_AUTOMOC("SKIP_AUTOMOC")
+ , SKIP_AUTOUIC("SKIP_AUTOUIC")
+ , SKIP_AUTORCC("SKIP_AUTORCC")
+ , AUTOUIC_OPTIONS("AUTOUIC_OPTIONS")
+ , AUTORCC_OPTIONS("AUTORCC_OPTIONS")
+ , qrc("qrc")
+ , ui("ui")
+{
+}
+
+cmQtAutoGenGlobalInitializer::cmQtAutoGenGlobalInitializer(
+ std::vector<cmLocalGenerator*> const& localGenerators)
+{
+ for (cmLocalGenerator* localGen : localGenerators) {
+ // Detect global autogen and autorcc target names
+ bool globalAutoGenTarget = false;
+ bool globalAutoRccTarget = false;
+ {
+ cmMakefile* makefile = localGen->GetMakefile();
+ // Detect global autogen target name
+ if (cmSystemTools::IsOn(
+ makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTOGEN_TARGET"))) {
+ std::string targetName =
+ makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTOGEN_TARGET_NAME");
+ if (targetName.empty()) {
+ targetName = "autogen";
+ }
+ GlobalAutoGenTargets_.emplace(localGen, std::move(targetName));
+ globalAutoGenTarget = true;
+ }
+
+ // Detect global autorcc target name
+ if (cmSystemTools::IsOn(
+ makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTORCC_TARGET"))) {
+ std::string targetName =
+ makefile->GetSafeDefinition("CMAKE_GLOBAL_AUTORCC_TARGET_NAME");
+ if (targetName.empty()) {
+ targetName = "autorcc";
+ }
+ GlobalAutoRccTargets_.emplace(localGen, std::move(targetName));
+ globalAutoRccTarget = true;
+ }
+ }
+
+ // Find targets that require AUTOMOC/UIC/RCC processing
+ for (cmGeneratorTarget* target : localGen->GetGeneratorTargets()) {
+ // Process only certain target types
+ switch (target->GetType()) {
+ case cmStateEnums::EXECUTABLE:
+ case cmStateEnums::STATIC_LIBRARY:
+ case cmStateEnums::SHARED_LIBRARY:
+ case cmStateEnums::MODULE_LIBRARY:
+ case cmStateEnums::OBJECT_LIBRARY:
+ // Process target
+ break;
+ default:
+ // Don't process target
+ continue;
+ }
+ if (target->IsImported()) {
+ // Don't process target
+ continue;
+ }
+
+ bool const moc = target->GetPropertyAsBool(kw().AUTOMOC);
+ bool const uic = target->GetPropertyAsBool(kw().AUTOUIC);
+ bool const rcc = target->GetPropertyAsBool(kw().AUTORCC);
+ if (moc || uic || rcc) {
+ std::string const mocExec =
+ target->GetSafeProperty(kw().AUTOMOC_EXECUTABLE);
+ std::string const uicExec =
+ target->GetSafeProperty(kw().AUTOUIC_EXECUTABLE);
+ std::string const rccExec =
+ target->GetSafeProperty(kw().AUTORCC_EXECUTABLE);
+
+ // We support Qt4, Qt5 and Qt6
+ auto qtVersion = cmQtAutoGenInitializer::GetQtVersion(target);
+ bool const validQt = (qtVersion.first.Major == 4) ||
+ (qtVersion.first.Major == 5) || (qtVersion.first.Major == 6);
+
+ bool const mocAvailable = (validQt || !mocExec.empty());
+ bool const uicAvailable = (validQt || !uicExec.empty());
+ bool const rccAvailable = (validQt || !rccExec.empty());
+ bool const mocIsValid = (moc && mocAvailable);
+ bool const uicIsValid = (uic && uicAvailable);
+ bool const rccIsValid = (rcc && rccAvailable);
+ // Disabled AUTOMOC/UIC/RCC warning
+ bool const mocDisabled = (moc && !mocAvailable);
+ bool const uicDisabled = (uic && !uicAvailable);
+ bool const rccDisabled = (rcc && !rccAvailable);
+ if (mocDisabled || uicDisabled || rccDisabled) {
+ std::string msg = "AUTOGEN: No valid Qt version found for target ";
+ msg += target->GetName();
+ msg += ". ";
+ msg += cmQtAutoGen::Tools(mocDisabled, uicDisabled, rccDisabled);
+ msg += " disabled. Consider adding:\n";
+ {
+ std::string version = (qtVersion.second == 0)
+ ? std::string("<QTVERSION>")
+ : std::to_string(qtVersion.second);
+ std::string comp = uicDisabled ? "Widgets" : "Core";
+ msg += " find_package(Qt";
+ msg += version;
+ msg += " COMPONENTS ";
+ msg += comp;
+ msg += ")\n";
+ }
+ msg += "to your CMakeLists.txt file.";
+ target->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, msg);
+ }
+ if (mocIsValid || uicIsValid || rccIsValid) {
+ // Create autogen target initializer
+ Initializers_.emplace_back(cm::make_unique<cmQtAutoGenInitializer>(
+ this, target, qtVersion.first, mocIsValid, uicIsValid, rccIsValid,
+ globalAutoGenTarget, globalAutoRccTarget));
+ }
+ }
+ }
+ }
+}
+
+cmQtAutoGenGlobalInitializer::~cmQtAutoGenGlobalInitializer() = default;
+
+void cmQtAutoGenGlobalInitializer::GetOrCreateGlobalTarget(
+ cmLocalGenerator* localGen, std::string const& name,
+ std::string const& comment)
+{
+ // Test if the target already exists
+ if (localGen->FindGeneratorTargetToUse(name) == nullptr) {
+ cmMakefile* makefile = localGen->GetMakefile();
+
+ // Create utility target
+ cmTarget* target = makefile->AddUtilityCommand(
+ name, cmMakefile::TargetOrigin::Generator, true,
+ makefile->GetHomeOutputDirectory().c_str() /*work dir*/,
+ std::vector<std::string>() /*output*/,
+ std::vector<std::string>() /*depends*/, cmCustomCommandLines(), false,
+ comment.c_str());
+ localGen->AddGeneratorTarget(new cmGeneratorTarget(target, localGen));
+
+ // Set FOLDER property in the target
+ {
+ char const* folder =
+ makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER");
+ if (folder != nullptr) {
+ target->SetProperty("FOLDER", folder);
+ }
+ }
+ }
+}
+
+void cmQtAutoGenGlobalInitializer::AddToGlobalAutoGen(
+ cmLocalGenerator* localGen, std::string const& targetName)
+{
+ auto it = GlobalAutoGenTargets_.find(localGen);
+ if (it != GlobalAutoGenTargets_.end()) {
+ cmGeneratorTarget* target = localGen->FindGeneratorTargetToUse(it->second);
+ if (target != nullptr) {
+ target->Target->AddUtility(targetName, localGen->GetMakefile());
+ }
+ }
+}
+
+void cmQtAutoGenGlobalInitializer::AddToGlobalAutoRcc(
+ cmLocalGenerator* localGen, std::string const& targetName)
+{
+ auto it = GlobalAutoRccTargets_.find(localGen);
+ if (it != GlobalAutoRccTargets_.end()) {
+ cmGeneratorTarget* target = localGen->FindGeneratorTargetToUse(it->second);
+ if (target != nullptr) {
+ target->Target->AddUtility(targetName, localGen->GetMakefile());
+ }
+ }
+}
+
+cmQtAutoGen::CompilerFeaturesHandle
+cmQtAutoGenGlobalInitializer::GetCompilerFeatures(
+ std::string const& generator, std::string const& executable,
+ std::string& error)
+{
+ // Check if we have cached features
+ {
+ auto it = this->CompilerFeatures_.find(executable);
+ if (it != this->CompilerFeatures_.end()) {
+ return it->second;
+ }
+ }
+
+ // Check if the executable exists
+ if (!cmSystemTools::FileExists(executable, true)) {
+ error = "The \"";
+ error += generator;
+ error += "\" executable ";
+ error += cmQtAutoGen::Quoted(executable);
+ error += " does not exist.";
+ return cmQtAutoGen::CompilerFeaturesHandle();
+ }
+
+ // Test the executable
+ std::string stdOut;
+ {
+ std::string stdErr;
+ std::vector<std::string> command;
+ command.emplace_back(executable);
+ command.emplace_back("-h");
+ int retVal = 0;
+ const bool runResult = cmSystemTools::RunSingleCommand(
+ command, &stdOut, &stdErr, &retVal, nullptr, cmSystemTools::OUTPUT_NONE,
+ cmDuration::zero(), cmProcessOutput::Auto);
+ if (!runResult) {
+ error = "Test run of \"";
+ error += generator;
+ error += "\" executable ";
+ error += cmQtAutoGen::Quoted(executable) + " failed.\n";
+ error += cmQtAutoGen::QuotedCommand(command);
+ error += "\n";
+ error += stdOut;
+ error += "\n";
+ error += stdErr;
+ return cmQtAutoGen::CompilerFeaturesHandle();
+ }
+ }
+
+ // Create valid handle
+ cmQtAutoGen::CompilerFeaturesHandle res =
+ std::make_shared<cmQtAutoGen::CompilerFeatures>();
+ res->HelpOutput = std::move(stdOut);
+
+ // Register compiler features
+ this->CompilerFeatures_.emplace(executable, res);
+
+ return res;
+}
+
+bool cmQtAutoGenGlobalInitializer::generate()
+{
+ return (InitializeCustomTargets() && SetupCustomTargets());
+}
+
+bool cmQtAutoGenGlobalInitializer::InitializeCustomTargets()
+{
+ // Initialize global autogen targets
+ {
+ std::string const comment = "Global AUTOGEN target";
+ for (auto const& pair : GlobalAutoGenTargets_) {
+ GetOrCreateGlobalTarget(pair.first, pair.second, comment);
+ }
+ }
+ // Initialize global autorcc targets
+ {
+ std::string const comment = "Global AUTORCC target";
+ for (auto const& pair : GlobalAutoRccTargets_) {
+ GetOrCreateGlobalTarget(pair.first, pair.second, comment);
+ }
+ }
+ // Initialize per target autogen targets
+ for (auto& initializer : Initializers_) {
+ if (!initializer->InitCustomTargets()) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool cmQtAutoGenGlobalInitializer::SetupCustomTargets()
+{
+ for (auto& initializer : Initializers_) {
+ if (!initializer->SetupCustomTargets()) {
+ return false;
+ }
+ }
+ return true;
+}
diff --git a/Source/cmQtAutoGenGlobalInitializer.h b/Source/cmQtAutoGenGlobalInitializer.h
new file mode 100644
index 000000000..d56153ab7
--- /dev/null
+++ b/Source/cmQtAutoGenGlobalInitializer.h
@@ -0,0 +1,86 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmQtAutoGenGlobalInitializer_h
+#define cmQtAutoGenGlobalInitializer_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cmQtAutoGen.h"
+
+#include <map>
+#include <memory> // IWYU pragma: keep
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+class cmLocalGenerator;
+class cmQtAutoGenInitializer;
+
+/// @brief Initializes the QtAutoGen generators
+class cmQtAutoGenGlobalInitializer
+{
+public:
+ /// @brief Collection of QtAutogen related keywords
+ class Keywords
+ {
+ public:
+ Keywords();
+
+ std::string AUTOMOC;
+ std::string AUTOUIC;
+ std::string AUTORCC;
+
+ std::string AUTOMOC_EXECUTABLE;
+ std::string AUTOUIC_EXECUTABLE;
+ std::string AUTORCC_EXECUTABLE;
+
+ std::string SKIP_AUTOGEN;
+ std::string SKIP_AUTOMOC;
+ std::string SKIP_AUTOUIC;
+ std::string SKIP_AUTORCC;
+
+ std::string AUTOUIC_OPTIONS;
+ std::string AUTORCC_OPTIONS;
+
+ std::string qrc;
+ std::string ui;
+ };
+
+public:
+ cmQtAutoGenGlobalInitializer(
+ std::vector<cmLocalGenerator*> const& localGenerators);
+ ~cmQtAutoGenGlobalInitializer();
+
+ Keywords const& kw() const { return Keywords_; };
+
+ bool generate();
+
+private:
+ friend class cmQtAutoGenInitializer;
+
+ bool InitializeCustomTargets();
+ bool SetupCustomTargets();
+
+ void GetOrCreateGlobalTarget(cmLocalGenerator* localGen,
+ std::string const& name,
+ std::string const& comment);
+
+ void AddToGlobalAutoGen(cmLocalGenerator* localGen,
+ std::string const& targetName);
+ void AddToGlobalAutoRcc(cmLocalGenerator* localGen,
+ std::string const& targetName);
+
+ cmQtAutoGen::CompilerFeaturesHandle GetCompilerFeatures(
+ std::string const& generator, std::string const& executable,
+ std::string& error);
+
+private:
+ std::vector<std::unique_ptr<cmQtAutoGenInitializer>> Initializers_;
+ std::map<cmLocalGenerator*, std::string> GlobalAutoGenTargets_;
+ std::map<cmLocalGenerator*, std::string> GlobalAutoRccTargets_;
+ std::unordered_map<std::string, cmQtAutoGen::CompilerFeaturesHandle>
+ CompilerFeatures_;
+ Keywords const Keywords_;
+};
+
+#endif
diff --git a/Source/cmQtAutoGenInitializer.cxx b/Source/cmQtAutoGenInitializer.cxx
new file mode 100644
index 000000000..9985f93eb
--- /dev/null
+++ b/Source/cmQtAutoGenInitializer.cxx
@@ -0,0 +1,1712 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmQtAutoGenInitializer.h"
+#include "cmQtAutoGen.h"
+#include "cmQtAutoGenGlobalInitializer.h"
+
+#include "cmAlgorithms.h"
+#include "cmCustomCommand.h"
+#include "cmCustomCommandLines.h"
+#include "cmFilePathChecksum.h"
+#include "cmGeneratorExpression.h"
+#include "cmGeneratorTarget.h"
+#include "cmGlobalGenerator.h"
+#include "cmLinkItem.h"
+#include "cmListFileCache.h"
+#include "cmLocalGenerator.h"
+#include "cmMakefile.h"
+#include "cmMessageType.h"
+#include "cmOutputConverter.h"
+#include "cmPolicies.h"
+#include "cmSourceFile.h"
+#include "cmSourceFileLocationKind.h"
+#include "cmSourceGroup.h"
+#include "cmState.h"
+#include "cmStateTypes.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+#include "cmake.h"
+#include "cmsys/SystemInformation.hxx"
+
+#include <algorithm>
+#include <array>
+#include <deque>
+#include <map>
+#include <set>
+#include <string>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+static std::size_t GetParallelCPUCount()
+{
+ static std::size_t count = 0;
+ // Detect only on the first call
+ if (count == 0) {
+ cmsys::SystemInformation info;
+ info.RunCPUCheck();
+ count = info.GetNumberOfPhysicalCPU();
+ count = std::max<std::size_t>(count, 1);
+ count = std::min<std::size_t>(count, cmQtAutoGen::ParallelMax);
+ }
+ return count;
+}
+
+static std::string FileProjectRelativePath(cmMakefile* makefile,
+ std::string const& fileName)
+{
+ std::string res;
+ {
+ std::string pSource = cmSystemTools::RelativePath(
+ makefile->GetCurrentSourceDirectory(), fileName);
+ std::string pBinary = cmSystemTools::RelativePath(
+ makefile->GetCurrentBinaryDirectory(), fileName);
+ if (pSource.size() < pBinary.size()) {
+ res = std::move(pSource);
+ } else if (pBinary.size() < fileName.size()) {
+ res = std::move(pBinary);
+ } else {
+ res = fileName;
+ }
+ }
+ return res;
+}
+
+/**
+ * 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;
+}
+
+cmQtAutoGenInitializer::InfoWriter::InfoWriter(std::string const& filename)
+{
+ Ofs_.SetCopyIfDifferent(true);
+ Ofs_.Open(filename, false, true);
+}
+
+template <class IT>
+std::string cmQtAutoGenInitializer::InfoWriter::ListJoin(IT it_begin,
+ IT it_end)
+{
+ std::string res;
+ for (IT it = it_begin; it != it_end; ++it) {
+ if (it != it_begin) {
+ res += ';';
+ }
+ for (const char* c = it->c_str(); *c; ++c) {
+ if (*c == '"') {
+ // Escape the double quote to avoid ending the argument.
+ res += "\\\"";
+ } else if (*c == '$') {
+ // Escape the dollar to avoid expanding variables.
+ res += "\\$";
+ } else if (*c == '\\') {
+ // Escape the backslash to avoid other escapes.
+ res += "\\\\";
+ } else if (*c == ';') {
+ // Escape the semicolon to avoid list expansion.
+ res += "\\;";
+ } else {
+ // Other characters will be parsed correctly.
+ res += *c;
+ }
+ }
+ }
+ return res;
+}
+
+std::string cmQtAutoGenInitializer::InfoWriter::ConfigKey(
+ const char* key, std::string const& config)
+{
+ std::string ckey = key;
+ ckey += '_';
+ ckey += config;
+ return ckey;
+}
+
+void cmQtAutoGenInitializer::InfoWriter::Write(const char* key,
+ std::string const& value)
+{
+ Ofs_ << "set(" << key << " " << cmOutputConverter::EscapeForCMake(value)
+ << ")\n";
+};
+
+void cmQtAutoGenInitializer::InfoWriter::WriteUInt(const char* key,
+ unsigned int value)
+{
+ Ofs_ << "set(" << key << " " << value << ")\n";
+};
+
+template <class C>
+void cmQtAutoGenInitializer::InfoWriter::WriteStrings(const char* key,
+ C const& container)
+{
+ Ofs_ << "set(" << key << " \""
+ << ListJoin(container.begin(), container.end()) << "\")\n";
+}
+
+void cmQtAutoGenInitializer::InfoWriter::WriteConfig(
+ const char* key, std::map<std::string, std::string> const& map)
+{
+ for (auto const& item : map) {
+ Write(ConfigKey(key, item.first).c_str(), item.second);
+ }
+};
+
+template <class C>
+void cmQtAutoGenInitializer::InfoWriter::WriteConfigStrings(
+ const char* key, std::map<std::string, C> const& map)
+{
+ for (auto const& item : map) {
+ WriteStrings(ConfigKey(key, item.first).c_str(), item.second);
+ }
+}
+
+void cmQtAutoGenInitializer::InfoWriter::WriteNestedLists(
+ const char* key, std::vector<std::vector<std::string>> const& lists)
+{
+ std::vector<std::string> seplist;
+ for (const std::vector<std::string>& list : lists) {
+ std::string blist = "{";
+ blist += ListJoin(list.begin(), list.end());
+ blist += "}";
+ seplist.push_back(std::move(blist));
+ }
+ Write(key, cmJoin(seplist, cmQtAutoGen::ListSep));
+};
+
+cmQtAutoGenInitializer::cmQtAutoGenInitializer(
+ cmQtAutoGenGlobalInitializer* globalInitializer, cmGeneratorTarget* target,
+ IntegerVersion const& qtVersion, bool mocEnabled, bool uicEnabled,
+ bool rccEnabled, bool globalAutogenTarget, bool globalAutoRccTarget)
+ : GlobalInitializer(globalInitializer)
+ , Target(target)
+ , QtVersion(qtVersion)
+{
+ AutogenTarget.GlobalTarget = globalAutogenTarget;
+ Moc.Enabled = mocEnabled;
+ Uic.Enabled = uicEnabled;
+ Rcc.Enabled = rccEnabled;
+ Rcc.GlobalTarget = globalAutoRccTarget;
+}
+
+bool cmQtAutoGenInitializer::InitCustomTargets()
+{
+ cmMakefile* makefile = this->Target->Target->GetMakefile();
+ cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
+ cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();
+
+ // Configurations
+ this->MultiConfig = globalGen->IsMultiConfig();
+ this->ConfigDefault = makefile->GetConfigurations(this->ConfigsList);
+ if (this->ConfigsList.empty()) {
+ this->ConfigsList.push_back(this->ConfigDefault);
+ }
+
+ // Verbosity
+ this->Verbosity = makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
+ if (!this->Verbosity.empty()) {
+ unsigned long iVerb = 0;
+ if (!cmSystemTools::StringToULong(this->Verbosity.c_str(), &iVerb)) {
+ // Non numeric verbosity
+ this->Verbosity = cmSystemTools::IsOn(this->Verbosity) ? "1" : "0";
+ }
+ }
+
+ // Targets FOLDER
+ {
+ const char* folder =
+ makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
+ if (folder == nullptr) {
+ folder =
+ makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER");
+ }
+ // Inherit FOLDER property from target (#13688)
+ if (folder == nullptr) {
+ folder = this->Target->GetProperty("FOLDER");
+ }
+ if (folder != nullptr) {
+ this->TargetsFolder = folder;
+ }
+ }
+
+ // Check status of policy CMP0071
+ {
+ cmPolicies::PolicyStatus const CMP0071_status =
+ makefile->GetPolicyStatus(cmPolicies::CMP0071);
+ switch (CMP0071_status) {
+ case cmPolicies::WARN:
+ this->CMP0071Warn = 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
+ this->CMP0071Accept = true;
+ break;
+ }
+ }
+
+ // Common directories
+ {
+ // Collapsed current binary directory
+ std::string const cbd = cmSystemTools::CollapseFullPath(
+ std::string(), makefile->GetCurrentBinaryDirectory());
+
+ // Info directory
+ this->Dir.Info = cbd;
+ this->Dir.Info += "/CMakeFiles";
+ this->Dir.Info += '/';
+ this->Dir.Info += this->Target->GetName();
+ this->Dir.Info += "_autogen";
+ this->Dir.Info += ".dir";
+ cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
+
+ // Build directory
+ this->Dir.Build = this->Target->GetSafeProperty("AUTOGEN_BUILD_DIR");
+ if (this->Dir.Build.empty()) {
+ this->Dir.Build = cbd;
+ this->Dir.Build += '/';
+ this->Dir.Build += this->Target->GetName();
+ this->Dir.Build += "_autogen";
+ }
+ cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
+ // Cleanup build directory
+ this->AddCleanFile(this->Dir.Build);
+
+ // Working directory
+ this->Dir.Work = cbd;
+ cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
+
+ // Include directory
+ this->Dir.Include = this->Dir.Build;
+ this->Dir.Include += "/include";
+ if (this->MultiConfig) {
+ this->Dir.Include += "_$<CONFIG>";
+ }
+ // Per config include directories
+ if (this->MultiConfig) {
+ for (std::string const& cfg : this->ConfigsList) {
+ std::string& dir = this->Dir.ConfigInclude[cfg];
+ dir = this->Dir.Build;
+ dir += "/include_";
+ dir += cfg;
+ }
+ }
+ }
+
+ // Moc, Uic and _autogen target settings
+ if (this->MocOrUicEnabled()) {
+ // Init moc specific settings
+ if (this->Moc.Enabled && !InitMoc()) {
+ return false;
+ }
+
+ // Init uic specific settings
+ if (this->Uic.Enabled && !InitUic()) {
+ return false;
+ }
+
+ // Autogen target name
+ this->AutogenTarget.Name = this->Target->GetName();
+ this->AutogenTarget.Name += "_autogen";
+
+ // Autogen target parallel processing
+ this->AutogenTarget.Parallel =
+ this->Target->GetSafeProperty("AUTOGEN_PARALLEL");
+ if (this->AutogenTarget.Parallel.empty() ||
+ (this->AutogenTarget.Parallel == "AUTO")) {
+ // Autodetect number of CPUs
+ this->AutogenTarget.Parallel = std::to_string(GetParallelCPUCount());
+ }
+
+ // Autogen target info and settings files
+ {
+ this->AutogenTarget.InfoFile = this->Dir.Info;
+ this->AutogenTarget.InfoFile += "/AutogenInfo.cmake";
+
+ this->AutogenTarget.SettingsFile = this->Dir.Info;
+ this->AutogenTarget.SettingsFile += "/AutogenOldSettings.txt";
+
+ if (this->MultiConfig) {
+ for (std::string const& cfg : this->ConfigsList) {
+ std::string& filename = this->AutogenTarget.ConfigSettingsFile[cfg];
+ filename =
+ AppendFilenameSuffix(this->AutogenTarget.SettingsFile, "_" + cfg);
+ this->AddCleanFile(filename);
+ }
+ } else {
+ this->AddCleanFile(this->AutogenTarget.SettingsFile);
+ }
+
+ this->AutogenTarget.ParseCacheFile = this->Dir.Info;
+ this->AutogenTarget.ParseCacheFile += "/ParseCache.txt";
+ this->AddCleanFile(this->AutogenTarget.ParseCacheFile);
+ }
+
+ // Autogen target: Compute user defined dependencies
+ {
+ this->AutogenTarget.DependOrigin =
+ this->Target->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
+
+ std::string const deps =
+ this->Target->GetSafeProperty("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) {
+ this->AutogenTarget.DependTargets.insert(depTarget);
+ } else {
+ this->AutogenTarget.DependFiles.insert(depName);
+ }
+ }
+ }
+ }
+
+ // CMAKE_AUTOMOC_RELAXED_MODE deprecation warning
+ if (this->Moc.Enabled) {
+ if (cmSystemTools::IsOn(
+ makefile->GetDefinition("CMAKE_AUTOMOC_RELAXED_MODE"))) {
+ std::string msg = "AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
+ "deprecated an will be removed in the future. ";
+ msg += "Consider disabling it and converting the target ";
+ msg += this->Target->GetName();
+ msg += " to regular mode.";
+ makefile->IssueMessage(MessageType::AUTHOR_WARNING, msg);
+ }
+ }
+ }
+
+ // Init rcc specific settings
+ if (this->Rcc.Enabled && !InitRcc()) {
+ return false;
+ }
+
+ // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
+ if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
+ this->Target->AddIncludeDirectory(this->Dir.Include, true);
+ }
+
+ // Scan files
+ if (!this->InitScanFiles()) {
+ return false;
+ }
+
+ // Create autogen target
+ if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
+ return false;
+ }
+
+ // Create rcc targets
+ if (this->Rcc.Enabled && !this->InitRccTargets()) {
+ return false;
+ }
+
+ return true;
+}
+
+bool cmQtAutoGenInitializer::InitMoc()
+{
+ cmMakefile* makefile = this->Target->Target->GetMakefile();
+ cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
+
+ // Mocs compilation file
+ this->Moc.MocsCompilation = this->Dir.Build;
+ this->Moc.MocsCompilation += "/mocs_compilation.cpp";
+
+ // Moc predefs command
+ if (this->Target->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
+ (this->QtVersion >= IntegerVersion(5, 8))) {
+ this->Moc.PredefsCmd =
+ makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND");
+ }
+
+ // Moc includes
+ {
+ bool const appendImplicit = (this->QtVersion.Major >= 5);
+ auto GetIncludeDirs =
+ [this, localGen,
+ appendImplicit](std::string const& cfg) -> std::vector<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> dirs;
+ localGen->GetIncludeDirectoriesImplicit(dirs, this->Target, "CXX", cfg,
+ false, appendImplicit);
+ return dirs;
+ };
+
+ // Default configuration include directories
+ this->Moc.Includes = GetIncludeDirs(this->ConfigDefault);
+ // Other configuration settings
+ if (this->MultiConfig) {
+ for (std::string const& cfg : this->ConfigsList) {
+ std::vector<std::string> dirs = GetIncludeDirs(cfg);
+ if (dirs != this->Moc.Includes) {
+ this->Moc.ConfigIncludes[cfg] = std::move(dirs);
+ }
+ }
+ }
+ }
+
+ // Moc compile definitions
+ {
+ auto GetCompileDefinitions =
+ [this, localGen](std::string const& cfg) -> std::set<std::string> {
+ std::set<std::string> defines;
+ localGen->GetTargetDefines(this->Target, cfg, "CXX", defines);
+#ifdef _WIN32
+ if (this->Moc.PredefsCmd.empty()) {
+ // Add WIN32 definition if we don't have a moc_predefs.h
+ defines.insert("WIN32");
+ }
+#endif
+ return defines;
+ };
+
+ // Default configuration defines
+ this->Moc.Defines = GetCompileDefinitions(this->ConfigDefault);
+ // Other configuration defines
+ if (this->MultiConfig) {
+ for (std::string const& cfg : this->ConfigsList) {
+ std::set<std::string> defines = GetCompileDefinitions(cfg);
+ if (defines != this->Moc.Defines) {
+ this->Moc.ConfigDefines[cfg] = std::move(defines);
+ }
+ }
+ }
+ }
+
+ // Moc executable
+ {
+ if (!this->GetQtExecutable(this->Moc, "moc", false)) {
+ return false;
+ }
+ // Let the _autogen target depend on the moc executable
+ if (this->Moc.ExecutableTarget != nullptr) {
+ this->AutogenTarget.DependTargets.insert(
+ this->Moc.ExecutableTarget->Target);
+ }
+ }
+
+ return true;
+}
+
+bool cmQtAutoGenInitializer::InitUic()
+{
+ cmMakefile* makefile = this->Target->Target->GetMakefile();
+
+ // Uic search paths
+ {
+ std::string const usp =
+ this->Target->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
+ if (!usp.empty()) {
+ cmSystemTools::ExpandListArgument(usp, this->Uic.SearchPaths);
+ std::string const& srcDir = makefile->GetCurrentSourceDirectory();
+ for (std::string& path : this->Uic.SearchPaths) {
+ path = cmSystemTools::CollapseFullPath(path, srcDir);
+ }
+ }
+ }
+ // Uic target options
+ {
+ auto UicGetOpts =
+ [this](std::string const& cfg) -> std::vector<std::string> {
+ std::vector<std::string> opts;
+ this->Target->GetAutoUicOptions(opts, cfg);
+ return opts;
+ };
+
+ // Default settings
+ this->Uic.Options = UicGetOpts(this->ConfigDefault);
+
+ // Configuration specific settings
+ if (this->MultiConfig) {
+ for (std::string const& cfg : this->ConfigsList) {
+ std::vector<std::string> options = UicGetOpts(cfg);
+ if (options != this->Uic.Options) {
+ this->Uic.ConfigOptions[cfg] = std::move(options);
+ }
+ }
+ }
+ }
+
+ // Uic executable
+ {
+ if (!this->GetQtExecutable(this->Uic, "uic", true)) {
+ return false;
+ }
+ // Let the _autogen target depend on the uic executable
+ if (this->Uic.ExecutableTarget != nullptr) {
+ this->AutogenTarget.DependTargets.insert(
+ this->Uic.ExecutableTarget->Target);
+ }
+ }
+
+ return true;
+}
+
+bool cmQtAutoGenInitializer::InitRcc()
+{
+ // Rcc executable
+ {
+ if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
+ return false;
+ }
+ // Evaluate test output on demand
+ CompilerFeatures& features = *this->Rcc.ExecutableFeatures;
+ if (!features.Evaluated) {
+ // Look for list options
+ if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
+ if (features.HelpOutput.find("--list") != std::string::npos) {
+ features.ListOptions.emplace_back("--list");
+ } else if (features.HelpOutput.find("-list") != std::string::npos) {
+ features.ListOptions.emplace_back("-list");
+ }
+ }
+ // Evaluation finished
+ features.Evaluated = true;
+ }
+ }
+
+ return true;
+}
+
+bool cmQtAutoGenInitializer::InitScanFiles()
+{
+ cmMakefile* makefile = this->Target->Target->GetMakefile();
+ auto const& kw = this->GlobalInitializer->kw();
+
+ auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
+ bool muIt) -> MUFileHandle {
+ MUFileHandle muf = cm::make_unique<MUFile>();
+ muf->RealPath = cmSystemTools::GetRealPath(fullPath);
+ muf->SF = sf;
+ muf->Generated = sf->GetIsGenerated();
+ bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
+ muf->SkipMoc = this->Moc.Enabled &&
+ (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
+ muf->SkipUic = this->Uic.Enabled &&
+ (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
+ if (muIt) {
+ muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
+ muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
+ }
+ return muf;
+ };
+
+ auto addMUFile = [&](MUFileHandle&& muf, bool isHeader) {
+ if ((muf->MocIt || muf->UicIt) && muf->Generated) {
+ this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
+ }
+ if (isHeader) {
+ this->AutogenTarget.Headers.emplace(muf->SF, std::move(muf));
+ } else {
+ this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
+ }
+ };
+
+ // Scan through target files
+ {
+ // Scan through target files
+ std::vector<cmSourceFile*> srcFiles;
+ this->Target->GetConfigCommonSourceFiles(srcFiles);
+ for (cmSourceFile* sf : srcFiles) {
+ // sf->GetExtension() is only valid after sf->GetFullPath() ...
+ // Since we're iterating over source files that might be not in the
+ // target we need to check for path errors (not existing files).
+ std::string pathError;
+ std::string const& fullPath = sf->GetFullPath(&pathError);
+ if (!pathError.empty() || fullPath.empty()) {
+ continue;
+ }
+ std::string const& ext = sf->GetExtension();
+
+ // Register files that will be scanned by moc or uic
+ if (this->MocOrUicEnabled()) {
+ switch (cmSystemTools::GetFileFormat(ext)) {
+ case cmSystemTools::HEADER_FILE_FORMAT:
+ addMUFile(makeMUFile(sf, fullPath, true), true);
+ break;
+ case cmSystemTools::CXX_FILE_FORMAT:
+ addMUFile(makeMUFile(sf, fullPath, true), false);
+ break;
+ default:
+ break;
+ }
+ }
+
+ // Register rcc enabled files
+ if (this->Rcc.Enabled) {
+ if ((ext == kw.qrc) && !sf->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
+ !sf->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
+ // Register qrc file
+ Qrc qrc;
+ qrc.QrcFile = cmSystemTools::GetRealPath(fullPath);
+ qrc.QrcName =
+ cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
+ qrc.Generated = sf->GetIsGenerated();
+ // RCC options
+ {
+ std::string const opts = sf->GetSafeProperty(kw.AUTORCC_OPTIONS);
+ if (!opts.empty()) {
+ cmSystemTools::ExpandListArgument(opts, qrc.Options);
+ }
+ }
+ this->Rcc.Qrcs.push_back(std::move(qrc));
+ }
+ }
+ }
+ }
+ // 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.
+ this->Target->ClearSourcesCache();
+
+ // For source files find additional headers and private headers
+ if (this->MocOrUicEnabled()) {
+ std::vector<MUFileHandle> extraHeaders;
+ extraHeaders.reserve(this->AutogenTarget.Sources.size() * 2);
+ // Header search suffixes and extensions
+ std::array<std::string, 2> const suffixes{ { "", "_p" } };
+ auto const& exts = makefile->GetCMakeInstance()->GetHeaderExtensions();
+ // Scan through sources
+ for (auto const& pair : this->AutogenTarget.Sources) {
+ MUFile const& muf = *pair.second;
+ if (muf.MocIt || muf.UicIt) {
+ // Search for the default header file and a private header
+ std::string const& srcPath = muf.SF->GetFullPath();
+ std::string basePath = cmQtAutoGen::SubDirPrefix(srcPath);
+ basePath += cmSystemTools::GetFilenameWithoutLastExtension(srcPath);
+ for (auto const& suffix : suffixes) {
+ std::string const suffixedPath = basePath + suffix;
+ for (auto const& ext : exts) {
+ std::string fullPath = suffixedPath;
+ fullPath += '.';
+ fullPath += ext;
+
+ auto constexpr locationKind = cmSourceFileLocationKind::Known;
+ cmSourceFile* sf = makefile->GetSource(fullPath, locationKind);
+ if (sf != nullptr) {
+ // Check if we know about this header already
+ if (this->AutogenTarget.Headers.find(sf) !=
+ this->AutogenTarget.Headers.end()) {
+ continue;
+ }
+ // We only accept not-GENERATED files that do exist.
+ if (!sf->GetIsGenerated() &&
+ !cmSystemTools::FileExists(fullPath)) {
+ continue;
+ }
+ } else if (cmSystemTools::FileExists(fullPath)) {
+ // Create a new source file for the existing file
+ sf = makefile->CreateSource(fullPath, false, locationKind);
+ }
+
+ if (sf != nullptr) {
+ auto eMuf = makeMUFile(sf, fullPath, true);
+ // Ony process moc/uic when the parent is processed as well
+ if (!muf.MocIt) {
+ eMuf->MocIt = false;
+ }
+ if (!muf.UicIt) {
+ eMuf->UicIt = false;
+ }
+ extraHeaders.emplace_back(std::move(eMuf));
+ }
+ }
+ }
+ }
+ }
+ // Move generated files to main headers list
+ for (auto& eMuf : extraHeaders) {
+ addMUFile(std::move(eMuf), true);
+ }
+ }
+
+ // Scan through all source files in the makefile to extract moc and uic
+ // parameters. Historically we support non target source file parameters.
+ // The reason is that their file names might be discovered from source files
+ // at generation time.
+ if (this->MocOrUicEnabled()) {
+ for (cmSourceFile* sf : makefile->GetSourceFiles()) {
+ // sf->GetExtension() is only valid after sf->GetFullPath() ...
+ // Since we're iterating over source files that might be not in the
+ // target we need to check for path errors (not existing files).
+ std::string pathError;
+ std::string const& fullPath = sf->GetFullPath(&pathError);
+ if (!pathError.empty() || fullPath.empty()) {
+ continue;
+ }
+ std::string const& ext = sf->GetExtension();
+
+ auto const fileFormat = cmSystemTools::GetFileFormat(ext);
+ if (fileFormat == cmSystemTools::HEADER_FILE_FORMAT) {
+ if (this->AutogenTarget.Headers.find(sf) ==
+ this->AutogenTarget.Headers.end()) {
+ auto muf = makeMUFile(sf, fullPath, false);
+ if (muf->SkipMoc || muf->SkipUic) {
+ this->AutogenTarget.Headers.emplace(sf, std::move(muf));
+ }
+ }
+ } else if (fileFormat == cmSystemTools::CXX_FILE_FORMAT) {
+ if (this->AutogenTarget.Sources.find(sf) ==
+ this->AutogenTarget.Sources.end()) {
+ auto muf = makeMUFile(sf, fullPath, false);
+ if (muf->SkipMoc || muf->SkipUic) {
+ this->AutogenTarget.Sources.emplace(sf, std::move(muf));
+ }
+ }
+ } else if (this->Uic.Enabled && (ext == kw.ui)) {
+ // .ui file
+ std::string realPath = cmSystemTools::GetRealPath(fullPath);
+ bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
+ bool const skipUic =
+ (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
+ if (!skipUic) {
+ // Check if the .ui file has uic options
+ std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
+ if (!uicOpts.empty()) {
+ this->Uic.FileFiles.push_back(std::move(realPath));
+ std::vector<std::string> optsVec;
+ cmSystemTools::ExpandListArgument(uicOpts, optsVec);
+ this->Uic.FileOptions.push_back(std::move(optsVec));
+ }
+ } else {
+ // Register skipped .ui file
+ this->Uic.SkipUi.insert(std::move(realPath));
+ }
+ }
+ }
+ }
+
+ // Process GENERATED sources and headers
+ if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
+ if (this->CMP0071Accept) {
+ // Let the autogen target depend on the GENERATED files
+ for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
+ this->AutogenTarget.DependFiles.insert(muf->RealPath);
+ }
+ } else if (this->CMP0071Warn) {
+ std::string msg;
+ msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071);
+ msg += '\n';
+ std::string property;
+ if (this->Moc.Enabled && this->Uic.Enabled) {
+ property = kw.SKIP_AUTOGEN;
+ } else if (this->Moc.Enabled) {
+ property = kw.SKIP_AUTOMOC;
+ } else if (this->Uic.Enabled) {
+ property = kw.SKIP_AUTOUIC;
+ }
+ msg += "For compatibility, CMake is excluding the GENERATED source "
+ "file(s):\n";
+ for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
+ msg += " ";
+ msg += Quoted(muf->RealPath);
+ msg += '\n';
+ }
+ msg += "from processing by ";
+ msg += cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false);
+ 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(MessageType::AUTHOR_WARNING, msg);
+ }
+ }
+
+ // Process qrc files
+ if (!this->Rcc.Qrcs.empty()) {
+ const bool modernQt = (this->QtVersion.Major >= 5);
+ // Target rcc options
+ std::vector<std::string> optionsTarget;
+ cmSystemTools::ExpandListArgument(
+ this->Target->GetSafeProperty(kw.AUTORCC_OPTIONS), optionsTarget);
+
+ // Check if file name is unique
+ for (Qrc& qrc : this->Rcc.Qrcs) {
+ qrc.Unique = true;
+ for (Qrc const& qrc2 : this->Rcc.Qrcs) {
+ if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
+ qrc.Unique = false;
+ break;
+ }
+ }
+ }
+ // Path checksum and file names
+ {
+ cmFilePathChecksum const fpathCheckSum(makefile);
+ for (Qrc& qrc : this->Rcc.Qrcs) {
+ qrc.PathChecksum = fpathCheckSum.getPart(qrc.QrcFile);
+ // RCC output file name
+ {
+ std::string rccFile = this->Dir.Build + "/";
+ rccFile += qrc.PathChecksum;
+ rccFile += "/qrc_";
+ rccFile += qrc.QrcName;
+ rccFile += ".cpp";
+ qrc.RccFile = std::move(rccFile);
+ }
+ {
+ std::string base = this->Dir.Info;
+ base += "/RCC";
+ base += qrc.QrcName;
+ if (!qrc.Unique) {
+ base += qrc.PathChecksum;
+ }
+
+ qrc.LockFile = base;
+ qrc.LockFile += ".lock";
+
+ qrc.InfoFile = base;
+ qrc.InfoFile += "Info.cmake";
+
+ qrc.SettingsFile = base;
+ qrc.SettingsFile += "Settings.txt";
+
+ if (this->MultiConfig) {
+ for (std::string const& cfg : this->ConfigsList) {
+ qrc.ConfigSettingsFile[cfg] =
+ AppendFilenameSuffix(qrc.SettingsFile, "_" + cfg);
+ }
+ }
+ }
+ }
+ }
+ // RCC options
+ for (Qrc& qrc : this->Rcc.Qrcs) {
+ // Target options
+ std::vector<std::string> opts = optionsTarget;
+ // Merge computed "-name XYZ" option
+ {
+ std::string name = qrc.QrcName;
+ // Replace '-' with '_'. The former is not valid for symbol names.
+ std::replace(name.begin(), name.end(), '-', '_');
+ if (!qrc.Unique) {
+ name += "_";
+ name += qrc.PathChecksum;
+ }
+ std::vector<std::string> nameOpts;
+ nameOpts.emplace_back("-name");
+ nameOpts.emplace_back(std::move(name));
+ RccMergeOptions(opts, nameOpts, modernQt);
+ }
+ // Merge file option
+ RccMergeOptions(opts, qrc.Options, modernQt);
+ qrc.Options = std::move(opts);
+ }
+ // RCC resources
+ for (Qrc& qrc : this->Rcc.Qrcs) {
+ if (!qrc.Generated) {
+ std::string error;
+ RccLister const lister(this->Rcc.Executable,
+ this->Rcc.ExecutableFeatures->ListOptions);
+ if (!lister.list(qrc.QrcFile, qrc.Resources, error)) {
+ cmSystemTools::Error(error);
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+bool cmQtAutoGenInitializer::InitAutogenTarget()
+{
+ cmMakefile* makefile = this->Target->Target->GetMakefile();
+ cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
+ cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();
+
+ // Register info file as generated by CMake
+ makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
+
+ // Files provided by the autogen target
+ std::vector<std::string> autogenProvides;
+ if (this->Moc.Enabled) {
+ this->AddGeneratedSource(this->Moc.MocsCompilation, this->Moc, true);
+ autogenProvides.push_back(this->Moc.MocsCompilation);
+ }
+
+ // Compose target comment
+ std::string autogenComment;
+ {
+ std::string tools;
+ if (this->Moc.Enabled) {
+ tools += "MOC";
+ }
+ if (this->Uic.Enabled) {
+ if (!tools.empty()) {
+ tools += " and ";
+ }
+ tools += "UIC";
+ }
+ autogenComment = "Automatic ";
+ autogenComment += tools;
+ autogenComment += " for target ";
+ autogenComment += this->Target->GetName();
+ }
+
+ // Compose command lines
+ cmCustomCommandLines commandLines;
+ {
+ cmCustomCommandLine currentLine;
+ currentLine.push_back(cmSystemTools::GetCMakeCommand());
+ currentLine.push_back("-E");
+ currentLine.push_back("cmake_autogen");
+ currentLine.push_back(this->AutogenTarget.InfoFile);
+ currentLine.push_back("$<CONFIGURATION>");
+ commandLines.push_back(std::move(currentLine));
+ }
+
+ // 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) {
+ // Cannot use PRE_BUILD with file depends
+ if (!this->AutogenTarget.DependFiles.empty()) {
+ usePRE_BUILD = false;
+ }
+ // Cannot use PRE_BUILD when a global autogen target is in place
+ if (AutogenTarget.GlobalTarget) {
+ usePRE_BUILD = false;
+ }
+ }
+ // Create the autogen target/command
+ if (usePRE_BUILD) {
+ // Add additional autogen target dependencies to origin target
+ for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
+ this->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.
+ //
+ // 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(),
+ this->Dir.Work.c_str());
+ cc.SetEscapeOldStyle(false);
+ cc.SetEscapeAllowMakeVars(true);
+ this->Target->Target->AddPreBuildCommand(cc);
+ } else {
+
+ // Add link library target dependencies to the autogen target
+ // dependencies
+ if (this->AutogenTarget.DependOrigin) {
+ // add_dependencies/addUtility do not support generator expressions.
+ // We depend only on the libraries found in all configs therefore.
+ std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
+ for (std::string const& config : this->ConfigsList) {
+ cmLinkImplementationLibraries const* libs =
+ this->Target->GetLinkImplementationLibraries(config);
+ if (libs != nullptr) {
+ for (cmLinkItem const& item : libs->Libraries) {
+ cmGeneratorTarget const* libTarget = item.Target;
+ if ((libTarget != nullptr) &&
+ !StaticLibraryCycle(this->Target, libTarget, config)) {
+ // Increment target config count
+ commonTargets[libTarget]++;
+ }
+ }
+ }
+ }
+ for (auto const& item : commonTargets) {
+ if (item.second == this->ConfigsList.size()) {
+ this->AutogenTarget.DependTargets.insert(item.first->Target);
+ }
+ }
+ }
+
+ // Create autogen target
+ cmTarget* autogenTarget = makefile->AddUtilityCommand(
+ this->AutogenTarget.Name, cmMakefile::TargetOrigin::Generator, true,
+ this->Dir.Work.c_str(), /*byproducts=*/autogenProvides,
+ std::vector<std::string>(this->AutogenTarget.DependFiles.begin(),
+ this->AutogenTarget.DependFiles.end()),
+ commandLines, false, autogenComment.c_str());
+ // Create autogen generator target
+ localGen->AddGeneratorTarget(
+ new cmGeneratorTarget(autogenTarget, localGen));
+
+ // Forward origin utilities to autogen target
+ if (this->AutogenTarget.DependOrigin) {
+ for (BT<std::string> const& depName : this->Target->GetUtilities()) {
+ autogenTarget->AddUtility(depName.Value, makefile);
+ }
+ }
+ // Add additional autogen target dependencies to autogen target
+ for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
+ autogenTarget->AddUtility(depTarget->GetName(), makefile);
+ }
+
+ // Set FOLDER property in autogen target
+ if (!this->TargetsFolder.empty()) {
+ autogenTarget->SetProperty("FOLDER", this->TargetsFolder.c_str());
+ }
+
+ // Add autogen target to the origin target dependencies
+ this->Target->Target->AddUtility(this->AutogenTarget.Name, makefile);
+
+ // Add autogen target to the global autogen target dependencies
+ if (this->AutogenTarget.GlobalTarget) {
+ this->GlobalInitializer->AddToGlobalAutoGen(localGen,
+ this->AutogenTarget.Name);
+ }
+ }
+
+ return true;
+}
+
+bool cmQtAutoGenInitializer::InitRccTargets()
+{
+ cmMakefile* makefile = this->Target->Target->GetMakefile();
+ cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
+
+ for (Qrc const& qrc : this->Rcc.Qrcs) {
+ // Register info file as generated by CMake
+ makefile->AddCMakeOutputFile(qrc.InfoFile);
+ // Register file at target
+ this->AddGeneratedSource(qrc.RccFile, this->Rcc);
+
+ std::vector<std::string> ccOutput;
+ ccOutput.push_back(qrc.RccFile);
+
+ std::vector<std::string> ccDepends;
+ // Add the .qrc and info file to the custom command dependencies
+ ccDepends.push_back(qrc.QrcFile);
+ ccDepends.push_back(qrc.InfoFile);
+
+ cmCustomCommandLines commandLines;
+ if (this->MultiConfig) {
+ // Build for all configurations
+ for (std::string const& config : this->ConfigsList) {
+ cmCustomCommandLine currentLine;
+ currentLine.push_back(cmSystemTools::GetCMakeCommand());
+ currentLine.push_back("-E");
+ currentLine.push_back("cmake_autorcc");
+ currentLine.push_back(qrc.InfoFile);
+ currentLine.push_back(config);
+ commandLines.push_back(std::move(currentLine));
+ }
+ } else {
+ cmCustomCommandLine currentLine;
+ currentLine.push_back(cmSystemTools::GetCMakeCommand());
+ currentLine.push_back("-E");
+ currentLine.push_back("cmake_autorcc");
+ currentLine.push_back(qrc.InfoFile);
+ currentLine.push_back("$<CONFIG>");
+ commandLines.push_back(std::move(currentLine));
+ }
+ std::string ccComment = "Automatic RCC for ";
+ ccComment += FileProjectRelativePath(makefile, qrc.QrcFile);
+
+ if (qrc.Generated || this->Rcc.GlobalTarget) {
+ // Create custom rcc target
+ std::string ccName;
+ {
+ ccName = this->Target->GetName();
+ ccName += "_arcc_";
+ ccName += qrc.QrcName;
+ if (!qrc.Unique) {
+ ccName += "_";
+ ccName += qrc.PathChecksum;
+ }
+
+ cmTarget* autoRccTarget = makefile->AddUtilityCommand(
+ ccName, cmMakefile::TargetOrigin::Generator, true,
+ this->Dir.Work.c_str(), ccOutput, ccDepends, commandLines, false,
+ ccComment.c_str());
+
+ // Create autogen generator target
+ localGen->AddGeneratorTarget(
+ new cmGeneratorTarget(autoRccTarget, localGen));
+
+ // Set FOLDER property in autogen target
+ if (!this->TargetsFolder.empty()) {
+ autoRccTarget->SetProperty("FOLDER", this->TargetsFolder.c_str());
+ }
+ if (!this->Rcc.ExecutableTargetName.empty()) {
+ autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, makefile);
+ }
+ }
+ // Add autogen target to the origin target dependencies
+ this->Target->Target->AddUtility(ccName, makefile);
+
+ // Add autogen target to the global autogen target dependencies
+ if (this->Rcc.GlobalTarget) {
+ this->GlobalInitializer->AddToGlobalAutoRcc(localGen, ccName);
+ }
+ } else {
+ // Create custom rcc command
+ {
+ std::vector<std::string> ccByproducts;
+
+ // Add the resource files to the dependencies
+ for (std::string const& fileName : qrc.Resources) {
+ // Add resource file to the custom command dependencies
+ ccDepends.push_back(fileName);
+ }
+ if (!this->Rcc.ExecutableTargetName.empty()) {
+ ccDepends.push_back(this->Rcc.ExecutableTargetName);
+ }
+ makefile->AddCustomCommandToOutput(ccOutput, ccByproducts, ccDepends,
+ /*main_dependency*/ std::string(),
+ commandLines, ccComment.c_str(),
+ this->Dir.Work.c_str());
+ }
+ // Reconfigure when .qrc file changes
+ makefile->AddCMakeDependFile(qrc.QrcFile);
+ }
+ }
+
+ return true;
+}
+
+bool cmQtAutoGenInitializer::SetupCustomTargets()
+{
+ // Create info directory on demand
+ if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
+ std::string emsg = ("AutoGen: Could not create directory: ");
+ emsg += Quoted(this->Dir.Info);
+ cmSystemTools::Error(emsg);
+ return false;
+ }
+
+ // Generate autogen target info file
+ if (this->MocOrUicEnabled()) {
+ // Write autogen target info files
+ if (!this->SetupWriteAutogenInfo()) {
+ return false;
+ }
+ }
+
+ // Write AUTORCC info files
+ return !this->Rcc.Enabled || this->SetupWriteRccInfo();
+}
+
+bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
+{
+ InfoWriter ofs(this->AutogenTarget.InfoFile);
+ if (ofs) {
+ // Utility lambdas
+ cmMakefile* makefile = this->Target->Target->GetMakefile();
+ auto MfDef = [makefile](const char* key) {
+ return makefile->GetSafeDefinition(key);
+ };
+
+ // Write common settings
+ ofs.Write("# Meta\n");
+ ofs.Write("AM_MULTI_CONFIG", this->MultiConfig ? "TRUE" : "FALSE");
+ ofs.Write("AM_PARALLEL", this->AutogenTarget.Parallel);
+ ofs.Write("AM_VERBOSITY", this->Verbosity);
+
+ ofs.Write("# Directories\n");
+ ofs.Write("AM_CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
+ ofs.Write("AM_CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
+ ofs.Write("AM_CMAKE_CURRENT_SOURCE_DIR",
+ MfDef("CMAKE_CURRENT_SOURCE_DIR"));
+ ofs.Write("AM_CMAKE_CURRENT_BINARY_DIR",
+ MfDef("CMAKE_CURRENT_BINARY_DIR"));
+ ofs.Write("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE",
+ MfDef("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE"));
+ ofs.Write("AM_BUILD_DIR", this->Dir.Build);
+ ofs.Write("AM_INCLUDE_DIR", this->Dir.Include);
+ ofs.WriteConfig("AM_INCLUDE_DIR", this->Dir.ConfigInclude);
+
+ std::vector<std::string> headers;
+ std::vector<std::string> headersFlags;
+ std::vector<std::string> headersBuildPaths;
+ std::vector<std::string> sources;
+ std::vector<std::string> sourcesFlags;
+ std::set<std::string> moc_skip;
+ std::set<std::string> uic_skip;
+
+ // Filter headers
+ {
+ auto headerCount = this->AutogenTarget.Headers.size();
+ headers.reserve(headerCount);
+ headersFlags.reserve(headerCount);
+
+ std::vector<MUFile const*> sortedHeaders;
+ {
+ sortedHeaders.reserve(headerCount);
+ for (auto const& pair : this->AutogenTarget.Headers) {
+ sortedHeaders.emplace_back(pair.second.get());
+ }
+ std::sort(sortedHeaders.begin(), sortedHeaders.end(),
+ [](MUFile const* a, MUFile const* b) {
+ return (a->RealPath < b->RealPath);
+ });
+ }
+
+ for (MUFile const* const muf : sortedHeaders) {
+ if (muf->Generated && !this->CMP0071Accept) {
+ continue;
+ }
+ if (muf->SkipMoc) {
+ moc_skip.insert(muf->RealPath);
+ }
+ if (muf->SkipUic) {
+ uic_skip.insert(muf->RealPath);
+ }
+ if (muf->MocIt || muf->UicIt) {
+ headers.emplace_back(muf->RealPath);
+ std::string flags;
+ flags += muf->MocIt ? 'M' : 'm';
+ flags += muf->UicIt ? 'U' : 'u';
+ headersFlags.emplace_back(std::move(flags));
+ }
+ }
+ }
+ // Header build paths
+ {
+ cmFilePathChecksum const fpathCheckSum(makefile);
+ std::unordered_set<std::string> emitted;
+ for (std::string const& hdr : headers) {
+ std::string basePath = fpathCheckSum.getPart(hdr);
+ basePath += "/moc_";
+ basePath += cmSystemTools::GetFilenameWithoutLastExtension(hdr);
+ for (unsigned int ii = 1; ii != 1024; ++ii) {
+ std::string path = basePath;
+ if (ii > 1) {
+ path += '_';
+ path += std::to_string(ii);
+ }
+ path += ".cpp";
+ if (emitted.emplace(path).second) {
+ headersBuildPaths.emplace_back(std::move(path));
+ break;
+ }
+ }
+ }
+ }
+
+ // Filter sources
+ {
+ auto sourcesCount = this->AutogenTarget.Sources.size();
+ sources.reserve(sourcesCount);
+ sourcesFlags.reserve(sourcesCount);
+
+ std::vector<MUFile const*> sorted;
+ sorted.reserve(sourcesCount);
+ for (auto const& pair : this->AutogenTarget.Sources) {
+ sorted.emplace_back(pair.second.get());
+ }
+ std::sort(sorted.begin(), sorted.end(),
+ [](MUFile const* a, MUFile const* b) {
+ return (a->RealPath < b->RealPath);
+ });
+
+ for (MUFile const* const muf : sorted) {
+ if (muf->Generated && !this->CMP0071Accept) {
+ continue;
+ }
+ if (muf->SkipMoc) {
+ moc_skip.insert(muf->RealPath);
+ }
+ if (muf->SkipUic) {
+ uic_skip.insert(muf->RealPath);
+ }
+ if (muf->MocIt || muf->UicIt) {
+ sources.emplace_back(muf->RealPath);
+ std::string flags;
+ flags += muf->MocIt ? 'M' : 'm';
+ flags += muf->UicIt ? 'U' : 'u';
+ sourcesFlags.emplace_back(std::move(flags));
+ }
+ }
+ }
+
+ ofs.Write("# Qt\n");
+ ofs.WriteUInt("AM_QT_VERSION_MAJOR", this->QtVersion.Major);
+ ofs.Write("AM_QT_MOC_EXECUTABLE", this->Moc.Executable);
+ ofs.Write("AM_QT_UIC_EXECUTABLE", this->Uic.Executable);
+
+ ofs.Write("# Files\n");
+ ofs.Write("AM_CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
+ ofs.Write("AM_SETTINGS_FILE", this->AutogenTarget.SettingsFile);
+ ofs.WriteConfig("AM_SETTINGS_FILE",
+ this->AutogenTarget.ConfigSettingsFile);
+ ofs.Write("AM_PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
+ ofs.WriteStrings("AM_HEADERS", headers);
+ ofs.WriteStrings("AM_HEADERS_FLAGS", headersFlags);
+ ofs.WriteStrings("AM_HEADERS_BUILD_PATHS", headersBuildPaths);
+ ofs.WriteStrings("AM_SOURCES", sources);
+ ofs.WriteStrings("AM_SOURCES_FLAGS", sourcesFlags);
+
+ // Write moc settings
+ if (this->Moc.Enabled) {
+ ofs.Write("# MOC settings\n");
+ ofs.WriteStrings("AM_MOC_SKIP", moc_skip);
+ ofs.WriteStrings("AM_MOC_DEFINITIONS", this->Moc.Defines);
+ ofs.WriteConfigStrings("AM_MOC_DEFINITIONS", this->Moc.ConfigDefines);
+ ofs.WriteStrings("AM_MOC_INCLUDES", this->Moc.Includes);
+ ofs.WriteConfigStrings("AM_MOC_INCLUDES", this->Moc.ConfigIncludes);
+ ofs.Write("AM_MOC_OPTIONS",
+ this->Target->GetSafeProperty("AUTOMOC_MOC_OPTIONS"));
+ ofs.Write("AM_MOC_RELAXED_MODE", MfDef("CMAKE_AUTOMOC_RELAXED_MODE"));
+ ofs.Write("AM_MOC_MACRO_NAMES",
+ this->Target->GetSafeProperty("AUTOMOC_MACRO_NAMES"));
+ ofs.Write("AM_MOC_DEPEND_FILTERS",
+ this->Target->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
+ ofs.Write("AM_MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
+ }
+
+ // Write uic settings
+ if (this->Uic.Enabled) {
+ // Add skipped .ui files
+ uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
+
+ ofs.Write("# UIC settings\n");
+ ofs.WriteStrings("AM_UIC_SKIP", uic_skip);
+ ofs.WriteStrings("AM_UIC_TARGET_OPTIONS", this->Uic.Options);
+ ofs.WriteConfigStrings("AM_UIC_TARGET_OPTIONS", this->Uic.ConfigOptions);
+ ofs.WriteStrings("AM_UIC_OPTIONS_FILES", this->Uic.FileFiles);
+ ofs.WriteNestedLists("AM_UIC_OPTIONS_OPTIONS", this->Uic.FileOptions);
+ ofs.WriteStrings("AM_UIC_SEARCH_PATHS", this->Uic.SearchPaths);
+ }
+ } else {
+ std::string err = "AutoGen: Could not write file ";
+ err += this->AutogenTarget.InfoFile;
+ cmSystemTools::Error(err);
+ return false;
+ }
+
+ return true;
+}
+
+bool cmQtAutoGenInitializer::SetupWriteRccInfo()
+{
+ for (Qrc const& qrc : this->Rcc.Qrcs) {
+ InfoWriter ofs(qrc.InfoFile);
+ if (ofs) {
+ // Write
+ ofs.Write("# Configurations\n");
+ ofs.Write("ARCC_MULTI_CONFIG", this->MultiConfig ? "TRUE" : "FALSE");
+ ofs.Write("ARCC_VERBOSITY", this->Verbosity);
+ ofs.Write("# Settings file\n");
+ ofs.Write("ARCC_SETTINGS_FILE", qrc.SettingsFile);
+ ofs.WriteConfig("ARCC_SETTINGS_FILE", qrc.ConfigSettingsFile);
+
+ ofs.Write("# Directories\n");
+ ofs.Write("ARCC_BUILD_DIR", this->Dir.Build);
+ ofs.Write("ARCC_INCLUDE_DIR", this->Dir.Include);
+ ofs.WriteConfig("ARCC_INCLUDE_DIR", this->Dir.ConfigInclude);
+
+ ofs.Write("# Rcc executable\n");
+ ofs.Write("ARCC_RCC_EXECUTABLE", this->Rcc.Executable);
+ ofs.WriteStrings("ARCC_RCC_LIST_OPTIONS",
+ this->Rcc.ExecutableFeatures->ListOptions);
+
+ ofs.Write("# Rcc job\n");
+ ofs.Write("ARCC_LOCK_FILE", qrc.LockFile);
+ ofs.Write("ARCC_SOURCE", qrc.QrcFile);
+ ofs.Write("ARCC_OUTPUT_CHECKSUM", qrc.PathChecksum);
+ ofs.Write("ARCC_OUTPUT_NAME",
+ cmSystemTools::GetFilenameName(qrc.RccFile));
+ ofs.WriteStrings("ARCC_OPTIONS", qrc.Options);
+ ofs.WriteStrings("ARCC_INPUTS", qrc.Resources);
+ } else {
+ std::string err = "AutoRcc: Could not write file ";
+ err += qrc.InfoFile;
+ cmSystemTools::Error(err);
+ return false;
+ }
+ }
+
+ return true;
+}
+
+void cmQtAutoGenInitializer::RegisterGeneratedSource(
+ std::string const& filename)
+{
+ cmMakefile* makefile = this->Target->Target->GetMakefile();
+ cmSourceFile* gFile = makefile->GetOrCreateSource(filename, true);
+ gFile->SetProperty("GENERATED", "1");
+ gFile->SetProperty("SKIP_AUTOGEN", "1");
+}
+
+bool cmQtAutoGenInitializer::AddGeneratedSource(std::string const& filename,
+ GenVarsT const& genVars,
+ bool prepend)
+{
+ // Register source at makefile
+ this->RegisterGeneratedSource(filename);
+ // Add source file to target
+ this->Target->AddSource(filename, prepend);
+ // Add source file to source group
+ return this->AddToSourceGroup(filename, genVars.GenNameUpper);
+}
+
+bool cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
+ std::string const& genNameUpper)
+{
+ cmMakefile* makefile = this->Target->Target->GetMakefile();
+ cmSourceGroup* sourceGroup = nullptr;
+ // Acquire source group
+ {
+ std::string property;
+ std::string groupName;
+ {
+ // Prefer generator specific source group name
+ std::array<std::string, 2> props{ { genNameUpper + "_SOURCE_GROUP",
+ "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;
+ }
+ }
+ }
+ // Generate a source group on demand
+ if (!groupName.empty()) {
+ sourceGroup = makefile->GetOrCreateSourceGroup(groupName);
+ if (sourceGroup == nullptr) {
+ std::string err;
+ err += genNameUpper;
+ err += " error in ";
+ err += property;
+ err += ": Could not find or create the source group ";
+ err += cmQtAutoGen::Quoted(groupName);
+ cmSystemTools::Error(err);
+ return false;
+ }
+ }
+ }
+ if (sourceGroup != nullptr) {
+ sourceGroup->AddGroupFile(fileName);
+ }
+ return true;
+}
+
+void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
+{
+ Target->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName.c_str(),
+ false);
+}
+
+static unsigned int CharPtrToUInt(const char* const input)
+{
+ unsigned long tmp = 0;
+ if (input != nullptr && cmSystemTools::StringToULong(input, &tmp)) {
+ return static_cast<unsigned int>(tmp);
+ }
+ return 0;
+}
+
+static std::vector<cmQtAutoGen::IntegerVersion> GetKnownQtVersions(
+ cmGeneratorTarget const* target)
+{
+ // Qt version variable prefixes
+ static std::array<std::string, 3> const prefixes{ { "Qt6Core", "Qt5Core",
+ "QT" } };
+
+ std::vector<cmQtAutoGen::IntegerVersion> result;
+ result.reserve(prefixes.size() * 2);
+ // Adds a version to the result (nullptr safe)
+ auto addVersion = [&result](const char* major, const char* minor) {
+ cmQtAutoGen::IntegerVersion ver(CharPtrToUInt(major),
+ CharPtrToUInt(minor));
+ if (ver.Major != 0) {
+ result.emplace_back(ver);
+ }
+ };
+ cmMakefile* makefile = target->Target->GetMakefile();
+
+ // Read versions from variables
+ for (const std::string& prefix : prefixes) {
+ addVersion(makefile->GetDefinition(prefix + "_VERSION_MAJOR"),
+ makefile->GetDefinition(prefix + "_VERSION_MINOR"));
+ }
+
+ // Read versions from directory properties
+ for (const std::string& prefix : prefixes) {
+ addVersion(makefile->GetProperty(prefix + "_VERSION_MAJOR"),
+ makefile->GetProperty(prefix + "_VERSION_MINOR"));
+ }
+
+ return result;
+}
+
+std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
+cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target)
+{
+ std::pair<IntegerVersion, unsigned int> res(
+ IntegerVersion(),
+ CharPtrToUInt(target->GetLinkInterfaceDependentStringProperty(
+ "QT_MAJOR_VERSION", "")));
+
+ auto knownQtVersions = GetKnownQtVersions(target);
+ if (!knownQtVersions.empty()) {
+ if (res.second == 0) {
+ // No specific version was requested by the target:
+ // Use highest known Qt version.
+ res.first = knownQtVersions.at(0);
+ } else {
+ // Pick a version from the known versions:
+ for (auto it : knownQtVersions) {
+ if (it.Major == res.second) {
+ res.first = it;
+ break;
+ }
+ }
+ }
+ }
+ return res;
+}
+
+bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
+ const std::string& executable,
+ bool ignoreMissingTarget) const
+{
+ auto print_err = [this, &genVars](std::string const& err) {
+ std::string msg = genVars.GenNameUpper;
+ msg += " for target ";
+ msg += this->Target->GetName();
+ msg += ": ";
+ msg += err;
+ cmSystemTools::Error(msg);
+ };
+
+ // Custom executable
+ {
+ std::string const prop = genVars.GenNameUpper + "_EXECUTABLE";
+ std::string const val = this->Target->Target->GetSafeProperty(prop);
+ if (!val.empty()) {
+ // Evaluate generator expression
+ {
+ cmListFileBacktrace lfbt =
+ this->Target->Target->GetMakefile()->GetBacktrace();
+ cmGeneratorExpression ge(lfbt);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
+ genVars.Executable =
+ cge->Evaluate(this->Target->GetLocalGenerator(), "");
+ }
+ if (genVars.Executable.empty() && !ignoreMissingTarget) {
+ print_err(prop + " evaluates to an empty value");
+ return false;
+ }
+
+ // Create empty compiler features.
+ genVars.ExecutableFeatures =
+ std::make_shared<cmQtAutoGen::CompilerFeatures>();
+ return true;
+ }
+ }
+
+ // Find executable target
+ {
+ // Find executable target name
+ std::string targetName;
+ if (this->QtVersion.Major == 4) {
+ targetName = "Qt4::";
+ } else if (this->QtVersion.Major == 5) {
+ targetName = "Qt5::";
+ } else if (this->QtVersion.Major == 6) {
+ targetName = "Qt6::";
+ }
+ targetName += executable;
+
+ // Find target
+ cmLocalGenerator* localGen = this->Target->GetLocalGenerator();
+ cmGeneratorTarget* target = localGen->FindGeneratorTargetToUse(targetName);
+ if (target != nullptr) {
+ genVars.ExecutableTargetName = targetName;
+ genVars.ExecutableTarget = target;
+ if (target->IsImported()) {
+ genVars.Executable = target->ImportedGetLocation("");
+ } else {
+ genVars.Executable = target->GetLocation("");
+ }
+ } else {
+ if (ignoreMissingTarget) {
+ // Create empty compiler features.
+ genVars.ExecutableFeatures =
+ std::make_shared<cmQtAutoGen::CompilerFeatures>();
+ return true;
+ }
+ std::string err = "Could not find ";
+ err += executable;
+ err += " executable target ";
+ err += targetName;
+ print_err(err);
+ return false;
+ }
+ }
+
+ // Get executable features
+ {
+ std::string err;
+ genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
+ executable, genVars.Executable, err);
+ if (!genVars.ExecutableFeatures) {
+ print_err(err);
+ return false;
+ }
+ }
+
+ return true;
+}
diff --git a/Source/cmQtAutoGenInitializer.h b/Source/cmQtAutoGenInitializer.h
new file mode 100644
index 000000000..aa073d1fd
--- /dev/null
+++ b/Source/cmQtAutoGenInitializer.h
@@ -0,0 +1,241 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmQtAutoGenInitializer_h
+#define cmQtAutoGenInitializer_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+#include "cmGeneratedFileStream.h"
+#include "cmQtAutoGen.h"
+
+#include <map>
+#include <memory> // IWYU pragma: keep
+#include <ostream>
+#include <set>
+#include <string>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+class cmGeneratorTarget;
+class cmTarget;
+class cmQtAutoGenGlobalInitializer;
+class cmSourceFile;
+
+/// @brief Initializes the QtAutoGen generators
+class cmQtAutoGenInitializer : public cmQtAutoGen
+{
+public:
+ /// @brief Rcc job information
+ class Qrc
+ {
+ public:
+ std::string LockFile;
+ std::string QrcFile;
+ std::string QrcName;
+ std::string PathChecksum;
+ std::string InfoFile;
+ std::string SettingsFile;
+ std::map<std::string, std::string> ConfigSettingsFile;
+ std::string RccFile;
+ bool Generated = false;
+ bool Unique = false;
+ std::vector<std::string> Options;
+ std::vector<std::string> Resources;
+ };
+
+ /// @brief Moc/Uic file
+ struct MUFile
+ {
+ std::string RealPath;
+ cmSourceFile* SF = nullptr;
+ bool Generated = false;
+ bool SkipMoc = false;
+ bool SkipUic = false;
+ bool MocIt = false;
+ bool UicIt = false;
+ };
+ typedef std::unique_ptr<MUFile> MUFileHandle;
+
+ /// @brief Abstract moc/uic/rcc generator variables base class
+ struct GenVarsT
+ {
+ bool Enabled = false;
+ // Generator type/name
+ GenT Gen;
+ std::string const& GenNameUpper;
+ // Executable
+ std::string ExecutableTargetName;
+ cmGeneratorTarget* ExecutableTarget = nullptr;
+ std::string Executable;
+ CompilerFeaturesHandle ExecutableFeatures;
+
+ /// @brief Constructor
+ GenVarsT(GenT gen)
+ : Gen(gen)
+ , GenNameUpper(cmQtAutoGen::GeneratorNameUpper(gen)){};
+ };
+
+ /// @brief Writes a CMake info file
+ class InfoWriter
+ {
+ public:
+ /// @brief Open the given file
+ InfoWriter(std::string const& filename);
+
+ /// @return True if the file is open
+ explicit operator bool() const { return static_cast<bool>(Ofs_); }
+
+ void Write(const char* text) { Ofs_ << text; }
+ void Write(const char* key, std::string const& value);
+ void WriteUInt(const char* key, unsigned int value);
+
+ template <class C>
+ void WriteStrings(const char* key, C const& container);
+ void WriteConfig(const char* key,
+ std::map<std::string, std::string> const& map);
+ template <class C>
+ void WriteConfigStrings(const char* key,
+ std::map<std::string, C> const& map);
+ void WriteNestedLists(const char* key,
+ std::vector<std::vector<std::string>> const& lists);
+
+ private:
+ template <class IT>
+ static std::string ListJoin(IT it_begin, IT it_end);
+ static std::string ConfigKey(const char* key, std::string const& config);
+
+ private:
+ cmGeneratedFileStream Ofs_;
+ };
+
+public:
+ /// @return The detected Qt version and the required Qt major version
+ static std::pair<IntegerVersion, unsigned int> GetQtVersion(
+ cmGeneratorTarget const* target);
+
+ cmQtAutoGenInitializer(cmQtAutoGenGlobalInitializer* globalInitializer,
+ cmGeneratorTarget* target,
+ IntegerVersion const& qtVersion, bool mocEnabled,
+ bool uicEnabled, bool rccEnabled,
+ bool globalAutogenTarget, bool globalAutoRccTarget);
+
+ bool InitCustomTargets();
+ bool SetupCustomTargets();
+
+private:
+ /// @brief If moc or uic is enabled, the autogen target will be generated
+ bool MocOrUicEnabled() const
+ {
+ return (this->Moc.Enabled || this->Uic.Enabled);
+ }
+
+ bool InitMoc();
+ bool InitUic();
+ bool InitRcc();
+
+ bool InitScanFiles();
+ bool InitAutogenTarget();
+ bool InitRccTargets();
+
+ bool SetupWriteAutogenInfo();
+ bool SetupWriteRccInfo();
+
+ void RegisterGeneratedSource(std::string const& filename);
+ bool AddGeneratedSource(std::string const& filename, GenVarsT const& genVars,
+ bool prepend = false);
+ bool AddToSourceGroup(std::string const& fileName,
+ std::string const& genNameUpper);
+ void AddCleanFile(std::string const& fileName);
+
+ bool GetQtExecutable(GenVarsT& genVars, const std::string& executable,
+ bool ignoreMissingTarget) const;
+
+private:
+ cmQtAutoGenGlobalInitializer* GlobalInitializer;
+ cmGeneratorTarget* Target;
+
+ // Configuration
+ IntegerVersion QtVersion;
+ bool MultiConfig = false;
+ std::string ConfigDefault;
+ std::vector<std::string> ConfigsList;
+ std::string Verbosity;
+ std::string TargetsFolder;
+ bool CMP0071Accept = false;
+ bool CMP0071Warn = false;
+
+ /// @brief Common directories
+ struct
+ {
+ std::string Info;
+ std::string Build;
+ std::string Work;
+ std::string Include;
+ std::map<std::string, std::string> ConfigInclude;
+ } Dir;
+
+ /// @brief Autogen target variables
+ struct
+ {
+ std::string Name;
+ bool GlobalTarget = false;
+ // Settings
+ std::string Parallel;
+ // Configuration files
+ std::string InfoFile;
+ std::string SettingsFile;
+ std::string ParseCacheFile;
+ std::map<std::string, std::string> ConfigSettingsFile;
+ // Dependencies
+ bool DependOrigin = false;
+ std::set<std::string> DependFiles;
+ std::set<cmTarget*> DependTargets;
+ // Sources to process
+ std::unordered_map<cmSourceFile*, MUFileHandle> Headers;
+ std::unordered_map<cmSourceFile*, MUFileHandle> Sources;
+ std::vector<MUFile*> FilesGenerated;
+ } AutogenTarget;
+
+ /// @brief Moc only variables
+ struct MocT : public GenVarsT
+ {
+ std::string PredefsCmd;
+ std::vector<std::string> Includes;
+ std::map<std::string, std::vector<std::string>> ConfigIncludes;
+ std::set<std::string> Defines;
+ std::map<std::string, std::set<std::string>> ConfigDefines;
+ std::string MocsCompilation;
+
+ /// @brief Constructor
+ MocT()
+ : GenVarsT(GenT::MOC){};
+ } Moc;
+
+ /// @brief Uic only variables
+ struct UicT : public GenVarsT
+ {
+ std::set<std::string> SkipUi;
+ std::vector<std::string> SearchPaths;
+ std::vector<std::string> Options;
+ std::map<std::string, std::vector<std::string>> ConfigOptions;
+ std::vector<std::string> FileFiles;
+ std::vector<std::vector<std::string>> FileOptions;
+
+ /// @brief Constructor
+ UicT()
+ : GenVarsT(GenT::UIC){};
+ } Uic;
+
+ /// @brief Rcc only variables
+ struct RccT : public GenVarsT
+ {
+ bool GlobalTarget = false;
+ std::vector<Qrc> Qrcs;
+
+ /// @brief Constructor
+ RccT()
+ : GenVarsT(GenT::RCC){};
+ } Rcc;
+};
+
+#endif
diff --git a/Source/cmQtAutoGenerator.cxx b/Source/cmQtAutoGenerator.cxx
new file mode 100644
index 000000000..e1c435be0
--- /dev/null
+++ b/Source/cmQtAutoGenerator.cxx
@@ -0,0 +1,332 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmQtAutoGenerator.h"
+#include "cmQtAutoGen.h"
+
+#include "cmsys/FStream.hxx"
+
+#include "cmAlgorithms.h"
+#include "cmGlobalGenerator.h"
+#include "cmMakefile.h"
+#include "cmState.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+cmQtAutoGenerator::Logger::Logger()
+{
+ // Initialize logger
+ {
+ std::string verbose;
+ if (cmSystemTools::GetEnv("VERBOSE", verbose) && !verbose.empty()) {
+ unsigned long iVerbose = 0;
+ if (cmSystemTools::StringToULong(verbose.c_str(), &iVerbose)) {
+ SetVerbosity(static_cast<unsigned int>(iVerbose));
+ } else {
+ // Non numeric verbosity
+ SetVerbose(cmSystemTools::IsOn(verbose));
+ }
+ }
+ }
+ {
+ std::string colorEnv;
+ cmSystemTools::GetEnv("COLOR", colorEnv);
+ if (!colorEnv.empty()) {
+ SetColorOutput(cmSystemTools::IsOn(colorEnv));
+ } else {
+ SetColorOutput(true);
+ }
+ }
+}
+
+cmQtAutoGenerator::Logger::~Logger() = default;
+
+void cmQtAutoGenerator::Logger::RaiseVerbosity(std::string const& value)
+{
+ unsigned long verbosity = 0;
+ if (cmSystemTools::StringToULong(value.c_str(), &verbosity)) {
+ if (this->Verbosity_ < verbosity) {
+ this->Verbosity_ = static_cast<unsigned int>(verbosity);
+ }
+ }
+}
+
+void cmQtAutoGenerator::Logger::SetColorOutput(bool value)
+{
+ ColorOutput_ = value;
+}
+
+std::string cmQtAutoGenerator::Logger::HeadLine(std::string const& title)
+{
+ std::string head = title;
+ head += '\n';
+ head.append(head.size() - 1, '-');
+ head += '\n';
+ return head;
+}
+
+void cmQtAutoGenerator::Logger::Info(GenT genType,
+ std::string const& message) const
+{
+ std::string msg = GeneratorName(genType);
+ msg += ": ";
+ msg += message;
+ if (msg.back() != '\n') {
+ msg.push_back('\n');
+ }
+ {
+ std::lock_guard<std::mutex> lock(Mutex_);
+ cmSystemTools::Stdout(msg);
+ }
+}
+
+void cmQtAutoGenerator::Logger::Warning(GenT genType,
+ std::string const& message) const
+{
+ std::string msg;
+ if (message.find('\n') == std::string::npos) {
+ // Single line message
+ msg += GeneratorName(genType);
+ msg += " warning: ";
+ } else {
+ // Multi line message
+ msg += HeadLine(GeneratorName(genType) + " warning");
+ }
+ // Message
+ msg += message;
+ if (msg.back() != '\n') {
+ msg.push_back('\n');
+ }
+ msg.push_back('\n');
+ {
+ std::lock_guard<std::mutex> lock(Mutex_);
+ cmSystemTools::Stdout(msg);
+ }
+}
+
+void cmQtAutoGenerator::Logger::WarningFile(GenT genType,
+ std::string const& filename,
+ std::string const& message) const
+{
+ std::string msg = " ";
+ msg += Quoted(filename);
+ msg.push_back('\n');
+ // Message
+ msg += message;
+ Warning(genType, msg);
+}
+
+void cmQtAutoGenerator::Logger::Error(GenT genType,
+ std::string const& message) const
+{
+ std::string msg;
+ msg += HeadLine(GeneratorName(genType) + " error");
+ // Message
+ msg += message;
+ if (msg.back() != '\n') {
+ msg.push_back('\n');
+ }
+ msg.push_back('\n');
+ {
+ std::lock_guard<std::mutex> lock(Mutex_);
+ cmSystemTools::Stderr(msg);
+ }
+}
+
+void cmQtAutoGenerator::Logger::ErrorFile(GenT genType,
+ std::string const& filename,
+ std::string const& message) const
+{
+ std::string emsg = " ";
+ emsg += Quoted(filename);
+ emsg += '\n';
+ // Message
+ emsg += message;
+ Error(genType, emsg);
+}
+
+void cmQtAutoGenerator::Logger::ErrorCommand(
+ GenT genType, std::string const& message,
+ std::vector<std::string> const& command, std::string const& output) const
+{
+ std::string msg;
+ msg.push_back('\n');
+ msg += HeadLine(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');
+ {
+ std::lock_guard<std::mutex> lock(Mutex_);
+ cmSystemTools::Stderr(msg);
+ }
+}
+
+bool cmQtAutoGenerator::MakeParentDirectory(std::string const& filename)
+{
+ bool success = true;
+ std::string const dirName = cmSystemTools::GetFilenamePath(filename);
+ if (!dirName.empty()) {
+ success = cmSystemTools::MakeDirectory(dirName);
+ }
+ return success;
+}
+
+bool cmQtAutoGenerator::FileRead(std::string& content,
+ std::string const& filename,
+ std::string* error)
+{
+ content.clear();
+ if (!cmSystemTools::FileExists(filename, true)) {
+ if (error != nullptr) {
+ *error = "Not a file.";
+ }
+ return false;
+ }
+
+ unsigned long const length = cmSystemTools::FileLength(filename);
+ cmsys::ifstream ifs(filename.c_str(), (std::ios::in | std::ios::binary));
+
+ // Use lambda to save destructor calls of ifs
+ return [&ifs, length, &content, error]() -> bool {
+ if (!ifs) {
+ if (error != nullptr) {
+ *error = "Opening the file for reading failed.";
+ }
+ return false;
+ }
+ content.reserve(length);
+ typedef std::istreambuf_iterator<char> IsIt;
+ content.assign(IsIt{ ifs }, IsIt{});
+ if (!ifs) {
+ content.clear();
+ if (error != nullptr) {
+ *error = "Reading from the file failed.";
+ }
+ return false;
+ }
+ return true;
+ }();
+}
+
+bool cmQtAutoGenerator::FileWrite(std::string const& filename,
+ std::string const& content,
+ std::string* error)
+{
+ // Make sure the parent directory exists
+ if (!cmQtAutoGenerator::MakeParentDirectory(filename)) {
+ if (error != nullptr) {
+ *error = "Could not create parent directory.";
+ }
+ return false;
+ }
+ cmsys::ofstream ofs;
+ ofs.open(filename.c_str(),
+ (std::ios::out | std::ios::binary | std::ios::trunc));
+
+ // Use lambda to save destructor calls of ofs
+ return [&ofs, &content, error]() -> bool {
+ if (!ofs) {
+ if (error != nullptr) {
+ *error = "Opening file for writing failed.";
+ }
+ return false;
+ }
+ ofs << content;
+ if (!ofs.good()) {
+ if (error != nullptr) {
+ *error = "File writing failed.";
+ }
+ return false;
+ }
+ return true;
+ }();
+}
+
+bool cmQtAutoGenerator::FileDiffers(std::string const& filename,
+ std::string const& content)
+{
+ bool differs = true;
+ std::string oldContents;
+ if (FileRead(oldContents, filename) && (oldContents == content)) {
+ differs = false;
+ }
+ return differs;
+}
+
+cmQtAutoGenerator::cmQtAutoGenerator() = default;
+
+cmQtAutoGenerator::~cmQtAutoGenerator() = default;
+
+bool cmQtAutoGenerator::Run(std::string const& infoFile,
+ std::string const& config)
+{
+ // Info settings
+ InfoFile_ = infoFile;
+ cmSystemTools::ConvertToUnixSlashes(InfoFile_);
+ if (!InfoFileTime_.Load(InfoFile_)) {
+ std::string msg = "AutoGen: The info file ";
+ msg += Quoted(InfoFile_);
+ msg += " is not readable\n";
+ cmSystemTools::Stderr(msg);
+ return false;
+ }
+ InfoDir_ = cmSystemTools::GetFilenamePath(infoFile);
+ InfoConfig_ = config;
+
+ bool success = false;
+ {
+ cmake cm(cmake::RoleScript, cmState::Unknown);
+ cm.SetHomeOutputDirectory(InfoDir());
+ cm.SetHomeDirectory(InfoDir());
+ cm.GetCurrentSnapshot().SetDefaultDefinitions();
+ cmGlobalGenerator gg(&cm);
+
+ cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
+ snapshot.GetDirectory().SetCurrentBinary(InfoDir());
+ snapshot.GetDirectory().SetCurrentSource(InfoDir());
+
+ auto makefile = cm::make_unique<cmMakefile>(&gg, snapshot);
+ // The OLD/WARN behavior for policy CMP0053 caused a speed regression.
+ // https://gitlab.kitware.com/cmake/cmake/issues/17570
+ makefile->SetPolicyVersion("3.9", std::string());
+ gg.SetCurrentMakefile(makefile.get());
+ success = this->Init(makefile.get());
+ }
+ if (success) {
+ success = this->Process();
+ }
+ return success;
+}
+
+std::string cmQtAutoGenerator::SettingsFind(std::string const& content,
+ const char* key)
+{
+ std::string prefix(key);
+ prefix += ':';
+ std::string::size_type pos = content.find(prefix);
+ if (pos != std::string::npos) {
+ pos += prefix.size();
+ if (pos < content.size()) {
+ std::string::size_type posE = content.find('\n', pos);
+ if ((posE != std::string::npos) && (posE != pos)) {
+ return content.substr(pos, posE - pos);
+ }
+ }
+ }
+ return std::string();
+}
diff --git a/Source/cmQtAutoGenerator.h b/Source/cmQtAutoGenerator.h
new file mode 100644
index 000000000..ff4c4c942
--- /dev/null
+++ b/Source/cmQtAutoGenerator.h
@@ -0,0 +1,109 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmQtAutoGenerator_h
+#define cmQtAutoGenerator_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cmFileTime.h"
+#include "cmQtAutoGen.h"
+
+#include <mutex>
+#include <string>
+#include <vector>
+
+class cmMakefile;
+
+/** \class cmQtAutoGenerator
+ * \brief Base class for QtAutoGen generators
+ */
+class cmQtAutoGenerator : public cmQtAutoGen
+{
+public:
+ // -- Types
+
+ /**
+ * Thread safe logger
+ */
+ class Logger
+ {
+ public:
+ // -- Construction
+ Logger();
+ ~Logger();
+ // -- Verbosity
+ unsigned int Verbosity() const { return this->Verbosity_; }
+ void SetVerbosity(unsigned int value) { this->Verbosity_ = value; }
+ void RaiseVerbosity(std::string const& value);
+ bool Verbose() const { return (this->Verbosity_ != 0); }
+ void SetVerbose(bool value) { this->Verbosity_ = value ? 1 : 0; }
+ // -- Color output
+ bool ColorOutput() const { return this->ColorOutput_; }
+ void SetColorOutput(bool value);
+ // -- Log info
+ void Info(GenT genType, std::string const& message) const;
+ // -- Log warning
+ void Warning(GenT genType, std::string const& message) const;
+ void WarningFile(GenT genType, std::string const& filename,
+ std::string const& message) const;
+ // -- Log error
+ void Error(GenT genType, std::string const& message) const;
+ void ErrorFile(GenT genType, std::string const& filename,
+ std::string const& message) const;
+ void ErrorCommand(GenT genType, std::string const& message,
+ std::vector<std::string> const& command,
+ std::string const& output) const;
+
+ private:
+ static std::string HeadLine(std::string const& title);
+
+ private:
+ mutable std::mutex Mutex_;
+ unsigned int Verbosity_ = 0;
+ bool ColorOutput_ = false;
+ };
+
+ // -- File system methods
+ static bool MakeParentDirectory(std::string const& filename);
+ static bool FileRead(std::string& content, std::string const& filename,
+ std::string* error = nullptr);
+ static bool FileWrite(std::string const& filename,
+ std::string const& content,
+ std::string* error = nullptr);
+ static bool FileDiffers(std::string const& filename,
+ std::string const& content);
+
+public:
+ // -- Constructors
+ cmQtAutoGenerator();
+ virtual ~cmQtAutoGenerator();
+
+ cmQtAutoGenerator(cmQtAutoGenerator const&) = delete;
+ cmQtAutoGenerator& operator=(cmQtAutoGenerator const&) = delete;
+
+ // -- Run
+ bool Run(std::string const& infoFile, std::string const& config);
+
+ // -- InfoFile
+ std::string const& InfoFile() const { return InfoFile_; }
+ cmFileTime const& InfoFileTime() const { return InfoFileTime_; }
+ std::string const& InfoDir() const { return InfoDir_; }
+ std::string const& InfoConfig() const { return InfoConfig_; }
+
+ // -- Utility
+ static std::string SettingsFind(std::string const& content, const char* key);
+
+protected:
+ // -- Abstract processing interface
+ virtual bool Init(cmMakefile* makefile) = 0;
+ virtual bool Process() = 0;
+
+private:
+ // -- Info settings
+ std::string InfoFile_;
+ cmFileTime InfoFileTime_;
+ std::string InfoDir_;
+ std::string InfoConfig_;
+};
+
+#endif
diff --git a/Source/cmQtAutoMocUic.cxx b/Source/cmQtAutoMocUic.cxx
new file mode 100644
index 000000000..641d8aa3f
--- /dev/null
+++ b/Source/cmQtAutoMocUic.cxx
@@ -0,0 +1,2193 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmQtAutoMocUic.h"
+
+#include <algorithm>
+#include <array>
+#include <list>
+#include <memory>
+#include <set>
+#include <sstream>
+#include <utility>
+
+#include "cmAlgorithms.h"
+#include "cmCryptoHash.h"
+#include "cmGeneratedFileStream.h"
+#include "cmMakefile.h"
+#include "cmQtAutoGen.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+#include "cmsys/FStream.hxx"
+
+#if defined(__APPLE__)
+# include <unistd.h>
+#endif
+
+static constexpr std::size_t MocUnderscoreLength = 4; // Length of "moc_"
+static constexpr std::size_t UiUnderscoreLength = 3; // Length of "ui_"
+
+cmQtAutoMocUic::IncludeKeyT::IncludeKeyT(std::string const& key,
+ std::size_t basePrefixLength)
+ : Key(key)
+ , Dir(SubDirPrefix(key))
+ , Base(cmSystemTools::GetFilenameWithoutLastExtension(key))
+{
+ if (basePrefixLength != 0) {
+ Base = Base.substr(basePrefixLength);
+ }
+}
+
+void cmQtAutoMocUic::ParseCacheT::FileT::Clear()
+{
+ Moc.Macro.clear();
+ Moc.Include.Underscore.clear();
+ Moc.Include.Dot.clear();
+ Moc.Depends.clear();
+
+ Uic.Include.clear();
+ Uic.Depends.clear();
+}
+
+cmQtAutoMocUic::ParseCacheT::FileHandleT cmQtAutoMocUic::ParseCacheT::Get(
+ std::string const& fileName) const
+{
+ auto it = Map_.find(fileName);
+ if (it != Map_.end()) {
+ return it->second;
+ }
+ return FileHandleT();
+}
+
+cmQtAutoMocUic::ParseCacheT::GetOrInsertT
+cmQtAutoMocUic::ParseCacheT::GetOrInsert(std::string const& fileName)
+{
+ // Find existing entry
+ {
+ auto it = Map_.find(fileName);
+ if (it != Map_.end()) {
+ return GetOrInsertT{ it->second, false };
+ }
+ }
+
+ // Insert new entry
+ return GetOrInsertT{
+ Map_.emplace(fileName, std::make_shared<FileT>()).first->second, true
+ };
+}
+
+cmQtAutoMocUic::ParseCacheT::ParseCacheT() = default;
+cmQtAutoMocUic::ParseCacheT::~ParseCacheT() = default;
+
+void cmQtAutoMocUic::ParseCacheT::Clear()
+{
+ Map_.clear();
+}
+
+bool cmQtAutoMocUic::ParseCacheT::ReadFromFile(std::string const& fileName)
+{
+ cmsys::ifstream fin(fileName.c_str());
+ if (!fin) {
+ return false;
+ }
+ FileHandleT fileHandle;
+
+ std::string line;
+ while (std::getline(fin, line)) {
+ // Check if this an empty or a comment line
+ if (line.empty() || line.front() == '#') {
+ continue;
+ }
+ // Drop carriage return character at the end
+ if (line.back() == '\r') {
+ line.pop_back();
+ if (line.empty()) {
+ continue;
+ }
+ }
+ // Check if this a file name line
+ if (line.front() != ' ') {
+ fileHandle = GetOrInsert(line).first;
+ continue;
+ }
+
+ // Bad line or bad file handle
+ if (!fileHandle || (line.size() < 6)) {
+ continue;
+ }
+
+ constexpr std::size_t offset = 5;
+ if (cmHasLiteralPrefix(line, " mmc:")) {
+ fileHandle->Moc.Macro = line.substr(offset);
+ continue;
+ }
+ if (cmHasLiteralPrefix(line, " miu:")) {
+ fileHandle->Moc.Include.Underscore.emplace_back(line.substr(offset),
+ MocUnderscoreLength);
+ continue;
+ }
+ if (cmHasLiteralPrefix(line, " mid:")) {
+ fileHandle->Moc.Include.Dot.emplace_back(line.substr(offset), 0);
+ continue;
+ }
+ if (cmHasLiteralPrefix(line, " mdp:")) {
+ fileHandle->Moc.Depends.emplace_back(line.substr(offset));
+ continue;
+ }
+ if (cmHasLiteralPrefix(line, " uic:")) {
+ fileHandle->Uic.Include.emplace_back(line.substr(offset),
+ UiUnderscoreLength);
+ continue;
+ }
+ if (cmHasLiteralPrefix(line, " udp:")) {
+ fileHandle->Uic.Depends.emplace_back(line.substr(offset));
+ continue;
+ }
+ }
+ return true;
+}
+
+bool cmQtAutoMocUic::ParseCacheT::WriteToFile(std::string const& fileName)
+{
+ cmGeneratedFileStream ofs(fileName);
+ if (!ofs) {
+ return false;
+ }
+ ofs << "# Generated by CMake. Changes will be overwritten." << std::endl;
+ for (auto const& pair : Map_) {
+ ofs << pair.first << std::endl;
+ FileT const& file = *pair.second;
+ if (!file.Moc.Macro.empty()) {
+ ofs << " mmc:" << file.Moc.Macro << std::endl;
+ }
+ for (IncludeKeyT const& item : file.Moc.Include.Underscore) {
+ ofs << " miu:" << item.Key << std::endl;
+ }
+ for (IncludeKeyT const& item : file.Moc.Include.Dot) {
+ ofs << " mid:" << item.Key << std::endl;
+ }
+ for (std::string const& item : file.Moc.Depends) {
+ ofs << " mdp:" << item << std::endl;
+ }
+ for (IncludeKeyT const& item : file.Uic.Include) {
+ ofs << " uic:" << item.Key << std::endl;
+ }
+ for (std::string const& item : file.Uic.Depends) {
+ ofs << " udp:" << item << std::endl;
+ }
+ }
+ return ofs.Close();
+}
+
+cmQtAutoMocUic::BaseSettingsT::BaseSettingsT() = default;
+cmQtAutoMocUic::BaseSettingsT::~BaseSettingsT() = default;
+
+cmQtAutoMocUic::MocSettingsT::MocSettingsT()
+{
+ RegExpInclude.compile(
+ "(^|\n)[ \t]*#[ \t]*include[ \t]+"
+ "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
+}
+
+cmQtAutoMocUic::MocSettingsT::~MocSettingsT() = default;
+
+bool cmQtAutoMocUic::MocSettingsT::skipped(std::string const& fileName) const
+{
+ return (!Enabled || (SkipList.find(fileName) != SkipList.end()));
+}
+
+std::string cmQtAutoMocUic::MocSettingsT::MacrosString() const
+{
+ std::string res;
+ const auto itB = MacroFilters.cbegin();
+ const auto itE = MacroFilters.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;
+}
+
+cmQtAutoMocUic::UicSettingsT::UicSettingsT()
+{
+ RegExpInclude.compile("(^|\n)[ \t]*#[ \t]*include[ \t]+"
+ "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
+}
+
+cmQtAutoMocUic::UicSettingsT::~UicSettingsT() = default;
+
+bool cmQtAutoMocUic::UicSettingsT::skipped(std::string const& fileName) const
+{
+ return (!Enabled || (SkipList.find(fileName) != SkipList.end()));
+}
+
+void cmQtAutoMocUic::JobT::LogError(GenT genType,
+ std::string const& message) const
+{
+ Gen()->AbortError();
+ Gen()->Log().Error(genType, message);
+}
+
+void cmQtAutoMocUic::JobT::LogFileError(GenT genType,
+ std::string const& filename,
+ std::string const& message) const
+{
+ Gen()->AbortError();
+ Gen()->Log().ErrorFile(genType, filename, message);
+}
+
+void cmQtAutoMocUic::JobT::LogCommandError(
+ GenT genType, std::string const& message,
+ std::vector<std::string> const& command, std::string const& output) const
+{
+ Gen()->AbortError();
+ Gen()->Log().ErrorCommand(genType, message, command, output);
+}
+
+bool cmQtAutoMocUic::JobT::RunProcess(GenT genType,
+ cmWorkerPool::ProcessResultT& result,
+ std::vector<std::string> const& command,
+ std::string* infoMessage)
+{
+ // Log command
+ if (Log().Verbose()) {
+ std::string msg;
+ if ((infoMessage != nullptr) && !infoMessage->empty()) {
+ msg = *infoMessage;
+ if (msg.back() != '\n') {
+ msg += '\n';
+ }
+ }
+ msg += QuotedCommand(command);
+ msg += '\n';
+ Log().Info(genType, msg);
+ }
+ return cmWorkerPool::JobT::RunProcess(result, command,
+ BaseConst().AutogenBuildDir);
+}
+
+void cmQtAutoMocUic::JobMocPredefsT::Process()
+{
+ // (Re)generate moc_predefs.h on demand
+ std::unique_ptr<std::string> reason;
+ if (Log().Verbose()) {
+ reason = cm::make_unique<std::string>();
+ }
+ if (!Update(reason.get())) {
+ return;
+ }
+ std::string const& predefsFileRel = MocConst().PredefsFileRel;
+ std::string const& predefsFileAbs = MocConst().PredefsFileAbs;
+ {
+ cmWorkerPool::ProcessResultT result;
+ {
+ // Compose command
+ std::vector<std::string> cmd = MocConst().PredefsCmd;
+ // Add includes
+ cmAppend(cmd, MocConst().Includes);
+ // Add definitions
+ for (std::string const& def : MocConst().Definitions) {
+ cmd.emplace_back("-D" + def);
+ }
+ // Execute command
+ if (!RunProcess(GenT::MOC, result, cmd, reason.get())) {
+ std::string msg = "The content generation command for ";
+ msg += Quoted(predefsFileRel);
+ msg += " failed.\n";
+ msg += result.ErrorMessage;
+ LogCommandError(GenT::MOC, msg, cmd, result.StdOut);
+ return;
+ }
+ }
+
+ // (Re)write predefs file only on demand
+ if (cmQtAutoGenerator::FileDiffers(predefsFileAbs, result.StdOut)) {
+ if (!cmQtAutoGenerator::FileWrite(predefsFileAbs, result.StdOut)) {
+ std::string msg = "Writing ";
+ msg += Quoted(predefsFileRel);
+ msg += " failed.";
+ LogFileError(GenT::MOC, predefsFileAbs, msg);
+ return;
+ }
+ } else {
+ // Touch to update the time stamp
+ if (Log().Verbose()) {
+ Log().Info(GenT::MOC, "Touching " + Quoted(predefsFileRel));
+ }
+ if (!cmSystemTools::Touch(predefsFileAbs, false)) {
+ std::string msg = "Touching ";
+ msg += Quoted(predefsFileAbs);
+ msg += " failed.";
+ LogFileError(GenT::MOC, predefsFileAbs, msg);
+ return;
+ }
+ }
+ }
+
+ // Read file time afterwards
+ if (!MocEval().PredefsTime.Load(predefsFileAbs)) {
+ LogFileError(GenT::MOC, predefsFileAbs, "File time reading failed.");
+ return;
+ }
+}
+
+bool cmQtAutoMocUic::JobMocPredefsT::Update(std::string* reason) const
+{
+ // Test if the file exists
+ if (!MocEval().PredefsTime.Load(MocConst().PredefsFileAbs)) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(MocConst().PredefsFileRel);
+ *reason += ", because it doesn't exist.";
+ }
+ return true;
+ }
+
+ // Test if the settings changed
+ if (MocConst().SettingsChanged) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(MocConst().PredefsFileRel);
+ *reason += ", because the moc settings changed.";
+ }
+ return true;
+ }
+
+ // Test if the executable is newer
+ {
+ std::string const& exec = MocConst().PredefsCmd.at(0);
+ cmFileTime execTime;
+ if (execTime.Load(exec)) {
+ if (MocEval().PredefsTime.Older(execTime)) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(MocConst().PredefsFileRel);
+ *reason += " because it is older than ";
+ *reason += Quoted(exec);
+ *reason += ".";
+ }
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+bool cmQtAutoMocUic::JobParseT::ReadFile()
+{
+ // Clear old parse information
+ FileHandle->ParseData->Clear();
+ std::string const& fileName = FileHandle->FileName;
+ // Write info
+ if (Log().Verbose()) {
+ Log().Info(GenT::GEN, "Parsing " + Quoted(fileName));
+ }
+ // Read file content
+ {
+ std::string error;
+ if (!cmQtAutoGenerator::FileRead(Content, fileName, &error)) {
+ LogFileError(GenT::GEN, fileName, "Could not read the file: " + error);
+ return false;
+ }
+ }
+ // Warn if empty
+ if (Content.empty()) {
+ Log().WarningFile(GenT::GEN, fileName, "The file is empty.");
+ return false;
+ }
+ return true;
+}
+
+void cmQtAutoMocUic::JobParseT::CreateKeys(std::vector<IncludeKeyT>& container,
+ std::set<std::string> const& source,
+ std::size_t basePrefixLength)
+{
+ if (source.empty()) {
+ return;
+ }
+ container.reserve(source.size());
+ for (std::string const& src : source) {
+ container.emplace_back(src, basePrefixLength);
+ }
+}
+
+void cmQtAutoMocUic::JobParseT::MocMacro()
+{
+ for (KeyExpT const& filter : MocConst().MacroFilters) {
+ // Run a simple find string check
+ if (Content.find(filter.Key) == std::string::npos) {
+ continue;
+ }
+ // Run the expensive regular expression check loop
+ cmsys::RegularExpressionMatch match;
+ if (filter.Exp.find(Content.c_str(), match)) {
+ // Keep detected macro name
+ FileHandle->ParseData->Moc.Macro = filter.Key;
+ return;
+ }
+ }
+}
+
+void cmQtAutoMocUic::JobParseT::MocDependecies()
+{
+ if (MocConst().DependFilters.empty()) {
+ return;
+ }
+
+ // Find dependency strings
+ std::set<std::string> parseDepends;
+ for (KeyExpT const& filter : MocConst().DependFilters) {
+ // Run a simple find string check
+ if (Content.find(filter.Key) == std::string::npos) {
+ continue;
+ }
+ // Run the expensive regular expression check loop
+ const char* contentChars = Content.c_str();
+ cmsys::RegularExpressionMatch match;
+ while (filter.Exp.find(contentChars, match)) {
+ {
+ std::string dep = match.match(1);
+ if (!dep.empty()) {
+ parseDepends.emplace(std::move(dep));
+ }
+ }
+ contentChars += match.end();
+ }
+ }
+
+ // Store dependency strings
+ {
+ auto& Depends = FileHandle->ParseData->Moc.Depends;
+ Depends.reserve(parseDepends.size());
+ for (std::string const& item : parseDepends) {
+ Depends.emplace_back(item);
+ // Replace end of line characters in filenames
+ std::string& path = Depends.back();
+ std::replace(path.begin(), path.end(), '\n', ' ');
+ std::replace(path.begin(), path.end(), '\r', ' ');
+ }
+ }
+}
+
+void cmQtAutoMocUic::JobParseT::MocIncludes()
+{
+ if (Content.find("moc") == std::string::npos) {
+ return;
+ }
+
+ std::set<std::string> underscore;
+ std::set<std::string> dot;
+ {
+ const char* contentChars = Content.c_str();
+ cmsys::RegularExpression const& regExp = MocConst().RegExpInclude;
+ cmsys::RegularExpressionMatch match;
+ while (regExp.find(contentChars, match)) {
+ std::string incString = match.match(2);
+ std::string const incBase =
+ cmSystemTools::GetFilenameWithoutLastExtension(incString);
+ if (cmHasLiteralPrefix(incBase, "moc_")) {
+ // moc_<BASE>.cpp
+ // Remove the moc_ part from the base name
+ underscore.emplace(std::move(incString));
+ } else {
+ // <BASE>.moc
+ dot.emplace(std::move(incString));
+ }
+ // Forward content pointer
+ contentChars += match.end();
+ }
+ }
+ auto& Include = FileHandle->ParseData->Moc.Include;
+ CreateKeys(Include.Underscore, underscore, MocUnderscoreLength);
+ CreateKeys(Include.Dot, dot, 0);
+}
+
+void cmQtAutoMocUic::JobParseT::UicIncludes()
+{
+ if (Content.find("ui_") == std::string::npos) {
+ return;
+ }
+
+ std::set<std::string> includes;
+ {
+ const char* contentChars = Content.c_str();
+ cmsys::RegularExpression const& regExp = UicConst().RegExpInclude;
+ cmsys::RegularExpressionMatch match;
+ while (regExp.find(contentChars, match)) {
+ includes.emplace(match.match(2));
+ // Forward content pointer
+ contentChars += match.end();
+ }
+ }
+ CreateKeys(FileHandle->ParseData->Uic.Include, includes, UiUnderscoreLength);
+}
+
+void cmQtAutoMocUic::JobParseHeaderT::Process()
+{
+ if (!ReadFile()) {
+ return;
+ }
+ // Moc parsing
+ if (FileHandle->Moc) {
+ MocMacro();
+ MocDependecies();
+ }
+ // Uic parsing
+ if (FileHandle->Uic) {
+ UicIncludes();
+ }
+}
+
+void cmQtAutoMocUic::JobParseSourceT::Process()
+{
+ if (!ReadFile()) {
+ return;
+ }
+ // Moc parsing
+ if (FileHandle->Moc) {
+ MocMacro();
+ MocDependecies();
+ MocIncludes();
+ }
+ // Uic parsing
+ if (FileHandle->Uic) {
+ UicIncludes();
+ }
+}
+
+void cmQtAutoMocUic::JobEvaluateT::Process()
+{
+ // Evaluate for moc
+ if (MocConst().Enabled) {
+ // Evaluate headers
+ for (auto const& pair : BaseEval().Headers) {
+ if (!MocEvalHeader(pair.second)) {
+ return;
+ }
+ }
+ // Evaluate sources
+ for (auto const& pair : BaseEval().Sources) {
+ if (!MocEvalSource(pair.second)) {
+ return;
+ }
+ }
+ }
+ // Evaluate for uic
+ if (UicConst().Enabled) {
+ if (!UicEval(BaseEval().Headers) || !UicEval(BaseEval().Sources)) {
+ return;
+ }
+ }
+
+ // Add discovered header parse jobs
+ Gen()->CreateParseJobs<JobParseHeaderT>(MocEval().HeadersDiscovered);
+ // Add generate job after
+ Gen()->WorkerPool().EmplaceJob<JobGenerateT>();
+}
+
+bool cmQtAutoMocUic::JobEvaluateT::MocEvalHeader(SourceFileHandleT source)
+{
+ SourceFileT const& sourceFile = *source;
+ auto const& parseData = sourceFile.ParseData->Moc;
+ if (!source->Moc) {
+ return true;
+ }
+
+ if (!parseData.Macro.empty()) {
+ // Create a new mapping
+ MappingHandleT handle = std::make_shared<MappingT>();
+ handle->SourceFile = std::move(source);
+
+ // Absolute build path
+ if (BaseConst().MultiConfig) {
+ handle->OutputFile = Gen()->AbsoluteIncludePath(sourceFile.BuildPath);
+ } else {
+ handle->OutputFile = Gen()->AbsoluteBuildPath(sourceFile.BuildPath);
+ }
+
+ // Register mapping in headers map
+ MocRegisterMapping(handle, true);
+ }
+
+ return true;
+}
+
+bool cmQtAutoMocUic::JobEvaluateT::MocEvalSource(
+ SourceFileHandleT const& source)
+{
+ SourceFileT const& sourceFile = *source;
+ auto const& parseData = sourceFile.ParseData->Moc;
+ if (!sourceFile.Moc ||
+ (parseData.Macro.empty() && parseData.Include.Underscore.empty() &&
+ parseData.Include.Dot.empty())) {
+ return true;
+ }
+
+ std::string const sourceDir = SubDirPrefix(sourceFile.FileName);
+ std::string const sourceBase =
+ cmSystemTools::GetFilenameWithoutLastExtension(sourceFile.FileName);
+
+ // For relaxed mode check if the own "moc_" or ".moc" file is included
+ bool const relaxedMode = MocConst().RelaxedMode;
+ bool sourceIncludesMocUnderscore = false;
+ bool sourceIncludesDotMoc = false;
+ // Check if the sources own "moc_" or ".moc" file is included
+ if (relaxedMode) {
+ for (IncludeKeyT const& incKey : parseData.Include.Underscore) {
+ if (incKey.Base == sourceBase) {
+ sourceIncludesMocUnderscore = true;
+ break;
+ }
+ }
+ }
+ for (IncludeKeyT const& incKey : parseData.Include.Dot) {
+ if (incKey.Base == sourceBase) {
+ sourceIncludesDotMoc = true;
+ break;
+ }
+ }
+
+ // Check if this source needs to be moc processed but doesn't.
+ if (!sourceIncludesDotMoc && !parseData.Macro.empty() &&
+ !(relaxedMode && sourceIncludesMocUnderscore)) {
+ {
+ std::string emsg = "The file contains a ";
+ emsg += Quoted(parseData.Macro);
+ emsg += " macro, but does not include ";
+ emsg += Quoted(sourceBase + ".moc");
+ emsg += "!\nConsider to\n - add #include \"";
+ emsg += sourceBase;
+ emsg += ".moc\"\n - enable SKIP_AUTOMOC for this file";
+ LogFileError(GenT::MOC, sourceFile.FileName, emsg);
+ }
+ return false;
+ }
+
+ // Evaluate "moc_" includes
+ for (IncludeKeyT const& incKey : parseData.Include.Underscore) {
+ std::string const headerBase = incKey.Dir + incKey.Base;
+ SourceFileHandleT header = MocFindIncludedHeader(sourceDir, headerBase);
+ if (!header) {
+ {
+ std::string msg = "The file includes the moc file ";
+ msg += Quoted(incKey.Key);
+ msg += ",\nbut the header could not be found "
+ "in the following locations\n";
+ msg += MocMessageTestHeaders(headerBase);
+ LogFileError(GenT::MOC, sourceFile.FileName, msg);
+ }
+ return false;
+ }
+ // The include might be handled differently in relaxed mode
+ if (relaxedMode && !sourceIncludesDotMoc && !parseData.Macro.empty() &&
+ (incKey.Base == sourceBase)) {
+ // The <BASE>.cpp file includes a Qt macro but does not include the
+ // <BASE>.moc file. In this case, the moc_<BASE>.cpp should probably
+ // be generated from <BASE>.cpp instead of <BASE>.h, because otherwise
+ // it won't build. But warn, since this is not how it is supposed to be
+ // used. This is for KDE4 compatibility.
+ {
+ // Issue a warning
+ std::string msg = "The file contains a ";
+ msg += Quoted(parseData.Macro);
+ msg += " macro, but does not include ";
+ msg += Quoted(sourceBase + ".moc");
+ msg += ".\nInstead it includes ";
+ msg += Quoted(incKey.Key);
+ msg += ".\nRunning moc on the source\n ";
+ msg += Quoted(sourceFile.FileName);
+ msg += "!\nBetter include ";
+ msg += Quoted(sourceBase + ".moc");
+ msg += " for compatibility with regular mode.\n";
+ msg += "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n";
+ Log().WarningFile(GenT::MOC, sourceFile.FileName, msg);
+ }
+ // Create mapping
+ if (!MocRegisterIncluded(incKey.Key, source, source, false)) {
+ return false;
+ }
+ continue;
+ }
+
+ // Check if header is skipped
+ if (MocConst().skipped(header->FileName)) {
+ continue;
+ }
+ // Create mapping
+ if (!MocRegisterIncluded(incKey.Key, source, std::move(header), true)) {
+ return false;
+ }
+ }
+
+ // Evaluate ".moc" includes
+ if (relaxedMode) {
+ // Relaxed mode
+ for (IncludeKeyT const& incKey : parseData.Include.Dot) {
+ // Check if this is the sources own .moc file
+ bool const ownMoc = (incKey.Base == sourceBase);
+ if (ownMoc && !parseData.Macro.empty()) {
+ // Create mapping for the regular use case
+ if (!MocRegisterIncluded(incKey.Key, source, source, false)) {
+ return false;
+ }
+ continue;
+ }
+ // Try to find a header instead but issue a warning.
+ // This is for KDE4 compatibility.
+ std::string const headerBase = incKey.Dir + incKey.Base;
+ SourceFileHandleT header = MocFindIncludedHeader(sourceDir, headerBase);
+ if (!header) {
+ std::string msg = "The file includes the moc file ";
+ msg += Quoted(incKey.Key);
+ msg += ",\nwhich seems to be the moc file from a different source "
+ "file.\nCMAKE_AUTOMOC_RELAXED_MODE: Also a matching header"
+ "could not be found in the following locations\n";
+ msg += MocMessageTestHeaders(headerBase);
+ LogFileError(GenT::MOC, sourceFile.FileName, msg);
+ return false;
+ }
+ // Check if header is skipped
+ if (MocConst().skipped(header->FileName)) {
+ continue;
+ }
+ // Issue a warning
+ if (ownMoc && parseData.Macro.empty()) {
+ std::string msg = "The file includes the moc file ";
+ msg += Quoted(incKey.Key);
+ msg += ", but does not contain a\n";
+ msg += MocConst().MacrosString();
+ msg += " macro.\nRunning moc on the header\n ";
+ msg += Quoted(header->FileName);
+ msg += "!\nBetter include ";
+ msg += Quoted("moc_" + incKey.Base + ".cpp");
+ msg += " for a compatibility with regular mode.\n";
+ msg += "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n";
+ Log().WarningFile(GenT::MOC, sourceFile.FileName, msg);
+ } else {
+ std::string msg = "The file includes the moc file ";
+ msg += Quoted(incKey.Key);
+ msg += " instead of ";
+ msg += Quoted("moc_" + incKey.Base + ".cpp");
+ msg += ".\nRunning moc on the header\n ";
+ msg += Quoted(header->FileName);
+ msg += "!\nBetter include ";
+ msg += Quoted("moc_" + incKey.Base + ".cpp");
+ msg += " for compatibility with regular mode.\n";
+ msg += "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n";
+ Log().WarningFile(GenT::MOC, sourceFile.FileName, msg);
+ }
+ // Create mapping
+ if (!MocRegisterIncluded(incKey.Key, source, std::move(header), true)) {
+ return false;
+ }
+ }
+ } else {
+ // Strict mode
+ for (IncludeKeyT const& incKey : parseData.Include.Dot) {
+ // Check if this is the sources own .moc file
+ bool const ownMoc = (incKey.Base == sourceBase);
+ if (!ownMoc) {
+ // Don't allow <BASE>.moc include other than own in regular mode
+ std::string msg = "The file includes the moc file ";
+ msg += Quoted(incKey.Key);
+ msg += ",\nwhich seems to be the moc file from a different "
+ "source file.\nThis is not supported. Include ";
+ msg += Quoted(sourceBase + ".moc");
+ msg += " to run moc on this source file.";
+ LogFileError(GenT::MOC, sourceFile.FileName, msg);
+ return false;
+ }
+ // Accept but issue a warning if moc isn't required
+ if (parseData.Macro.empty()) {
+ std::string msg = "The file includes the moc file ";
+ msg += Quoted(incKey.Key);
+ msg += ", but does not contain a ";
+ msg += MocConst().MacrosString();
+ msg += " macro.";
+ Log().WarningFile(GenT::MOC, sourceFile.FileName, msg);
+ }
+ // Create mapping
+ if (!MocRegisterIncluded(incKey.Key, source, source, false)) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+cmQtAutoMocUic::SourceFileHandleT
+cmQtAutoMocUic::JobEvaluateT::MocFindIncludedHeader(
+ std::string const& includerDir, std::string const& includeBase) const
+{
+ // Search in vicinity of the source
+ {
+ SourceFileHandleT res = MocFindHeader(includerDir + includeBase);
+ if (res) {
+ return res;
+ }
+ }
+ // Search in include directories
+ for (std::string const& path : MocConst().IncludePaths) {
+ std::string testPath = path;
+ testPath += '/';
+ testPath += includeBase;
+ SourceFileHandleT res = MocFindHeader(testPath);
+ if (res) {
+ return res;
+ }
+ }
+ // Return without success
+ return SourceFileHandleT();
+}
+
+cmQtAutoMocUic::SourceFileHandleT cmQtAutoMocUic::JobEvaluateT::MocFindHeader(
+ std::string const& basePath) const
+{
+ std::string testPath;
+ testPath.reserve(basePath.size() + 8);
+ for (std::string const& ext : BaseConst().HeaderExtensions) {
+ testPath.clear();
+ testPath += basePath;
+ testPath += '.';
+ testPath += ext;
+ cmFileTime fileTime;
+ if (fileTime.Load(testPath)) {
+ // Compute real path of the file
+ testPath = cmSystemTools::GetRealPath(testPath);
+ // Return a known file if it exists already
+ {
+ auto it = BaseEval().Headers.find(testPath);
+ if (it != BaseEval().Headers.end()) {
+ return it->second;
+ }
+ }
+ // Created and return discovered file entry
+ SourceFileHandleT& res = MocEval().HeadersDiscovered[testPath];
+ if (!res) {
+ res = std::make_shared<SourceFileT>(testPath);
+ res->FileTime = fileTime;
+ res->Moc = true;
+ }
+ return res;
+ }
+ }
+ // Return without success
+ return SourceFileHandleT();
+}
+
+std::string cmQtAutoMocUic::JobEvaluateT::MocMessageTestHeaders(
+ std::string const& fileBase) const
+{
+ std::ostringstream res;
+ {
+ std::string exts = ".{";
+ exts += cmJoin(BaseConst().HeaderExtensions, ",");
+ exts += '}';
+ // Compose result string
+ res << " " << fileBase << exts << '\n';
+ for (std::string const& path : MocConst().IncludePaths) {
+ res << " " << path << '/' << fileBase << exts << '\n';
+ }
+ }
+ return res.str();
+}
+
+bool cmQtAutoMocUic::JobEvaluateT::MocRegisterIncluded(
+ std::string const& includeString, SourceFileHandleT includerFileHandle,
+ SourceFileHandleT sourceFileHandle, bool sourceIsHeader) const
+{
+ // Check if this file is already included
+ MappingHandleT& handle = MocEval().Includes[includeString];
+ if (handle) {
+ // Check if the output file would be generated from different source files
+ if (handle->SourceFile != sourceFileHandle) {
+ std::string msg = "The source files\n ";
+ msg += Quoted(includerFileHandle->FileName);
+ msg += '\n';
+ for (auto const& item : handle->IncluderFiles) {
+ msg += " ";
+ msg += Quoted(item->FileName);
+ msg += '\n';
+ }
+ msg += "contain the same include string ";
+ msg += Quoted(includeString);
+ msg += ", but\nthe moc file would be generated from different "
+ "source files\n ";
+ msg += Quoted(sourceFileHandle->FileName);
+ msg += " and\n ";
+ msg += Quoted(handle->SourceFile->FileName);
+ msg += ".\nConsider 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";
+ LogError(GenT::MOC, msg);
+ return false;
+ }
+
+ // The same mapping already exists. Just add to the includers list.
+ handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
+ return true;
+ }
+
+ // Create a new mapping
+ handle = std::make_shared<MappingT>();
+ handle->IncludeString = includeString;
+ handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
+ handle->SourceFile = std::move(sourceFileHandle);
+ handle->OutputFile += Gen()->AbsoluteIncludePath(includeString);
+
+ // Register mapping in sources/headers map
+ MocRegisterMapping(handle, sourceIsHeader);
+ return true;
+}
+
+void cmQtAutoMocUic::JobEvaluateT::MocRegisterMapping(
+ MappingHandleT mappingHandle, bool sourceIsHeader) const
+{
+ auto& regMap =
+ sourceIsHeader ? MocEval().HeaderMappings : MocEval().SourceMappings;
+ // Check if source file already gets mapped
+ auto& regHandle = regMap[mappingHandle->SourceFile->FileName];
+ if (!regHandle) {
+ // Yet unknown mapping
+ regHandle = std::move(mappingHandle);
+ } else {
+ // Mappings with include string override those without
+ if (!mappingHandle->IncludeString.empty()) {
+ regHandle = std::move(mappingHandle);
+ }
+ }
+}
+
+bool cmQtAutoMocUic::JobEvaluateT::UicEval(SourceFileMapT const& fileMap)
+{
+ for (auto const& pair : fileMap) {
+ if (!UicEvalFile(pair.second)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool cmQtAutoMocUic::JobEvaluateT::UicEvalFile(
+ SourceFileHandleT const& sourceFileHandle)
+{
+ SourceFileT const& sourceFile = *sourceFileHandle;
+ auto const& Include = sourceFile.ParseData->Uic.Include;
+ if (!sourceFile.Uic || Include.empty()) {
+ return true;
+ }
+
+ std::string const sourceDir = SubDirPrefix(sourceFile.FileName);
+ for (IncludeKeyT const& incKey : Include) {
+ // Find .ui file name
+ SourceFileHandleT uiFileHandle =
+ UicFindIncludedUi(sourceFile.FileName, sourceDir, incKey);
+ if (!uiFileHandle || UicConst().skipped(uiFileHandle->FileName)) {
+ continue;
+ }
+ // Register mapping
+ if (!UicRegisterMapping(incKey.Key, std::move(uiFileHandle),
+ sourceFileHandle)) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool cmQtAutoMocUic::JobEvaluateT::UicRegisterMapping(
+ std::string const& includeString, SourceFileHandleT uiFileHandle,
+ SourceFileHandleT includerFileHandle)
+{
+ auto& Includes = Gen()->UicEval().Includes;
+ auto it = Includes.find(includeString);
+ if (it != Includes.end()) {
+ MappingHandleT const& handle = it->second;
+ if (handle->SourceFile != uiFileHandle) {
+ // The output file already gets generated - from a different .ui file!
+ std::string msg = "The source files\n ";
+ msg += Quoted(includerFileHandle->FileName);
+ msg += '\n';
+ for (auto const& item : handle->IncluderFiles) {
+ msg += " ";
+ msg += Quoted(item->FileName);
+ msg += '\n';
+ }
+ msg += "contain the same include string ";
+ msg += Quoted(includeString);
+ msg += ", but\nthe uic file would be generated from different "
+ "user interface files\n ";
+ msg += Quoted(uiFileHandle->FileName);
+ msg += " and\n ";
+ msg += Quoted(handle->SourceFile->FileName);
+ msg += ".\nConsider 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";
+ LogError(GenT::UIC, msg);
+ return false;
+ }
+ // Add includer file to existing mapping
+ handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
+ } else {
+ // New mapping handle
+ MappingHandleT handle = std::make_shared<MappingT>();
+ handle->IncludeString = includeString;
+ handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
+ handle->SourceFile = std::move(uiFileHandle);
+ handle->OutputFile += Gen()->AbsoluteIncludePath(includeString);
+ // Register mapping
+ Includes.emplace(includeString, std::move(handle));
+ }
+ return true;
+}
+
+cmQtAutoMocUic::SourceFileHandleT
+cmQtAutoMocUic::JobEvaluateT::UicFindIncludedUi(
+ std::string const& sourceFile, std::string const& sourceDir,
+ IncludeKeyT const& incKey) const
+{
+ std::string searchFileName = incKey.Base;
+ searchFileName += ".ui";
+ // Collect search paths list
+ std::vector<std::string> testFiles;
+ {
+ auto& searchPaths = UicConst().SearchPaths;
+ testFiles.reserve((searchPaths.size() + 1) * 2);
+
+ // Vicinity of the source
+ testFiles.emplace_back(sourceDir + searchFileName);
+ if (!incKey.Dir.empty()) {
+ std::string path = sourceDir;
+ path += incKey.Dir;
+ path += searchFileName;
+ testFiles.emplace_back(path);
+ }
+ // AUTOUIC search paths
+ if (!searchPaths.empty()) {
+ for (std::string const& sPath : searchPaths) {
+ std::string path = sPath;
+ path += '/';
+ path += searchFileName;
+ testFiles.emplace_back(std::move(path));
+ }
+ if (!incKey.Dir.empty()) {
+ for (std::string const& sPath : searchPaths) {
+ std::string path = sPath;
+ path += '/';
+ path += incKey.Dir;
+ path += searchFileName;
+ testFiles.emplace_back(std::move(path));
+ }
+ }
+ }
+ }
+
+ // Search for the .ui file!
+ for (std::string const& testFile : testFiles) {
+ cmFileTime fileTime;
+ if (fileTime.Load(testFile)) {
+ // .ui file found in files system!
+ std::string realPath = cmSystemTools::GetRealPath(testFile);
+ // Get or create .ui file handle
+ SourceFileHandleT& handle = Gen()->UicEval().UiFiles[realPath];
+ if (!handle) {
+ // The file wasn't registered, yet
+ handle = std::make_shared<SourceFileT>(realPath);
+ handle->FileTime = fileTime;
+ }
+ return handle;
+ }
+ }
+
+ // Log error
+ {
+ std::string msg = "The file includes the uic file ";
+ msg += Quoted(incKey.Key);
+ msg += ",\nbut the user interface file ";
+ msg += Quoted(searchFileName);
+ msg += "\ncould not be found in the following locations\n";
+ for (std::string const& testFile : testFiles) {
+ msg += " ";
+ msg += Quoted(testFile);
+ msg += '\n';
+ }
+ LogFileError(GenT::UIC, sourceFile, msg);
+ }
+
+ return SourceFileHandleT();
+}
+
+void cmQtAutoMocUic::JobGenerateT::Process()
+{
+ // Add moc compile jobs
+ if (MocConst().Enabled) {
+ for (auto const& pair : MocEval().HeaderMappings) {
+ // Register if this mapping is a candidate for mocs_compilation.cpp
+ bool const compFile = pair.second->IncludeString.empty();
+ if (compFile) {
+ MocEval().CompFiles.emplace_back(pair.second->SourceFile->BuildPath);
+ }
+ if (!MocGenerate(pair.second, compFile)) {
+ return;
+ }
+ }
+ for (auto const& pair : MocEval().SourceMappings) {
+ if (!MocGenerate(pair.second, false)) {
+ return;
+ }
+ }
+
+ // Add mocs compilations job on demand
+ Gen()->WorkerPool().EmplaceJob<JobMocsCompilationT>();
+ }
+
+ // Add uic compile jobs
+ if (UicConst().Enabled) {
+ for (auto const& pair : Gen()->UicEval().Includes) {
+ if (!UicGenerate(pair.second)) {
+ return;
+ }
+ }
+ }
+
+ // Add finish job
+ Gen()->WorkerPool().EmplaceJob<JobFinishT>();
+}
+
+bool cmQtAutoMocUic::JobGenerateT::MocGenerate(MappingHandleT const& mapping,
+ bool compFile) const
+{
+ std::unique_ptr<std::string> reason;
+ if (Log().Verbose()) {
+ reason = cm::make_unique<std::string>();
+ }
+ if (MocUpdate(*mapping, reason.get())) {
+ // Create the parent directory
+ if (!MakeParentDirectory(mapping->OutputFile)) {
+ LogFileError(GenT::MOC, mapping->OutputFile,
+ "Could not create parent directory.");
+ return false;
+ }
+ // Add moc job
+ Gen()->WorkerPool().EmplaceJob<JobMocT>(mapping, std::move(reason));
+ // Check if a moc job for a mocs_compilation.cpp entry was generated
+ if (compFile) {
+ MocEval().CompUpdated = true;
+ }
+ }
+ return true;
+}
+
+bool cmQtAutoMocUic::JobGenerateT::MocUpdate(MappingT const& mapping,
+ std::string* reason) const
+{
+ std::string const& sourceFile = mapping.SourceFile->FileName;
+ std::string const& outputFile = mapping.OutputFile;
+
+ // Test if the output file exists
+ cmFileTime outputFileTime;
+ if (!outputFileTime.Load(outputFile)) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(outputFile);
+ *reason += ", because it doesn't exist, from ";
+ *reason += Quoted(sourceFile);
+ }
+ return true;
+ }
+
+ // Test if any setting changed
+ if (MocConst().SettingsChanged) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(outputFile);
+ *reason += ", because the uic settings changed, from ";
+ *reason += Quoted(sourceFile);
+ }
+ return true;
+ }
+
+ // Test if the source file is newer
+ if (outputFileTime.Older(mapping.SourceFile->FileTime)) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(outputFile);
+ *reason += ", because it's older than its source file, from ";
+ *reason += Quoted(sourceFile);
+ }
+ return true;
+ }
+
+ // Test if the moc_predefs file is newer
+ if (!MocConst().PredefsFileAbs.empty()) {
+ if (outputFileTime.Older(MocEval().PredefsTime)) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(outputFile);
+ *reason += ", because it's older than ";
+ *reason += Quoted(MocConst().PredefsFileAbs);
+ *reason += ", from ";
+ *reason += Quoted(sourceFile);
+ }
+ return true;
+ }
+ }
+
+ // Test if the moc executable is newer
+ if (outputFileTime.Older(MocConst().ExecutableTime)) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(outputFile);
+ *reason += ", because it's older than the moc executable, from ";
+ *reason += Quoted(sourceFile);
+ }
+ return true;
+ }
+
+ // Test if a dependency file is newer
+ {
+ // Check dependency timestamps
+ std::string const sourceDir = SubDirPrefix(sourceFile);
+ for (std::string const& dep : mapping.SourceFile->ParseData->Moc.Depends) {
+ // Find dependency file
+ auto const depMatch = MocFindDependency(sourceDir, dep);
+ if (depMatch.first.empty()) {
+ Log().WarningFile(GenT::MOC, sourceFile,
+ "Could not find dependency file " + Quoted(dep));
+ continue;
+ }
+ // Test if dependency file is older
+ if (outputFileTime.Older(depMatch.second)) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(outputFile);
+ *reason += ", because it's older than its dependency file ";
+ *reason += Quoted(depMatch.first);
+ *reason += ", from ";
+ *reason += Quoted(sourceFile);
+ }
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+std::pair<std::string, cmFileTime>
+cmQtAutoMocUic::JobGenerateT::MocFindDependency(
+ std::string const& sourceDir, std::string const& includeString) const
+{
+ typedef std::pair<std::string, cmFileTime> ResPair;
+ // Search in vicinity of the source
+ {
+ ResPair res{ sourceDir + includeString, {} };
+ if (res.second.Load(res.first)) {
+ return res;
+ }
+ }
+ // Search in include directories
+ for (std::string const& includePath : MocConst().IncludePaths) {
+ ResPair res{ includePath, {} };
+ res.first += '/';
+ res.first += includeString;
+ if (res.second.Load(res.first)) {
+ return res;
+ }
+ }
+ // Return empty
+ return ResPair();
+}
+
+bool cmQtAutoMocUic::JobGenerateT::UicGenerate(
+ MappingHandleT const& mapping) const
+{
+ std::unique_ptr<std::string> reason;
+ if (Log().Verbose()) {
+ reason = cm::make_unique<std::string>();
+ }
+ if (UicUpdate(*mapping, reason.get())) {
+ // Create the parent directory
+ if (!MakeParentDirectory(mapping->OutputFile)) {
+ LogFileError(GenT::UIC, mapping->OutputFile,
+ "Could not create parent directory.");
+ return false;
+ }
+ // Add uic job
+ Gen()->WorkerPool().EmplaceJob<JobUicT>(mapping, std::move(reason));
+ }
+ return true;
+}
+
+bool cmQtAutoMocUic::JobGenerateT::UicUpdate(MappingT const& mapping,
+ std::string* reason) const
+{
+ std::string const& sourceFile = mapping.SourceFile->FileName;
+ std::string const& outputFile = mapping.OutputFile;
+
+ // Test if the build file exists
+ cmFileTime outputFileTime;
+ if (!outputFileTime.Load(outputFile)) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(outputFile);
+ *reason += ", because it doesn't exist, from ";
+ *reason += Quoted(sourceFile);
+ }
+ return true;
+ }
+
+ // Test if the uic settings changed
+ if (UicConst().SettingsChanged) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(outputFile);
+ *reason += ", because the uic settings changed, from ";
+ *reason += Quoted(sourceFile);
+ }
+ return true;
+ }
+
+ // Test if the source file is newer
+ if (outputFileTime.Older(mapping.SourceFile->FileTime)) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(outputFile);
+ *reason += " because it's older than the source file ";
+ *reason += Quoted(sourceFile);
+ }
+ return true;
+ }
+
+ // Test if the uic executable is newer
+ if (outputFileTime.Older(UicConst().ExecutableTime)) {
+ if (reason != nullptr) {
+ *reason = "Generating ";
+ *reason += Quoted(outputFile);
+ *reason += ", because it's older than the uic executable, from ";
+ *reason += Quoted(sourceFile);
+ }
+ return true;
+ }
+
+ return false;
+}
+
+void cmQtAutoMocUic::JobMocT::Process()
+{
+ std::string const& sourceFile = Mapping->SourceFile->FileName;
+ std::string const& outputFile = Mapping->OutputFile;
+
+ // Compose moc command
+ std::vector<std::string> cmd;
+ cmd.push_back(MocConst().Executable);
+ // Add options
+ cmAppend(cmd, MocConst().AllOptions);
+ // Add predefs include
+ if (!MocConst().PredefsFileAbs.empty()) {
+ cmd.emplace_back("--include");
+ cmd.push_back(MocConst().PredefsFileAbs);
+ }
+ cmd.emplace_back("-o");
+ cmd.push_back(outputFile);
+ cmd.push_back(sourceFile);
+
+ // Execute moc command
+ cmWorkerPool::ProcessResultT result;
+ if (RunProcess(GenT::MOC, result, cmd, Reason.get())) {
+ // Moc command success. Print moc output.
+ if (!result.StdOut.empty()) {
+ Log().Info(GenT::MOC, result.StdOut);
+ }
+ } else {
+ // Moc command failed
+ std::string msg = "The moc process failed to compile\n ";
+ msg += Quoted(sourceFile);
+ msg += "\ninto\n ";
+ msg += Quoted(outputFile);
+ if (Mapping->IncluderFiles.empty()) {
+ msg += ".\n";
+ } else {
+ msg += "\nincluded by\n";
+ for (auto const& item : Mapping->IncluderFiles) {
+ msg += " ";
+ msg += Quoted(item->FileName);
+ msg += '\n';
+ }
+ }
+ msg += result.ErrorMessage;
+ LogCommandError(GenT::MOC, msg, cmd, result.StdOut);
+ }
+}
+
+void cmQtAutoMocUic::JobUicT::Process()
+{
+ std::string const& sourceFile = Mapping->SourceFile->FileName;
+ std::string const& outputFile = Mapping->OutputFile;
+
+ // Compose uic command
+ std::vector<std::string> cmd;
+ cmd.push_back(UicConst().Executable);
+ {
+ std::vector<std::string> allOpts = UicConst().TargetOptions;
+ auto optionIt = UicConst().Options.find(sourceFile);
+ if (optionIt != UicConst().Options.end()) {
+ UicMergeOptions(allOpts, optionIt->second,
+ (BaseConst().QtVersionMajor == 5));
+ }
+ cmAppend(cmd, allOpts);
+ }
+ cmd.emplace_back("-o");
+ cmd.emplace_back(outputFile);
+ cmd.emplace_back(sourceFile);
+
+ cmWorkerPool::ProcessResultT result;
+ if (RunProcess(GenT::UIC, result, cmd, Reason.get())) {
+ // Uic command success
+ // Print uic output
+ if (!result.StdOut.empty()) {
+ Log().Info(GenT::UIC, result.StdOut);
+ }
+ } else {
+ // Uic command failed
+ std::string msg = "The uic process failed to compile\n ";
+ msg += Quoted(sourceFile);
+ msg += "\ninto\n ";
+ msg += Quoted(outputFile);
+ msg += "\nincluded by\n";
+ for (auto const& item : Mapping->IncluderFiles) {
+ msg += " ";
+ msg += Quoted(item->FileName);
+ msg += '\n';
+ }
+ msg += result.ErrorMessage;
+ LogCommandError(GenT::UIC, msg, cmd, result.StdOut);
+ }
+}
+
+void cmQtAutoMocUic::JobMocsCompilationT::Process()
+{
+ // Compose mocs compilation file content
+ std::string content =
+ "// This file is autogenerated. Changes will be overwritten.\n";
+
+ if (MocEval().CompFiles.empty()) {
+ // Placeholder content
+ content += "// No files found that require moc or the moc files are "
+ "included\n";
+ content += "enum some_compilers { need_more_than_nothing };\n";
+ } else {
+ // Valid content
+ char const clampB = BaseConst().MultiConfig ? '<' : '"';
+ char const clampE = BaseConst().MultiConfig ? '>' : '"';
+ for (std::string const& mocfile : MocEval().CompFiles) {
+ content += "#include ";
+ content += clampB;
+ content += mocfile;
+ content += clampE;
+ content += '\n';
+ }
+ }
+
+ std::string const& compAbs = MocConst().CompFileAbs;
+ if (cmQtAutoGenerator::FileDiffers(compAbs, content)) {
+ // Actually write mocs compilation file
+ if (Log().Verbose()) {
+ Log().Info(GenT::MOC, "Generating MOC compilation " + compAbs);
+ }
+ if (!FileWrite(compAbs, content)) {
+ LogFileError(GenT::MOC, compAbs,
+ "mocs compilation file writing failed.");
+ }
+ } else if (MocEval().CompUpdated) {
+ // Only touch mocs compilation file
+ if (Log().Verbose()) {
+ Log().Info(GenT::MOC, "Touching mocs compilation " + compAbs);
+ }
+ if (!cmSystemTools::Touch(compAbs, false)) {
+ LogFileError(GenT::MOC, compAbs,
+ "mocs compilation file touching failed.");
+ }
+ }
+}
+
+void cmQtAutoMocUic::JobFinishT::Process()
+{
+ Gen()->AbortSuccess();
+}
+
+cmQtAutoMocUic::cmQtAutoMocUic() = default;
+cmQtAutoMocUic::~cmQtAutoMocUic() = default;
+
+bool cmQtAutoMocUic::Init(cmMakefile* makefile)
+{
+ // 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(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 += ListSep.size();
+ }
+ }
+ return lists;
+ };
+ auto InfoGetConfig = [makefile, this](const char* key) -> std::string {
+ const char* valueConf = nullptr;
+ {
+ std::string keyConf = key;
+ keyConf += '_';
+ keyConf += InfoConfig();
+ valueConf = makefile->GetDefinition(keyConf);
+ }
+ if (valueConf == nullptr) {
+ return 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;
+ };
+ auto LogInfoError = [this](std::string const& msg) -> bool {
+ std::ostringstream err;
+ err << "In " << Quoted(this->InfoFile()) << ":\n" << msg;
+ this->Log().Error(GenT::GEN, err.str());
+ return false;
+ };
+ auto MatchSizes = [&LogInfoError](const char* keyA, const char* keyB,
+ std::size_t sizeA,
+ std::size_t sizeB) -> bool {
+ if (sizeA == sizeB) {
+ return true;
+ }
+ std::ostringstream err;
+ err << "Lists sizes mismatch " << keyA << '(' << sizeA << ") " << keyB
+ << '(' << sizeB << ')';
+ return LogInfoError(err.str());
+ };
+
+ // -- Read info file
+ if (!makefile->ReadListFile(InfoFile())) {
+ return LogInfoError("File processing failed");
+ }
+
+ // -- Meta
+ Logger_.RaiseVerbosity(InfoGet("AM_VERBOSITY"));
+ BaseConst_.MultiConfig = InfoGetBool("AM_MULTI_CONFIG");
+ {
+ unsigned long num = 1;
+ if (cmSystemTools::StringToULong(InfoGet("AM_PARALLEL").c_str(), &num)) {
+ num = std::max<unsigned long>(num, 1);
+ num = std::min<unsigned long>(num, ParallelMax);
+ }
+ WorkerPool_.SetThreadCount(static_cast<unsigned int>(num));
+ }
+ BaseConst_.HeaderExtensions =
+ makefile->GetCMakeInstance()->GetHeaderExtensions();
+
+ // - Files and directories
+ BaseConst_.IncludeProjectDirsBefore =
+ InfoGetBool("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
+ BaseConst_.ProjectSourceDir = InfoGet("AM_CMAKE_SOURCE_DIR");
+ BaseConst_.ProjectBinaryDir = InfoGet("AM_CMAKE_BINARY_DIR");
+ BaseConst_.CurrentSourceDir = InfoGet("AM_CMAKE_CURRENT_SOURCE_DIR");
+ BaseConst_.CurrentBinaryDir = InfoGet("AM_CMAKE_CURRENT_BINARY_DIR");
+ BaseConst_.AutogenBuildDir = InfoGet("AM_BUILD_DIR");
+ if (BaseConst_.AutogenBuildDir.empty()) {
+ return LogInfoError("Autogen build directory missing.");
+ }
+ BaseConst_.AutogenIncludeDir = InfoGetConfig("AM_INCLUDE_DIR");
+ if (BaseConst_.AutogenIncludeDir.empty()) {
+ return LogInfoError("Autogen include directory missing.");
+ }
+ BaseConst_.CMakeExecutable = InfoGetConfig("AM_CMAKE_EXECUTABLE");
+ if (BaseConst_.CMakeExecutable.empty()) {
+ return LogInfoError("CMake executable file name missing.");
+ }
+ if (!BaseConst_.CMakeExecutableTime.Load(BaseConst_.CMakeExecutable)) {
+ std::string error = "The CMake executable ";
+ error += Quoted(BaseConst_.CMakeExecutable);
+ error += " does not exist.";
+ return LogInfoError(error);
+ }
+ BaseConst_.ParseCacheFile = InfoGetConfig("AM_PARSE_CACHE_FILE");
+ if (BaseConst_.ParseCacheFile.empty()) {
+ return LogInfoError("Parse cache file name missing.");
+ }
+
+ // - Settings file
+ SettingsFile_ = InfoGetConfig("AM_SETTINGS_FILE");
+ if (SettingsFile_.empty()) {
+ return LogInfoError("Settings file name missing.");
+ }
+
+ // - Qt environment
+ {
+ unsigned long qtv = BaseConst_.QtVersionMajor;
+ if (cmSystemTools::StringToULong(InfoGet("AM_QT_VERSION_MAJOR").c_str(),
+ &qtv)) {
+ BaseConst_.QtVersionMajor = static_cast<unsigned int>(qtv);
+ }
+ }
+
+ // - Moc
+ MocConst_.Executable = InfoGet("AM_QT_MOC_EXECUTABLE");
+ if (!MocConst().Executable.empty()) {
+ MocConst_.Enabled = true;
+ // Load the executable file time
+ if (!MocConst_.ExecutableTime.Load(MocConst_.Executable)) {
+ std::string error = "The moc executable ";
+ error += Quoted(MocConst_.Executable);
+ error += " does not exist.";
+ return LogInfoError(error);
+ }
+ for (std::string& sfl : InfoGetList("AM_MOC_SKIP")) {
+ MocConst_.SkipList.insert(std::move(sfl));
+ }
+ MocConst_.Definitions = InfoGetConfigList("AM_MOC_DEFINITIONS");
+ MocConst_.IncludePaths = InfoGetConfigList("AM_MOC_INCLUDES");
+ MocConst_.Options = InfoGetList("AM_MOC_OPTIONS");
+ MocConst_.RelaxedMode = InfoGetBool("AM_MOC_RELAXED_MODE");
+ for (std::string const& item : InfoGetList("AM_MOC_MACRO_NAMES")) {
+ MocConst_.MacroFilters.emplace_back(
+ item, ("[\n][ \t]*{?[ \t]*" + item).append("[^a-zA-Z0-9_]"));
+ }
+ {
+ auto addFilter = [this, &LogInfoError](std::string const& key,
+ std::string const& exp) -> bool {
+ auto filterErr = [&LogInfoError, &key, &exp](const char* err) -> bool {
+ std::ostringstream ferr;
+ ferr << "AUTOMOC_DEPEND_FILTERS: " << err << '\n';
+ ferr << " Key: " << Quoted(key) << '\n';
+ ferr << " Exp: " << Quoted(exp) << '\n';
+ return LogInfoError(ferr.str());
+ };
+ if (key.empty()) {
+ return filterErr("Key is empty");
+ }
+ if (exp.empty()) {
+ return filterErr("Regular expression is empty");
+ }
+ this->MocConst_.DependFilters.emplace_back(key, exp);
+ if (!this->MocConst_.DependFilters.back().Exp.is_valid()) {
+ return filterErr("Regular expression compiling failed");
+ }
+ return true;
+ };
+
+ // Insert default filter for Q_PLUGIN_METADATA
+ if (BaseConst().QtVersionMajor != 4) {
+ if (!addFilter("Q_PLUGIN_METADATA",
+ "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
+ "[^\\)]*FILE[ \t]*\"([^\"]+)\"")) {
+ return false;
+ }
+ }
+ // Insert user defined dependency filters
+ std::vector<std::string> flts = InfoGetList("AM_MOC_DEPEND_FILTERS");
+ if ((flts.size() % 2) != 0) {
+ return LogInfoError(
+ "AUTOMOC_DEPEND_FILTERS list size is not a multiple of 2");
+ }
+ for (auto itC = flts.begin(), itE = flts.end(); itC != itE; itC += 2) {
+ if (!addFilter(*itC, *(itC + 1))) {
+ return false;
+ }
+ }
+ }
+ MocConst_.PredefsCmd = InfoGetList("AM_MOC_PREDEFS_CMD");
+ }
+
+ // - Uic
+ UicConst_.Executable = InfoGet("AM_QT_UIC_EXECUTABLE");
+ if (!UicConst().Executable.empty()) {
+ UicConst_.Enabled = true;
+ // Load the executable file time
+ if (!UicConst_.ExecutableTime.Load(UicConst_.Executable)) {
+ std::string error = "The uic executable ";
+ error += Quoted(UicConst_.Executable);
+ error += " does not exist.";
+ return LogInfoError(error);
+ }
+ for (std::string& sfl : InfoGetList("AM_UIC_SKIP")) {
+ UicConst_.SkipList.insert(std::move(sfl));
+ }
+ UicConst_.SearchPaths = InfoGetList("AM_UIC_SEARCH_PATHS");
+ UicConst_.TargetOptions = InfoGetConfigList("AM_UIC_TARGET_OPTIONS");
+ {
+ const char* keyFiles = "AM_UIC_OPTIONS_FILES";
+ const char* keyOpts = "AM_UIC_OPTIONS_OPTIONS";
+ auto sources = InfoGetList(keyFiles);
+ auto options = InfoGetLists(keyOpts);
+ if (!MatchSizes(keyFiles, keyOpts, sources.size(), options.size())) {
+ return false;
+ }
+ auto fitEnd = sources.cend();
+ auto fit = sources.begin();
+ auto oit = options.begin();
+ while (fit != fitEnd) {
+ UicConst_.Options[*fit] = std::move(*oit);
+ ++fit;
+ ++oit;
+ }
+ }
+ }
+
+ // - Headers and sources
+ {
+ auto makeSource =
+ [&LogInfoError](std::string const& fileName,
+ std::string const& fileFlags) -> SourceFileHandleT {
+ if (fileFlags.size() != 2) {
+ LogInfoError("Invalid file flags string size");
+ return SourceFileHandleT();
+ }
+ cmFileTime fileTime;
+ if (!fileTime.Load(fileName)) {
+ LogInfoError("The source file " + cmQtAutoGen::Quoted(fileName) +
+ " does not exist.");
+ return SourceFileHandleT();
+ }
+ SourceFileHandleT sfh = std::make_shared<SourceFileT>(fileName);
+ sfh->FileTime = fileTime;
+ sfh->Moc = (fileFlags[0] == 'M');
+ sfh->Uic = (fileFlags[1] == 'U');
+ return sfh;
+ };
+
+ // Headers
+ {
+ // Get file lists
+ const char *keyFiles = "AM_HEADERS", *keyFlags = "AM_HEADERS_FLAGS";
+ std::vector<std::string> files = InfoGetList(keyFiles);
+ std::vector<std::string> flags = InfoGetList(keyFlags);
+ std::vector<std::string> builds;
+ if (!MatchSizes(keyFiles, keyFlags, files.size(), flags.size())) {
+ return false;
+ }
+ if (MocConst().Enabled) {
+ const char* keyPaths = "AM_HEADERS_BUILD_PATHS";
+ builds = InfoGetList(keyPaths);
+ if (!MatchSizes(keyFiles, keyPaths, files.size(), builds.size())) {
+ return false;
+ }
+ }
+ // Process file lists
+ for (std::size_t ii = 0; ii != files.size(); ++ii) {
+ std::string& fileName(files[ii]);
+ SourceFileHandleT sfh = makeSource(fileName, flags[ii]);
+ if (!sfh) {
+ return false;
+ }
+ if (MocConst().Enabled) {
+ sfh->BuildPath = std::move(builds[ii]);
+ if (sfh->BuildPath.empty()) {
+ Log().ErrorFile(GenT::GEN, this->InfoFile(),
+ "Header file build path is empty");
+ return false;
+ }
+ }
+ BaseEval().Headers.emplace(std::move(fileName), std::move(sfh));
+ }
+ }
+
+ // Sources
+ {
+ const char *keyFiles = "AM_SOURCES", *keyFlags = "AM_SOURCES_FLAGS";
+ std::vector<std::string> files = InfoGetList(keyFiles);
+ std::vector<std::string> flags = InfoGetList(keyFlags);
+ if (!MatchSizes(keyFiles, keyFlags, files.size(), flags.size())) {
+ return false;
+ }
+ // Process file lists
+ for (std::size_t ii = 0; ii != files.size(); ++ii) {
+ std::string& fileName(files[ii]);
+ SourceFileHandleT sfh = makeSource(fileName, flags[ii]);
+ if (!sfh) {
+ return false;
+ }
+ BaseEval().Sources.emplace(std::move(fileName), std::move(sfh));
+ }
+ }
+ }
+
+ // Init derived information
+ // ------------------------
+
+ // Moc variables
+ if (MocConst().Enabled) {
+ // Mocs compilation file
+ MocConst_.CompFileAbs = AbsoluteBuildPath("mocs_compilation.cpp");
+
+ // Moc predefs file
+ if (!MocConst_.PredefsCmd.empty()) {
+ MocConst_.PredefsFileRel = "moc_predefs";
+ if (BaseConst_.MultiConfig) {
+ MocConst_.PredefsFileRel += '_';
+ MocConst_.PredefsFileRel += InfoConfig();
+ }
+ MocConst_.PredefsFileRel += ".h";
+ MocConst_.PredefsFileAbs = AbsoluteBuildPath(MocConst().PredefsFileRel);
+ }
+
+ // Sort include directories on demand
+ if (BaseConst().IncludeProjectDirsBefore) {
+ // Move strings to temporary list
+ std::list<std::string> includes(MocConst().IncludePaths.begin(),
+ MocConst().IncludePaths.end());
+ MocConst_.IncludePaths.clear();
+ MocConst_.IncludePaths.reserve(includes.size());
+ // Append project directories only
+ {
+ std::array<std::string const*, 2> const movePaths = {
+ { &BaseConst().ProjectBinaryDir, &BaseConst().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())) {
+ MocConst_.IncludePaths.push_back(path);
+ it = includes.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ }
+ }
+ // Append remaining directories
+ MocConst_.IncludePaths.insert(MocConst_.IncludePaths.end(),
+ includes.begin(), includes.end());
+ }
+ // Compose moc includes list
+ {
+ std::set<std::string> frameworkPaths;
+ for (std::string const& path : MocConst().IncludePaths) {
+ MocConst_.Includes.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);
+ frameworkPaths.emplace(cmSystemTools::JoinPath(
+ pathComponents.begin(), pathComponents.end() - 2));
+ }
+ }
+ // Append framework includes
+ for (std::string const& path : frameworkPaths) {
+ MocConst_.Includes.emplace_back("-F");
+ MocConst_.Includes.push_back(path);
+ }
+ }
+ // Setup single list with all options
+ {
+ // Add includes
+ MocConst_.AllOptions.insert(MocConst_.AllOptions.end(),
+ MocConst().Includes.begin(),
+ MocConst().Includes.end());
+ // Add definitions
+ for (std::string const& def : MocConst().Definitions) {
+ MocConst_.AllOptions.push_back("-D" + def);
+ }
+ // Add options
+ MocConst_.AllOptions.insert(MocConst_.AllOptions.end(),
+ MocConst().Options.begin(),
+ MocConst().Options.end());
+ }
+ }
+
+ return true;
+}
+
+template <class JOBTYPE>
+void cmQtAutoMocUic::CreateParseJobs(SourceFileMapT const& sourceMap)
+{
+ cmFileTime const parseCacheTime = BaseEval().ParseCacheTime;
+ ParseCacheT& parseCache = BaseEval().ParseCache;
+ for (auto& src : sourceMap) {
+ // Get or create the file parse data reference
+ ParseCacheT::GetOrInsertT cacheEntry = parseCache.GetOrInsert(src.first);
+ src.second->ParseData = std::move(cacheEntry.first);
+ // Create a parse job if the cache file was missing or is older
+ if (cacheEntry.second || src.second->FileTime.Newer(parseCacheTime)) {
+ BaseEval().ParseCacheChanged = true;
+ WorkerPool().EmplaceJob<JOBTYPE>(src.second);
+ }
+ }
+}
+
+void cmQtAutoMocUic::InitJobs()
+{
+ // Add moc_predefs.h job
+ if (MocConst().Enabled && !MocConst().PredefsCmd.empty()) {
+ WorkerPool().EmplaceJob<JobMocPredefsT>();
+ }
+ // Add header parse jobs
+ CreateParseJobs<JobParseHeaderT>(BaseEval().Headers);
+ // Add source parse jobs
+ CreateParseJobs<JobParseSourceT>(BaseEval().Sources);
+ // Add evaluate job
+ WorkerPool().EmplaceJob<JobEvaluateT>();
+}
+
+bool cmQtAutoMocUic::Process()
+{
+ SettingsFileRead();
+ ParseCacheRead();
+ if (!CreateDirectories()) {
+ return false;
+ }
+ InitJobs();
+ if (!WorkerPool_.Process(this)) {
+ return false;
+ }
+ if (JobError_) {
+ return false;
+ }
+ if (!ParseCacheWrite()) {
+ return false;
+ }
+ if (!SettingsFileWrite()) {
+ return false;
+ }
+ return true;
+}
+
+void cmQtAutoMocUic::SettingsFileRead()
+{
+ // Compose current settings strings
+ {
+ cmCryptoHash cryptoHash(cmCryptoHash::AlgoSHA256);
+ std::string const sep(";");
+ auto cha = [&cryptoHash, &sep](std::string const& value) {
+ cryptoHash.Append(value);
+ cryptoHash.Append(sep);
+ };
+
+ if (MocConst_.Enabled) {
+ cryptoHash.Initialize();
+ cha(MocConst().Executable);
+ for (auto const& value : MocConst().AllOptions) {
+ cha(value);
+ }
+ cha(BaseConst().IncludeProjectDirsBefore ? "TRUE" : "FALSE");
+ for (auto const& value : MocConst().PredefsCmd) {
+ cha(value);
+ }
+ for (auto const& filter : MocConst().DependFilters) {
+ cha(filter.Key);
+ }
+ for (auto const& filter : MocConst().MacroFilters) {
+ cha(filter.Key);
+ }
+ SettingsStringMoc_ = cryptoHash.FinalizeHex();
+ }
+
+ if (UicConst().Enabled) {
+ cryptoHash.Initialize();
+ cha(UicConst().Executable);
+ for (auto const& value : UicConst().TargetOptions) {
+ cha(value);
+ }
+ for (const auto& item : UicConst().Options) {
+ cha(item.first);
+ for (auto const& svalue : item.second) {
+ cha(svalue);
+ }
+ }
+ SettingsStringUic_ = cryptoHash.FinalizeHex();
+ }
+ }
+
+ // Read old settings and compare
+ {
+ std::string content;
+ if (cmQtAutoGenerator::FileRead(content, SettingsFile_)) {
+ if (MocConst().Enabled) {
+ if (SettingsStringMoc_ != SettingsFind(content, "moc")) {
+ MocConst_.SettingsChanged = true;
+ }
+ }
+ if (UicConst().Enabled) {
+ if (SettingsStringUic_ != SettingsFind(content, "uic")) {
+ UicConst_.SettingsChanged = 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 (MocConst().SettingsChanged || UicConst().SettingsChanged) {
+ cmSystemTools::RemoveFile(SettingsFile_);
+ }
+ } else {
+ // Settings file read failed
+ if (MocConst().Enabled) {
+ MocConst_.SettingsChanged = true;
+ }
+ if (UicConst().Enabled) {
+ UicConst_.SettingsChanged = true;
+ }
+ }
+ }
+}
+
+bool cmQtAutoMocUic::SettingsFileWrite()
+{
+ // Only write if any setting changed
+ if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
+ if (Log().Verbose()) {
+ Log().Info(GenT::GEN, "Writing settings file " + Quoted(SettingsFile_));
+ }
+ // Compose settings file content
+ std::string content;
+ {
+ auto SettingAppend = [&content](const char* key,
+ std::string const& value) {
+ if (!value.empty()) {
+ content += key;
+ content += ':';
+ content += value;
+ content += '\n';
+ }
+ };
+ SettingAppend("moc", SettingsStringMoc_);
+ SettingAppend("uic", SettingsStringUic_);
+ }
+ // Write settings file
+ std::string error;
+ if (!cmQtAutoGenerator::FileWrite(SettingsFile_, content, &error)) {
+ Log().ErrorFile(GenT::GEN, SettingsFile_,
+ "Settings file writing failed. " + error);
+ // Remove old settings file to trigger a full rebuild on the next run
+ cmSystemTools::RemoveFile(SettingsFile_);
+ return false;
+ }
+ }
+ return true;
+}
+
+void cmQtAutoMocUic::ParseCacheRead()
+{
+ const char* reason = nullptr;
+ // Don't read the cache if it is invalid
+ if (!BaseEval().ParseCacheTime.Load(BaseConst().ParseCacheFile)) {
+ reason = "Refreshing parse cache because it doesn't exist.";
+ } else if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
+ reason = "Refreshing parse cache because the settings changed.";
+ } else if (BaseEval().ParseCacheTime.Older(
+ BaseConst().CMakeExecutableTime)) {
+ reason =
+ "Refreshing parse cache because it is older than the CMake executable.";
+ }
+
+ if (reason != nullptr) {
+ // Don't read but refresh the complete parse cache
+ if (Log().Verbose()) {
+ Log().Info(GenT::GEN, reason);
+ }
+ BaseEval().ParseCacheChanged = true;
+ } else {
+ // Read parse cache
+ BaseEval().ParseCache.ReadFromFile(BaseConst().ParseCacheFile);
+ }
+}
+
+bool cmQtAutoMocUic::ParseCacheWrite()
+{
+ if (BaseEval().ParseCacheChanged) {
+ if (Log().Verbose()) {
+ Log().Info(GenT::GEN,
+ "Writing parse cache file " +
+ Quoted(BaseConst().ParseCacheFile));
+ }
+ if (!BaseEval().ParseCache.WriteToFile(BaseConst().ParseCacheFile)) {
+ Log().ErrorFile(GenT::GEN, BaseConst().ParseCacheFile,
+ "Parse cache file writing failed.");
+ return false;
+ }
+ }
+ return true;
+}
+
+bool cmQtAutoMocUic::CreateDirectories()
+{
+ // Create AUTOGEN include directory
+ if (!cmSystemTools::MakeDirectory(BaseConst().AutogenIncludeDir)) {
+ Log().ErrorFile(GenT::GEN, BaseConst().AutogenIncludeDir,
+ "Could not create directory.");
+ return false;
+ }
+ return true;
+}
+
+void cmQtAutoMocUic::Abort(bool error)
+{
+ if (error) {
+ JobError_.store(true);
+ }
+ WorkerPool_.Abort();
+}
+
+std::string cmQtAutoMocUic::AbsoluteBuildPath(
+ std::string const& relativePath) const
+{
+ std::string res(BaseConst().AutogenBuildDir);
+ res += '/';
+ res += relativePath;
+ return res;
+}
+
+std::string cmQtAutoMocUic::AbsoluteIncludePath(
+ std::string const& relativePath) const
+{
+ std::string res(BaseConst().AutogenIncludeDir);
+ res += '/';
+ res += relativePath;
+ return res;
+}
diff --git a/Source/cmQtAutoMocUic.h b/Source/cmQtAutoMocUic.h
new file mode 100644
index 000000000..81546cc18
--- /dev/null
+++ b/Source/cmQtAutoMocUic.h
@@ -0,0 +1,576 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmQtAutoMocUic_h
+#define cmQtAutoMocUic_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cmFileTime.h"
+#include "cmQtAutoGen.h"
+#include "cmQtAutoGenerator.h"
+#include "cmWorkerPool.h"
+#include "cmsys/RegularExpression.hxx"
+
+#include <atomic>
+#include <cstddef>
+#include <map>
+#include <memory> // IWYU pragma: keep
+#include <set>
+#include <string>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+class cmMakefile;
+
+/** \class cmQtAutoMocUic
+ * \brief AUTOMOC and AUTOUIC generator
+ */
+class cmQtAutoMocUic : public cmQtAutoGenerator
+{
+public:
+ cmQtAutoMocUic();
+ ~cmQtAutoMocUic() override;
+
+ cmQtAutoMocUic(cmQtAutoMocUic const&) = delete;
+ cmQtAutoMocUic& operator=(cmQtAutoMocUic const&) = delete;
+
+public:
+ // -- Types
+
+ /**
+ * Search key plus regular expression pair
+ */
+ struct KeyExpT
+ {
+ KeyExpT() = default;
+
+ KeyExpT(const char* key, const char* exp)
+ : Key(key)
+ , Exp(exp)
+ {
+ }
+
+ KeyExpT(std::string key, std::string const& exp)
+ : Key(std::move(key))
+ , Exp(exp)
+ {
+ }
+
+ std::string Key;
+ cmsys::RegularExpression Exp;
+ };
+
+ /**
+ * Include string with sub parts
+ */
+ struct IncludeKeyT
+ {
+ IncludeKeyT(std::string const& key, std::size_t basePrefixLength);
+
+ std::string Key; // Full include string
+ std::string Dir; // Include directory
+ std::string Base; // Base part of the include file name
+ };
+
+ /**
+ * Source file parsing cache
+ */
+ class ParseCacheT
+ {
+ public:
+ // -- Types
+ /**
+ * Entry of the file parsing cache
+ */
+ struct FileT
+ {
+ void Clear();
+
+ struct MocT
+ {
+ std::string Macro;
+ struct IncludeT
+ {
+ std::vector<IncludeKeyT> Underscore;
+ std::vector<IncludeKeyT> Dot;
+ } Include;
+ std::vector<std::string> Depends;
+ } Moc;
+
+ struct UicT
+ {
+ std::vector<IncludeKeyT> Include;
+ std::vector<std::string> Depends;
+ } Uic;
+ };
+ typedef std::shared_ptr<FileT> FileHandleT;
+ typedef std::pair<FileHandleT, bool> GetOrInsertT;
+
+ public:
+ ParseCacheT();
+ ~ParseCacheT();
+
+ void Clear();
+
+ bool ReadFromFile(std::string const& fileName);
+ bool WriteToFile(std::string const& fileName);
+
+ //! Might return an invalid handle
+ FileHandleT Get(std::string const& fileName) const;
+ //! Always returns a valid handle
+ GetOrInsertT GetOrInsert(std::string const& fileName);
+
+ private:
+ std::unordered_map<std::string, FileHandleT> Map_;
+ };
+
+ /**
+ * Source file data
+ */
+ class SourceFileT
+ {
+ public:
+ SourceFileT(std::string fileName)
+ : FileName(std::move(fileName))
+ {
+ }
+
+ public:
+ std::string FileName;
+ cmFileTime FileTime;
+ ParseCacheT::FileHandleT ParseData;
+ std::string BuildPath;
+ bool Moc = false;
+ bool Uic = false;
+ };
+ typedef std::shared_ptr<SourceFileT> SourceFileHandleT;
+ typedef std::map<std::string, SourceFileHandleT> SourceFileMapT;
+
+ /**
+ * Meta compiler file mapping information
+ */
+ struct MappingT
+ {
+ SourceFileHandleT SourceFile;
+ std::string OutputFile;
+ std::string IncludeString;
+ std::vector<SourceFileHandleT> IncluderFiles;
+ };
+ typedef std::shared_ptr<MappingT> MappingHandleT;
+ typedef std::map<std::string, MappingHandleT> MappingMapT;
+
+ /**
+ * Common settings
+ */
+ class BaseSettingsT
+ {
+ public:
+ // -- Constructors
+ BaseSettingsT();
+ ~BaseSettingsT();
+
+ BaseSettingsT(BaseSettingsT const&) = delete;
+ BaseSettingsT& operator=(BaseSettingsT const&) = delete;
+
+ // -- Attributes
+ // - Config
+ bool MultiConfig = false;
+ bool IncludeProjectDirsBefore = false;
+ unsigned int QtVersionMajor = 4;
+ // - Directories
+ std::string ProjectSourceDir;
+ std::string ProjectBinaryDir;
+ std::string CurrentSourceDir;
+ std::string CurrentBinaryDir;
+ std::string AutogenBuildDir;
+ std::string AutogenIncludeDir;
+ // - Files
+ std::string CMakeExecutable;
+ cmFileTime CMakeExecutableTime;
+ std::string ParseCacheFile;
+ std::vector<std::string> HeaderExtensions;
+ };
+
+ /**
+ * Shared common variables
+ */
+ class BaseEvalT
+ {
+ public:
+ // -- Parse Cache
+ bool ParseCacheChanged = false;
+ cmFileTime ParseCacheTime;
+ ParseCacheT ParseCache;
+
+ // -- Sources
+ SourceFileMapT Headers;
+ SourceFileMapT Sources;
+ };
+
+ /**
+ * Moc settings
+ */
+ class MocSettingsT
+ {
+ public:
+ // -- Constructors
+ MocSettingsT();
+ ~MocSettingsT();
+
+ MocSettingsT(MocSettingsT const&) = delete;
+ MocSettingsT& operator=(MocSettingsT const&) = delete;
+
+ // -- Const methods
+ bool skipped(std::string const& fileName) const;
+ std::string MacrosString() const;
+
+ // -- Attributes
+ bool Enabled = false;
+ bool SettingsChanged = false;
+ bool RelaxedMode = false;
+ cmFileTime ExecutableTime;
+ std::string Executable;
+ std::string CompFileAbs;
+ std::string PredefsFileRel;
+ std::string PredefsFileAbs;
+ std::unordered_set<std::string> SkipList;
+ std::vector<std::string> IncludePaths;
+ std::vector<std::string> Includes;
+ std::vector<std::string> Definitions;
+ std::vector<std::string> Options;
+ std::vector<std::string> AllOptions;
+ std::vector<std::string> PredefsCmd;
+ std::vector<KeyExpT> DependFilters;
+ std::vector<KeyExpT> MacroFilters;
+ cmsys::RegularExpression RegExpInclude;
+ };
+
+ /**
+ * Moc shared variables
+ */
+ class MocEvalT
+ {
+ public:
+ // -- predefines file
+ cmFileTime PredefsTime;
+ // -- Mappings
+ MappingMapT HeaderMappings;
+ MappingMapT SourceMappings;
+ MappingMapT Includes;
+ // -- Discovered files
+ SourceFileMapT HeadersDiscovered;
+ // -- Mocs compilation
+ bool CompUpdated = false;
+ std::vector<std::string> CompFiles;
+ };
+
+ /**
+ * Uic settings
+ */
+ class UicSettingsT
+ {
+ public:
+ UicSettingsT();
+ ~UicSettingsT();
+
+ UicSettingsT(UicSettingsT const&) = delete;
+ UicSettingsT& operator=(UicSettingsT const&) = delete;
+
+ // -- Const methods
+ bool skipped(std::string const& fileName) const;
+
+ // -- Attributes
+ bool Enabled = false;
+ bool SettingsChanged = false;
+ cmFileTime ExecutableTime;
+ std::string Executable;
+ std::unordered_set<std::string> SkipList;
+ std::vector<std::string> TargetOptions;
+ std::map<std::string, std::vector<std::string>> Options;
+ std::vector<std::string> SearchPaths;
+ cmsys::RegularExpression RegExpInclude;
+ };
+
+ /**
+ * Uic shared variables
+ */
+ class UicEvalT
+ {
+ public:
+ SourceFileMapT UiFiles;
+ MappingMapT Includes;
+ };
+
+ /**
+ * Abstract job class for concurrent job processing
+ */
+ class JobT : public cmWorkerPool::JobT
+ {
+ protected:
+ /**
+ * @brief Protected default constructor
+ */
+ JobT(bool fence = false)
+ : cmWorkerPool::JobT(fence)
+ {
+ }
+
+ //! Get the generator. Only valid during Process() call!
+ cmQtAutoMocUic* Gen() const
+ {
+ return static_cast<cmQtAutoMocUic*>(UserData());
+ };
+
+ // -- Accessors. Only valid during Process() call!
+ Logger const& Log() const { return Gen()->Log(); }
+ BaseSettingsT const& BaseConst() const { return Gen()->BaseConst(); }
+ BaseEvalT& BaseEval() const { return Gen()->BaseEval(); }
+ MocSettingsT const& MocConst() const { return Gen()->MocConst(); }
+ MocEvalT& MocEval() const { return Gen()->MocEval(); }
+ UicSettingsT const& UicConst() const { return Gen()->UicConst(); }
+ UicEvalT& UicEval() const { return Gen()->UicEval(); }
+
+ // -- Error logging with automatic abort
+ void LogError(GenT genType, std::string const& message) const;
+ void LogFileError(GenT genType, std::string const& filename,
+ std::string const& message) const;
+ void LogCommandError(GenT genType, std::string const& message,
+ std::vector<std::string> const& command,
+ std::string const& output) const;
+
+ /**
+ * @brief Run an external process. Use only during Process() call!
+ */
+ bool RunProcess(GenT genType, cmWorkerPool::ProcessResultT& result,
+ std::vector<std::string> const& command,
+ std::string* infoMessage = nullptr);
+ };
+
+ /**
+ * Fence job utility class
+ */
+ class JobFenceT : public JobT
+ {
+ public:
+ JobFenceT()
+ : JobT(true)
+ {
+ }
+ void Process() override{};
+ };
+
+ /**
+ * Generate moc_predefs.h
+ */
+ class JobMocPredefsT : public JobFenceT
+ {
+ void Process() override;
+ bool Update(std::string* reason) const;
+ };
+
+ /**
+ * File parse job base class
+ */
+ class JobParseT : public JobT
+ {
+ public:
+ JobParseT(SourceFileHandleT fileHandle)
+ : FileHandle(std::move(fileHandle))
+ {
+ }
+
+ protected:
+ bool ReadFile();
+ void CreateKeys(std::vector<IncludeKeyT>& container,
+ std::set<std::string> const& source,
+ std::size_t basePrefixLength);
+ void MocMacro();
+ void MocDependecies();
+ void MocIncludes();
+ void UicIncludes();
+
+ protected:
+ SourceFileHandleT FileHandle;
+ std::string Content;
+ };
+
+ /**
+ * Header file parse job
+ */
+ class JobParseHeaderT : public JobParseT
+ {
+ public:
+ using JobParseT::JobParseT;
+ void Process() override;
+ };
+
+ /**
+ * Source file parse job
+ */
+ class JobParseSourceT : public JobParseT
+ {
+ public:
+ using JobParseT::JobParseT;
+ void Process() override;
+ };
+
+ /**
+ * Evaluate parsed files
+ */
+ class JobEvaluateT : public JobFenceT
+ {
+ void Process() override;
+
+ // -- Moc
+ bool MocEvalHeader(SourceFileHandleT source);
+ bool MocEvalSource(SourceFileHandleT const& source);
+ SourceFileHandleT MocFindIncludedHeader(
+ std::string const& includerDir, std::string const& includeBase) const;
+ SourceFileHandleT MocFindHeader(std::string const& basePath) const;
+ std::string MocMessageTestHeaders(std::string const& fileBase) const;
+ bool MocRegisterIncluded(std::string const& includeString,
+ SourceFileHandleT includerFileHandle,
+ SourceFileHandleT sourceFileHandle,
+ bool sourceIsHeader) const;
+ void MocRegisterMapping(MappingHandleT mappingHandle,
+ bool sourceIsHeader) const;
+
+ // -- Uic
+ bool UicEval(SourceFileMapT const& fileMap);
+ bool UicEvalFile(SourceFileHandleT const& sourceFileHandle);
+ SourceFileHandleT UicFindIncludedUi(std::string const& sourceFile,
+ std::string const& sourceDir,
+ IncludeKeyT const& incKey) const;
+ bool UicRegisterMapping(std::string const& includeString,
+ SourceFileHandleT uiFileHandle,
+ SourceFileHandleT includerFileHandle);
+ };
+
+ /**
+ * Generates moc/uic jobs
+ */
+ class JobGenerateT : public JobFenceT
+ {
+ void Process() override;
+ // -- Moc
+ bool MocGenerate(MappingHandleT const& mapping, bool compFile) const;
+ bool MocUpdate(MappingT const& mapping, std::string* reason) const;
+ std::pair<std::string, cmFileTime> MocFindDependency(
+ std::string const& sourceDir, std::string const& includeString) const;
+ // -- Uic
+ bool UicGenerate(MappingHandleT const& mapping) const;
+ bool UicUpdate(MappingT const& mapping, std::string* reason) const;
+ };
+
+ /**
+ * File compiling base job
+ */
+ class JobCompileT : public JobT
+ {
+ public:
+ JobCompileT(MappingHandleT uicMapping, std::unique_ptr<std::string> reason)
+ : Mapping(std::move(uicMapping))
+ , Reason(std::move(reason))
+ {
+ }
+
+ protected:
+ MappingHandleT Mapping;
+ std::unique_ptr<std::string> Reason;
+ };
+
+ /**
+ * moc compiles a file
+ */
+ class JobMocT : public JobCompileT
+ {
+ public:
+ using JobCompileT::JobCompileT;
+ void Process() override;
+ };
+
+ /**
+ * uic compiles a file
+ */
+ class JobUicT : public JobCompileT
+ {
+ public:
+ using JobCompileT::JobCompileT;
+ void Process() override;
+ };
+
+ /// @brief Generate mocs_compilation.cpp
+ ///
+ class JobMocsCompilationT : public JobFenceT
+ {
+ private:
+ void Process() override;
+ };
+
+ /// @brief The last job
+ ///
+ class JobFinishT : public JobFenceT
+ {
+ private:
+ void Process() override;
+ };
+
+ // -- Const settings interface
+ BaseSettingsT const& BaseConst() const { return this->BaseConst_; }
+ BaseEvalT& BaseEval() { return this->BaseEval_; }
+ MocSettingsT const& MocConst() const { return this->MocConst_; }
+ MocEvalT& MocEval() { return this->MocEval_; }
+ UicSettingsT const& UicConst() const { return this->UicConst_; }
+ UicEvalT& UicEval() { return this->UicEval_; }
+
+ // -- Parallel job processing interface
+ cmWorkerPool& WorkerPool() { return WorkerPool_; }
+ void AbortError() { Abort(true); }
+ void AbortSuccess() { Abort(false); }
+
+ // -- Utility
+ std::string AbsoluteBuildPath(std::string const& relativePath) const;
+ std::string AbsoluteIncludePath(std::string const& relativePath) const;
+ template <class JOBTYPE>
+ void CreateParseJobs(SourceFileMapT const& sourceMap);
+
+private:
+ // -- Utility accessors
+ Logger const& Log() const { return Logger_; }
+ // -- Abstract processing interface
+ bool Init(cmMakefile* makefile) override;
+ void InitJobs();
+ bool Process() override;
+ // -- Settings file
+ void SettingsFileRead();
+ bool SettingsFileWrite();
+ // -- Parse cache
+ void ParseCacheRead();
+ bool ParseCacheWrite();
+ // -- Thread processing
+ void Abort(bool error);
+ // -- Generation
+ bool CreateDirectories();
+
+private:
+ // -- Utility
+ Logger Logger_;
+ // -- Settings
+ BaseSettingsT BaseConst_;
+ BaseEvalT BaseEval_;
+ MocSettingsT MocConst_;
+ MocEvalT MocEval_;
+ UicSettingsT UicConst_;
+ UicEvalT UicEval_;
+ // -- Settings file
+ std::string SettingsFile_;
+ std::string SettingsStringMoc_;
+ std::string SettingsStringUic_;
+ // -- Worker thread pool
+ std::atomic<bool> JobError_ = ATOMIC_VAR_INIT(false);
+ cmWorkerPool WorkerPool_;
+};
+
+#endif
diff --git a/Source/cmQtAutoRcc.cxx b/Source/cmQtAutoRcc.cxx
new file mode 100644
index 000000000..20885df93
--- /dev/null
+++ b/Source/cmQtAutoRcc.cxx
@@ -0,0 +1,523 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmQtAutoRcc.h"
+#include "cmQtAutoGen.h"
+
+#include <sstream>
+
+#include "cmAlgorithms.h"
+#include "cmCryptoHash.h"
+#include "cmDuration.h"
+#include "cmFileLockResult.h"
+#include "cmMakefile.h"
+#include "cmProcessOutput.h"
+#include "cmSystemTools.h"
+
+// -- Class methods
+
+cmQtAutoRcc::cmQtAutoRcc() = default;
+
+cmQtAutoRcc::~cmQtAutoRcc() = default;
+
+bool cmQtAutoRcc::Init(cmMakefile* makefile)
+{
+ // -- Utility lambdas
+ auto InfoGet = [makefile](std::string const& key) {
+ return makefile->GetSafeDefinition(key);
+ };
+ auto InfoGetList =
+ [makefile](std::string const& key) -> std::vector<std::string> {
+ std::vector<std::string> list;
+ cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition(key), list);
+ return list;
+ };
+ auto InfoGetConfig = [makefile,
+ this](std::string const& key) -> std::string {
+ const char* valueConf = nullptr;
+ {
+ std::string keyConf = key;
+ keyConf += '_';
+ keyConf += InfoConfig();
+ valueConf = makefile->GetDefinition(keyConf);
+ }
+ if (valueConf == nullptr) {
+ return makefile->GetSafeDefinition(key);
+ }
+ return std::string(valueConf);
+ };
+ auto InfoGetConfigList =
+ [&InfoGetConfig](std::string const& key) -> std::vector<std::string> {
+ std::vector<std::string> list;
+ cmSystemTools::ExpandListArgument(InfoGetConfig(key), list);
+ return list;
+ };
+ auto LogInfoError = [this](std::string const& msg) -> bool {
+ std::ostringstream err;
+ err << "In " << Quoted(this->InfoFile()) << ":\n" << msg;
+ this->Log().Error(GenT::RCC, err.str());
+ return false;
+ };
+
+ // -- Read info file
+ if (!makefile->ReadListFile(InfoFile())) {
+ return LogInfoError("File processing failed.");
+ }
+
+ // - Configurations
+ Logger_.RaiseVerbosity(InfoGet("ARCC_VERBOSITY"));
+ MultiConfig_ = makefile->IsOn("ARCC_MULTI_CONFIG");
+
+ // - Directories
+ AutogenBuildDir_ = InfoGet("ARCC_BUILD_DIR");
+ if (AutogenBuildDir_.empty()) {
+ return LogInfoError("Build directory empty.");
+ }
+
+ IncludeDir_ = InfoGetConfig("ARCC_INCLUDE_DIR");
+ if (IncludeDir_.empty()) {
+ return LogInfoError("Include directory empty.");
+ }
+
+ // - Rcc executable
+ RccExecutable_ = InfoGet("ARCC_RCC_EXECUTABLE");
+ if (!RccExecutableTime_.Load(RccExecutable_)) {
+ std::string error = "The rcc executable ";
+ error += Quoted(RccExecutable_);
+ error += " does not exist.";
+ return LogInfoError(error);
+ }
+ RccListOptions_ = InfoGetList("ARCC_RCC_LIST_OPTIONS");
+
+ // - Job
+ LockFile_ = InfoGet("ARCC_LOCK_FILE");
+ QrcFile_ = InfoGet("ARCC_SOURCE");
+ QrcFileName_ = cmSystemTools::GetFilenameName(QrcFile_);
+ QrcFileDir_ = cmSystemTools::GetFilenamePath(QrcFile_);
+ RccPathChecksum_ = InfoGet("ARCC_OUTPUT_CHECKSUM");
+ RccFileName_ = InfoGet("ARCC_OUTPUT_NAME");
+ Options_ = InfoGetConfigList("ARCC_OPTIONS");
+ Inputs_ = InfoGetList("ARCC_INPUTS");
+
+ // - Settings file
+ SettingsFile_ = InfoGetConfig("ARCC_SETTINGS_FILE");
+
+ // - Validity checks
+ if (LockFile_.empty()) {
+ return LogInfoError("Lock file name missing.");
+ }
+ if (SettingsFile_.empty()) {
+ return LogInfoError("Settings file name missing.");
+ }
+ if (AutogenBuildDir_.empty()) {
+ return LogInfoError("Autogen build directory missing.");
+ }
+ if (RccExecutable_.empty()) {
+ return LogInfoError("rcc executable missing.");
+ }
+ if (QrcFile_.empty()) {
+ return LogInfoError("rcc input file missing.");
+ }
+ if (RccFileName_.empty()) {
+ return LogInfoError("rcc output file missing.");
+ }
+
+ // Init derived information
+ // ------------------------
+
+ RccFilePublic_ = AutogenBuildDir_;
+ RccFilePublic_ += '/';
+ RccFilePublic_ += RccPathChecksum_;
+ RccFilePublic_ += '/';
+ RccFilePublic_ += RccFileName_;
+
+ // Compute rcc output file name
+ if (IsMultiConfig()) {
+ RccFileOutput_ = IncludeDir_;
+ RccFileOutput_ += '/';
+ RccFileOutput_ += MultiConfigOutput();
+ } else {
+ RccFileOutput_ = RccFilePublic_;
+ }
+
+ return true;
+}
+
+bool cmQtAutoRcc::Process()
+{
+ if (!SettingsFileRead()) {
+ return false;
+ }
+
+ // Test if the rcc output needs to be regenerated
+ bool generate = false;
+ if (!TestQrcRccFiles(generate)) {
+ return false;
+ }
+ if (!generate && !TestResources(generate)) {
+ return false;
+ }
+ // Generate on demand
+ if (generate) {
+ if (!GenerateRcc()) {
+ return false;
+ }
+ } else {
+ // Test if the info file is newer than the output file
+ if (!TestInfoFile()) {
+ return false;
+ }
+ }
+
+ if (!GenerateWrapper()) {
+ return false;
+ }
+
+ return SettingsFileWrite();
+}
+
+std::string cmQtAutoRcc::MultiConfigOutput() const
+{
+ static std::string const suffix = "_CMAKE_";
+ std::string res;
+ res += RccPathChecksum_;
+ res += '/';
+ res += AppendFilenameSuffix(RccFileName_, suffix);
+ return res;
+}
+
+bool cmQtAutoRcc::SettingsFileRead()
+{
+ // Compose current settings strings
+ {
+ cmCryptoHash crypt(cmCryptoHash::AlgoSHA256);
+ std::string const sep(" ~~~ ");
+ {
+ std::string str;
+ str += RccExecutable_;
+ str += sep;
+ str += cmJoin(RccListOptions_, ";");
+ str += sep;
+ str += QrcFile_;
+ str += sep;
+ str += RccPathChecksum_;
+ str += sep;
+ str += RccFileName_;
+ str += sep;
+ str += cmJoin(Options_, ";");
+ str += sep;
+ str += cmJoin(Inputs_, ";");
+ str += sep;
+ SettingsString_ = crypt.HashString(str);
+ }
+ }
+
+ // Make sure the settings file exists
+ if (!cmSystemTools::FileExists(SettingsFile_, true)) {
+ // Touch the settings file to make sure it exists
+ if (!cmSystemTools::Touch(SettingsFile_, true)) {
+ Log().ErrorFile(GenT::RCC, SettingsFile_,
+ "Settings file creation failed.");
+ return false;
+ }
+ }
+
+ // Lock the lock file
+ {
+ // Make sure the lock file exists
+ if (!cmSystemTools::FileExists(LockFile_, true)) {
+ if (!cmSystemTools::Touch(LockFile_, true)) {
+ Log().ErrorFile(GenT::RCC, LockFile_, "Lock file creation failed.");
+ return false;
+ }
+ }
+ // Lock the lock file
+ cmFileLockResult lockResult =
+ LockFileLock_.Lock(LockFile_, static_cast<unsigned long>(-1));
+ if (!lockResult.IsOk()) {
+ Log().ErrorFile(GenT::RCC, LockFile_,
+ "File lock failed: " + lockResult.GetOutputMessage());
+ return false;
+ }
+ }
+
+ // Read old settings
+ {
+ std::string content;
+ if (FileRead(content, SettingsFile_)) {
+ SettingsChanged_ = (SettingsString_ != SettingsFind(content, "rcc"));
+ // In case any setting changed clear 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 (SettingsChanged_) {
+ std::string error;
+ if (!FileWrite(SettingsFile_, "", &error)) {
+ Log().ErrorFile(GenT::RCC, SettingsFile_,
+ "Settings file clearing failed. " + error);
+ return false;
+ }
+ }
+ } else {
+ SettingsChanged_ = true;
+ }
+ }
+
+ return true;
+}
+
+bool cmQtAutoRcc::SettingsFileWrite()
+{
+ // Only write if any setting changed
+ if (SettingsChanged_) {
+ if (Log().Verbose()) {
+ Log().Info(GenT::RCC, "Writing settings file " + Quoted(SettingsFile_));
+ }
+ // Write settings file
+ std::string content = "rcc:";
+ content += SettingsString_;
+ content += '\n';
+ std::string error;
+ if (!FileWrite(SettingsFile_, content, &error)) {
+ Log().ErrorFile(GenT::RCC, SettingsFile_,
+ "Settings file writing failed. " + error);
+ // Remove old settings file to trigger a full rebuild on the next run
+ cmSystemTools::RemoveFile(SettingsFile_);
+ return false;
+ }
+ }
+
+ // Unlock the lock file
+ LockFileLock_.Release();
+ return true;
+}
+
+/// Do basic checks if rcc generation is required
+bool cmQtAutoRcc::TestQrcRccFiles(bool& generate)
+{
+ // Test if the rcc input file exists
+ if (!QrcFileTime_.Load(QrcFile_)) {
+ std::string error;
+ error = "The resources file ";
+ error += Quoted(QrcFile_);
+ error += " does not exist";
+ Log().ErrorFile(GenT::RCC, QrcFile_, error);
+ return false;
+ }
+
+ // Test if the rcc output file exists
+ if (!RccFileTime_.Load(RccFileOutput_)) {
+ if (Log().Verbose()) {
+ Reason = "Generating ";
+ Reason += Quoted(RccFileOutput_);
+ Reason += ", because it doesn't exist, from ";
+ Reason += Quoted(QrcFile_);
+ }
+ generate = true;
+ return true;
+ }
+
+ // Test if the settings changed
+ if (SettingsChanged_) {
+ if (Log().Verbose()) {
+ Reason = "Generating ";
+ Reason += Quoted(RccFileOutput_);
+ Reason += ", because the rcc settings changed, from ";
+ Reason += Quoted(QrcFile_);
+ }
+ generate = true;
+ return true;
+ }
+
+ // Test if the rcc output file is older than the .qrc file
+ if (RccFileTime_.Older(QrcFileTime_)) {
+ if (Log().Verbose()) {
+ Reason = "Generating ";
+ Reason += Quoted(RccFileOutput_);
+ Reason += ", because it is older than ";
+ Reason += Quoted(QrcFile_);
+ Reason += ", from ";
+ Reason += Quoted(QrcFile_);
+ }
+ generate = true;
+ return true;
+ }
+
+ // Test if the rcc output file is older than the rcc executable
+ if (RccFileTime_.Older(RccExecutableTime_)) {
+ if (Log().Verbose()) {
+ Reason = "Generating ";
+ Reason += Quoted(RccFileOutput_);
+ Reason += ", because it is older than the rcc executable, from ";
+ Reason += Quoted(QrcFile_);
+ }
+ generate = true;
+ return true;
+ }
+
+ return true;
+}
+
+bool cmQtAutoRcc::TestResources(bool& generate)
+{
+ // Read resource files list
+ if (Inputs_.empty()) {
+ std::string error;
+ RccLister const lister(RccExecutable_, RccListOptions_);
+ if (!lister.list(QrcFile_, Inputs_, error, Log().Verbose())) {
+ Log().ErrorFile(GenT::RCC, QrcFile_, error);
+ return false;
+ }
+ }
+
+ // Check if any resource file is newer than the rcc output file
+ for (std::string const& resFile : Inputs_) {
+ // Check if the resource file exists
+ cmFileTime fileTime;
+ if (!fileTime.Load(resFile)) {
+ std::string error;
+ error = "Could not find the resource file\n ";
+ error += Quoted(resFile);
+ error += '\n';
+ Log().ErrorFile(GenT::RCC, QrcFile_, error);
+ return false;
+ }
+ // Check if the resource file is newer than the rcc output file
+ if (RccFileTime_.Older(fileTime)) {
+ if (Log().Verbose()) {
+ Reason = "Generating ";
+ Reason += Quoted(RccFileOutput_);
+ Reason += ", because it is older than ";
+ Reason += Quoted(resFile);
+ Reason += ", from ";
+ Reason += Quoted(QrcFile_);
+ }
+ generate = true;
+ break;
+ }
+ }
+ return true;
+}
+
+bool cmQtAutoRcc::TestInfoFile()
+{
+ // Test if the rcc output file is older than the info file
+ if (RccFileTime_.Older(InfoFileTime())) {
+ if (Log().Verbose()) {
+ std::string reason = "Touching ";
+ reason += Quoted(RccFileOutput_);
+ reason += " because it is older than ";
+ reason += Quoted(InfoFile());
+ Log().Info(GenT::RCC, reason);
+ }
+ // Touch build file
+ if (!cmSystemTools::Touch(RccFileOutput_, false)) {
+ Log().ErrorFile(GenT::RCC, RccFileOutput_, "Build file touch failed");
+ return false;
+ }
+ BuildFileChanged_ = true;
+ }
+
+ return true;
+}
+
+bool cmQtAutoRcc::GenerateRcc()
+{
+ // Make parent directory
+ if (!MakeParentDirectory(RccFileOutput_)) {
+ Log().ErrorFile(GenT::RCC, RccFileOutput_,
+ "Could not create parent directory");
+ return false;
+ }
+
+ // Compose rcc command
+ std::vector<std::string> cmd;
+ cmd.push_back(RccExecutable_);
+ cmAppend(cmd, Options_);
+ cmd.emplace_back("-o");
+ cmd.push_back(RccFileOutput_);
+ cmd.push_back(QrcFile_);
+
+ // Log reason and command
+ if (Log().Verbose()) {
+ std::string msg = Reason;
+ if (!msg.empty() && (msg.back() != '\n')) {
+ msg += '\n';
+ }
+ msg += QuotedCommand(cmd);
+ msg += '\n';
+ Log().Info(GenT::RCC, msg);
+ }
+
+ std::string rccStdOut;
+ std::string rccStdErr;
+ int retVal = 0;
+ bool result = cmSystemTools::RunSingleCommand(
+ cmd, &rccStdOut, &rccStdErr, &retVal, AutogenBuildDir_.c_str(),
+ cmSystemTools::OUTPUT_NONE, cmDuration::zero(), cmProcessOutput::Auto);
+ if (!result || (retVal != 0)) {
+ // rcc process failed
+ {
+ std::string err = "The rcc process failed to compile\n ";
+ err += Quoted(QrcFile_);
+ err += "\ninto\n ";
+ err += Quoted(RccFileOutput_);
+ Log().ErrorCommand(GenT::RCC, err, cmd, rccStdOut + rccStdErr);
+ }
+ cmSystemTools::RemoveFile(RccFileOutput_);
+ return false;
+ }
+
+ // rcc process success
+ // Print rcc output
+ if (!rccStdOut.empty()) {
+ Log().Info(GenT::RCC, rccStdOut);
+ }
+ BuildFileChanged_ = true;
+
+ return true;
+}
+
+bool cmQtAutoRcc::GenerateWrapper()
+{
+ // Generate a wrapper source file on demand
+ if (IsMultiConfig()) {
+ // Wrapper file content
+ std::string content;
+ content += "// This is an autogenerated configuration wrapper file.\n";
+ content += "// Changes will be overwritten.\n";
+ content += "#include <";
+ content += MultiConfigOutput();
+ content += ">\n";
+
+ // Compare with existing file content
+ bool fileDiffers = true;
+ {
+ std::string oldContents;
+ if (FileRead(oldContents, RccFilePublic_)) {
+ fileDiffers = (oldContents != content);
+ }
+ }
+ if (fileDiffers) {
+ // Write new wrapper file
+ if (Log().Verbose()) {
+ Log().Info(GenT::RCC, "Generating RCC wrapper file " + RccFilePublic_);
+ }
+ std::string error;
+ if (!FileWrite(RccFilePublic_, content, &error)) {
+ Log().ErrorFile(GenT::RCC, RccFilePublic_,
+ "RCC wrapper file writing failed. " + error);
+ return false;
+ }
+ } else if (BuildFileChanged_) {
+ // Just touch the wrapper file
+ if (Log().Verbose()) {
+ Log().Info(GenT::RCC, "Touching RCC wrapper file " + RccFilePublic_);
+ }
+ if (!cmSystemTools::Touch(RccFilePublic_, false)) {
+ Log().ErrorFile(GenT::RCC, RccFilePublic_,
+ "RCC wrapper file touch failed.");
+ return false;
+ }
+ }
+ }
+ return true;
+}
diff --git a/Source/cmQtAutoRcc.h b/Source/cmQtAutoRcc.h
new file mode 100644
index 000000000..636a6672d
--- /dev/null
+++ b/Source/cmQtAutoRcc.h
@@ -0,0 +1,81 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmQtAutoRcc_h
+#define cmQtAutoRcc_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cmFileLock.h"
+#include "cmFileTime.h"
+#include "cmQtAutoGenerator.h"
+
+#include <string>
+#include <vector>
+
+class cmMakefile;
+
+// @brief AUTORCC generator
+class cmQtAutoRcc : public cmQtAutoGenerator
+{
+public:
+ cmQtAutoRcc();
+ ~cmQtAutoRcc() override;
+
+ cmQtAutoRcc(cmQtAutoRcc const&) = delete;
+ cmQtAutoRcc& operator=(cmQtAutoRcc const&) = delete;
+
+private:
+ // -- Utility
+ Logger const& Log() const { return Logger_; }
+ bool IsMultiConfig() const { return MultiConfig_; }
+ std::string MultiConfigOutput() const;
+
+ // -- Abstract processing interface
+ bool Init(cmMakefile* makefile) override;
+ bool Process() override;
+ // -- Settings file
+ bool SettingsFileRead();
+ bool SettingsFileWrite();
+ // -- Tests
+ bool TestQrcRccFiles(bool& generate);
+ bool TestResources(bool& generate);
+ bool TestInfoFile();
+ // -- Generation
+ bool GenerateRcc();
+ bool GenerateWrapper();
+
+private:
+ // -- Logging
+ Logger Logger_;
+ // -- Config settings
+ bool MultiConfig_ = false;
+ // -- Directories
+ std::string AutogenBuildDir_;
+ std::string IncludeDir_;
+ // -- Qt environment
+ std::string RccExecutable_;
+ cmFileTime RccExecutableTime_;
+ std::vector<std::string> RccListOptions_;
+ // -- Job
+ std::string LockFile_;
+ cmFileLock LockFileLock_;
+ std::string QrcFile_;
+ std::string QrcFileName_;
+ std::string QrcFileDir_;
+ cmFileTime QrcFileTime_;
+ std::string RccPathChecksum_;
+ std::string RccFileName_;
+ std::string RccFileOutput_;
+ std::string RccFilePublic_;
+ cmFileTime RccFileTime_;
+ std::string Reason;
+ std::vector<std::string> Options_;
+ std::vector<std::string> Inputs_;
+ // -- Settings file
+ std::string SettingsFile_;
+ std::string SettingsString_;
+ bool SettingsChanged_ = false;
+ bool BuildFileChanged_ = false;
+};
+
+#endif
diff --git a/Source/cmRange.h b/Source/cmRange.h
new file mode 100644
index 000000000..3be5193e7
--- /dev/null
+++ b/Source/cmRange.h
@@ -0,0 +1,239 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmRange_h
+#define cmRange_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <algorithm>
+#include <functional>
+#include <iterator>
+
+namespace RangeIterators {
+
+template <typename Iter, typename UnaryPredicate>
+class FilterIterator
+{
+public:
+ using iterator_category = std::bidirectional_iterator_tag;
+ using value_type = typename std::iterator_traits<Iter>::value_type;
+ using difference_type = typename std::iterator_traits<Iter>::difference_type;
+ using pointer = typename std::iterator_traits<Iter>::pointer;
+ using reference = typename std::iterator_traits<Iter>::reference;
+
+ FilterIterator(Iter b, Iter e, UnaryPredicate p)
+ : Cur(std::move(b))
+ , End(std::move(e))
+ , Pred(std::move(p))
+ {
+ this->SatisfyPredicate();
+ }
+
+ FilterIterator& operator++()
+ {
+ ++this->Cur;
+ this->SatisfyPredicate();
+ return *this;
+ }
+
+ FilterIterator& operator--()
+ {
+ do {
+ --this->Cur;
+ } while (!this->Pred(*this->Cur));
+ return *this;
+ }
+
+ bool operator==(FilterIterator const& other) const
+ {
+ return this->Cur == other.Cur;
+ }
+
+ bool operator!=(FilterIterator const& other) const
+ {
+ return !this->operator==(other);
+ }
+
+ auto operator*() const -> decltype(*std::declval<Iter>())
+ {
+ return *this->Cur;
+ }
+
+private:
+ void SatisfyPredicate()
+ {
+ while (this->Cur != this->End && !this->Pred(*this->Cur)) {
+ ++this->Cur;
+ }
+ }
+
+ Iter Cur;
+ Iter End;
+ UnaryPredicate Pred;
+};
+
+template <typename Iter, typename UnaryFunction>
+class TransformIterator
+{
+public:
+ using iterator_category = std::bidirectional_iterator_tag;
+ using value_type =
+ typename std::remove_cv<typename std::remove_reference<decltype(
+ std::declval<UnaryFunction>()(*std::declval<Iter>()))>::type>::type;
+ using difference_type = typename std::iterator_traits<Iter>::difference_type;
+ using pointer = value_type const*;
+ using reference = value_type const&;
+
+ TransformIterator(Iter i, UnaryFunction f)
+ : Base(std::move(i))
+ , Func(std::move(f))
+ {
+ }
+
+ TransformIterator& operator++()
+ {
+ ++this->Base;
+ return *this;
+ }
+
+ TransformIterator& operator--()
+ {
+ --this->Base;
+ return *this;
+ }
+
+ bool operator==(TransformIterator const& other) const
+ {
+ return this->Base == other.Base;
+ }
+
+ bool operator!=(TransformIterator const& other) const
+ {
+ return !this->operator==(other);
+ }
+
+ auto operator*() const
+ -> decltype(std::declval<UnaryFunction>()(*std::declval<Iter>()))
+ {
+ return this->Func(*this->Base);
+ }
+
+private:
+ Iter Base;
+ UnaryFunction Func;
+};
+
+} // namespace RangeIterators
+
+template <typename Iter>
+class cmRange
+{
+public:
+ using const_iterator = Iter;
+ using value_type = typename std::iterator_traits<Iter>::value_type;
+ using difference_type = typename std::iterator_traits<Iter>::difference_type;
+
+ cmRange(Iter b, Iter e)
+ : Begin(std::move(b))
+ , End(std::move(e))
+ {
+ }
+
+ Iter begin() const { return this->Begin; }
+ Iter end() const { return this->End; }
+ bool empty() const { return this->Begin == this->End; }
+
+ difference_type size() const
+ {
+ return std::distance(this->Begin, this->End);
+ }
+
+ cmRange& advance(difference_type amount) &
+ {
+ std::advance(this->Begin, amount);
+ return *this;
+ }
+
+ cmRange advance(difference_type amount) &&
+ {
+ std::advance(this->Begin, amount);
+ return std::move(*this);
+ }
+
+ cmRange& retreat(difference_type amount) &
+ {
+ std::advance(this->End, -amount);
+ return *this;
+ }
+
+ cmRange retreat(difference_type amount) &&
+ {
+ std::advance(this->End, -amount);
+ return std::move(*this);
+ }
+
+ template <typename UnaryPredicate>
+ bool all_of(UnaryPredicate p) const
+ {
+ return std::all_of(this->Begin, this->End, std::ref(p));
+ }
+
+ template <typename UnaryPredicate>
+ bool any_of(UnaryPredicate p) const
+ {
+ return std::any_of(this->Begin, this->End, std::ref(p));
+ }
+
+ template <typename UnaryPredicate>
+ bool none_of(UnaryPredicate p) const
+ {
+ return std::none_of(this->Begin, this->End, std::ref(p));
+ }
+
+ template <typename UnaryPredicate>
+ auto filter(UnaryPredicate p) const
+ -> cmRange<RangeIterators::FilterIterator<Iter, UnaryPredicate>>
+ {
+ using It = RangeIterators::FilterIterator<Iter, UnaryPredicate>;
+ return { It(this->Begin, this->End, p), It(this->End, this->End, p) };
+ }
+
+ template <typename UnaryFunction>
+ auto transform(UnaryFunction f) const
+ -> cmRange<RangeIterators::TransformIterator<Iter, UnaryFunction>>
+ {
+ using It = RangeIterators::TransformIterator<Iter, UnaryFunction>;
+ return { It(this->Begin, f), It(this->End, f) };
+ }
+
+private:
+ Iter Begin;
+ Iter End;
+};
+
+template <typename Iter1, typename Iter2>
+bool operator==(cmRange<Iter1> const& left, cmRange<Iter2> const& right)
+{
+ return left.size() == right.size() &&
+ std::equal(left.begin(), left.end(), right.begin());
+}
+
+template <typename Iter1, typename Iter2>
+auto cmMakeRange(Iter1 begin, Iter2 end) -> cmRange<Iter1>
+{
+ return { begin, end };
+}
+
+template <typename Range>
+auto cmMakeRange(Range const& range) -> cmRange<decltype(range.begin())>
+{
+ return { range.begin(), range.end() };
+}
+
+template <typename Range>
+auto cmReverseRange(Range const& range) -> cmRange<decltype(range.rbegin())>
+{
+ return { range.rbegin(), range.rend() };
+}
+
+#endif
diff --git a/Source/cmSourceFileLocationKind.h b/Source/cmSourceFileLocationKind.h
new file mode 100644
index 000000000..dd4c6dd4f
--- /dev/null
+++ b/Source/cmSourceFileLocationKind.h
@@ -0,0 +1,15 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmSourceFileLocationKind_h
+#define cmSourceFileLocationKind_h
+
+enum class cmSourceFileLocationKind
+{
+ // The location is user-specified and may be ambiguous.
+ Ambiguous,
+ // The location is known to be at the given location; do not try to guess at
+ // extensions or absolute path.
+ Known
+};
+
+#endif
diff --git a/Source/cmString.cxx b/Source/cmString.cxx
new file mode 100644
index 000000000..2a0c125e6
--- /dev/null
+++ b/Source/cmString.cxx
@@ -0,0 +1,152 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#define _SCL_SECURE_NO_WARNINGS
+
+#include "cmString.hxx"
+
+#include <memory>
+#include <ostream>
+#include <stdexcept>
+#include <string>
+#include <type_traits>
+
+namespace cm {
+
+static std::string const empty_string_;
+
+void String::internally_mutate_to_stable_string()
+{
+ // We assume that only one thread mutates this instance at
+ // a time even if we point to a shared string buffer refernced
+ // by other threads.
+ *this = String(data(), size());
+}
+
+bool String::is_stable() const
+{
+ return str_if_stable() != nullptr;
+}
+
+void String::stabilize()
+{
+ if (is_stable()) {
+ return;
+ }
+ this->internally_mutate_to_stable_string();
+}
+
+std::string const* String::str_if_stable() const
+{
+ if (!data()) {
+ // We view no string.
+ // This is stable for the lifetime of our current value.
+ return &empty_string_;
+ }
+
+ if (string_ && data() == string_->data() && size() == string_->size()) {
+ // We view an entire string.
+ // This is stable for the lifetime of our current value.
+ return string_.get();
+ }
+
+ return nullptr;
+}
+
+std::string const& String::str()
+{
+ if (std::string const* s = str_if_stable()) {
+ return *s;
+ }
+ // Mutate to hold a std::string that is stable for the lifetime
+ // of our current value.
+ this->internally_mutate_to_stable_string();
+ return *string_;
+}
+
+const char* String::c_str()
+{
+ const char* c = data();
+ if (c == nullptr) {
+ return c;
+ }
+
+ // We always point into a null-terminated string so it is safe to
+ // access one past the end. If it is a null byte then we can use
+ // the pointer directly.
+ if (c[size()] == '\0') {
+ return c;
+ }
+
+ // Mutate to hold a std::string so we can get a null terminator.
+ this->internally_mutate_to_stable_string();
+ c = string_->c_str();
+ return c;
+}
+
+String& String::insert(size_type index, size_type count, char ch)
+{
+ std::string s;
+ s.reserve(size() + count);
+ s.assign(data(), size());
+ s.insert(index, count, ch);
+ return *this = std::move(s);
+}
+
+String& String::erase(size_type index, size_type count)
+{
+ if (index > size()) {
+ throw std::out_of_range("Index out of range in String::erase");
+ }
+ size_type const rcount = std::min(count, size() - index);
+ size_type const rindex = index + rcount;
+ std::string s;
+ s.reserve(size() - rcount);
+ s.assign(data(), index);
+ s.append(data() + rindex, size() - rindex);
+ return *this = std::move(s);
+}
+
+String String::substr(size_type pos, size_type count) const
+{
+ if (pos > size()) {
+ throw std::out_of_range("Index out of range in String::substr");
+ }
+ return String(*this, pos, count);
+}
+
+String::String(std::string&& s, Private)
+ : string_(std::make_shared<std::string>(std::move(s)))
+ , view_(string_->data(), string_->size())
+{
+}
+
+String::size_type String::copy(char* dest, size_type count,
+ size_type pos) const
+{
+ return view_.copy(dest, count, pos);
+}
+
+std::ostream& operator<<(std::ostream& os, String const& s)
+{
+ return os.write(s.data(), s.size());
+}
+
+std::string& operator+=(std::string& self, String const& s)
+{
+ return self += s.view();
+}
+
+String IntoString<char*>::into_string(const char* s)
+{
+ if (!s) {
+ return String();
+ }
+ return std::string(s);
+}
+
+string_view AsStringView<String>::view(String const& s)
+{
+ return s.view();
+}
+
+} // namespace cm
diff --git a/Source/cmString.hxx b/Source/cmString.hxx
new file mode 100644
index 000000000..49bad7870
--- /dev/null
+++ b/Source/cmString.hxx
@@ -0,0 +1,815 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmString_hxx
+#define cmString_hxx
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cm_static_string_view.hxx"
+#include "cm_string_view.hxx"
+
+#include <algorithm>
+#include <functional>
+#include <initializer_list>
+#include <memory>
+#include <ostream>
+#include <string>
+#include <type_traits>
+#include <utility>
+
+namespace cm {
+
+class String;
+
+/**
+ * Trait to convert type T into a String.
+ * Implementations must derive from 'std::true_type'
+ * and define an 'into_string' member that accepts
+ * type T (by value or reference) and returns one of:
+ *
+ * - 'std::string' to construct an owned instance.
+ * - 'cm::string_view' to construct a borrowed or null instances.
+ * The buffer from which the view is borrowed must outlive
+ * all copies of the resulting String, e.g. static storage.
+ * - 'cm::String' for already-constructed instances.
+ */
+template <typename T>
+struct IntoString : std::false_type
+{
+};
+
+template <typename T>
+struct IntoString<T&> : IntoString<T>
+{
+};
+
+template <typename T>
+struct IntoString<T const> : IntoString<T>
+{
+};
+
+template <typename T>
+struct IntoString<T const*> : IntoString<T*>
+{
+};
+
+template <typename T, std::string::size_type N>
+struct IntoString<T const[N]> : IntoString<T[N]>
+{
+};
+
+template <>
+struct IntoString<char*> : std::true_type
+{
+ static String into_string(const char* s);
+};
+
+template <>
+struct IntoString<std::nullptr_t> : std::true_type
+{
+ static string_view into_string(std::nullptr_t) { return string_view(); }
+};
+
+template <std::string::size_type N>
+struct IntoString<char[N]> : std::true_type
+{
+ static std::string into_string(char const (&s)[N])
+ {
+ return std::string(s, N - 1);
+ }
+};
+
+template <>
+struct IntoString<std::string> : std::true_type
+{
+ static std::string into_string(std::string s) { return s; }
+};
+
+template <>
+struct IntoString<string_view> : std::true_type
+{
+ static std::string into_string(string_view s) { return std::string(s); }
+};
+
+template <>
+struct IntoString<static_string_view> : std::true_type
+{
+ static string_view into_string(static_string_view s) { return s; }
+};
+
+template <>
+struct IntoString<char> : std::true_type
+{
+ static std::string into_string(char const& c) { return std::string(1, c); }
+};
+
+/**
+ * Trait to convert type T into a 'cm::string_view'.
+ * Implementations must derive from 'std::true_type' and
+ * define a 'view' member that accepts type T (by reference)
+ * and returns a 'cm::string_view'.
+ */
+template <typename T>
+struct AsStringView : std::false_type
+{
+};
+
+template <typename T>
+struct AsStringView<T&> : AsStringView<T>
+{
+};
+
+template <typename T>
+struct AsStringView<T const> : AsStringView<T>
+{
+};
+
+template <typename T>
+struct AsStringView<T const*> : AsStringView<T*>
+{
+};
+
+template <typename T, std::string::size_type N>
+struct AsStringView<T const[N]> : AsStringView<T[N]>
+{
+};
+
+template <>
+struct AsStringView<char*> : std::true_type
+{
+ static string_view view(const char* s) { return s; }
+};
+
+template <std::string::size_type N>
+struct AsStringView<char[N]> : std::true_type
+{
+ static string_view view(char const (&s)[N]) { return string_view(s, N - 1); }
+};
+
+template <>
+struct AsStringView<std::string> : std::true_type
+{
+ static string_view view(std::string const& s) { return s; }
+};
+
+template <>
+struct AsStringView<char> : std::true_type
+{
+ static string_view view(const char& s) { return string_view(&s, 1); }
+};
+
+template <>
+struct AsStringView<string_view> : std::true_type
+{
+ static string_view view(string_view const& s) { return s; }
+};
+
+template <>
+struct AsStringView<static_string_view> : std::true_type
+{
+ static string_view view(static_string_view const& s) { return s; }
+};
+
+template <>
+struct AsStringView<String> : std::true_type
+{
+ static string_view view(String const& s);
+};
+
+/**
+ * \class String
+ *
+ * A custom string type that holds a view of a string buffer
+ * and optionally shares ownership of the buffer. Instances
+ * may have one of the following states:
+ *
+ * - null: views and owns nothing.
+ * Conversion to 'bool' is 'false'.
+ * 'data()' and 'c_str()' return nullptr.
+ * 'size()' returns 0.
+ * 'str()' returns an empty string.
+ *
+ * - borrowed: views a string but does not own it. This is used
+ * to bind to static storage (e.g. string literals) or for
+ * temporary instances that do not outlive the borrowed buffer.
+ * Copies and substrings still borrow the original buffer.
+ * Mutation allocates a new internal string and converts to
+ * the 'owned' state.
+ * Conversion to 'bool' is 'true'.
+ * 'c_str()' may internally mutate to the 'owned' state.
+ * 'str()' internally mutates to the 'owned' state.
+ *
+ * - owned: views an immutable 'std::string' instance owned internally.
+ * Copies and substrings share ownership of the internal string.
+ * Mutation allocates a new internal string.
+ * Conversion to 'bool' is 'true'.
+ */
+class String
+{
+ enum class Private
+ {
+ };
+
+public:
+ using traits_type = std::string::traits_type;
+ using value_type = string_view::value_type;
+ using pointer = string_view::pointer;
+ using const_pointer = string_view::const_pointer;
+ using reference = string_view::reference;
+ using const_reference = string_view::const_reference;
+ using const_iterator = string_view::const_iterator;
+ using iterator = string_view::const_iterator;
+ using const_reverse_iterator = string_view::const_reverse_iterator;
+ using reverse_iterator = string_view::const_reverse_iterator;
+ using difference_type = string_view::difference_type;
+ using size_type = string_view::size_type;
+
+ static size_type const npos = string_view::npos;
+
+ /** Construct a null string. */
+ String() = default;
+
+ /** Construct from any type implementing the IntoString trait. */
+ template <typename T,
+ typename = typename std::enable_if<IntoString<T>::value>::type>
+ String(T&& s)
+ : String(IntoString<T>::into_string(std::forward<T>(s)), Private())
+ {
+ }
+
+ /** Construct via std::string initializer list constructor. */
+ String(std::initializer_list<char> il)
+ : String(std::string(il))
+ {
+ }
+
+ /** Construct by copying the specified buffer. */
+ String(const char* d, size_type s)
+ : String(std::string(d, s))
+ {
+ }
+
+ /** Construct by copying from input iterator range. */
+ template <typename InputIterator>
+ String(InputIterator first, InputIterator last)
+ : String(std::string(first, last))
+ {
+ }
+
+ /** Construct a string with 'n' copies of character 'c'. */
+ String(size_type n, char c)
+ : String(std::string(n, c))
+ {
+ }
+
+ /** Construct from a substring of another String instance.
+ This shares ownership of the other string's buffer
+ but views only a substring. */
+ String(String const& s, size_type pos, size_type count = npos)
+ : string_(s.string_)
+ , view_(s.data() + pos, std::min(count, s.size() - pos))
+ {
+ }
+
+ /** Construct by moving from another String instance.
+ The other instance is left as a null string. */
+ String(String&& s) noexcept
+ : string_(std::move(s.string_))
+ , view_(s.view_)
+ {
+ s.view_ = string_view();
+ }
+
+ /** Construct by copying from another String instance.
+ This shares ownership of the other string's buffer. */
+ String(String const&) noexcept = default;
+
+ ~String() = default;
+
+ /** Construct by borrowing an externally-owned buffer. The buffer
+ must outlive the returned instance and all copies of it. */
+ static String borrow(string_view v) { return String(v, Private()); }
+
+ /** Assign by moving from another String instance.
+ The other instance is left as a null string. */
+ String& operator=(String&& s) noexcept
+ {
+ string_ = std::move(s.string_);
+ view_ = s.view_;
+ s.view_ = string_view();
+ return *this;
+ }
+
+ /** Assign by copying from another String instance.
+ This shares ownership of the other string's buffer. */
+ String& operator=(String const&) noexcept = default;
+
+ /** Assign from any type implementing the IntoString trait. */
+ template <typename T>
+ typename // NOLINT(*)
+ std::enable_if<IntoString<T>::value, String&>::type
+ operator=(T&& s)
+ {
+ *this = String(std::forward<T>(s));
+ return *this;
+ }
+
+ /** Assign via std::string initializer list constructor. */
+ String& operator=(std::initializer_list<char> il)
+ {
+ *this = String(il);
+ return *this;
+ }
+
+ /** Return true if the instance is not a null string. */
+ explicit operator bool() const noexcept { return data() != nullptr; }
+
+ /** Return a view of the string. */
+ string_view view() const noexcept { return view_; }
+
+ /** Return true if the instance is an empty stringn or null string. */
+ bool empty() const noexcept { return view_.empty(); }
+
+ /** Return a pointer to the start of the string. */
+ const char* data() const noexcept { return view_.data(); }
+
+ /** Return the length of the string in bytes. */
+ size_type size() const noexcept { return view_.size(); }
+ size_type length() const noexcept { return view_.length(); }
+
+ /** Return the character at the given position.
+ No bounds checking is performed. */
+ char operator[](size_type pos) const noexcept { return view_[pos]; }
+
+ /** Return the character at the given position.
+ If the position is out of bounds, throws std::out_of_range. */
+ char at(size_type pos) const { return view_.at(pos); }
+
+ char front() const noexcept { return view_.front(); }
+
+ char back() const noexcept { return view_.back(); }
+
+ /** Return true if this instance is stable and otherwise false.
+ An instance is stable if it is in the 'null' state or if it is
+ an 'owned' state not produced by substring operations, or
+ after a call to 'stabilize()' or 'str()'. */
+ bool is_stable() const;
+
+ /** If 'is_stable()' does not return true, mutate so it does. */
+ void stabilize();
+
+ /** Get a pointer to a normal std::string if 'is_stable()' returns
+ true and otherwise nullptr. The pointer is valid until this
+ instance is mutated or destroyed. */
+ std::string const* str_if_stable() const;
+
+ /** Get a refernce to a normal std::string. The reference
+ is valid until this instance is mutated or destroyed. */
+ std::string const& str();
+
+ /** Get a pointer to a C-style null-terminated string
+ containing the same value as this instance. The pointer
+ is valid until this instance is mutated, destroyed,
+ or str() is called. */
+ const char* c_str();
+
+ const_iterator begin() const noexcept { return view_.begin(); }
+ const_iterator end() const noexcept { return view_.end(); }
+ const_iterator cbegin() const noexcept { return begin(); }
+ const_iterator cend() const noexcept { return end(); }
+
+ const_reverse_iterator rbegin() const noexcept { return view_.rbegin(); }
+ const_reverse_iterator rend() const noexcept { return view_.rend(); }
+ const_reverse_iterator crbegin() const noexcept { return rbegin(); }
+ const_reverse_iterator crend() const noexcept { return rend(); }
+
+ /** Append to the string using any type that implements the
+ AsStringView trait. */
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, String&>::type operator+=(
+ T&& s)
+ {
+ string_view v = AsStringView<T>::view(std::forward<T>(s));
+ std::string r;
+ r.reserve(size() + v.size());
+ r.assign(data(), size());
+ r.append(v.data(), v.size());
+ return *this = std::move(r);
+ }
+
+ /** Assign to an empty string. */
+ void clear() { *this = ""_s; }
+
+ /** Insert 'count' copies of 'ch' at position 'index'. */
+ String& insert(size_type index, size_type count, char ch);
+
+ /** Erase 'count' characters starting at position 'index'. */
+ String& erase(size_type index = 0, size_type count = npos);
+
+ void push_back(char ch)
+ {
+ std::string s;
+ s.reserve(size() + 1);
+ s.assign(data(), size());
+ s.push_back(ch);
+ *this = std::move(s);
+ }
+
+ void pop_back() { *this = String(*this, 0, size() - 1); }
+
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, String&>::type replace(
+ size_type pos, size_type count, T&& s)
+ {
+ const_iterator first = begin() + pos;
+ const_iterator last = first + count;
+ return replace(first, last, std::forward<T>(s));
+ }
+
+ template <typename InputIterator>
+ String& replace(const_iterator first, const_iterator last,
+ InputIterator first2, InputIterator last2)
+ {
+ std::string out;
+ out.append(view_.begin(), first);
+ out.append(first2, last2);
+ out.append(last, view_.end());
+ return *this = std::move(out);
+ }
+
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, String&>::type replace(
+ const_iterator first, const_iterator last, T&& s)
+ {
+ string_view v = AsStringView<T>::view(std::forward<T>(s));
+ std::string out;
+ out.reserve((first - view_.begin()) + v.size() + (view_.end() - last));
+ out.append(view_.begin(), first);
+ out.append(v.data(), v.size());
+ out.append(last, view_.end());
+ return *this = std::move(out);
+ }
+
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, String&>::type replace(
+ size_type pos, size_type count, T&& s, size_type pos2,
+ size_type count2 = npos)
+ {
+ string_view v = AsStringView<T>::view(std::forward<T>(s));
+ v = v.substr(pos2, count2);
+ return replace(pos, count, v);
+ }
+
+ String& replace(size_type pos, size_type count, size_type count2, char ch)
+ {
+ const_iterator first = begin() + pos;
+ const_iterator last = first + count;
+ return replace(first, last, count2, ch);
+ }
+
+ String& replace(const_iterator first, const_iterator last, size_type count2,
+ char ch)
+ {
+ std::string out;
+ out.reserve((first - view_.begin()) + count2 + (view_.end() - last));
+ out.append(view_.begin(), first);
+ out.append(count2, ch);
+ out.append(last, view_.end());
+ return *this = std::move(out);
+ }
+
+ size_type copy(char* dest, size_type count, size_type pos = 0) const;
+
+ void resize(size_type count) { resize(count, char()); }
+
+ void resize(size_type count, char ch)
+ {
+ std::string s;
+ s.reserve(count);
+ if (count <= size()) {
+ s.assign(data(), count);
+ } else {
+ s.assign(data(), size());
+ s.resize(count, ch);
+ }
+ *this = std::move(s);
+ }
+
+ void swap(String& other)
+ {
+ std::swap(string_, other.string_);
+ std::swap(view_, other.view_);
+ }
+
+ /** Return a substring starting at position 'pos' and
+ consisting of at most 'count' characters. */
+ String substr(size_type pos = 0, size_type count = npos) const;
+
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, int>::type compare(
+ T&& s) const
+ {
+ return view_.compare(AsStringView<T>::view(std::forward<T>(s)));
+ }
+
+ int compare(size_type pos1, size_type count1, string_view v) const
+ {
+ return view_.compare(pos1, count1, v);
+ }
+
+ int compare(size_type pos1, size_type count1, string_view v, size_type pos2,
+ size_type count2) const
+ {
+ return view_.compare(pos1, count1, v, pos2, count2);
+ }
+
+ int compare(size_type pos1, size_type count1, const char* s) const
+ {
+ return view_.compare(pos1, count1, s);
+ }
+
+ int compare(size_type pos1, size_type count1, const char* s,
+ size_type count2) const
+ {
+ return view_.compare(pos1, count1, s, count2);
+ }
+
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, size_type>::type find(
+ T&& s, size_type pos = 0) const
+ {
+ string_view v = AsStringView<T>::view(std::forward<T>(s));
+ return view_.find(v, pos);
+ }
+
+ size_type find(const char* s, size_type pos, size_type count) const
+ {
+ return view_.find(s, pos, count);
+ }
+
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, size_type>::type rfind(
+ T&& s, size_type pos = npos) const
+ {
+ string_view v = AsStringView<T>::view(std::forward<T>(s));
+ return view_.rfind(v, pos);
+ }
+
+ size_type rfind(const char* s, size_type pos, size_type count) const
+ {
+ return view_.rfind(s, pos, count);
+ }
+
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, size_type>::type
+ find_first_of(T&& s, size_type pos = 0) const
+ {
+ string_view v = AsStringView<T>::view(std::forward<T>(s));
+ return view_.find_first_of(v, pos);
+ }
+
+ size_type find_first_of(const char* s, size_type pos, size_type count) const
+ {
+ return view_.find_first_of(s, pos, count);
+ }
+
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, size_type>::type
+ find_first_not_of(T&& s, size_type pos = 0) const
+ {
+ string_view v = AsStringView<T>::view(std::forward<T>(s));
+ return view_.find_first_not_of(v, pos);
+ }
+
+ size_type find_first_not_of(const char* s, size_type pos,
+ size_type count) const
+ {
+ return view_.find_first_not_of(s, pos, count);
+ }
+
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, size_type>::type
+ find_last_of(T&& s, size_type pos = npos) const
+ {
+ string_view v = AsStringView<T>::view(std::forward<T>(s));
+ return view_.find_last_of(v, pos);
+ }
+
+ size_type find_last_of(const char* s, size_type pos, size_type count) const
+ {
+ return view_.find_last_of(s, pos, count);
+ }
+
+ template <typename T>
+ typename std::enable_if<AsStringView<T>::value, size_type>::type
+ find_last_not_of(T&& s, size_type pos = npos) const
+ {
+ string_view v = AsStringView<T>::view(std::forward<T>(s));
+ return view_.find_last_not_of(v, pos);
+ }
+
+ size_type find_last_not_of(const char* s, size_type pos,
+ size_type count) const
+ {
+ return view_.find_last_not_of(s, pos, count);
+ }
+
+private:
+ // Internal constructor to move from existing String.
+ String(String&& s, Private) noexcept
+ : String(std::move(s))
+ {
+ }
+
+ // Internal constructor for dynamically allocated string.
+ String(std::string&& s, Private);
+
+ // Internal constructor for view of statically allocated string.
+ String(string_view v, Private)
+ : view_(v)
+ {
+ }
+
+ void internally_mutate_to_stable_string();
+
+ std::shared_ptr<std::string const> string_;
+ string_view view_;
+};
+
+template <typename L, typename R>
+typename std::enable_if<AsStringView<L>::value && AsStringView<R>::value,
+ bool>::type
+operator==(L&& l, R&& r)
+{
+ return (AsStringView<L>::view(std::forward<L>(l)) ==
+ AsStringView<R>::view(std::forward<R>(r)));
+}
+
+template <typename L, typename R>
+typename std::enable_if<AsStringView<L>::value && AsStringView<R>::value,
+ bool>::type
+operator!=(L&& l, R&& r)
+{
+ return (AsStringView<L>::view(std::forward<L>(l)) !=
+ AsStringView<R>::view(std::forward<R>(r)));
+}
+
+template <typename L, typename R>
+typename std::enable_if<AsStringView<L>::value && AsStringView<R>::value,
+ bool>::type
+operator<(L&& l, R&& r)
+{
+ return (AsStringView<L>::view(std::forward<L>(l)) <
+ AsStringView<R>::view(std::forward<R>(r)));
+}
+
+template <typename L, typename R>
+typename std::enable_if<AsStringView<L>::value && AsStringView<R>::value,
+ bool>::type
+operator<=(L&& l, R&& r)
+{
+ return (AsStringView<L>::view(std::forward<L>(l)) <=
+ AsStringView<R>::view(std::forward<R>(r)));
+}
+
+template <typename L, typename R>
+typename std::enable_if<AsStringView<L>::value && AsStringView<R>::value,
+ bool>::type
+operator>(L&& l, R&& r)
+{
+ return (AsStringView<L>::view(std::forward<L>(l)) >
+ AsStringView<R>::view(std::forward<R>(r)));
+}
+
+template <typename L, typename R>
+typename std::enable_if<AsStringView<L>::value && AsStringView<R>::value,
+ bool>::type
+operator>=(L&& l, R&& r)
+{
+ return (AsStringView<L>::view(std::forward<L>(l)) >=
+ AsStringView<R>::view(std::forward<R>(r)));
+}
+
+std::ostream& operator<<(std::ostream& os, String const& s);
+std::string& operator+=(std::string& self, String const& s);
+
+template <typename L, typename R>
+struct StringOpPlus
+{
+ L l;
+ R r;
+#if defined(__SUNPRO_CC)
+ StringOpPlus(L in_l, R in_r)
+ : l(in_l)
+ , r(in_r)
+ {
+ }
+#endif
+ operator std::string() const;
+ std::string::size_type size() const { return l.size() + r.size(); }
+};
+
+template <typename T>
+struct StringAdd
+{
+ static const bool value = AsStringView<T>::value;
+ typedef string_view temp_type;
+ template <typename S>
+ static temp_type temp(S&& s)
+ {
+ return AsStringView<T>::view(std::forward<S>(s));
+ }
+};
+
+template <typename L, typename R>
+struct StringAdd<StringOpPlus<L, R>> : std::true_type
+{
+ typedef StringOpPlus<L, R> const& temp_type;
+ static temp_type temp(temp_type s) { return s; }
+};
+
+template <typename L, typename R>
+StringOpPlus<L, R>::operator std::string() const
+{
+ std::string s;
+ s.reserve(size());
+ s += *this;
+ return s;
+}
+
+template <typename L, typename R>
+std::string& operator+=(std::string& s, StringOpPlus<L, R> const& a)
+{
+ s.reserve(s.size() + a.size());
+ s += a.l;
+ s += a.r;
+ return s;
+}
+
+template <typename L, typename R>
+String& operator+=(String& s, StringOpPlus<L, R> const& a)
+{
+ std::string r;
+ r.reserve(s.size() + a.size());
+ r.assign(s.data(), s.size());
+ r += a.l;
+ r += a.r;
+ s = std::move(r);
+ return s;
+}
+
+template <typename L, typename R>
+std::ostream& operator<<(std::ostream& os, StringOpPlus<L, R> const& a)
+{
+ return os << a.l << a.r;
+}
+
+template <typename L, typename R>
+struct IntoString<StringOpPlus<L, R>> : std::true_type
+{
+ static std::string into_string(StringOpPlus<L, R> const& a) { return a; }
+};
+
+template <typename L, typename R>
+typename std::enable_if<StringAdd<L>::value && StringAdd<R>::value,
+ StringOpPlus<typename StringAdd<L>::temp_type,
+ typename StringAdd<R>::temp_type>>::type
+operator+(L&& l, R&& r)
+{
+ return { StringAdd<L>::temp(std::forward<L>(l)),
+ StringAdd<R>::temp(std::forward<R>(r)) };
+}
+
+template <typename LL, typename LR, typename R>
+typename std::enable_if<AsStringView<R>::value, bool>::type operator==(
+ StringOpPlus<LL, LR> const& l, R&& r)
+{
+ return std::string(l) == AsStringView<R>::view(std::forward<R>(r));
+}
+
+template <typename L, typename RL, typename RR>
+typename std::enable_if<AsStringView<L>::value, bool>::type operator==(
+ L&& l, StringOpPlus<RL, RR> const& r)
+{
+ return AsStringView<L>::view(std::forward<L>(l)) == std::string(r);
+}
+
+} // namespace cm
+
+namespace std {
+
+template <>
+struct hash<cm::String>
+{
+ typedef cm::String argument_type;
+ typedef size_t result_type;
+
+ result_type operator()(argument_type const& s) const noexcept
+ {
+ result_type const h(std::hash<cm::string_view>{}(s.view()));
+ return h;
+ }
+};
+}
+
+#endif
diff --git a/Source/cmStringReplaceHelper.cxx b/Source/cmStringReplaceHelper.cxx
new file mode 100644
index 000000000..4a6298782
--- /dev/null
+++ b/Source/cmStringReplaceHelper.cxx
@@ -0,0 +1,120 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#include "cmStringReplaceHelper.h"
+
+#include "cmMakefile.h"
+#include <sstream>
+#include <utility>
+
+cmStringReplaceHelper::cmStringReplaceHelper(const std::string& regex,
+ std::string replace_expr,
+ cmMakefile* makefile)
+ : RegExString(regex)
+ , RegularExpression(regex)
+ , ReplaceExpression(std::move(replace_expr))
+ , Makefile(makefile)
+{
+ this->ParseReplaceExpression();
+}
+
+bool cmStringReplaceHelper::Replace(const std::string& input,
+ std::string& output)
+{
+ output.clear();
+
+ // Scan through the input for all matches.
+ std::string::size_type base = 0;
+ while (this->RegularExpression.find(input.c_str() + base)) {
+ if (this->Makefile != nullptr) {
+ this->Makefile->ClearMatches();
+ this->Makefile->StoreMatches(this->RegularExpression);
+ }
+ auto l2 = this->RegularExpression.start();
+ auto r = this->RegularExpression.end();
+
+ // Concatenate the part of the input that was not matched.
+ output += input.substr(base, l2);
+
+ // Make sure the match had some text.
+ if (r - l2 == 0) {
+ std::ostringstream error;
+ error << "regex \"" << this->RegExString << "\" matched an empty string";
+ this->ErrorString = error.str();
+ return false;
+ }
+
+ // Concatenate the replacement for the match.
+ for (const auto& replacement : this->Replacements) {
+ if (replacement.Number < 0) {
+ // This is just a plain-text part of the replacement.
+ output += replacement.Value;
+ } else {
+ // Replace with part of the match.
+ auto n = replacement.Number;
+ auto start = this->RegularExpression.start(n);
+ auto end = this->RegularExpression.end(n);
+ auto len = input.length() - base;
+ if ((start != std::string::npos) && (end != std::string::npos) &&
+ (start <= len) && (end <= len)) {
+ output += input.substr(base + start, end - start);
+ } else {
+ std::ostringstream error;
+ error << "replace expression \"" << this->ReplaceExpression
+ << "\" contains an out-of-range escape for regex \""
+ << this->RegExString << "\"";
+ this->ErrorString = error.str();
+ return false;
+ }
+ }
+ }
+
+ // Move past the match.
+ base += r;
+ }
+
+ // Concatenate the text after the last match.
+ output += input.substr(base, input.length() - base);
+
+ return true;
+}
+
+void cmStringReplaceHelper::ParseReplaceExpression()
+{
+ std::string::size_type l = 0;
+ while (l < this->ReplaceExpression.length()) {
+ auto r = this->ReplaceExpression.find('\\', l);
+ if (r == std::string::npos) {
+ r = this->ReplaceExpression.length();
+ this->Replacements.emplace_back(
+ this->ReplaceExpression.substr(l, r - l));
+ } else {
+ if (r - l > 0) {
+ this->Replacements.emplace_back(
+ this->ReplaceExpression.substr(l, r - l));
+ }
+ if (r == (this->ReplaceExpression.length() - 1)) {
+ this->ValidReplaceExpression = false;
+ this->ErrorString = "replace-expression ends in a backslash";
+ return;
+ }
+ if ((this->ReplaceExpression[r + 1] >= '0') &&
+ (this->ReplaceExpression[r + 1] <= '9')) {
+ this->Replacements.emplace_back(this->ReplaceExpression[r + 1] - '0');
+ } else if (this->ReplaceExpression[r + 1] == 'n') {
+ this->Replacements.emplace_back("\n");
+ } else if (this->ReplaceExpression[r + 1] == '\\') {
+ this->Replacements.emplace_back("\\");
+ } else {
+ this->ValidReplaceExpression = false;
+ std::ostringstream error;
+ error << "Unknown escape \"" << this->ReplaceExpression.substr(r, 2)
+ << "\" in replace-expression";
+ this->ErrorString = error.str();
+ return;
+ }
+ r += 2;
+ }
+ l = r;
+ }
+}
diff --git a/Source/cmStringReplaceHelper.h b/Source/cmStringReplaceHelper.h
new file mode 100644
index 000000000..b3e470416
--- /dev/null
+++ b/Source/cmStringReplaceHelper.h
@@ -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. */
+#ifndef cmStringReplaceHelper_h
+#define cmStringReplaceHelper_h
+
+#include "cmsys/RegularExpression.hxx"
+
+#include <string>
+#include <utility>
+#include <vector>
+
+class cmMakefile;
+
+class cmStringReplaceHelper
+{
+public:
+ cmStringReplaceHelper(const std::string& regex, std::string replace_expr,
+ cmMakefile* makefile = nullptr);
+
+ bool IsRegularExpressionValid() const
+ {
+ return this->RegularExpression.is_valid();
+ }
+ bool IsReplaceExpressionValid() const
+ {
+ return this->ValidReplaceExpression;
+ }
+
+ bool Replace(const std::string& input, std::string& output);
+
+ const std::string& GetError() { return this->ErrorString; }
+
+private:
+ class RegexReplacement
+ {
+ public:
+ RegexReplacement(const char* s)
+ : Number(-1)
+ , Value(s)
+ {
+ }
+ RegexReplacement(std::string s)
+ : Number(-1)
+ , Value(std::move(s))
+ {
+ }
+ RegexReplacement(int n)
+ : Number(n)
+ {
+ }
+ RegexReplacement() = default;
+
+ int Number;
+ std::string Value;
+ };
+
+ void ParseReplaceExpression();
+
+ std::string ErrorString;
+ std::string RegExString;
+ cmsys::RegularExpression RegularExpression;
+ bool ValidReplaceExpression = true;
+ std::string ReplaceExpression;
+ std::vector<RegexReplacement> Replacements;
+ cmMakefile* Makefile = nullptr;
+};
+
+#endif
diff --git a/Source/cmTargetLinkDirectoriesCommand.cxx b/Source/cmTargetLinkDirectoriesCommand.cxx
new file mode 100644
index 000000000..269f7513e
--- /dev/null
+++ b/Source/cmTargetLinkDirectoriesCommand.cxx
@@ -0,0 +1,61 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmTargetLinkDirectoriesCommand.h"
+
+#include <sstream>
+
+#include "cmAlgorithms.h"
+#include "cmGeneratorExpression.h"
+#include "cmListFileCache.h"
+#include "cmMakefile.h"
+#include "cmMessageType.h"
+#include "cmSystemTools.h"
+#include "cmTarget.h"
+
+class cmExecutionStatus;
+
+bool cmTargetLinkDirectoriesCommand::InitialPass(
+ std::vector<std::string> const& args, cmExecutionStatus&)
+{
+ return this->HandleArguments(args, "LINK_DIRECTORIES", PROCESS_BEFORE);
+}
+
+void cmTargetLinkDirectoriesCommand::HandleMissingTarget(
+ const std::string& name)
+{
+ std::ostringstream e;
+ e << "Cannot specify link directories for target \"" << name
+ << "\" which is not built by this project.";
+ this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
+}
+
+std::string cmTargetLinkDirectoriesCommand::Join(
+ const std::vector<std::string>& content)
+{
+ std::vector<std::string> directories;
+
+ for (const auto& dir : content) {
+ auto unixPath = dir;
+ cmSystemTools::ConvertToUnixSlashes(unixPath);
+ if (!cmSystemTools::FileIsFullPath(unixPath) &&
+ !cmGeneratorExpression::StartsWithGeneratorExpression(unixPath)) {
+ auto tmp = this->Makefile->GetCurrentSourceDirectory();
+ tmp += "/";
+ tmp += unixPath;
+ unixPath = tmp;
+ }
+ directories.push_back(unixPath);
+ }
+
+ return cmJoin(directories, ";");
+}
+
+bool cmTargetLinkDirectoriesCommand::HandleDirectContent(
+ cmTarget* tgt, const std::vector<std::string>& content, bool prepend, bool)
+{
+ cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
+
+ tgt->InsertLinkDirectory(this->Join(content), lfbt, prepend);
+
+ return true; // Successfully handled.
+}
diff --git a/Source/cmTargetLinkDirectoriesCommand.h b/Source/cmTargetLinkDirectoriesCommand.h
new file mode 100644
index 000000000..52c75a0b9
--- /dev/null
+++ b/Source/cmTargetLinkDirectoriesCommand.h
@@ -0,0 +1,41 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmTargetLinkDirectoriesCommand_h
+#define cmTargetLinkDirectoriesCommand_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+#include "cmTargetPropCommandBase.h"
+
+class cmCommand;
+class cmExecutionStatus;
+class cmTarget;
+
+class cmTargetLinkDirectoriesCommand : public cmTargetPropCommandBase
+{
+public:
+ /**
+ * This is a virtual constructor for the command.
+ */
+ cmCommand* Clone() override { return new cmTargetLinkDirectoriesCommand; }
+
+ /**
+ * 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;
+
+private:
+ void HandleMissingTarget(const std::string& name) override;
+
+ std::string Join(const std::vector<std::string>& content) override;
+ bool HandleDirectContent(cmTarget* tgt,
+ const std::vector<std::string>& content,
+ bool prepend, bool system) override;
+};
+
+#endif
diff --git a/Source/cmTargetLinkOptionsCommand.cxx b/Source/cmTargetLinkOptionsCommand.cxx
new file mode 100644
index 000000000..536648638
--- /dev/null
+++ b/Source/cmTargetLinkOptionsCommand.cxx
@@ -0,0 +1,41 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmTargetLinkOptionsCommand.h"
+
+#include <sstream>
+
+#include "cmAlgorithms.h"
+#include "cmListFileCache.h"
+#include "cmMakefile.h"
+#include "cmMessageType.h"
+#include "cmTarget.h"
+
+class cmExecutionStatus;
+
+bool cmTargetLinkOptionsCommand::InitialPass(
+ std::vector<std::string> const& args, cmExecutionStatus&)
+{
+ return this->HandleArguments(args, "LINK_OPTIONS", PROCESS_BEFORE);
+}
+
+void cmTargetLinkOptionsCommand::HandleMissingTarget(const std::string& name)
+{
+ std::ostringstream e;
+ e << "Cannot specify link options for target \"" << name
+ << "\" which is not built by this project.";
+ this->Makefile->IssueMessage(MessageType::FATAL_ERROR, e.str());
+}
+
+std::string cmTargetLinkOptionsCommand::Join(
+ const std::vector<std::string>& content)
+{
+ return cmJoin(content, ";");
+}
+
+bool cmTargetLinkOptionsCommand::HandleDirectContent(
+ cmTarget* tgt, const std::vector<std::string>& content, bool prepend, bool)
+{
+ cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
+ tgt->InsertLinkOption(this->Join(content), lfbt, prepend);
+ return true; // Successfully handled.
+}
diff --git a/Source/cmTargetLinkOptionsCommand.h b/Source/cmTargetLinkOptionsCommand.h
new file mode 100644
index 000000000..a1fc9fc2e
--- /dev/null
+++ b/Source/cmTargetLinkOptionsCommand.h
@@ -0,0 +1,41 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmTargetLinkOptionsCommand_h
+#define cmTargetLinkOptionsCommand_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+#include "cmTargetPropCommandBase.h"
+
+class cmCommand;
+class cmExecutionStatus;
+class cmTarget;
+
+class cmTargetLinkOptionsCommand : public cmTargetPropCommandBase
+{
+public:
+ /**
+ * This is a virtual constructor for the command.
+ */
+ cmCommand* Clone() override { return new cmTargetLinkOptionsCommand; }
+
+ /**
+ * 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;
+
+private:
+ void HandleMissingTarget(const std::string& name) override;
+
+ bool HandleDirectContent(cmTarget* tgt,
+ const std::vector<std::string>& content,
+ bool prepend, bool system) override;
+ std::string Join(const std::vector<std::string>& content) override;
+};
+
+#endif
diff --git a/Source/cmUVHandlePtr.cxx b/Source/cmUVHandlePtr.cxx
new file mode 100644
index 000000000..db674636c
--- /dev/null
+++ b/Source/cmUVHandlePtr.cxx
@@ -0,0 +1,267 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#define cmUVHandlePtr_cxx
+#include "cmUVHandlePtr.h"
+
+#include <assert.h>
+#include <mutex>
+#include <stdlib.h>
+
+#include "cm_uv.h"
+
+namespace cm {
+
+struct uv_loop_deleter
+{
+ void operator()(uv_loop_t* loop) const;
+};
+
+void uv_loop_deleter::operator()(uv_loop_t* loop) const
+{
+ uv_run(loop, UV_RUN_DEFAULT);
+ int result = uv_loop_close(loop);
+ (void)result;
+ assert(result >= 0);
+ free(loop);
+}
+
+int uv_loop_ptr::init(void* data)
+{
+ this->reset();
+
+ this->loop.reset(static_cast<uv_loop_t*>(calloc(1, sizeof(uv_loop_t))),
+ uv_loop_deleter());
+ this->loop->data = data;
+
+ return uv_loop_init(this->loop.get());
+}
+
+void uv_loop_ptr::reset()
+{
+ this->loop.reset();
+}
+
+uv_loop_ptr::operator uv_loop_t*()
+{
+ return this->loop.get();
+}
+
+uv_loop_t* uv_loop_ptr::operator->() const noexcept
+{
+ return this->loop.get();
+}
+
+uv_loop_t* uv_loop_ptr::get() const
+{
+ return this->loop.get();
+}
+
+template <typename T>
+static void handle_default_delete(T* type_handle)
+{
+ auto handle = reinterpret_cast<uv_handle_t*>(type_handle);
+ if (handle) {
+ assert(!uv_is_closing(handle));
+ if (!uv_is_closing(handle)) {
+ uv_close(handle, [](uv_handle_t* h) { free(h); });
+ }
+ }
+}
+
+/**
+ * Encapsulates delete logic for a given handle type T
+ */
+template <typename T>
+struct uv_handle_deleter
+{
+ void operator()(T* type_handle) const { handle_default_delete(type_handle); }
+};
+
+template <typename T>
+void uv_handle_ptr_base_<T>::allocate(void* data)
+{
+ reset();
+
+ /*
+ We use calloc since we know all these types are c structs
+ and we just want to 0 init them. New would do the same thing;
+ but casting from uv_handle_t to certain other types -- namely
+ uv_timer_t -- triggers a cast_align warning on certain systems.
+ */
+ handle.reset(static_cast<T*>(calloc(1, sizeof(T))), uv_handle_deleter<T>());
+ handle->data = data;
+}
+
+template <typename T>
+void uv_handle_ptr_base_<T>::reset()
+{
+ handle.reset();
+}
+
+template <typename T>
+uv_handle_ptr_base_<T>::operator uv_handle_t*()
+{
+ return reinterpret_cast<uv_handle_t*>(handle.get());
+}
+
+template <typename T>
+T* uv_handle_ptr_base_<T>::operator->() const noexcept
+{
+ return handle.get();
+}
+
+template <typename T>
+T* uv_handle_ptr_base_<T>::get() const
+{
+ return handle.get();
+}
+
+template <typename T>
+uv_handle_ptr_<T>::operator T*() const
+{
+ return this->handle.get();
+}
+
+#ifdef CMAKE_BUILD_WITH_CMAKE
+template <>
+struct uv_handle_deleter<uv_async_t>
+{
+ /***
+ * Wile uv_async_send is itself thread-safe, there are
+ * no strong guarantees that close hasn't already been
+ * called on the handle; and that it might be deleted
+ * as the send call goes through. This mutex guards
+ * against that.
+ *
+ * The shared_ptr here is to allow for copy construction
+ * which is mandated by the standard for Deleter on
+ * shared_ptrs.
+ */
+ std::shared_ptr<std::mutex> handleMutex;
+
+ uv_handle_deleter()
+ : handleMutex(std::make_shared<std::mutex>())
+ {
+ }
+
+ void operator()(uv_async_t* handle)
+ {
+ std::lock_guard<std::mutex> lock(*handleMutex);
+ handle_default_delete(handle);
+ }
+};
+
+void uv_async_ptr::send()
+{
+ auto deleter = std::get_deleter<uv_handle_deleter<uv_async_t>>(this->handle);
+ assert(deleter);
+
+ std::lock_guard<std::mutex> lock(*deleter->handleMutex);
+ if (this->handle) {
+ uv_async_send(*this);
+ }
+}
+
+int uv_async_ptr::init(uv_loop_t& loop, uv_async_cb async_cb, void* data)
+{
+ allocate(data);
+ return uv_async_init(&loop, handle.get(), async_cb);
+}
+#endif
+
+template <>
+struct uv_handle_deleter<uv_signal_t>
+{
+ void operator()(uv_signal_t* handle) const
+ {
+ if (handle) {
+ uv_signal_stop(handle);
+ handle_default_delete(handle);
+ }
+ }
+};
+
+int uv_signal_ptr::init(uv_loop_t& loop, void* data)
+{
+ allocate(data);
+ return uv_signal_init(&loop, handle.get());
+}
+
+int uv_signal_ptr::start(uv_signal_cb cb, int signum)
+{
+ assert(handle);
+ return uv_signal_start(*this, cb, signum);
+}
+
+void uv_signal_ptr::stop()
+{
+ if (handle) {
+ uv_signal_stop(*this);
+ }
+}
+
+int uv_pipe_ptr::init(uv_loop_t& loop, int ipc, void* data)
+{
+ allocate(data);
+ return uv_pipe_init(&loop, *this, ipc);
+}
+
+uv_pipe_ptr::operator uv_stream_t*() const
+{
+ return reinterpret_cast<uv_stream_t*>(handle.get());
+}
+
+int uv_process_ptr::spawn(uv_loop_t& loop, uv_process_options_t const& options,
+ void* data)
+{
+ allocate(data);
+ return uv_spawn(&loop, *this, &options);
+}
+
+int uv_timer_ptr::init(uv_loop_t& loop, void* data)
+{
+ allocate(data);
+ return uv_timer_init(&loop, *this);
+}
+
+int uv_timer_ptr::start(uv_timer_cb cb, uint64_t timeout, uint64_t repeat)
+{
+ assert(handle);
+ return uv_timer_start(*this, cb, timeout, repeat);
+}
+
+#ifdef CMAKE_BUILD_WITH_CMAKE
+uv_tty_ptr::operator uv_stream_t*() const
+{
+ return reinterpret_cast<uv_stream_t*>(handle.get());
+}
+
+int uv_tty_ptr::init(uv_loop_t& loop, int fd, int readable, void* data)
+{
+ allocate(data);
+ return uv_tty_init(&loop, *this, fd, readable);
+}
+#endif
+
+template class uv_handle_ptr_base_<uv_handle_t>;
+
+#define UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(NAME) \
+ template class uv_handle_ptr_base_<uv_##NAME##_t>; \
+ template class uv_handle_ptr_<uv_##NAME##_t>;
+
+UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(signal)
+
+UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(pipe)
+
+UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(stream)
+
+UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(process)
+
+UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(timer)
+
+#ifdef CMAKE_BUILD_WITH_CMAKE
+UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(async)
+
+UV_HANDLE_PTR_INSTANTIATE_EXPLICIT(tty)
+#endif
+}
diff --git a/Source/cmUVHandlePtr.h b/Source/cmUVHandlePtr.h
new file mode 100644
index 000000000..c09e4bfdf
--- /dev/null
+++ b/Source/cmUVHandlePtr.h
@@ -0,0 +1,271 @@
+/* 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 <cstddef>
+#include <cstdint>
+#include <memory>
+#include <type_traits>
+
+#include "cm_uv.h"
+
+#if defined(__SUNPRO_CC)
+
+# include <utility>
+
+# define CM_INHERIT_CTOR(Class, Base, Tpl) \
+ template <typename... Args> \
+ Class(Args&&... args) \
+ : Base Tpl(std::forward<Args>(args)...) \
+ { \
+ }
+
+#else
+
+# define CM_INHERIT_CTOR(Class, Base, Tpl) using Base Tpl ::Base;
+
+#endif
+
+namespace cm {
+
+/***
+ * RAII class to simplify and ensure the safe usage of uv_loop_t. This includes
+ * making sure resources are properly freed.
+ */
+class uv_loop_ptr
+{
+protected:
+ std::shared_ptr<uv_loop_t> loop;
+
+public:
+ uv_loop_ptr(uv_loop_ptr const&) = delete;
+ uv_loop_ptr& operator=(uv_loop_ptr const&) = delete;
+ uv_loop_ptr(uv_loop_ptr&&) noexcept;
+ uv_loop_ptr& operator=(uv_loop_ptr&&) noexcept;
+
+ // Dtor and ctor need to be inline defined like this for default ctors and
+ // dtors to work. Some compilers do not like '= default' here.
+ uv_loop_ptr() {} // NOLINT(modernize-use-equals-default)
+ uv_loop_ptr(std::nullptr_t) {}
+ ~uv_loop_ptr() { this->reset(); }
+
+ int init(void* data = nullptr);
+
+ /**
+ * Properly close the handle if needed and sets the inner handle to nullptr
+ */
+ void reset();
+
+ /**
+ * Allow less verbose calling of uv_loop_* functions
+ * @return reinterpreted handle
+ */
+ operator uv_loop_t*();
+
+ uv_loop_t* get() const;
+ uv_loop_t* operator->() const noexcept;
+};
+
+/***
+ * RAII class to simplify and ensure the safe usage of uv_*_t types. This
+ * includes making sure resources are properly freed and contains casting
+ * operators which allow for passing into relevant uv_* functions.
+ *
+ *@tparam T actual uv_*_t type represented.
+ */
+template <typename T>
+class uv_handle_ptr_base_
+{
+protected:
+ template <typename _T>
+ friend class uv_handle_ptr_base_;
+
+ /**
+ * This must be a pointer type since the handle can outlive this class.
+ * When uv_close is eventually called on the handle, the memory the
+ * handle inhabits must be valid until the close callback is called
+ * which can be later on in the loop.
+ */
+ std::shared_ptr<T> handle;
+
+ /**
+ * Allocate memory for the type and optionally set it's 'data' pointer.
+ * Protected since this should only be called for an appropriate 'init'
+ * call.
+ *
+ * @param data data pointer to set
+ */
+ void allocate(void* data = nullptr);
+
+public:
+ uv_handle_ptr_base_(uv_handle_ptr_base_ const&) = delete;
+ uv_handle_ptr_base_& operator=(uv_handle_ptr_base_ const&) = delete;
+ uv_handle_ptr_base_(uv_handle_ptr_base_&&) noexcept;
+ uv_handle_ptr_base_& operator=(uv_handle_ptr_base_&&) noexcept;
+
+ /**
+ * This move constructor allows us to move out of a more specialized
+ * uv type into a less specialized one. The only constraint is that
+ * the right hand side is castable to T.
+ *
+ * This allows you to return uv_handle_ptr or uv_stream_ptr from a function
+ * that initializes something like uv_pipe_ptr or uv_tcp_ptr and interact
+ * and clean up after it without caring about the exact type.
+ */
+ template <typename S,
+ typename = typename std::enable_if<
+ std::is_rvalue_reference<S&&>::value>::type>
+ uv_handle_ptr_base_(S&& rhs)
+ {
+ // This will force a compiler error if rhs doesn't have a casting
+ // operator to get T*
+ this->handle = std::shared_ptr<T>(rhs.handle, rhs);
+ rhs.handle.reset();
+ }
+
+ // Dtor and ctor need to be inline defined like this for default ctors and
+ // dtors to work. Some compilers do not like '= default' here.
+ uv_handle_ptr_base_() {} // NOLINT(modernize-use-equals-default)
+ uv_handle_ptr_base_(std::nullptr_t) {}
+ ~uv_handle_ptr_base_() { reset(); }
+
+ /**
+ * Properly close the handle if needed and sets the inner handle to nullptr
+ */
+ void reset();
+
+ /**
+ * Allow less verbose calling of uv_handle_* functions
+ * @return reinterpreted handle
+ */
+ operator uv_handle_t*();
+
+ T* get() const;
+ T* operator->() const noexcept;
+};
+
+template <typename T>
+inline uv_handle_ptr_base_<T>::uv_handle_ptr_base_(
+ uv_handle_ptr_base_<T>&&) noexcept = default;
+template <typename T>
+inline uv_handle_ptr_base_<T>& uv_handle_ptr_base_<T>::operator=(
+ uv_handle_ptr_base_<T>&&) noexcept = default;
+
+/**
+ * While uv_handle_ptr_base_ only exposes uv_handle_t*, this exposes uv_T_t*
+ * too. It is broken out like this so we can reuse most of the code for the
+ * uv_handle_ptr class.
+ */
+template <typename T>
+class uv_handle_ptr_ : public uv_handle_ptr_base_<T>
+{
+ template <typename _T>
+ friend class uv_handle_ptr_;
+
+public:
+ CM_INHERIT_CTOR(uv_handle_ptr_, uv_handle_ptr_base_, <T>);
+
+ /***
+ * Allow less verbose calling of uv_<T> functions
+ * @return reinterpreted handle
+ */
+ operator T*() const;
+};
+
+/***
+ * This specialization is required to avoid duplicate 'operator uv_handle_t*()'
+ * declarations
+ */
+template <>
+class uv_handle_ptr_<uv_handle_t> : public uv_handle_ptr_base_<uv_handle_t>
+{
+public:
+ CM_INHERIT_CTOR(uv_handle_ptr_, uv_handle_ptr_base_, <uv_handle_t>);
+};
+
+class uv_async_ptr : public uv_handle_ptr_<uv_async_t>
+{
+public:
+ CM_INHERIT_CTOR(uv_async_ptr, uv_handle_ptr_, <uv_async_t>);
+
+ int init(uv_loop_t& loop, uv_async_cb async_cb, void* data = nullptr);
+
+ void send();
+};
+
+struct uv_signal_ptr : public uv_handle_ptr_<uv_signal_t>
+{
+ CM_INHERIT_CTOR(uv_signal_ptr, uv_handle_ptr_, <uv_signal_t>);
+
+ int init(uv_loop_t& loop, void* data = nullptr);
+
+ int start(uv_signal_cb cb, int signum);
+
+ void stop();
+};
+
+struct uv_pipe_ptr : public uv_handle_ptr_<uv_pipe_t>
+{
+ CM_INHERIT_CTOR(uv_pipe_ptr, uv_handle_ptr_, <uv_pipe_t>);
+
+ operator uv_stream_t*() const;
+
+ int init(uv_loop_t& loop, int ipc, void* data = nullptr);
+};
+
+struct uv_process_ptr : public uv_handle_ptr_<uv_process_t>
+{
+ CM_INHERIT_CTOR(uv_process_ptr, uv_handle_ptr_, <uv_process_t>);
+
+ int spawn(uv_loop_t& loop, uv_process_options_t const& options,
+ void* data = nullptr);
+};
+
+struct uv_timer_ptr : public uv_handle_ptr_<uv_timer_t>
+{
+ CM_INHERIT_CTOR(uv_timer_ptr, uv_handle_ptr_, <uv_timer_t>);
+
+ int init(uv_loop_t& loop, void* data = nullptr);
+
+ int start(uv_timer_cb cb, uint64_t timeout, uint64_t repeat);
+};
+
+struct uv_tty_ptr : public uv_handle_ptr_<uv_tty_t>
+{
+ CM_INHERIT_CTOR(uv_tty_ptr, uv_handle_ptr_, <uv_tty_t>);
+
+ operator uv_stream_t*() const;
+
+ int init(uv_loop_t& loop, int fd, int readable, void* data = nullptr);
+};
+
+typedef uv_handle_ptr_<uv_stream_t> uv_stream_ptr;
+typedef uv_handle_ptr_<uv_handle_t> uv_handle_ptr;
+
+#ifndef cmUVHandlePtr_cxx
+
+extern template class uv_handle_ptr_base_<uv_handle_t>;
+
+# define UV_HANDLE_PTR_INSTANTIATE_EXTERN(NAME) \
+ extern template class uv_handle_ptr_base_<uv_##NAME##_t>; \
+ extern template class uv_handle_ptr_<uv_##NAME##_t>;
+
+UV_HANDLE_PTR_INSTANTIATE_EXTERN(async)
+
+UV_HANDLE_PTR_INSTANTIATE_EXTERN(signal)
+
+UV_HANDLE_PTR_INSTANTIATE_EXTERN(pipe)
+
+UV_HANDLE_PTR_INSTANTIATE_EXTERN(process)
+
+UV_HANDLE_PTR_INSTANTIATE_EXTERN(stream)
+
+UV_HANDLE_PTR_INSTANTIATE_EXTERN(timer)
+
+UV_HANDLE_PTR_INSTANTIATE_EXTERN(tty)
+
+# undef UV_HANDLE_PTR_INSTANTIATE_EXTERN
+
+#endif
+}
diff --git a/Source/cmUVProcessChain.cxx b/Source/cmUVProcessChain.cxx
new file mode 100644
index 000000000..90ece0bc5
--- /dev/null
+++ b/Source/cmUVProcessChain.cxx
@@ -0,0 +1,395 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmUVProcessChain.h"
+
+#include "cmAlgorithms.h"
+#include "cmGetPipes.h"
+#include "cmUVHandlePtr.h"
+#include "cmUVStreambuf.h"
+#include "cm_uv.h"
+
+#include <assert.h>
+
+#include <iterator>
+#include <memory>
+#include <utility>
+
+struct cmUVProcessChain::InternalData
+{
+ struct BasicStreamData
+ {
+ cmUVStreambuf Streambuf;
+ cm::uv_pipe_ptr BuiltinStream;
+ uv_stdio_container_t Stdio;
+ };
+
+ template <typename IOStream>
+ struct StreamData : public BasicStreamData
+ {
+ StreamData()
+ : BuiltinIOStream(&this->Streambuf)
+ {
+ }
+
+ IOStream BuiltinIOStream;
+
+ IOStream* GetBuiltinStream()
+ {
+ if (this->BuiltinStream.get()) {
+ return &this->BuiltinIOStream;
+ }
+ return nullptr;
+ }
+ };
+
+ struct ProcessData
+ {
+ cmUVProcessChain::InternalData* Data;
+ cm::uv_process_ptr Process;
+ cm::uv_pipe_ptr OutputPipe;
+ bool Finished = false;
+ Status ProcessStatus;
+ };
+
+ const cmUVProcessChainBuilder* Builder = nullptr;
+
+ bool Valid = false;
+
+ cm::uv_loop_ptr Loop;
+
+ StreamData<std::istream> OutputStreamData;
+ StreamData<std::istream> ErrorStreamData;
+
+ unsigned int ProcessesCompleted = 0;
+ std::vector<std::unique_ptr<ProcessData>> Processes;
+
+ bool Prepare(const cmUVProcessChainBuilder* builder);
+ bool AddCommand(const cmUVProcessChainBuilder::ProcessConfiguration& config,
+ bool first, bool last);
+ bool Finish();
+
+ static const Status* GetStatus(const ProcessData& data);
+};
+
+cmUVProcessChainBuilder::cmUVProcessChainBuilder()
+{
+ this->SetNoStream(Stream_INPUT)
+ .SetNoStream(Stream_OUTPUT)
+ .SetNoStream(Stream_ERROR);
+}
+
+cmUVProcessChainBuilder& cmUVProcessChainBuilder::AddCommand(
+ const std::vector<std::string>& arguments)
+{
+ if (!arguments.empty()) {
+ this->Processes.emplace_back();
+ this->Processes.back().Arguments = arguments;
+ }
+ return *this;
+}
+
+cmUVProcessChainBuilder& cmUVProcessChainBuilder::SetNoStream(Stream stdio)
+{
+ switch (stdio) {
+ case Stream_INPUT:
+ case Stream_OUTPUT:
+ case Stream_ERROR: {
+ auto& streamData = this->Stdio[stdio];
+ streamData.Type = None;
+ break;
+ }
+ }
+ return *this;
+}
+
+cmUVProcessChainBuilder& cmUVProcessChainBuilder::SetBuiltinStream(
+ Stream stdio)
+{
+ switch (stdio) {
+ case Stream_INPUT:
+ // FIXME
+ break;
+
+ case Stream_OUTPUT:
+ case Stream_ERROR: {
+ auto& streamData = this->Stdio[stdio];
+ streamData.Type = Builtin;
+ break;
+ }
+ }
+ return *this;
+}
+
+cmUVProcessChainBuilder& cmUVProcessChainBuilder::SetExternalStream(
+ Stream stdio, int fd)
+{
+ switch (stdio) {
+ case Stream_INPUT:
+ // FIXME
+ break;
+
+ case Stream_OUTPUT:
+ case Stream_ERROR: {
+ auto& streamData = this->Stdio[stdio];
+ streamData.Type = External;
+ streamData.FileDescriptor = fd;
+ break;
+ }
+ }
+ return *this;
+}
+
+cmUVProcessChain cmUVProcessChainBuilder::Start() const
+{
+ cmUVProcessChain chain;
+
+ if (!chain.Data->Prepare(this)) {
+ return chain;
+ }
+
+ for (auto it = this->Processes.begin(); it != this->Processes.end(); ++it) {
+ if (!chain.Data->AddCommand(*it, it == this->Processes.begin(),
+ it == std::prev(this->Processes.end()))) {
+ return chain;
+ }
+ }
+
+ chain.Data->Finish();
+
+ return chain;
+}
+
+const cmUVProcessChain::Status* cmUVProcessChain::InternalData::GetStatus(
+ const cmUVProcessChain::InternalData::ProcessData& data)
+{
+ if (data.Finished) {
+ return &data.ProcessStatus;
+ }
+ return nullptr;
+}
+
+bool cmUVProcessChain::InternalData::Prepare(
+ const cmUVProcessChainBuilder* builder)
+{
+ this->Builder = builder;
+
+ auto const& output =
+ this->Builder->Stdio[cmUVProcessChainBuilder::Stream_OUTPUT];
+ auto& outputData = this->OutputStreamData;
+ switch (output.Type) {
+ case cmUVProcessChainBuilder::None:
+ outputData.Stdio.flags = UV_IGNORE;
+ break;
+
+ case cmUVProcessChainBuilder::Builtin:
+ outputData.BuiltinStream.init(*this->Loop, 0);
+ outputData.Stdio.flags =
+ static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE);
+ outputData.Stdio.data.stream = outputData.BuiltinStream;
+ break;
+
+ case cmUVProcessChainBuilder::External:
+ outputData.Stdio.flags = UV_INHERIT_FD;
+ outputData.Stdio.data.fd = output.FileDescriptor;
+ break;
+ }
+
+ auto const& error =
+ this->Builder->Stdio[cmUVProcessChainBuilder::Stream_ERROR];
+ auto& errorData = this->ErrorStreamData;
+ switch (error.Type) {
+ case cmUVProcessChainBuilder::None:
+ errorData.Stdio.flags = UV_IGNORE;
+ break;
+
+ case cmUVProcessChainBuilder::Builtin: {
+ int pipeFd[2];
+ if (cmGetPipes(pipeFd) < 0) {
+ return false;
+ }
+
+ errorData.BuiltinStream.init(*this->Loop, 0);
+ if (uv_pipe_open(errorData.BuiltinStream, pipeFd[0]) < 0) {
+ return false;
+ }
+ errorData.Stdio.flags = UV_INHERIT_FD;
+ errorData.Stdio.data.fd = pipeFd[1];
+ break;
+ }
+
+ case cmUVProcessChainBuilder::External:
+ errorData.Stdio.flags = UV_INHERIT_FD;
+ errorData.Stdio.data.fd = error.FileDescriptor;
+ break;
+ }
+
+ return true;
+}
+
+bool cmUVProcessChain::InternalData::AddCommand(
+ const cmUVProcessChainBuilder::ProcessConfiguration& config, bool first,
+ bool last)
+{
+ this->Processes.emplace_back(cm::make_unique<ProcessData>());
+ auto& process = *this->Processes.back();
+ process.Data = this;
+
+ auto options = uv_process_options_t();
+
+ // Bounds were checked at add time, first element is guaranteed to exist
+ options.file = config.Arguments[0].c_str();
+
+ std::vector<const char*> arguments;
+ for (auto const& arg : config.Arguments) {
+ arguments.push_back(arg.c_str());
+ }
+ arguments.push_back(nullptr);
+ options.args = const_cast<char**>(arguments.data());
+ options.flags = UV_PROCESS_WINDOWS_HIDE;
+
+ std::array<uv_stdio_container_t, 3> stdio;
+ stdio[0] = uv_stdio_container_t();
+ if (first) {
+ stdio[0].flags = UV_IGNORE;
+ } else {
+ assert(this->Processes.size() >= 2);
+ auto& prev = *this->Processes[this->Processes.size() - 2];
+ stdio[0].flags = UV_INHERIT_STREAM;
+ stdio[0].data.stream = prev.OutputPipe;
+ }
+ if (last) {
+ stdio[1] = this->OutputStreamData.Stdio;
+ } else {
+ if (process.OutputPipe.init(*this->Loop, 0) < 0) {
+ return false;
+ }
+ stdio[1] = uv_stdio_container_t();
+ stdio[1].flags =
+ static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE);
+ stdio[1].data.stream = process.OutputPipe;
+ }
+ stdio[2] = this->ErrorStreamData.Stdio;
+
+ options.stdio = stdio.data();
+ options.stdio_count = 3;
+ options.exit_cb = [](uv_process_t* handle, int64_t exitStatus,
+ int termSignal) {
+ auto* processData = static_cast<ProcessData*>(handle->data);
+ processData->Finished = true;
+ processData->ProcessStatus.ExitStatus = exitStatus;
+ processData->ProcessStatus.TermSignal = termSignal;
+ processData->Data->ProcessesCompleted++;
+ };
+
+ return process.Process.spawn(*this->Loop, options, &process) >= 0;
+}
+
+bool cmUVProcessChain::InternalData::Finish()
+{
+ if (this->Builder->Stdio[cmUVProcessChainBuilder::Stream_OUTPUT].Type ==
+ cmUVProcessChainBuilder::Builtin) {
+ this->OutputStreamData.Streambuf.open(
+ this->OutputStreamData.BuiltinStream);
+ }
+
+ if (this->Builder->Stdio[cmUVProcessChainBuilder::Stream_ERROR].Type ==
+ cmUVProcessChainBuilder::Builtin) {
+ cm::uv_pipe_ptr tmpPipe;
+ if (tmpPipe.init(*this->Loop, 0) < 0) {
+ return false;
+ }
+ if (uv_pipe_open(tmpPipe, this->ErrorStreamData.Stdio.data.fd) < 0) {
+ return false;
+ }
+ tmpPipe.reset();
+
+ this->ErrorStreamData.Streambuf.open(this->ErrorStreamData.BuiltinStream);
+ }
+
+ this->Valid = true;
+ return true;
+}
+
+cmUVProcessChain::cmUVProcessChain()
+ : Data(cm::make_unique<InternalData>())
+{
+ this->Data->Loop.init();
+}
+
+cmUVProcessChain::cmUVProcessChain(cmUVProcessChain&& other) noexcept
+ : Data(std::move(other.Data))
+{
+}
+
+cmUVProcessChain::~cmUVProcessChain() = default;
+
+cmUVProcessChain& cmUVProcessChain::operator=(
+ cmUVProcessChain&& other) noexcept
+{
+ this->Data = std::move(other.Data);
+ return *this;
+}
+
+uv_loop_t& cmUVProcessChain::GetLoop()
+{
+ return *this->Data->Loop;
+}
+
+std::istream* cmUVProcessChain::OutputStream()
+{
+ return this->Data->OutputStreamData.GetBuiltinStream();
+}
+
+std::istream* cmUVProcessChain::ErrorStream()
+{
+ return this->Data->ErrorStreamData.GetBuiltinStream();
+}
+
+bool cmUVProcessChain::Valid() const
+{
+ return this->Data->Valid;
+}
+
+bool cmUVProcessChain::Wait(int64_t milliseconds)
+{
+ bool timeout = false;
+ cm::uv_timer_ptr timer;
+
+ if (milliseconds >= 0) {
+ timer.init(*this->Data->Loop, &timeout);
+ timer.start(
+ [](uv_timer_t* handle) {
+ auto* timeoutPtr = static_cast<bool*>(handle->data);
+ *timeoutPtr = true;
+ },
+ milliseconds, 0);
+ }
+
+ while (!timeout &&
+ this->Data->ProcessesCompleted < this->Data->Processes.size()) {
+ uv_run(this->Data->Loop, UV_RUN_ONCE);
+ }
+
+ return !timeout;
+}
+
+std::vector<const cmUVProcessChain::Status*> cmUVProcessChain::GetStatus()
+ const
+{
+ std::vector<const cmUVProcessChain::Status*> statuses(
+ this->Data->Processes.size(), nullptr);
+ for (std::size_t i = 0; i < statuses.size(); i++) {
+ statuses[i] = this->GetStatus(i);
+ }
+ return statuses;
+}
+
+const cmUVProcessChain::Status* cmUVProcessChain::GetStatus(
+ std::size_t index) const
+{
+ auto const& process = *this->Data->Processes[index];
+ if (process.Finished) {
+ return &process.ProcessStatus;
+ }
+ return nullptr;
+}
diff --git a/Source/cmUVProcessChain.h b/Source/cmUVProcessChain.h
new file mode 100644
index 000000000..2b3352070
--- /dev/null
+++ b/Source/cmUVProcessChain.h
@@ -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. */
+#ifndef cmUVProcessChain_h
+#define cmUVProcessChain_h
+
+#include "cm_uv.h"
+
+#include <array>
+#include <iosfwd>
+#include <memory> // IWYU pragma: keep
+#include <string>
+#include <vector>
+
+#include <stdint.h>
+
+class cmUVProcessChain;
+
+class cmUVProcessChainBuilder
+{
+public:
+ enum Stream
+ {
+ Stream_INPUT = 0,
+ Stream_OUTPUT = 1,
+ Stream_ERROR = 2,
+ };
+
+ cmUVProcessChainBuilder();
+
+ cmUVProcessChainBuilder& AddCommand(
+ const std::vector<std::string>& arguments);
+ cmUVProcessChainBuilder& SetNoStream(Stream stdio);
+ cmUVProcessChainBuilder& SetBuiltinStream(Stream stdio);
+ cmUVProcessChainBuilder& SetExternalStream(Stream stdio, int fd);
+
+ cmUVProcessChain Start() const;
+
+private:
+ enum StdioType
+ {
+ None,
+ Builtin,
+ External,
+ };
+
+ friend class cmUVProcessChain;
+
+ struct StdioConfiguration
+ {
+ StdioType Type;
+ int FileDescriptor;
+ };
+
+ struct ProcessConfiguration
+ {
+ std::vector<std::string> Arguments;
+ };
+
+ std::array<StdioConfiguration, 3> Stdio;
+ std::vector<ProcessConfiguration> Processes;
+};
+
+class cmUVProcessChain
+{
+public:
+ struct Status
+ {
+ int64_t ExitStatus;
+ int TermSignal;
+ };
+
+ cmUVProcessChain(const cmUVProcessChain& other) = delete;
+ cmUVProcessChain(cmUVProcessChain&& other) noexcept;
+
+ ~cmUVProcessChain();
+
+ cmUVProcessChain& operator=(const cmUVProcessChain& other) = delete;
+ cmUVProcessChain& operator=(cmUVProcessChain&& other) noexcept;
+
+ uv_loop_t& GetLoop();
+
+ // FIXME: Add stdin support
+ std::istream* OutputStream();
+ std::istream* ErrorStream();
+
+ bool Valid() const;
+ bool Wait(int64_t milliseconds = -1);
+ std::vector<const Status*> GetStatus() const;
+ const Status* GetStatus(std::size_t index) const;
+
+private:
+ friend class cmUVProcessChainBuilder;
+
+ cmUVProcessChain();
+
+ struct InternalData;
+ std::unique_ptr<InternalData> Data;
+};
+
+#endif
diff --git a/Source/cmUVSignalHackRAII.h b/Source/cmUVSignalHackRAII.h
new file mode 100644
index 000000000..63599db82
--- /dev/null
+++ b/Source/cmUVSignalHackRAII.h
@@ -0,0 +1,45 @@
+/* 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"
+
+#if defined(CMAKE_USE_SYSTEM_LIBUV) && !defined(_WIN32) && \
+ UV_VERSION_MAJOR == 1 && UV_VERSION_MINOR < 19
+# define CMAKE_UV_SIGNAL_HACK
+# include "cmUVHandlePtr.h"
+/*
+ libuv does not use SA_RESTART on its signal handler, but C++ streams
+ depend on it for reliable i/o operations. This RAII helper convinces
+ libuv to install its handler, and then revises the handler to add the
+ SA_RESTART flag. We use a distinct uv loop that never runs to avoid
+ ever really getting a callback. libuv may fill the hack loop's signal
+ pipe and then stop writing, but that won't break any real loops.
+ */
+class cmUVSignalHackRAII
+{
+ uv_loop_t HackLoop;
+ cm::uv_signal_ptr HackSignal;
+ static void HackCB(uv_signal_t*, int) {}
+
+public:
+ cmUVSignalHackRAII()
+ {
+ uv_loop_init(&this->HackLoop);
+ this->HackSignal.init(this->HackLoop);
+ this->HackSignal.start(HackCB, SIGCHLD);
+ struct sigaction hack_sa;
+ sigaction(SIGCHLD, nullptr, &hack_sa);
+ if (!(hack_sa.sa_flags & SA_RESTART)) {
+ hack_sa.sa_flags |= SA_RESTART;
+ sigaction(SIGCHLD, &hack_sa, nullptr);
+ }
+ }
+ ~cmUVSignalHackRAII()
+ {
+ this->HackSignal.stop();
+ uv_loop_close(&this->HackLoop);
+ }
+};
+#endif
diff --git a/Source/cmUVStreambuf.h b/Source/cmUVStreambuf.h
new file mode 100644
index 000000000..873352b1a
--- /dev/null
+++ b/Source/cmUVStreambuf.h
@@ -0,0 +1,219 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmUVStreambuf_h
+#define cmUVStreambuf_h
+
+#include "cmUVHandlePtr.h"
+
+#include "cm_uv.h"
+
+#include <algorithm>
+#include <cstring>
+#include <streambuf>
+#include <vector>
+
+/*
+ * This file is based on example code from:
+ *
+ * http://www.voidcn.com/article/p-vjnlygmc-gy.html
+ *
+ * The example code was distributed under the following license:
+ *
+ * Copyright 2007 Edd Dawson.
+ * Distributed under the Boost Software License, Version 1.0.
+ *
+ * Boost Software License - Version 1.0 - August 17th, 2003
+ *
+ * Permission is hereby granted, free of charge, to any person or organization
+ * obtaining a copy of the software and accompanying documentation covered by
+ * this license (the "Software") to use, reproduce, display, distribute,
+ * execute, and transmit the Software, and to prepare derivative works of the
+ * Software, and to permit third-parties to whom the Software is furnished to
+ * do so, all subject to the following:
+ *
+ * The copyright notices in the Software and this entire statement, including
+ * the above license grant, this restriction and the following disclaimer,
+ * must be included in all copies of the Software, in whole or in part, and
+ * all derivative works of the Software, unless such copies or derivative
+ * works are solely in the form of machine-executable object code generated by
+ * a source language processor.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+ * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+ * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+template <typename CharT, typename Traits = std::char_traits<CharT>>
+class cmBasicUVStreambuf : public std::basic_streambuf<CharT, Traits>
+{
+public:
+ cmBasicUVStreambuf(std::size_t bufSize = 256, std::size_t putBack = 8);
+ ~cmBasicUVStreambuf() override;
+
+ bool is_open() const;
+
+ cmBasicUVStreambuf* open(uv_stream_t* stream);
+
+ cmBasicUVStreambuf* close();
+
+protected:
+ typename cmBasicUVStreambuf::int_type underflow() override;
+ std::streamsize showmanyc() override;
+
+ // FIXME: Add write support
+
+private:
+ uv_stream_t* Stream = nullptr;
+ void* OldStreamData = nullptr;
+ const std::size_t PutBack = 0;
+ std::vector<CharT> InputBuffer;
+ bool EndOfFile = false;
+
+ void StreamReadStartStop();
+
+ void StreamRead(ssize_t nread);
+ void HandleAlloc(uv_buf_t* buf);
+};
+
+template <typename CharT, typename Traits>
+cmBasicUVStreambuf<CharT, Traits>::cmBasicUVStreambuf(std::size_t bufSize,
+ std::size_t putBack)
+ : PutBack(std::max<std::size_t>(putBack, 1))
+ , InputBuffer(std::max<std::size_t>(this->PutBack, bufSize) + this->PutBack)
+{
+ this->close();
+}
+
+template <typename CharT, typename Traits>
+cmBasicUVStreambuf<CharT, Traits>::~cmBasicUVStreambuf()
+{
+ this->close();
+}
+
+template <typename CharT, typename Traits>
+bool cmBasicUVStreambuf<CharT, Traits>::is_open() const
+{
+ return this->Stream != nullptr;
+}
+
+template <typename CharT, typename Traits>
+cmBasicUVStreambuf<CharT, Traits>* cmBasicUVStreambuf<CharT, Traits>::open(
+ uv_stream_t* stream)
+{
+ this->close();
+ this->Stream = stream;
+ this->EndOfFile = false;
+ if (this->Stream) {
+ this->OldStreamData = this->Stream->data;
+ this->Stream->data = this;
+ }
+ this->StreamReadStartStop();
+ return this;
+}
+
+template <typename CharT, typename Traits>
+cmBasicUVStreambuf<CharT, Traits>* cmBasicUVStreambuf<CharT, Traits>::close()
+{
+ if (this->Stream) {
+ uv_read_stop(this->Stream);
+ this->Stream->data = this->OldStreamData;
+ }
+ this->Stream = nullptr;
+ CharT* readEnd = this->InputBuffer.data() + this->InputBuffer.size();
+ this->setg(readEnd, readEnd, readEnd);
+ return this;
+}
+
+template <typename CharT, typename Traits>
+typename cmBasicUVStreambuf<CharT, Traits>::int_type
+cmBasicUVStreambuf<CharT, Traits>::underflow()
+{
+ if (!this->is_open()) {
+ return Traits::eof();
+ }
+
+ if (this->gptr() < this->egptr()) {
+ return Traits::to_int_type(*this->gptr());
+ }
+
+ this->StreamReadStartStop();
+ while (this->in_avail() == 0) {
+ uv_run(this->Stream->loop, UV_RUN_ONCE);
+ }
+ if (this->in_avail() == -1) {
+ return Traits::eof();
+ }
+ return Traits::to_int_type(*this->gptr());
+}
+
+template <typename CharT, typename Traits>
+std::streamsize cmBasicUVStreambuf<CharT, Traits>::showmanyc()
+{
+ if (!this->is_open() || this->EndOfFile) {
+ return -1;
+ }
+ return 0;
+}
+
+template <typename CharT, typename Traits>
+void cmBasicUVStreambuf<CharT, Traits>::StreamReadStartStop()
+{
+ if (this->Stream) {
+ uv_read_stop(this->Stream);
+ if (this->gptr() >= this->egptr()) {
+ uv_read_start(
+ this->Stream,
+ [](uv_handle_t* handle, size_t /* unused */, uv_buf_t* buf) {
+ auto streambuf =
+ static_cast<cmBasicUVStreambuf<CharT, Traits>*>(handle->data);
+ streambuf->HandleAlloc(buf);
+ },
+ [](uv_stream_t* stream2, ssize_t nread, const uv_buf_t* /* unused */) {
+ auto streambuf =
+ static_cast<cmBasicUVStreambuf<CharT, Traits>*>(stream2->data);
+ streambuf->StreamRead(nread);
+ });
+ }
+ }
+}
+
+template <typename CharT, typename Traits>
+void cmBasicUVStreambuf<CharT, Traits>::HandleAlloc(uv_buf_t* buf)
+{
+ auto size = this->egptr() - this->gptr();
+ std::memmove(this->InputBuffer.data(), this->gptr(),
+ this->egptr() - this->gptr());
+ this->setg(this->InputBuffer.data(), this->InputBuffer.data(),
+ this->InputBuffer.data() + size);
+ buf->base = this->egptr();
+#ifdef _WIN32
+# define BUF_LEN_TYPE ULONG
+#else
+# define BUF_LEN_TYPE size_t
+#endif
+ buf->len = BUF_LEN_TYPE(
+ (this->InputBuffer.data() + this->InputBuffer.size() - this->egptr()) *
+ sizeof(CharT));
+#undef BUF_LEN_TYPE
+}
+
+template <typename CharT, typename Traits>
+void cmBasicUVStreambuf<CharT, Traits>::StreamRead(ssize_t nread)
+{
+ if (nread > 0) {
+ this->setg(this->eback(), this->gptr(),
+ this->egptr() + nread / sizeof(CharT));
+ uv_read_stop(this->Stream);
+ } else if (nread < 0 /*|| nread == UV_EOF*/) {
+ this->EndOfFile = true;
+ uv_read_stop(this->Stream);
+ }
+}
+
+using cmUVStreambuf = cmBasicUVStreambuf<char>;
+
+#endif
diff --git a/Source/cmWorkerPool.cxx b/Source/cmWorkerPool.cxx
new file mode 100644
index 000000000..cbf070e91
--- /dev/null
+++ b/Source/cmWorkerPool.cxx
@@ -0,0 +1,763 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmWorkerPool.h"
+
+#include "cmRange.h"
+#include "cmUVHandlePtr.h"
+#include "cmUVSignalHackRAII.h" // IWYU pragma: keep
+#include "cm_uv.h"
+
+#include <algorithm>
+#include <array>
+#include <condition_variable>
+#include <deque>
+#include <functional>
+#include <mutex>
+#include <stddef.h>
+#include <thread>
+
+/**
+ * @brief libuv pipe buffer class
+ */
+class cmUVPipeBuffer
+{
+public:
+ typedef cmRange<char const*> DataRange;
+ typedef std::function<void(DataRange)> DataFunction;
+ /// On error the ssize_t argument is a non zero libuv error code
+ typedef std::function<void(ssize_t)> EndFunction;
+
+public:
+ /**
+ * Reset to construction state
+ */
+ void reset();
+
+ /**
+ * Initializes uv_pipe(), uv_stream() and uv_handle()
+ * @return true on success
+ */
+ bool init(uv_loop_t* uv_loop);
+
+ /**
+ * Start reading
+ * @return true on success
+ */
+ bool startRead(DataFunction dataFunction, EndFunction endFunction);
+
+ //! libuv pipe
+ uv_pipe_t* uv_pipe() const { return UVPipe_.get(); }
+ //! uv_pipe() casted to libuv stream
+ uv_stream_t* uv_stream() const { return static_cast<uv_stream_t*>(UVPipe_); }
+ //! uv_pipe() casted to libuv handle
+ uv_handle_t* uv_handle() { return static_cast<uv_handle_t*>(UVPipe_); }
+
+private:
+ // -- Libuv callbacks
+ static void UVAlloc(uv_handle_t* handle, size_t suggestedSize,
+ uv_buf_t* buf);
+ static void UVData(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf);
+
+private:
+ cm::uv_pipe_ptr UVPipe_;
+ std::vector<char> Buffer_;
+ DataFunction DataFunction_;
+ EndFunction EndFunction_;
+};
+
+void cmUVPipeBuffer::reset()
+{
+ if (UVPipe_.get() != nullptr) {
+ EndFunction_ = nullptr;
+ DataFunction_ = nullptr;
+ Buffer_.clear();
+ Buffer_.shrink_to_fit();
+ UVPipe_.reset();
+ }
+}
+
+bool cmUVPipeBuffer::init(uv_loop_t* uv_loop)
+{
+ reset();
+ if (uv_loop == nullptr) {
+ return false;
+ }
+ int ret = UVPipe_.init(*uv_loop, 0, this);
+ return (ret == 0);
+}
+
+bool cmUVPipeBuffer::startRead(DataFunction dataFunction,
+ EndFunction endFunction)
+{
+ if (UVPipe_.get() == nullptr) {
+ return false;
+ }
+ if (!dataFunction || !endFunction) {
+ return false;
+ }
+ DataFunction_ = std::move(dataFunction);
+ EndFunction_ = std::move(endFunction);
+ int ret = uv_read_start(uv_stream(), &cmUVPipeBuffer::UVAlloc,
+ &cmUVPipeBuffer::UVData);
+ return (ret == 0);
+}
+
+void cmUVPipeBuffer::UVAlloc(uv_handle_t* handle, size_t suggestedSize,
+ uv_buf_t* buf)
+{
+ auto& pipe = *reinterpret_cast<cmUVPipeBuffer*>(handle->data);
+ pipe.Buffer_.resize(suggestedSize);
+ buf->base = pipe.Buffer_.data();
+ buf->len = static_cast<unsigned long>(pipe.Buffer_.size());
+}
+
+void cmUVPipeBuffer::UVData(uv_stream_t* stream, ssize_t nread,
+ const uv_buf_t* buf)
+{
+ auto& pipe = *reinterpret_cast<cmUVPipeBuffer*>(stream->data);
+ if (nread > 0) {
+ if (buf->base != nullptr) {
+ // Call data function
+ pipe.DataFunction_(DataRange(buf->base, buf->base + nread));
+ }
+ } else if (nread < 0) {
+ // Save the end function on the stack before resetting the pipe
+ EndFunction efunc;
+ efunc.swap(pipe.EndFunction_);
+ // Reset pipe before calling the end function
+ pipe.reset();
+ // Call end function
+ efunc((nread == UV_EOF) ? 0 : nread);
+ }
+}
+
+/**
+ * @brief External process management class
+ */
+class cmUVReadOnlyProcess
+{
+public:
+ // -- Types
+ //! @brief Process settings
+ struct SetupT
+ {
+ std::string WorkingDirectory;
+ std::vector<std::string> Command;
+ cmWorkerPool::ProcessResultT* Result = nullptr;
+ bool MergedOutput = false;
+ };
+
+public:
+ // -- Const accessors
+ SetupT const& Setup() const { return Setup_; }
+ cmWorkerPool::ProcessResultT* Result() const { return Setup_.Result; }
+ bool IsStarted() const { return IsStarted_; }
+ bool IsFinished() const { return IsFinished_; }
+
+ // -- Runtime
+ void setup(cmWorkerPool::ProcessResultT* result, bool mergedOutput,
+ std::vector<std::string> const& command,
+ std::string const& workingDirectory = std::string());
+ bool start(uv_loop_t* uv_loop, std::function<void()> finishedCallback);
+
+private:
+ // -- Libuv callbacks
+ static void UVExit(uv_process_t* handle, int64_t exitStatus, int termSignal);
+ void UVPipeOutData(cmUVPipeBuffer::DataRange data);
+ void UVPipeOutEnd(ssize_t error);
+ void UVPipeErrData(cmUVPipeBuffer::DataRange data);
+ void UVPipeErrEnd(ssize_t error);
+ void UVTryFinish();
+
+private:
+ // -- Setup
+ SetupT Setup_;
+ // -- Runtime
+ bool IsStarted_ = false;
+ bool IsFinished_ = false;
+ std::function<void()> FinishedCallback_;
+ std::vector<const char*> CommandPtr_;
+ std::array<uv_stdio_container_t, 3> UVOptionsStdIO_;
+ uv_process_options_t UVOptions_;
+ cm::uv_process_ptr UVProcess_;
+ cmUVPipeBuffer UVPipeOut_;
+ cmUVPipeBuffer UVPipeErr_;
+};
+
+void cmUVReadOnlyProcess::setup(cmWorkerPool::ProcessResultT* result,
+ bool mergedOutput,
+ std::vector<std::string> const& command,
+ std::string const& workingDirectory)
+{
+ Setup_.WorkingDirectory = workingDirectory;
+ Setup_.Command = command;
+ Setup_.Result = result;
+ Setup_.MergedOutput = mergedOutput;
+}
+
+bool cmUVReadOnlyProcess::start(uv_loop_t* uv_loop,
+ std::function<void()> finishedCallback)
+{
+ if (IsStarted() || (Result() == nullptr)) {
+ return false;
+ }
+
+ // Reset result before the start
+ Result()->reset();
+
+ // Fill command string pointers
+ if (!Setup().Command.empty()) {
+ CommandPtr_.reserve(Setup().Command.size() + 1);
+ for (std::string const& arg : Setup().Command) {
+ CommandPtr_.push_back(arg.c_str());
+ }
+ CommandPtr_.push_back(nullptr);
+ } else {
+ Result()->ErrorMessage = "Empty command";
+ }
+
+ if (!Result()->error()) {
+ if (!UVPipeOut_.init(uv_loop)) {
+ Result()->ErrorMessage = "libuv stdout pipe initialization failed";
+ }
+ }
+ if (!Result()->error()) {
+ if (!UVPipeErr_.init(uv_loop)) {
+ Result()->ErrorMessage = "libuv stderr pipe initialization failed";
+ }
+ }
+ if (!Result()->error()) {
+ // -- Setup process stdio options
+ // stdin
+ UVOptionsStdIO_[0].flags = UV_IGNORE;
+ UVOptionsStdIO_[0].data.stream = nullptr;
+ // stdout
+ UVOptionsStdIO_[1].flags =
+ static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE);
+ UVOptionsStdIO_[1].data.stream = UVPipeOut_.uv_stream();
+ // stderr
+ UVOptionsStdIO_[2].flags =
+ static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE);
+ UVOptionsStdIO_[2].data.stream = UVPipeErr_.uv_stream();
+
+ // -- Setup process options
+ std::fill_n(reinterpret_cast<char*>(&UVOptions_), sizeof(UVOptions_), 0);
+ UVOptions_.exit_cb = &cmUVReadOnlyProcess::UVExit;
+ UVOptions_.file = CommandPtr_[0];
+ UVOptions_.args = const_cast<char**>(CommandPtr_.data());
+ UVOptions_.cwd = Setup_.WorkingDirectory.c_str();
+ UVOptions_.flags = UV_PROCESS_WINDOWS_HIDE;
+ UVOptions_.stdio_count = static_cast<int>(UVOptionsStdIO_.size());
+ UVOptions_.stdio = UVOptionsStdIO_.data();
+
+ // -- Spawn process
+ int uvErrorCode = UVProcess_.spawn(*uv_loop, UVOptions_, this);
+ if (uvErrorCode != 0) {
+ Result()->ErrorMessage = "libuv process spawn failed";
+ if (const char* uvErr = uv_strerror(uvErrorCode)) {
+ Result()->ErrorMessage += ": ";
+ Result()->ErrorMessage += uvErr;
+ }
+ }
+ }
+ // -- Start reading from stdio streams
+ if (!Result()->error()) {
+ if (!UVPipeOut_.startRead(
+ [this](cmUVPipeBuffer::DataRange range) {
+ this->UVPipeOutData(range);
+ },
+ [this](ssize_t error) { this->UVPipeOutEnd(error); })) {
+ Result()->ErrorMessage = "libuv start reading from stdout pipe failed";
+ }
+ }
+ if (!Result()->error()) {
+ if (!UVPipeErr_.startRead(
+ [this](cmUVPipeBuffer::DataRange range) {
+ this->UVPipeErrData(range);
+ },
+ [this](ssize_t error) { this->UVPipeErrEnd(error); })) {
+ Result()->ErrorMessage = "libuv start reading from stderr pipe failed";
+ }
+ }
+
+ if (!Result()->error()) {
+ IsStarted_ = true;
+ FinishedCallback_ = std::move(finishedCallback);
+ } else {
+ // Clear libuv handles and finish
+ UVProcess_.reset();
+ UVPipeOut_.reset();
+ UVPipeErr_.reset();
+ CommandPtr_.clear();
+ }
+
+ return IsStarted();
+}
+
+void cmUVReadOnlyProcess::UVExit(uv_process_t* handle, int64_t exitStatus,
+ int termSignal)
+{
+ auto& proc = *reinterpret_cast<cmUVReadOnlyProcess*>(handle->data);
+ if (proc.IsStarted() && !proc.IsFinished()) {
+ // Set error message on demand
+ proc.Result()->ExitStatus = exitStatus;
+ proc.Result()->TermSignal = termSignal;
+ if (!proc.Result()->error()) {
+ if (termSignal != 0) {
+ proc.Result()->ErrorMessage = "Process was terminated by signal ";
+ proc.Result()->ErrorMessage +=
+ std::to_string(proc.Result()->TermSignal);
+ } else if (exitStatus != 0) {
+ proc.Result()->ErrorMessage = "Process failed with return value ";
+ proc.Result()->ErrorMessage +=
+ std::to_string(proc.Result()->ExitStatus);
+ }
+ }
+
+ // Reset process handle
+ proc.UVProcess_.reset();
+ // Try finish
+ proc.UVTryFinish();
+ }
+}
+
+void cmUVReadOnlyProcess::UVPipeOutData(cmUVPipeBuffer::DataRange data)
+{
+ Result()->StdOut.append(data.begin(), data.end());
+}
+
+void cmUVReadOnlyProcess::UVPipeOutEnd(ssize_t error)
+{
+ // Process pipe error
+ if ((error != 0) && !Result()->error()) {
+ Result()->ErrorMessage =
+ "Reading from stdout pipe failed with libuv error code ";
+ Result()->ErrorMessage += std::to_string(error);
+ }
+ // Try finish
+ UVTryFinish();
+}
+
+void cmUVReadOnlyProcess::UVPipeErrData(cmUVPipeBuffer::DataRange data)
+{
+ std::string* str =
+ Setup_.MergedOutput ? &Result()->StdOut : &Result()->StdErr;
+ str->append(data.begin(), data.end());
+}
+
+void cmUVReadOnlyProcess::UVPipeErrEnd(ssize_t error)
+{
+ // Process pipe error
+ if ((error != 0) && !Result()->error()) {
+ Result()->ErrorMessage =
+ "Reading from stderr pipe failed with libuv error code ";
+ Result()->ErrorMessage += std::to_string(error);
+ }
+ // Try finish
+ UVTryFinish();
+}
+
+void cmUVReadOnlyProcess::UVTryFinish()
+{
+ // There still might be data in the pipes after the process has finished.
+ // Therefore check if the process is finished AND all pipes are closed
+ // before signaling the worker thread to continue.
+ if ((UVProcess_.get() != nullptr) || (UVPipeOut_.uv_pipe() != nullptr) ||
+ (UVPipeErr_.uv_pipe() != nullptr)) {
+ return;
+ }
+ IsFinished_ = true;
+ FinishedCallback_();
+}
+
+/**
+ * @brief Worker pool worker thread
+ */
+class cmWorkerPoolWorker
+{
+public:
+ cmWorkerPoolWorker(uv_loop_t& uvLoop);
+ ~cmWorkerPoolWorker();
+
+ cmWorkerPoolWorker(cmWorkerPoolWorker const&) = delete;
+ cmWorkerPoolWorker& operator=(cmWorkerPoolWorker const&) = delete;
+
+ /**
+ * Set the internal thread
+ */
+ void SetThread(std::thread&& aThread) { Thread_ = std::move(aThread); }
+
+ /**
+ * Run an external process
+ */
+ bool RunProcess(cmWorkerPool::ProcessResultT& result,
+ std::vector<std::string> const& command,
+ std::string const& workingDirectory);
+
+private:
+ // -- Libuv callbacks
+ static void UVProcessStart(uv_async_t* handle);
+ void UVProcessFinished();
+
+private:
+ // -- Process management
+ struct
+ {
+ std::mutex Mutex;
+ cm::uv_async_ptr Request;
+ std::condition_variable Condition;
+ std::unique_ptr<cmUVReadOnlyProcess> ROP;
+ } Proc_;
+ // -- System thread
+ std::thread Thread_;
+};
+
+cmWorkerPoolWorker::cmWorkerPoolWorker(uv_loop_t& uvLoop)
+{
+ Proc_.Request.init(uvLoop, &cmWorkerPoolWorker::UVProcessStart, this);
+}
+
+cmWorkerPoolWorker::~cmWorkerPoolWorker()
+{
+ if (Thread_.joinable()) {
+ Thread_.join();
+ }
+}
+
+bool cmWorkerPoolWorker::RunProcess(cmWorkerPool::ProcessResultT& result,
+ std::vector<std::string> const& command,
+ std::string const& workingDirectory)
+{
+ if (command.empty()) {
+ return false;
+ }
+ // Create process instance
+ {
+ std::lock_guard<std::mutex> lock(Proc_.Mutex);
+ Proc_.ROP = cm::make_unique<cmUVReadOnlyProcess>();
+ Proc_.ROP->setup(&result, true, command, workingDirectory);
+ }
+ // Send asynchronous process start request to libuv loop
+ Proc_.Request.send();
+ // Wait until the process has been finished and destroyed
+ {
+ std::unique_lock<std::mutex> ulock(Proc_.Mutex);
+ while (Proc_.ROP) {
+ Proc_.Condition.wait(ulock);
+ }
+ }
+ return !result.error();
+}
+
+void cmWorkerPoolWorker::UVProcessStart(uv_async_t* handle)
+{
+ auto* wrk = reinterpret_cast<cmWorkerPoolWorker*>(handle->data);
+ bool startFailed = false;
+ {
+ auto& Proc = wrk->Proc_;
+ std::lock_guard<std::mutex> lock(Proc.Mutex);
+ if (Proc.ROP && !Proc.ROP->IsStarted()) {
+ startFailed =
+ !Proc.ROP->start(handle->loop, [wrk] { wrk->UVProcessFinished(); });
+ }
+ }
+ // Clean up if starting of the process failed
+ if (startFailed) {
+ wrk->UVProcessFinished();
+ }
+}
+
+void cmWorkerPoolWorker::UVProcessFinished()
+{
+ {
+ std::lock_guard<std::mutex> lock(Proc_.Mutex);
+ if (Proc_.ROP && (Proc_.ROP->IsFinished() || !Proc_.ROP->IsStarted())) {
+ Proc_.ROP.reset();
+ }
+ }
+ // Notify idling thread
+ Proc_.Condition.notify_one();
+}
+
+/**
+ * @brief Private worker pool internals
+ */
+class cmWorkerPoolInternal
+{
+public:
+ // -- Constructors
+ cmWorkerPoolInternal(cmWorkerPool* pool);
+ ~cmWorkerPoolInternal();
+
+ /**
+ * Runs the libuv loop.
+ */
+ bool Process();
+
+ /**
+ * Clear queue and abort threads.
+ */
+ void Abort();
+
+ /**
+ * Push a job to the queue and notify a worker.
+ */
+ bool PushJob(cmWorkerPool::JobHandleT&& jobHandle);
+
+ /**
+ * Worker thread main loop method.
+ */
+ void Work(unsigned int workerIndex);
+
+ // -- Request slots
+ static void UVSlotBegin(uv_async_t* handle);
+ static void UVSlotEnd(uv_async_t* handle);
+
+public:
+ // -- UV loop
+#ifdef CMAKE_UV_SIGNAL_HACK
+ std::unique_ptr<cmUVSignalHackRAII> UVHackRAII;
+#endif
+ std::unique_ptr<uv_loop_t> UVLoop;
+ cm::uv_async_ptr UVRequestBegin;
+ cm::uv_async_ptr UVRequestEnd;
+
+ // -- Thread pool and job queue
+ std::mutex Mutex;
+ bool Processing = false;
+ bool Aborting = false;
+ bool FenceProcessing = false;
+ unsigned int WorkersRunning = 0;
+ unsigned int WorkersIdle = 0;
+ unsigned int JobsProcessing = 0;
+ std::deque<cmWorkerPool::JobHandleT> Queue;
+ std::condition_variable Condition;
+ std::vector<std::unique_ptr<cmWorkerPoolWorker>> Workers;
+
+ // -- References
+ cmWorkerPool* Pool = nullptr;
+};
+
+void cmWorkerPool::ProcessResultT::reset()
+{
+ ExitStatus = 0;
+ TermSignal = 0;
+ if (!StdOut.empty()) {
+ StdOut.clear();
+ StdOut.shrink_to_fit();
+ }
+ if (!StdErr.empty()) {
+ StdErr.clear();
+ StdErr.shrink_to_fit();
+ }
+ if (!ErrorMessage.empty()) {
+ ErrorMessage.clear();
+ ErrorMessage.shrink_to_fit();
+ }
+}
+
+cmWorkerPoolInternal::cmWorkerPoolInternal(cmWorkerPool* pool)
+ : Pool(pool)
+{
+ // Initialize libuv loop
+ uv_disable_stdio_inheritance();
+#ifdef CMAKE_UV_SIGNAL_HACK
+ UVHackRAII = cm::make_unique<cmUVSignalHackRAII>();
+#endif
+ UVLoop = cm::make_unique<uv_loop_t>();
+ uv_loop_init(UVLoop.get());
+}
+
+cmWorkerPoolInternal::~cmWorkerPoolInternal()
+{
+ uv_loop_close(UVLoop.get());
+}
+
+bool cmWorkerPoolInternal::Process()
+{
+ // Reset state flags
+ Processing = true;
+ Aborting = false;
+ // Initialize libuv asynchronous request
+ UVRequestBegin.init(*UVLoop, &cmWorkerPoolInternal::UVSlotBegin, this);
+ UVRequestEnd.init(*UVLoop, &cmWorkerPoolInternal::UVSlotEnd, this);
+ // Send begin request
+ UVRequestBegin.send();
+ // Run libuv loop
+ bool success = (uv_run(UVLoop.get(), UV_RUN_DEFAULT) == 0);
+ // Update state flags
+ Processing = false;
+ Aborting = false;
+ return success;
+}
+
+void cmWorkerPoolInternal::Abort()
+{
+ bool notifyThreads = false;
+ // Clear all jobs and set abort flag
+ {
+ std::lock_guard<std::mutex> guard(Mutex);
+ if (Processing && !Aborting) {
+ // Register abort and clear queue
+ Aborting = true;
+ Queue.clear();
+ notifyThreads = true;
+ }
+ }
+ if (notifyThreads) {
+ // Wake threads
+ Condition.notify_all();
+ }
+}
+
+inline bool cmWorkerPoolInternal::PushJob(cmWorkerPool::JobHandleT&& jobHandle)
+{
+ std::lock_guard<std::mutex> guard(Mutex);
+ if (Aborting) {
+ return false;
+ }
+ // Append the job to the queue
+ Queue.emplace_back(std::move(jobHandle));
+ // Notify an idle worker if there's one
+ if (WorkersIdle != 0) {
+ Condition.notify_one();
+ }
+ // Return success
+ return true;
+}
+
+void cmWorkerPoolInternal::UVSlotBegin(uv_async_t* handle)
+{
+ auto& gint = *reinterpret_cast<cmWorkerPoolInternal*>(handle->data);
+ // Create worker threads
+ {
+ unsigned int const num = gint.Pool->ThreadCount();
+ // Create workers
+ gint.Workers.reserve(num);
+ for (unsigned int ii = 0; ii != num; ++ii) {
+ gint.Workers.emplace_back(
+ cm::make_unique<cmWorkerPoolWorker>(*gint.UVLoop));
+ }
+ // Start worker threads
+ for (unsigned int ii = 0; ii != num; ++ii) {
+ gint.Workers[ii]->SetThread(
+ std::thread(&cmWorkerPoolInternal::Work, &gint, ii));
+ }
+ }
+ // Destroy begin request
+ gint.UVRequestBegin.reset();
+}
+
+void cmWorkerPoolInternal::UVSlotEnd(uv_async_t* handle)
+{
+ auto& gint = *reinterpret_cast<cmWorkerPoolInternal*>(handle->data);
+ // Join and destroy worker threads
+ gint.Workers.clear();
+ // Destroy end request
+ gint.UVRequestEnd.reset();
+}
+
+void cmWorkerPoolInternal::Work(unsigned int workerIndex)
+{
+ cmWorkerPool::JobHandleT jobHandle;
+ std::unique_lock<std::mutex> uLock(Mutex);
+ // Increment running workers count
+ ++WorkersRunning;
+ // Enter worker main loop
+ while (true) {
+ // Abort on request
+ if (Aborting) {
+ break;
+ }
+ // Wait for new jobs
+ if (Queue.empty()) {
+ ++WorkersIdle;
+ Condition.wait(uLock);
+ --WorkersIdle;
+ continue;
+ }
+
+ // Check for fence jobs
+ if (FenceProcessing || Queue.front()->IsFence()) {
+ if (JobsProcessing != 0) {
+ Condition.wait(uLock);
+ continue;
+ }
+ // No jobs get processed. Set the fence job processing flag.
+ FenceProcessing = true;
+ }
+
+ // Pop next job from queue
+ jobHandle = std::move(Queue.front());
+ Queue.pop_front();
+
+ // Unlocked scope for job processing
+ ++JobsProcessing;
+ {
+ uLock.unlock();
+ jobHandle->Work(Pool, workerIndex); // Process job
+ jobHandle.reset(); // Destroy job
+ uLock.lock();
+ }
+ --JobsProcessing;
+
+ // Was this a fence job?
+ if (FenceProcessing) {
+ FenceProcessing = false;
+ Condition.notify_all();
+ }
+ }
+
+ // Decrement running workers count
+ if (--WorkersRunning == 0) {
+ // Last worker thread about to finish. Send libuv event.
+ UVRequestEnd.send();
+ }
+}
+
+cmWorkerPool::JobT::~JobT() = default;
+
+bool cmWorkerPool::JobT::RunProcess(ProcessResultT& result,
+ std::vector<std::string> const& command,
+ std::string const& workingDirectory)
+{
+ // Get worker by index
+ auto* wrk = Pool_->Int_->Workers.at(WorkerIndex_).get();
+ return wrk->RunProcess(result, command, workingDirectory);
+}
+
+cmWorkerPool::cmWorkerPool()
+ : Int_(cm::make_unique<cmWorkerPoolInternal>(this))
+{
+}
+
+cmWorkerPool::~cmWorkerPool() = default;
+
+void cmWorkerPool::SetThreadCount(unsigned int threadCount)
+{
+ if (!Int_->Processing) {
+ ThreadCount_ = (threadCount > 0) ? threadCount : 1u;
+ }
+}
+
+bool cmWorkerPool::Process(void* userData)
+{
+ // Setup user data
+ UserData_ = userData;
+ // Run libuv loop
+ bool success = Int_->Process();
+ // Clear user data
+ UserData_ = nullptr;
+ // Return
+ return success;
+}
+
+bool cmWorkerPool::PushJob(JobHandleT&& jobHandle)
+{
+ return Int_->PushJob(std::move(jobHandle));
+}
+
+void cmWorkerPool::Abort()
+{
+ Int_->Abort();
+}
diff --git a/Source/cmWorkerPool.h b/Source/cmWorkerPool.h
new file mode 100644
index 000000000..f08bb4f8d
--- /dev/null
+++ b/Source/cmWorkerPool.h
@@ -0,0 +1,226 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmWorkerPool_h
+#define cmWorkerPool_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cmAlgorithms.h" // IWYU pragma: keep
+
+#include <memory> // IWYU pragma: keep
+#include <stdint.h>
+#include <string>
+#include <utility>
+#include <vector>
+
+// -- Types
+class cmWorkerPoolInternal;
+
+/** @class cmWorkerPool
+ * @brief Thread pool with job queue
+ */
+class cmWorkerPool
+{
+public:
+ /**
+ * Return value and output of an external process.
+ */
+ struct ProcessResultT
+ {
+ void reset();
+ bool error() const
+ {
+ return (ExitStatus != 0) || (TermSignal != 0) || !ErrorMessage.empty();
+ }
+
+ std::int64_t ExitStatus = 0;
+ int TermSignal = 0;
+ std::string StdOut;
+ std::string StdErr;
+ std::string ErrorMessage;
+ };
+
+ /**
+ * Abstract job class for concurrent job processing.
+ */
+ class JobT
+ {
+ public:
+ JobT(JobT const&) = delete;
+ JobT& operator=(JobT const&) = delete;
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~JobT();
+
+ /**
+ * Fence job flag
+ *
+ * Fence jobs require that:
+ * - all jobs before in the queue have been processed
+ * - no jobs later in the queue will be processed before this job was
+ * processed
+ */
+ bool IsFence() const { return Fence_; }
+
+ protected:
+ /**
+ * Protected default constructor
+ */
+ JobT(bool fence = false)
+ : Fence_(fence)
+ {
+ }
+
+ /**
+ * Abstract processing interface that must be implement in derived classes.
+ */
+ virtual void Process() = 0;
+
+ /**
+ * Get the worker pool.
+ * Only valid during the JobT::Process() call!
+ */
+ cmWorkerPool* Pool() const { return Pool_; }
+
+ /**
+ * Get the user data.
+ * Only valid during the JobT::Process() call!
+ */
+ void* UserData() const { return Pool_->UserData(); };
+
+ /**
+ * Get the worker index.
+ * This is the index of the thread processing this job and is in the range
+ * [0..ThreadCount).
+ * Concurrently processing jobs will never have the same WorkerIndex().
+ * Only valid during the JobT::Process() call!
+ */
+ unsigned int WorkerIndex() const { return WorkerIndex_; }
+
+ /**
+ * Run an external read only process.
+ * Use only during JobT::Process() call!
+ */
+ bool RunProcess(ProcessResultT& result,
+ std::vector<std::string> const& command,
+ std::string const& workingDirectory);
+
+ private:
+ //! Needs access to Work()
+ friend class cmWorkerPoolInternal;
+ //! Worker thread entry method.
+ void Work(cmWorkerPool* pool, unsigned int workerIndex)
+ {
+ Pool_ = pool;
+ WorkerIndex_ = workerIndex;
+ this->Process();
+ }
+
+ private:
+ cmWorkerPool* Pool_ = nullptr;
+ unsigned int WorkerIndex_ = 0;
+ bool Fence_ = false;
+ };
+
+ /**
+ * Job handle type
+ */
+ typedef std::unique_ptr<JobT> JobHandleT;
+
+ /**
+ * Fence job base class
+ */
+ class JobFenceT : public JobT
+ {
+ public:
+ JobFenceT()
+ : JobT(true)
+ {
+ }
+ //! Does nothing
+ void Process() override{};
+ };
+
+ /**
+ * Fence job that aborts the worker pool.
+ *
+ * Useful as the last job in the job queue.
+ */
+ class JobEndT : JobFenceT
+ {
+ public:
+ //! Does nothing
+ void Process() override { Pool()->Abort(); }
+ };
+
+public:
+ // -- Methods
+ cmWorkerPool();
+ ~cmWorkerPool();
+
+ /**
+ * Number of worker threads.
+ */
+ unsigned int ThreadCount() const { return ThreadCount_; }
+
+ /**
+ * Set the number of worker threads.
+ *
+ * Calling this method during Process() has no effect.
+ */
+ void SetThreadCount(unsigned int threadCount);
+
+ /**
+ * Blocking function that starts threads to process all Jobs in the queue.
+ *
+ * This method blocks until a job calls the Abort() method.
+ * @arg threadCount Number of threads to process jobs.
+ * @arg userData Common user data pointer available in all Jobs.
+ */
+ bool Process(void* userData = nullptr);
+
+ /**
+ * User data reference passed to Process().
+ *
+ * Only valid during Process().
+ */
+ void* UserData() const { return UserData_; }
+
+ // -- Job processing interface
+
+ /**
+ * Clears the job queue and aborts all worker threads.
+ *
+ * This method is thread safe and can be called from inside a job.
+ */
+ void Abort();
+
+ /**
+ * Push job to the queue.
+ *
+ * This method is thread safe and can be called from inside a job or before
+ * Process().
+ */
+ bool PushJob(JobHandleT&& jobHandle);
+
+ /**
+ * Push job to the queue
+ *
+ * This method is thread safe and can be called from inside a job or before
+ * Process().
+ */
+ template <class T, typename... Args>
+ bool EmplaceJob(Args&&... args)
+ {
+ return PushJob(cm::make_unique<T>(std::forward<Args>(args)...));
+ }
+
+private:
+ void* UserData_ = nullptr;
+ unsigned int ThreadCount_ = 1;
+ std::unique_ptr<cmWorkerPoolInternal> Int_;
+};
+
+#endif
diff --git a/Source/cm_static_string_view.hxx b/Source/cm_static_string_view.hxx
new file mode 100644
index 000000000..1bef0c68b
--- /dev/null
+++ b/Source/cm_static_string_view.hxx
@@ -0,0 +1,41 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cm_static_string_view_hxx
+#define cm_static_string_view_hxx
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cm_string_view.hxx"
+
+#include <cstddef>
+
+namespace cm {
+
+/** A string_view that only binds to static storage.
+ *
+ * This is used together with the `""_s` user-defined literal operator
+ * to construct a type-safe abstraction of a string_view that only views
+ * statically allocated strings. These strings are const and available
+ * for the entire lifetime of the program.
+ */
+class static_string_view : public string_view
+{
+ static_string_view(string_view v)
+ : string_view(v)
+ {
+ }
+
+ friend static_string_view operator"" _s(const char* data, size_t size);
+};
+
+/** Create a static_string_view using `""_s` literal syntax. */
+inline static_string_view operator"" _s(const char* data, size_t size)
+{
+ return string_view(data, size);
+}
+
+} // namespace cm
+
+using cm::operator"" _s;
+
+#endif
diff --git a/Source/cm_string_view.cxx b/Source/cm_string_view.cxx
new file mode 100644
index 000000000..61fa80e82
--- /dev/null
+++ b/Source/cm_string_view.cxx
@@ -0,0 +1,301 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#include "cm_string_view.hxx"
+
+#ifndef CMake_HAVE_CXX_STRING_VIEW
+
+# include "cm_kwiml.h"
+
+# include <algorithm>
+# include <ostream>
+# include <stdexcept>
+
+namespace cm {
+
+string_view::const_reference string_view::at(size_type pos) const
+{
+ if (pos >= size_) {
+ throw std::out_of_range("Index out of range in string_view::at");
+ }
+ return data_[pos];
+}
+
+string_view::size_type string_view::copy(char* dest, size_type count,
+ size_type pos) const
+{
+ if (pos > size_) {
+ throw std::out_of_range("Index out of range in string_view::copy");
+ }
+ size_type const rcount = std::min(count, size_ - pos);
+ traits_type::copy(dest, data_ + pos, rcount);
+ return rcount;
+}
+
+string_view string_view::substr(size_type pos, size_type count) const
+{
+ if (pos > size_) {
+ throw std::out_of_range("Index out of range in string_view::substr");
+ }
+ size_type const rcount = std::min(count, size_ - pos);
+ return string_view(data_ + pos, rcount);
+}
+
+int string_view::compare(string_view v) const noexcept
+{
+ size_type const rlen = std::min(size_, v.size_);
+ int c = traits_type::compare(data_, v.data_, rlen);
+ if (c == 0) {
+ if (size_ < v.size_) {
+ c = -1;
+ } else if (size_ > v.size_) {
+ c = 1;
+ }
+ }
+ return c;
+}
+
+int string_view::compare(size_type pos1, size_type count1, string_view v) const
+{
+ return substr(pos1, count1).compare(v);
+}
+
+int string_view::compare(size_type pos1, size_type count1, string_view v,
+ size_type pos2, size_type count2) const
+{
+ return substr(pos1, count1).compare(v.substr(pos2, count2));
+}
+
+int string_view::compare(const char* s) const
+{
+ return compare(string_view(s));
+}
+
+int string_view::compare(size_type pos1, size_type count1, const char* s) const
+{
+ return substr(pos1, count1).compare(string_view(s));
+}
+
+int string_view::compare(size_type pos1, size_type count1, const char* s,
+ size_type count2) const
+{
+ return substr(pos1, count1).compare(string_view(s, count2));
+}
+
+string_view::size_type string_view::find(string_view v, size_type pos) const
+ noexcept
+{
+ for (; pos + v.size_ <= size_; ++pos) {
+ if (std::char_traits<char>::compare(data_ + pos, v.data_, v.size_) == 0) {
+ return pos;
+ }
+ }
+ return npos;
+}
+
+string_view::size_type string_view::find(char c, size_type pos) const noexcept
+{
+ return find(string_view(&c, 1), pos);
+}
+
+string_view::size_type string_view::find(const char* s, size_type pos,
+ size_type count) const
+{
+ return find(string_view(s, count), pos);
+}
+
+string_view::size_type string_view::find(const char* s, size_type pos) const
+{
+ return find(string_view(s), pos);
+}
+
+string_view::size_type string_view::rfind(string_view v, size_type pos) const
+ noexcept
+{
+ if (size_ >= v.size_) {
+ for (pos = std::min(pos, size_ - v.size_) + 1; pos > 0;) {
+ --pos;
+ if (std::char_traits<char>::compare(data_ + pos, v.data_, v.size_) ==
+ 0) {
+ return pos;
+ }
+ }
+ }
+ return npos;
+}
+
+string_view::size_type string_view::rfind(char c, size_type pos) const noexcept
+{
+ return rfind(string_view(&c, 1), pos);
+}
+
+string_view::size_type string_view::rfind(const char* s, size_type pos,
+ size_type count) const
+{
+ return rfind(string_view(s, count), pos);
+}
+
+string_view::size_type string_view::rfind(const char* s, size_type pos) const
+{
+ return rfind(string_view(s), pos);
+}
+
+string_view::size_type string_view::find_first_of(string_view v,
+ size_type pos) const noexcept
+{
+ for (; pos < size_; ++pos) {
+ if (traits_type::find(v.data_, v.size_, data_[pos])) {
+ return pos;
+ }
+ }
+ return npos;
+}
+
+string_view::size_type string_view::find_first_of(char c, size_type pos) const
+ noexcept
+{
+ return find_first_of(string_view(&c, 1), pos);
+}
+
+string_view::size_type string_view::find_first_of(const char* s, size_type pos,
+ size_type count) const
+{
+ return find_first_of(string_view(s, count), pos);
+}
+
+string_view::size_type string_view::find_first_of(const char* s,
+ size_type pos) const
+{
+ return find_first_of(string_view(s), pos);
+}
+
+string_view::size_type string_view::find_last_of(string_view v,
+ size_type pos) const noexcept
+{
+ if (size_ > 0) {
+ for (pos = std::min(pos, size_ - 1) + 1; pos > 0;) {
+ --pos;
+ if (traits_type::find(v.data_, v.size_, data_[pos])) {
+ return pos;
+ }
+ }
+ }
+ return npos;
+}
+
+string_view::size_type string_view::find_last_of(char c, size_type pos) const
+ noexcept
+{
+ return find_last_of(string_view(&c, 1), pos);
+}
+
+string_view::size_type string_view::find_last_of(const char* s, size_type pos,
+ size_type count) const
+{
+ return find_last_of(string_view(s, count), pos);
+}
+
+string_view::size_type string_view::find_last_of(const char* s,
+ size_type pos) const
+{
+ return find_last_of(string_view(s), pos);
+}
+
+string_view::size_type string_view::find_first_not_of(string_view v,
+ size_type pos) const
+ noexcept
+{
+ for (; pos < size_; ++pos) {
+ if (!traits_type::find(v.data_, v.size_, data_[pos])) {
+ return pos;
+ }
+ }
+ return npos;
+}
+
+string_view::size_type string_view::find_first_not_of(char c,
+ size_type pos) const
+ noexcept
+{
+ return find_first_not_of(string_view(&c, 1), pos);
+}
+
+string_view::size_type string_view::find_first_not_of(const char* s,
+ size_type pos,
+ size_type count) const
+{
+ return find_first_not_of(string_view(s, count), pos);
+}
+
+string_view::size_type string_view::find_first_not_of(const char* s,
+ size_type pos) const
+{
+ return find_first_not_of(string_view(s), pos);
+}
+
+string_view::size_type string_view::find_last_not_of(string_view v,
+ size_type pos) const
+ noexcept
+{
+ if (size_ > 0) {
+ for (pos = std::min(pos, size_ - 1) + 1; pos > 0;) {
+ --pos;
+ if (!traits_type::find(v.data_, v.size_, data_[pos])) {
+ return pos;
+ }
+ }
+ }
+ return npos;
+}
+
+string_view::size_type string_view::find_last_not_of(char c,
+ size_type pos) const
+ noexcept
+{
+ return find_last_not_of(string_view(&c, 1), pos);
+}
+
+string_view::size_type string_view::find_last_not_of(const char* s,
+ size_type pos,
+ size_type count) const
+{
+ return find_last_not_of(string_view(s, count), pos);
+}
+
+string_view::size_type string_view::find_last_not_of(const char* s,
+ size_type pos) const
+{
+ return find_last_not_of(string_view(s), pos);
+}
+
+std::ostream& operator<<(std::ostream& o, string_view v)
+{
+ return o.write(v.data(), v.size());
+}
+
+std::string& operator+=(std::string& s, string_view v)
+{
+ s.append(v.data(), v.size());
+ return s;
+}
+}
+
+std::hash<cm::string_view>::result_type std::hash<cm::string_view>::operator()(
+ argument_type const& s) const noexcept
+{
+ // FNV-1a hash.
+ static KWIML_INT_uint64_t const fnv_offset_basis = 0xcbf29ce484222325;
+ static KWIML_INT_uint64_t const fnv_prime = 0x100000001b3;
+ KWIML_INT_uint64_t h = fnv_offset_basis;
+ for (char const& c : s) {
+ h = h ^ KWIML_INT_uint64_t(KWIML_INT_uint8_t(c));
+ h = h * fnv_prime;
+ }
+ return result_type(h);
+}
+#else
+// Avoid empty translation unit.
+void cm_string_view_cxx()
+{
+}
+#endif
diff --git a/Source/cm_string_view.hxx b/Source/cm_string_view.hxx
new file mode 100644
index 000000000..d368ed8e2
--- /dev/null
+++ b/Source/cm_string_view.hxx
@@ -0,0 +1,217 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cm_string_view_hxx
+#define cm_string_view_hxx
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#if __cplusplus >= 201703L || defined(_MSVC_LANG) && _MSVC_LANG >= 201703L
+# define CMake_HAVE_CXX_STRING_VIEW
+#endif
+
+#ifdef CMake_HAVE_CXX_STRING_VIEW
+# include <string_view>
+namespace cm {
+using std::string_view;
+}
+#else
+# include <cstddef>
+# include <functional>
+# include <iosfwd>
+# include <iterator>
+# include <string>
+
+namespace cm {
+
+class string_view
+{
+public:
+ using traits_type = std::string::traits_type;
+ using value_type = char;
+ using pointer = char*;
+ using const_pointer = const char*;
+ using reference = char&;
+ using const_reference = char const&;
+ using const_iterator = const char*;
+ using iterator = const_iterator;
+ using const_reverse_iterator = std::reverse_iterator<const_iterator>;
+ using reverse_iterator = const_reverse_iterator;
+ using size_type = std::string::size_type;
+ using difference_type = std::string::difference_type;
+
+ static size_type const npos = static_cast<size_type>(-1);
+
+ string_view() noexcept = default;
+ string_view(string_view const&) noexcept = default;
+
+ string_view(const char* s, size_t count) noexcept
+ : data_(s)
+ , size_(count)
+ {
+ }
+
+ string_view(const char* s) noexcept
+ : data_(s)
+ , size_(traits_type::length(s))
+ {
+ }
+
+ // C++17 does not define this constructor. Instead it defines
+ // a conversion operator on std::string to create a string_view.
+ // Since this implementation is used in C++11, std::string does
+ // not have that conversion.
+ string_view(std::string const& s) noexcept
+ : data_(s.data())
+ , size_(s.size())
+ {
+ }
+
+ // C++17 does not define this conversion. Instead it defines
+ // a constructor on std::string that can take a string_view.
+ // Since this implementation is used in C++11, std::string does
+ // not have that constructor.
+ explicit operator std::string() const { return std::string(data_, size_); }
+
+ string_view& operator=(string_view const&) = default;
+
+ const_iterator begin() const noexcept { return data_; }
+ const_iterator end() const noexcept { return data_ + size_; }
+ const_iterator cbegin() const noexcept { return begin(); }
+ const_iterator cend() const noexcept { return end(); }
+
+ const_reverse_iterator rbegin() const noexcept
+ {
+ return const_reverse_iterator(end());
+ }
+ const_reverse_iterator rend() const noexcept
+ {
+ return const_reverse_iterator(begin());
+ }
+ const_reverse_iterator crbegin() const noexcept { return rbegin(); }
+ const_reverse_iterator crend() const noexcept { return rend(); }
+
+ const_reference operator[](size_type pos) const noexcept
+ {
+ return data_[pos];
+ }
+ const_reference at(size_type pos) const;
+ const_reference front() const noexcept { return data_[0]; }
+ const_reference back() const noexcept { return data_[size_ - 1]; }
+ const_pointer data() const noexcept { return data_; }
+
+ size_type size() const noexcept { return size_; }
+ size_type length() const noexcept { return size_; }
+ size_type max_size() const noexcept { return npos - 1; }
+ bool empty() const noexcept { return size_ == 0; }
+
+ void remove_prefix(size_type n) noexcept
+ {
+ data_ += n;
+ size_ -= n;
+ }
+ void remove_suffix(size_type n) noexcept { size_ -= n; }
+ void swap(string_view& v) noexcept
+ {
+ string_view tmp = v;
+ v = *this;
+ *this = tmp;
+ }
+
+ size_type copy(char* dest, size_type count, size_type pos = 0) const;
+ string_view substr(size_type pos = 0, size_type count = npos) const;
+
+ int compare(string_view v) const noexcept;
+ int compare(size_type pos1, size_type count1, string_view v) const;
+ int compare(size_type pos1, size_type count1, string_view v, size_type pos2,
+ size_type count2) const;
+ int compare(const char* s) const;
+ int compare(size_type pos1, size_type count1, const char* s) const;
+ int compare(size_type pos1, size_type count1, const char* s,
+ size_type count2) const;
+
+ size_type find(string_view v, size_type pos = 0) const noexcept;
+ size_type find(char c, size_type pos = 0) const noexcept;
+ size_type find(const char* s, size_type pos, size_type count) const;
+ size_type find(const char* s, size_type pos = 0) const;
+
+ size_type rfind(string_view v, size_type pos = npos) const noexcept;
+ size_type rfind(char c, size_type pos = npos) const noexcept;
+ size_type rfind(const char* s, size_type pos, size_type count) const;
+ size_type rfind(const char* s, size_type pos = npos) const;
+
+ size_type find_first_of(string_view v, size_type pos = 0) const noexcept;
+ size_type find_first_of(char c, size_type pos = 0) const noexcept;
+ size_type find_first_of(const char* s, size_type pos, size_type count) const;
+ size_type find_first_of(const char* s, size_type pos = 0) const;
+
+ size_type find_last_of(string_view v, size_type pos = npos) const noexcept;
+ size_type find_last_of(char c, size_type pos = npos) const noexcept;
+ size_type find_last_of(const char* s, size_type pos, size_type count) const;
+ size_type find_last_of(const char* s, size_type pos = npos) const;
+
+ size_type find_first_not_of(string_view v, size_type pos = 0) const noexcept;
+ size_type find_first_not_of(char c, size_type pos = 0) const noexcept;
+ size_type find_first_not_of(const char* s, size_type pos,
+ size_type count) const;
+ size_type find_first_not_of(const char* s, size_type pos = 0) const;
+
+ size_type find_last_not_of(string_view v, size_type pos = npos) const
+ noexcept;
+ size_type find_last_not_of(char c, size_type pos = npos) const noexcept;
+ size_type find_last_not_of(const char* s, size_type pos,
+ size_type count) const;
+ size_type find_last_not_of(const char* s, size_type pos = npos) const;
+
+private:
+ const char* data_ = nullptr;
+ size_type size_ = 0;
+};
+
+std::ostream& operator<<(std::ostream& o, string_view v);
+
+std::string& operator+=(std::string& s, string_view v);
+
+inline bool operator==(string_view l, string_view r) noexcept
+{
+ return l.compare(r) == 0;
+}
+
+inline bool operator!=(string_view l, string_view r) noexcept
+{
+ return l.compare(r) != 0;
+}
+
+inline bool operator<(string_view l, string_view r) noexcept
+{
+ return l.compare(r) < 0;
+}
+
+inline bool operator<=(string_view l, string_view r) noexcept
+{
+ return l.compare(r) <= 0;
+}
+
+inline bool operator>(string_view l, string_view r) noexcept
+{
+ return l.compare(r) > 0;
+}
+
+inline bool operator>=(string_view l, string_view r) noexcept
+{
+ return l.compare(r) >= 0;
+}
+}
+
+namespace std {
+
+template <>
+struct hash<cm::string_view>
+{
+ typedef cm::string_view argument_type;
+ typedef size_t result_type;
+ result_type operator()(argument_type const& s) const noexcept;
+};
+}
+
+#endif
+#endif
diff --git a/Source/cm_thread.hxx b/Source/cm_thread.hxx
new file mode 100644
index 000000000..b1f064585
--- /dev/null
+++ b/Source/cm_thread.hxx
@@ -0,0 +1,48 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef CM_THREAD_HXX
+#define CM_THREAD_HXX
+
+#include "cmConfigure.h" // IWYU pragma: keep
+#include "cm_uv.h"
+
+namespace cm {
+
+class shared_mutex
+{
+ uv_rwlock_t _M_;
+
+public:
+ shared_mutex() { uv_rwlock_init(&_M_); }
+ ~shared_mutex() { uv_rwlock_destroy(&_M_); }
+
+ shared_mutex(shared_mutex const&) = delete;
+ shared_mutex& operator=(shared_mutex const&) = delete;
+
+ void lock() { uv_rwlock_wrlock(&_M_); }
+ void unlock() { uv_rwlock_wrunlock(&_M_); }
+
+ void lock_shared() { uv_rwlock_rdlock(&_M_); }
+ void unlock_shared() { uv_rwlock_rdunlock(&_M_); }
+};
+
+template <typename T>
+class shared_lock
+{
+ T& _mutex;
+
+public:
+ shared_lock(T& m)
+ : _mutex(m)
+ {
+ _mutex.lock_shared();
+ }
+
+ ~shared_lock() { _mutex.unlock_shared(); }
+
+ shared_lock(shared_lock const&) = delete;
+ shared_lock& operator=(shared_lock const&) = delete;
+};
+}
+
+#endif
diff --git a/Source/kwsys/testConfigure.cxx b/Source/kwsys/testConfigure.cxx
new file mode 100644
index 000000000..a3c2ed3ae
--- /dev/null
+++ b/Source/kwsys/testConfigure.cxx
@@ -0,0 +1,30 @@
+/* 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)
+
+// Work-around CMake dependency scanning limitation. This must
+// duplicate the above list of headers.
+#if 0
+# include "Configure.hxx.in"
+#endif
+
+static bool testFallthrough(int n)
+{
+ int r = 0;
+ switch (n) {
+ case 1:
+ ++r;
+ KWSYS_FALLTHROUGH;
+ default:
+ ++r;
+ }
+ return r == 2;
+}
+
+int testConfigure(int, char* [])
+{
+ bool res = true;
+ res = testFallthrough(1) && res;
+ return res ? 0 : 1;
+}
diff --git a/Source/kwsys/testDirectory.cxx b/Source/kwsys/testDirectory.cxx
new file mode 100644
index 000000000..b1ab0c872
--- /dev/null
+++ b/Source/kwsys/testDirectory.cxx
@@ -0,0 +1,110 @@
+/* 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 _copyDirectoryTest()
+{
+ using namespace kwsys;
+ const std::string source(TEST_SYSTEMTOOLS_BINARY_DIR
+ "/directory_testing/copyDirectoryTestSrc");
+ if (SystemTools::PathExists(source)) {
+ std::cerr << source << " shouldn't exist before test" << std::endl;
+ return 1;
+ }
+ const std::string destination(TEST_SYSTEMTOOLS_BINARY_DIR
+ "/directory_testing/copyDirectoryTestDst");
+ if (SystemTools::PathExists(destination)) {
+ std::cerr << destination << " shouldn't exist before test" << std::endl;
+ return 2;
+ }
+ const bool copysuccess = SystemTools::CopyADirectory(source, destination);
+ const bool destinationexists = SystemTools::PathExists(destination);
+ if (copysuccess) {
+ std::cerr << "CopyADirectory should have returned false" << std::endl;
+ SystemTools::RemoveADirectory(destination);
+ return 3;
+ }
+ if (destinationexists) {
+ std::cerr << "CopyADirectory returned false, but destination directory"
+ << " has been created" << std::endl;
+ SystemTools::RemoveADirectory(destination);
+ return 4;
+ }
+ return 0;
+}
+
+int testDirectory(int, char* [])
+{
+ return _doLongPathTest() + _copyDirectoryTest();
+}
diff --git a/Source/kwsys/testDynloadImpl.c b/Source/kwsys/testDynloadImpl.c
new file mode 100644
index 000000000..2b9069bc7
--- /dev/null
+++ b/Source/kwsys/testDynloadImpl.c
@@ -0,0 +1,10 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
+
+#include "testDynloadImpl.h"
+
+int TestDynamicLoaderImplData = 0;
+
+void TestDynamicLoaderImplSymbolPointer()
+{
+}
diff --git a/Source/kwsys/testDynloadImpl.h b/Source/kwsys/testDynloadImpl.h
new file mode 100644
index 000000000..d0c9dfb75
--- /dev/null
+++ b/Source/kwsys/testDynloadImpl.h
@@ -0,0 +1,15 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
+#ifdef _WIN32
+# ifdef BUILDING_TestDynloadImpl
+# define DLIMPL_EXPORT __declspec(dllexport)
+# else
+# define DLIMPL_EXPORT __declspec(dllimport)
+# endif
+#else
+# define DLIMPL_EXPORT
+#endif
+
+DLIMPL_EXPORT int TestDynamicLoaderImplData;
+
+DLIMPL_EXPORT void TestDynamicLoaderImplSymbolPointer();
diff --git a/Source/kwsys/testDynloadUse.c b/Source/kwsys/testDynloadUse.c
new file mode 100644
index 000000000..5402add6a
--- /dev/null
+++ b/Source/kwsys/testDynloadUse.c
@@ -0,0 +1,15 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
+#include "testDynloadImpl.h"
+
+#ifdef _WIN32
+# define DL_EXPORT __declspec(dllexport)
+#else
+# define DL_EXPORT
+#endif
+
+DL_EXPORT int TestLoad()
+{
+ TestDynamicLoaderImplSymbolPointer();
+ return TestDynamicLoaderImplData;
+}
diff --git a/Templates/MSBuild/FlagTables/v10_CL.json b/Templates/MSBuild/FlagTables/v10_CL.json
new file mode 100644
index 000000000..06158bee7
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v10_CL.json
@@ -0,0 +1,981 @@
+[
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Z7",
+ "comment": "C7 compatible",
+ "value": "OldStyle",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Zi",
+ "comment": "Program Database",
+ "value": "ProgramDatabase",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "ZI",
+ "comment": "Program Database for Edit And Continue",
+ "value": "EditAndContinue",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "",
+ "comment": "No Common Language RunTime Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr",
+ "comment": "Common Language RunTime Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:pure",
+ "comment": "Pure MSIL Common Language RunTime Support",
+ "value": "Pure",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:safe",
+ "comment": "Safe MSIL Common Language RunTime Support",
+ "value": "Safe",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:oldSyntax",
+ "comment": "Common Language RunTime Support, Old Syntax",
+ "value": "OldSyntax",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W0",
+ "comment": "Turn Off All Warnings",
+ "value": "TurnOffAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W1",
+ "comment": "Level1",
+ "value": "Level1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W2",
+ "comment": "Level2",
+ "value": "Level2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W3",
+ "comment": "Level3",
+ "value": "Level3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W4",
+ "comment": "Level4",
+ "value": "Level4",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "Wall",
+ "comment": "EnableAllWarnings",
+ "value": "EnableAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Od",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O1",
+ "comment": "Minimize Size",
+ "value": "MinSpace",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O2",
+ "comment": "Maximize Speed",
+ "value": "MaxSpeed",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Ox",
+ "comment": "Full Optimization",
+ "value": "Full",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob0",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob1",
+ "comment": "Only __inline",
+ "value": "OnlyExplicitInline",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob2",
+ "comment": "Any Suitable",
+ "value": "AnySuitable",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Os",
+ "comment": "Favor small code",
+ "value": "Size",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Ot",
+ "comment": "Favor fast code",
+ "value": "Speed",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "",
+ "comment": "Neither",
+ "value": "Neither",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHa",
+ "comment": "Yes with SEH Exceptions",
+ "value": "Async",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHsc",
+ "comment": "Yes",
+ "value": "Sync",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHs",
+ "comment": "Yes with Extern C functions",
+ "value": "SyncCThrow",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCs",
+ "comment": "Stack Frames",
+ "value": "StackFrameRuntimeCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCu",
+ "comment": "Uninitialized variables",
+ "value": "UninitializedLocalUsageCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTC1",
+ "comment": "Both (/RTC1, equiv. to /RTCsu)",
+ "value": "EnableFastChecks",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MT",
+ "comment": "Multi-threaded",
+ "value": "MultiThreaded",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MTd",
+ "comment": "Multi-threaded Debug",
+ "value": "MultiThreadedDebug",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MD",
+ "comment": "Multi-threaded DLL",
+ "value": "MultiThreadedDLL",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MDd",
+ "comment": "Multi-threaded Debug DLL",
+ "value": "MultiThreadedDebugDLL",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp1",
+ "comment": "1 Byte",
+ "value": "1Byte",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp2",
+ "comment": "2 Bytes",
+ "value": "2Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp4",
+ "comment": "4 Byte",
+ "value": "4Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp8",
+ "comment": "8 Bytes",
+ "value": "8Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp16",
+ "comment": "16 Bytes",
+ "value": "16Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE",
+ "comment": "Streaming SIMD Extensions (/arch:SSE)",
+ "value": "StreamingSIMDExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE2",
+ "comment": "Streaming SIMD Extensions 2 (/arch:SSE2)",
+ "value": "StreamingSIMDExtensions2",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:precise",
+ "comment": "Precise",
+ "value": "Precise",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:strict",
+ "comment": "Strict",
+ "value": "Strict",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:fast",
+ "comment": "Fast",
+ "value": "Fast",
+ "flags": []
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yc",
+ "comment": "Create",
+ "value": "Create",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yu",
+ "comment": "Use",
+ "value": "Use",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Y-",
+ "comment": "Not Using Precompiled Headers",
+ "value": "NotUsing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "",
+ "comment": "No Listing",
+ "value": "NoListing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FA",
+ "comment": "Assembly-Only Listing",
+ "value": "AssemblyCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAc",
+ "comment": "Assembly With Machine Code",
+ "value": "AssemblyAndMachineCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAs",
+ "comment": "Assembly With Source Code",
+ "value": "AssemblyAndSourceCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAcs",
+ "comment": "Assembly, Machine Code and Source",
+ "value": "All",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gd",
+ "comment": "__cdecl",
+ "value": "Cdecl",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gr",
+ "comment": "__fastcall",
+ "value": "FastCall",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gz",
+ "comment": "__stdcall",
+ "value": "StdCall",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TC",
+ "comment": "Compile as C Code",
+ "value": "CompileAsC",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TP",
+ "comment": "Compile as C++ Code",
+ "value": "CompileAsCpp",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:none",
+ "comment": "Do Not Send Report",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "Prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:queue",
+ "comment": "Queue For Next Login",
+ "value": "Queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:send",
+ "comment": "Send Automatically",
+ "value": "Send",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo-",
+ "comment": "Suppress Startup Banner",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX-",
+ "comment": "Treat Warnings As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MultiProcessorCompilation",
+ "switch": "MP",
+ "comment": "Multi-processor Compilation",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "IntrinsicFunctions",
+ "switch": "Oi",
+ "comment": "Enable Intrinsic Functions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy-",
+ "comment": "Omit Frame Pointers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy",
+ "comment": "Omit Frame Pointers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableFiberSafeOptimizations",
+ "switch": "GT",
+ "comment": "Enable Fiber-Safe Optimizations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WholeProgramOptimization",
+ "switch": "GL",
+ "comment": "Whole Program Optimization",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UndefineAllPreprocessorDefinitions",
+ "switch": "u",
+ "comment": "Undefine All Preprocessor Definitions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreStandardIncludePath",
+ "switch": "X",
+ "comment": "Ignore Standard Include Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessToFile",
+ "switch": "P",
+ "comment": "Preprocess to a File",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessSuppressLineNumbers",
+ "switch": "EP",
+ "comment": "Preprocess Suppress Line Numbers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessKeepComments",
+ "switch": "C",
+ "comment": "Keep Comments",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF-",
+ "comment": "Enable String Pooling",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF",
+ "comment": "Enable String Pooling",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm-",
+ "comment": "Enable Minimal Rebuild",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm",
+ "comment": "Enable Minimal Rebuild",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SmallerTypeCheck",
+ "switch": "RTCc",
+ "comment": "Smaller Type Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS-",
+ "comment": "Buffer Security Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS",
+ "comment": "Buffer Security Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy-",
+ "comment": "Enable Function-Level Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy",
+ "comment": "Enable Function-Level Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except-",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CreateHotpatchableImage",
+ "switch": "hotpatch",
+ "comment": "Create Hotpatchable Image",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DisableLanguageExtensions",
+ "switch": "Za",
+ "comment": "Disable Language Extensions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t-",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope-",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR-",
+ "comment": "Enable Run-Time Type Information",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR",
+ "comment": "Enable Run-Time Type Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp-",
+ "comment": "Open MP Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp",
+ "comment": "Open MP Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ExpandAttributedSource",
+ "switch": "Fx",
+ "comment": "Expand Attributed Source",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateXMLDocumentationFiles",
+ "switch": "doc",
+ "comment": "Generate XML Documentation Files",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "BrowseInformation",
+ "switch": "FR",
+ "comment": "Enable Browse Information",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "ShowIncludes",
+ "switch": "showIncludes",
+ "comment": "Show Includes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze-",
+ "comment": "Enable Code Analysis",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze",
+ "comment": "Enable Code Analysis",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseFullPaths",
+ "switch": "FC",
+ "comment": "Use Full Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitDefaultLibName",
+ "switch": "Zl",
+ "comment": "Omit Default Library Name",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseUnicodeForAssemblerListing",
+ "switch": "FAu",
+ "comment": "Use Unicode For Assembler Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalIncludeDirectories",
+ "switch": "I",
+ "comment": "Additional Include Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalUsingDirectories",
+ "switch": "AI",
+ "comment": "Resolve #using References",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "U",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DisableSpecificWarnings",
+ "switch": "wd",
+ "comment": "Disable Specific Warnings",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedIncludeFiles",
+ "switch": "FI",
+ "comment": "Forced Include File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedUsingFiles",
+ "switch": "FU",
+ "comment": "Forced #using File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "TreatSpecificWarningsAsErrors",
+ "switch": "we",
+ "comment": "Treat Specific Warnings As Errors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PreprocessOutputPath",
+ "switch": "Fi",
+ "comment": "Preprocess Output Path",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yu",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yc",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderOutputFile",
+ "switch": "Fp",
+ "comment": "Precompiled Header Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "AssemblerListingLocation",
+ "switch": "Fa",
+ "comment": "ASM List Location",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ObjectFileName",
+ "switch": "Fo",
+ "comment": "Object File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDataBaseFileName",
+ "switch": "Fd",
+ "comment": "Program Database File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "XMLDocumentationFileName",
+ "switch": "doc",
+ "comment": "XML Documentation File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "BrowseInformationFile",
+ "switch": "FR",
+ "comment": "Browse Information File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ProcessorNumber",
+ "switch": "MP",
+ "comment": "Number of processors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v10_CSharp.json b/Templates/MSBuild/FlagTables/v10_CSharp.json
new file mode 100644
index 000000000..5989aea1e
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v10_CSharp.json
@@ -0,0 +1,574 @@
+[
+ {
+ "name": "ProjectName",
+ "switch": "out:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:exe",
+ "comment": "",
+ "value": "Exe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:winexe",
+ "comment": "",
+ "value": "Winexe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:library",
+ "comment": "",
+ "value": "Library",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:module",
+ "comment": "",
+ "value": "Module",
+ "flags": []
+ },
+ {
+ "name": "DocumentationFile",
+ "switch": "doc",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x86",
+ "comment": "",
+ "value": "x86",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:Itanium",
+ "comment": "",
+ "value": "Itanium",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x64",
+ "comment": "",
+ "value": "x64",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:arm",
+ "comment": "",
+ "value": "arm",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu32bitpreferred",
+ "comment": "",
+ "value": "anycpu32bitpreferred",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu",
+ "comment": "",
+ "value": "anycpu",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "mit alias",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "dateiliste",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AddModules",
+ "switch": "addmodule:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "Win32Resource",
+ "switch": "win32res:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationIcon",
+ "switch": "win32icon:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationManifest",
+ "switch": "win32manifest:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "NoWin32Manifest",
+ "switch": "nowin32manifest",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineDebug",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": [
+ "Continue"
+ ]
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:none",
+ "comment": "",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:full",
+ "comment": "",
+ "value": "full",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:pdbonly",
+ "comment": "",
+ "value": "pdbonly",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:0",
+ "comment": "",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:1",
+ "comment": "",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:2",
+ "comment": "",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "NoWarn",
+ "switch": "nowarn:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "CommaAppendable"
+ ]
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineConstants",
+ "switch": "define:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable",
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-1",
+ "comment": "",
+ "value": "ISO-1",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-2",
+ "comment": "",
+ "value": "ISO-2",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:5",
+ "comment": "",
+ "value": "5",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:6",
+ "comment": "",
+ "value": "6",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:default",
+ "comment": "",
+ "value": "default",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyOriginatorKeyFile",
+ "switch": "keyfile",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "KeyContainerName",
+ "switch": "keycontainer",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoLogo",
+ "switch": "nologo",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoConfig",
+ "switch": "noconfig",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "baseaddress:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "CodePage",
+ "switch": "codepage",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "Utf8Output",
+ "switch": "utf8output",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "MainEntryPoint",
+ "switch": "main:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "GenerateFullPaths",
+ "switch": "fullpaths",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FileAlignment",
+ "switch": "filealign",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "PdbFile",
+ "switch": "pdb:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SubsystemVersion",
+ "switch": "subsystemversion",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibPaths",
+ "switch": "lib:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:none",
+ "comment": "Do Not Send Report",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:queue",
+ "comment": "Queue For Next Login",
+ "value": "queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:send",
+ "comment": "Send Automatically",
+ "value": "send",
+ "flags": []
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v10_Cuda.json b/Templates/MSBuild/FlagTables/v10_Cuda.json
new file mode 100644
index 000000000..1831b8aaf
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v10_Cuda.json
@@ -0,0 +1,224 @@
+[
+ {
+ "name": "AdditionalCompilerOptions",
+ "switch": "Xcompiler=",
+ "comment": "Host compiler options",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SpaceAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalCompilerOptions",
+ "switch": "Xcompiler",
+ "comment": "Host compiler options",
+ "value": "",
+ "flags": [
+ "UserFollowing",
+ "SpaceAppendable"
+ ]
+ },
+ {
+ "name": "CudaRuntime",
+ "switch": "cudart=none",
+ "comment": "No CUDA runtime library",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "CudaRuntime",
+ "switch": "cudart=shared",
+ "comment": "Shared/dynamic CUDA runtime library",
+ "value": "Shared",
+ "flags": []
+ },
+ {
+ "name": "CudaRuntime",
+ "switch": "cudart=static",
+ "comment": "Static CUDA runtime library",
+ "value": "Static",
+ "flags": []
+ },
+ {
+ "name": "CudaRuntime",
+ "switch": "cudart",
+ "comment": "CUDA runtime library",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ },
+ {
+ "name": "cmake-temp-gencode",
+ "switch": "gencode=",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "cmake-temp-gencode",
+ "switch": "gencode",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserFollowing",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "cmake-temp-gencode",
+ "switch": "-generate-code=",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "cmake-temp-gencode",
+ "switch": "-generate-code",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserFollowing",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "cmake-temp-code",
+ "switch": "code=",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "cmake-temp-code",
+ "switch": "code",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ },
+ {
+ "name": "cmake-temp-code",
+ "switch": "-gpu-code=",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "cmake-temp-code",
+ "switch": "-gpu-code",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ },
+ {
+ "name": "cmake-temp-arch",
+ "switch": "arch=",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "cmake-temp-arch",
+ "switch": "arch",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ },
+ {
+ "name": "cmake-temp-arch",
+ "switch": "-gpu-architecture=",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "cmake-temp-arch",
+ "switch": "-gpu-architecture",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ },
+ {
+ "name": "FastMath",
+ "switch": "use_fast_math",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FastMath",
+ "switch": "-use_fast_math",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GPUDebugInfo",
+ "switch": "G",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GPUDebugInfo",
+ "switch": "-device-debug",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "HostDebugInfo",
+ "switch": "g",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "HostDebugInfo",
+ "switch": "-debug",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MaxRegCount",
+ "switch": "maxrregcount=",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MaxRegCount",
+ "switch": "maxrregcount",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v10_CudaHost.json b/Templates/MSBuild/FlagTables/v10_CudaHost.json
new file mode 100644
index 000000000..2593ff146
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v10_CudaHost.json
@@ -0,0 +1,149 @@
+[
+ {
+ "name": "Optimization",
+ "switch": "Od",
+ "comment": "Disabled",
+ "value": "Od",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O1",
+ "comment": "Minimize Size",
+ "value": "O1",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O2",
+ "comment": "Maximize Speed",
+ "value": "O2",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Ox",
+ "comment": "Full Optimization",
+ "value": "O3",
+ "flags": []
+ },
+ {
+ "name": "Runtime",
+ "switch": "MT",
+ "comment": "Multi-Threaded",
+ "value": "MT",
+ "flags": []
+ },
+ {
+ "name": "Runtime",
+ "switch": "MTd",
+ "comment": "Multi-Threaded Debug",
+ "value": "MTd",
+ "flags": []
+ },
+ {
+ "name": "Runtime",
+ "switch": "MD",
+ "comment": "Multi-Threaded DLL",
+ "value": "MD",
+ "flags": []
+ },
+ {
+ "name": "Runtime",
+ "switch": "MDd",
+ "comment": "Multi-threaded Debug DLL",
+ "value": "MDd",
+ "flags": []
+ },
+ {
+ "name": "Runtime",
+ "switch": "ML",
+ "comment": "Single-Threaded",
+ "value": "ML",
+ "flags": []
+ },
+ {
+ "name": "Runtime",
+ "switch": "MLd",
+ "comment": "Single-Threaded Debug",
+ "value": "MLd",
+ "flags": []
+ },
+ {
+ "name": "RuntimeChecks",
+ "switch": "RTCs",
+ "comment": "Stack Frames",
+ "value": "RTCs",
+ "flags": []
+ },
+ {
+ "name": "RuntimeChecks",
+ "switch": "RTCu",
+ "comment": "Uninitialized Variables",
+ "value": "RTCu",
+ "flags": []
+ },
+ {
+ "name": "RuntimeChecks",
+ "switch": "RTC1",
+ "comment": "Both",
+ "value": "RTC1",
+ "flags": []
+ },
+ {
+ "name": "TypeInfo",
+ "switch": "GR",
+ "comment": "Yes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TypeInfo",
+ "switch": "GR-",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "Warning",
+ "switch": "W0",
+ "comment": "Off: Turn Off All Warnings",
+ "value": "W0",
+ "flags": []
+ },
+ {
+ "name": "Warning",
+ "switch": "W1",
+ "comment": "Level 1",
+ "value": "W1",
+ "flags": []
+ },
+ {
+ "name": "Warning",
+ "switch": "W2",
+ "comment": "Level 2",
+ "value": "W2",
+ "flags": []
+ },
+ {
+ "name": "Warning",
+ "switch": "W3",
+ "comment": "Level 3",
+ "value": "W3",
+ "flags": []
+ },
+ {
+ "name": "Warning",
+ "switch": "W4",
+ "comment": "Level 4",
+ "value": "W4",
+ "flags": []
+ },
+ {
+ "name": "Warning",
+ "switch": "Wall",
+ "comment": "Enable All Warnings",
+ "value": "Wall",
+ "flags": []
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v10_LIB.json b/Templates/MSBuild/FlagTables/v10_LIB.json
new file mode 100644
index 000000000..58a238c97
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v10_LIB.json
@@ -0,0 +1,297 @@
+[
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:PROMPT",
+ "comment": "PromptImmediately",
+ "value": "PromptImmediately",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:QUEUE",
+ "comment": "Queue For Next Login",
+ "value": "QueueForNextLogin",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:SEND",
+ "comment": "Send Error Report",
+ "value": "SendErrorReport",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:NONE",
+ "comment": "No Error Report",
+ "value": "NoErrorReport",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM",
+ "comment": "MachineARM",
+ "value": "MachineARM",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:EBC",
+ "comment": "MachineEBC",
+ "value": "MachineEBC",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:IA64",
+ "comment": "MachineIA64",
+ "value": "MachineIA64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS",
+ "comment": "MachineMIPS",
+ "value": "MachineMIPS",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS16",
+ "comment": "MachineMIPS16",
+ "value": "MachineMIPS16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU",
+ "comment": "MachineMIPSFPU",
+ "value": "MachineMIPSFPU",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU16",
+ "comment": "MachineMIPSFPU16",
+ "value": "MachineMIPSFPU16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:SH4",
+ "comment": "MachineSH4",
+ "value": "MachineSH4",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:THUMB",
+ "comment": "MachineTHUMB",
+ "value": "MachineTHUMB",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X64",
+ "comment": "MachineX64",
+ "value": "MachineX64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X86",
+ "comment": "MachineX86",
+ "value": "MachineX86",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:CONSOLE",
+ "comment": "Console",
+ "value": "Console",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWS",
+ "comment": "Windows",
+ "value": "Windows",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:NATIVE",
+ "comment": "Native",
+ "value": "Native",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_APPLICATION",
+ "comment": "EFI Application",
+ "value": "EFI Application",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+ "comment": "EFI Boot Service Driver",
+ "value": "EFI Boot Service Driver",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_ROM",
+ "comment": "EFI ROM",
+ "value": "EFI ROM",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+ "comment": "EFI Runtime",
+ "value": "EFI Runtime",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWSCE",
+ "comment": "WindowsCE",
+ "value": "WindowsCE",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:POSIX",
+ "comment": "POSIX",
+ "value": "POSIX",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "NOLOGO",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreAllDefaultLibraries",
+ "switch": "NODEFAULTLIB",
+ "comment": "Ignore All Default Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatLibWarningAsErrors",
+ "switch": "WX:NO",
+ "comment": "Treat Lib Warning As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatLibWarningAsErrors",
+ "switch": "WX",
+ "comment": "Treat Lib Warning As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Verbose",
+ "switch": "VERBOSE",
+ "comment": "Verbose",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG",
+ "comment": "Link Time Code Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibraryDirectories",
+ "switch": "LIBPATH:",
+ "comment": "Additional Library Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IgnoreSpecificDefaultLibraries",
+ "switch": "NODEFAULTLIB:",
+ "comment": "Ignore Specific Default Libraries",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ExportNamedFunctions",
+ "switch": "EXPORT:",
+ "comment": "Export Named Functions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "RemoveObjects",
+ "switch": "REMOVE:",
+ "comment": "Remove Objects",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFile",
+ "switch": "OUT:",
+ "comment": "Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ModuleDefinitionFile",
+ "switch": "DEF:",
+ "comment": "Module Definition File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ForceSymbolReferences",
+ "switch": "INCLUDE:",
+ "comment": "Force Symbol References",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "DisplayLibrary",
+ "switch": "LIST:",
+ "comment": "Display Library to standard output",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "Name",
+ "switch": "NAME:",
+ "comment": "Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v10_Link.json b/Templates/MSBuild/FlagTables/v10_Link.json
new file mode 100644
index 000000000..ac5b8b16c
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v10_Link.json
@@ -0,0 +1,1137 @@
+[
+ {
+ "name": "ShowProgress",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE",
+ "comment": "Display all progress messages",
+ "value": "LinkVerbose",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:Lib",
+ "comment": "For Libraries Searched",
+ "value": "LinkVerboseLib",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:ICF",
+ "comment": "About COMDAT folding during optimized linking",
+ "value": "LinkVerboseICF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:REF",
+ "comment": "About data removed during optimized linking",
+ "value": "LinkVerboseREF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:SAFESEH",
+ "comment": "About Modules incompatible with SEH",
+ "value": "LinkVerboseSAFESEH",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:CLR",
+ "comment": "About linker activity related to managed code",
+ "value": "LinkVerboseCLR",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:MULTIPLE",
+ "comment": "Multiply Defined Symbol Only",
+ "value": "MultiplyDefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:UNRESOLVED",
+ "comment": "Undefined Symbol Only",
+ "value": "UndefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:5",
+ "comment": "X86 Image Only",
+ "value": "X86Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:6",
+ "comment": "X64 Image Only",
+ "value": "X64Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:16",
+ "comment": "Itanium Image Only",
+ "value": "ItaniumImage",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='asInvoker'",
+ "comment": "asInvoker",
+ "value": "AsInvoker",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='highestAvailable'",
+ "comment": "highestAvailable",
+ "value": "HighestAvailable",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='requireAdministrator'",
+ "comment": "requireAdministrator",
+ "value": "RequireAdministrator",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:CONSOLE",
+ "comment": "Console",
+ "value": "Console",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWS",
+ "comment": "Windows",
+ "value": "Windows",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:NATIVE",
+ "comment": "Native",
+ "value": "Native",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_APPLICATION",
+ "comment": "EFI Application",
+ "value": "EFI Application",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+ "comment": "EFI Boot Service Driver",
+ "value": "EFI Boot Service Driver",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_ROM",
+ "comment": "EFI ROM",
+ "value": "EFI ROM",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+ "comment": "EFI Runtime",
+ "value": "EFI Runtime",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWSCE",
+ "comment": "WindowsCE",
+ "value": "WindowsCE",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:POSIX",
+ "comment": "POSIX",
+ "value": "POSIX",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "Driver",
+ "comment": "Driver",
+ "value": "Driver",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:UPONLY",
+ "comment": "UP Only",
+ "value": "UpOnly",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:WDM",
+ "comment": "WDM",
+ "value": "WDM",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG",
+ "comment": "Use Link Time Code Generation",
+ "value": "UseLinkTimeCodeGeneration",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGInstrument",
+ "comment": "Profile Guided Optimization - Instrument",
+ "value": "PGInstrument",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGOptimize",
+ "comment": "Profile Guided Optimization - Optimization",
+ "value": "PGOptimization",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGUpdate",
+ "comment": "Profile Guided Optimization - Update",
+ "value": "PGUpdate",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM",
+ "comment": "MachineARM",
+ "value": "MachineARM",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:EBC",
+ "comment": "MachineEBC",
+ "value": "MachineEBC",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:IA64",
+ "comment": "MachineIA64",
+ "value": "MachineIA64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS",
+ "comment": "MachineMIPS",
+ "value": "MachineMIPS",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS16",
+ "comment": "MachineMIPS16",
+ "value": "MachineMIPS16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU",
+ "comment": "MachineMIPSFPU",
+ "value": "MachineMIPSFPU",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU16",
+ "comment": "MachineMIPSFPU16",
+ "value": "MachineMIPSFPU16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:SH4",
+ "comment": "MachineSH4",
+ "value": "MachineSH4",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:THUMB",
+ "comment": "MachineTHUMB",
+ "value": "MachineTHUMB",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X64",
+ "comment": "MachineX64",
+ "value": "MachineX64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X86",
+ "comment": "MachineX86",
+ "value": "MachineX86",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:MTA",
+ "comment": "MTA threading attribute",
+ "value": "MTAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:STA",
+ "comment": "STA threading attribute",
+ "value": "STAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:NONE",
+ "comment": "Default threading attribute",
+ "value": "DefaultThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:IJW",
+ "comment": "Force IJW image",
+ "value": "ForceIJWImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:PURE",
+ "comment": "Force Pure IL Image",
+ "value": "ForcePureILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:SAFE",
+ "comment": "Force Safe IL Image",
+ "value": "ForceSafeILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "",
+ "comment": "Default image type",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:PROMPT",
+ "comment": "PromptImmediately",
+ "value": "PromptImmediately",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:QUEUE",
+ "comment": "Queue For Next Login",
+ "value": "QueueForNextLogin",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:SEND",
+ "comment": "Send Error Report",
+ "value": "SendErrorReport",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:NONE",
+ "comment": "No Error Report",
+ "value": "NoErrorReport",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:NO",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:SYSTEMDLL",
+ "comment": "System Dlls Only",
+ "value": "SystemDlls",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL:NO",
+ "comment": "Enable Incremental Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL",
+ "comment": "Enable Incremental Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "NOLOGO",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:NOSTATUS",
+ "comment": "Link Status",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:STATUS",
+ "comment": "Link Status",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND:NO",
+ "comment": "Prevent Dll Binding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND",
+ "comment": "Prevent Dll Binding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX:NO",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreAllDefaultLibraries",
+ "switch": "NODEFAULTLIB",
+ "comment": "Ignore All Default Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST:NO",
+ "comment": "Generate Manifest",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST",
+ "comment": "Generate Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "ALLOWISOLATION:NO",
+ "comment": "Allow Isolation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "ALLOWISOLATION",
+ "comment": "Allow Isolation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableUAC",
+ "switch": "MANIFESTUAC:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "SpaceAppendable"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='true'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG",
+ "comment": "Generate Debug Info",
+ "value": "true",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateMapFile",
+ "switch": "MAP",
+ "comment": "Generate Map File",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "MapExports",
+ "switch": "MAPINFO:EXPORTS",
+ "comment": "Map Exports",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG:DISABLE",
+ "comment": "Debuggable Assembly",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG",
+ "comment": "Debuggable Assembly",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE:NO",
+ "comment": "Enable Large Addresses",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE",
+ "comment": "Enable Large Addresses",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE:NO",
+ "comment": "Terminal Server",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE",
+ "comment": "Terminal Server",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromCD",
+ "switch": "SWAPRUN:CD",
+ "comment": "Swap Run From CD",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromNET",
+ "switch": "SWAPRUN:NET",
+ "comment": "Swap Run From Network",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:NOREF",
+ "comment": "References",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:REF",
+ "comment": "References",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:NOICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:ICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreEmbeddedIDL",
+ "switch": "IGNOREIDL",
+ "comment": "Ignore Embedded IDL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoEntryPoint",
+ "switch": "NOENTRY",
+ "comment": "No Entry Point",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SetChecksum",
+ "switch": "RELEASE",
+ "comment": "Set Checksum",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE:NO",
+ "comment": "Randomized Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE",
+ "comment": "Randomized Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED:NO",
+ "comment": "Fixed Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED",
+ "comment": "Fixed Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT:NO",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TurnOffAssemblyGeneration",
+ "switch": "NOASSEMBLY",
+ "comment": "Turn Off Assembly Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportUnloadOfDelayLoadedDLL",
+ "switch": "DELAY:UNLOAD",
+ "comment": "Unload delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportNobindOfDelayLoadedDLL",
+ "switch": "DELAY:NOBIND",
+ "comment": "Nobind delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Profile",
+ "switch": "PROFILE",
+ "comment": "Profile",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN:NO",
+ "comment": "Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN",
+ "comment": "Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK:NO",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH:NO",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDLL",
+ "switch": "DLL",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibraryDirectories",
+ "switch": "LIBPATH:",
+ "comment": "Additional Library Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IgnoreSpecificDefaultLibraries",
+ "switch": "NODEFAULTLIB:",
+ "comment": "Ignore Specific Default Libraries",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AddModuleNamesToAssembly",
+ "switch": "ASSEMBLYMODULE:",
+ "comment": "Add Module to Assembly",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "EmbedManagedResourceFile",
+ "switch": "ASSEMBLYRESOURCE:",
+ "comment": "Embed Managed Resource File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForceSymbolReferences",
+ "switch": "INCLUDE:",
+ "comment": "Force Symbol References",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DelayLoadDLLs",
+ "switch": "DELAYLOAD:",
+ "comment": "Delay Loaded Dlls",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AssemblyLinkResource",
+ "switch": "ASSEMBLYLINKRESOURCE:",
+ "comment": "Assembly Link Resource",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalManifestDependencies",
+ "switch": "MANIFESTDEPENDENCY:",
+ "comment": "Additional Manifest Dependencies",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFile",
+ "switch": "OUT:",
+ "comment": "Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "Version",
+ "switch": "VERSION:",
+ "comment": "Version",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SpecifySectionAttributes",
+ "switch": "SECTION:",
+ "comment": "Specify Section Attributes",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MSDOSStubFileName",
+ "switch": "STUB:",
+ "comment": "MS-DOS Stub File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ModuleDefinitionFile",
+ "switch": "DEF:",
+ "comment": "Module Definition File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ManifestFile",
+ "switch": "ManifestFile:",
+ "comment": "Manifest File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDatabaseFile",
+ "switch": "PDB:",
+ "comment": "Generate Program Database File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StripPrivateSymbols",
+ "switch": "PDBSTRIPPED:",
+ "comment": "Strip Private Symbols",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MapFileName",
+ "switch": "MAP:",
+ "comment": "Map File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "HeapReserveSize",
+ "switch": "HEAP:",
+ "comment": "Heap Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "HeapCommitSize",
+ "switch": "HEAP",
+ "comment": "Heap Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "StackReserveSize",
+ "switch": "STACK:",
+ "comment": "Stack Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StackCommitSize",
+ "switch": "STACK",
+ "comment": "Stack Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "FunctionOrder",
+ "switch": "ORDER:@",
+ "comment": "Function Order",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProfileGuidedDatabase",
+ "switch": "PGD:",
+ "comment": "Profile Guided Database",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MidlCommandFile",
+ "switch": "MIDL:@",
+ "comment": "MIDL Commands",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergedIDLBaseFileName",
+ "switch": "IDLOUT:",
+ "comment": "Merged IDL Base File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryFile",
+ "switch": "TLBOUT:",
+ "comment": "Type Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "EntryPointSymbol",
+ "switch": "ENTRY:",
+ "comment": "Entry Point",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "BASE:",
+ "comment": "Base Address",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ImportLibrary",
+ "switch": "IMPLIB:",
+ "comment": "Import Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergeSections",
+ "switch": "MERGE:",
+ "comment": "Merge Sections",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LinkKeyFile",
+ "switch": "KEYFILE:",
+ "comment": "Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "KeyContainer",
+ "switch": "KEYCONTAINER:",
+ "comment": "Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryResourceID",
+ "switch": "TLBID:",
+ "comment": "TypeLib Resource ID",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SectionAlignment",
+ "switch": "ALIGN:",
+ "comment": "SectionAlignment",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v10_MASM.json b/Templates/MSBuild/FlagTables/v10_MASM.json
new file mode 100644
index 000000000..4634306b1
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v10_MASM.json
@@ -0,0 +1,295 @@
+[
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cp",
+ "comment": "Preserves Identifier Case (/Cp)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cu",
+ "comment": "Maps all identifiers to upper case. (/Cu)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cx",
+ "comment": "Preserves case in public and extern symbols. (/Cx)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W0",
+ "comment": "Warning Level 0 (/W0)",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W1",
+ "comment": "Warning Level 1 (/W1)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W2",
+ "comment": "Warning Level 2 (/W2)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W3",
+ "comment": "Warning Level 3 (/W3)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp1",
+ "comment": "One Byte Boundary (/Zp1)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp2",
+ "comment": "Two Byte Boundary (/Zp2)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp4",
+ "comment": "Four Byte Boundary (/Zp4)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp8",
+ "comment": "Eight Byte Boundary (/Zp8)",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp16",
+ "comment": "Sixteen Byte Boundary (/Zp16)",
+ "value": "5",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gd",
+ "comment": "Use C-style Calling Convention (/Gd)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gz",
+ "comment": "Use stdcall Calling Convention (/Gz)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gc",
+ "comment": "Use Pascal Calling Convention (/Gc)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:prompt",
+ "comment": "Prompt to send report immediately (/errorReport:prompt)",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:queue",
+ "comment": "Prompt to send report at the next logon (/errorReport:queue)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:send",
+ "comment": "Automatically send report (/errorReport:send)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:none",
+ "comment": "Do not send report (/errorReport:none)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "NoLogo",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GeneratePreprocessedSourceListing",
+ "switch": "EP",
+ "comment": "Generate Preprocessed Source Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ListAllAvailableInformation",
+ "switch": "Sa",
+ "comment": "List All Available Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseSafeExceptionHandlers",
+ "switch": "safeseh",
+ "comment": "Use Safe Exception Handlers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AddFirstPassListing",
+ "switch": "Sf",
+ "comment": "Add First Pass Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableAssemblyGeneratedCodeListing",
+ "switch": "Sg",
+ "comment": "Enable Assembly Generated Code Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DisableSymbolTable",
+ "switch": "Sn",
+ "comment": "Disable Symbol Table",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableFalseConditionalsInListing",
+ "switch": "Sx",
+ "comment": "Enable False Conditionals In Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "WX",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MakeAllSymbolsPublic",
+ "switch": "Zf",
+ "comment": "Make All Symbols Public",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "Zi",
+ "comment": "Generate Debug Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableMASM51Compatibility",
+ "switch": "Zm",
+ "comment": "Enable MASM 5.1 Compatibility",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PerformSyntaxCheckOnly",
+ "switch": "Zs",
+ "comment": "Perform Syntax Check Only",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IncludePaths",
+ "switch": "I",
+ "comment": "Include Paths",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "BrowseFile",
+ "switch": "FR",
+ "comment": "Generate Browse Information File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ObjectFileName",
+ "switch": "Fo",
+ "comment": "Object File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "AssembledCodeListingFile",
+ "switch": "Fl",
+ "comment": "Assembled Code Listing File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v10_NASM.json b/Templates/MSBuild/FlagTables/v10_NASM.json
new file mode 100644
index 000000000..434cd634e
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v10_NASM.json
@@ -0,0 +1,201 @@
+[
+ {
+ "name": "Outputswitch",
+ "switch": "fwin",
+ "comment": "Object File win32",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "Outputswitch",
+ "switch": "fwin32",
+ "comment": "Object File win32",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "Outputswitch",
+ "switch": "fwin64",
+ "comment": "Object File win64",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "Outputswitch",
+ "switch": "felf",
+ "comment": "ELF32 (i386) object files (e.g. Linux)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "Outputswitch",
+ "switch": "felf32",
+ "comment": "ELF32 (i386) object files (e.g. Linux)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "Outputswitch",
+ "switch": "felf64",
+ "comment": "ELF64 (x86_64) object files (e.g. Linux)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "ErrorReportingFormat",
+ "switch": "Xgnu",
+ "comment": "-Xgnu GNU format: Default format",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "ErrorReportingFormat",
+ "switch": "Xvc",
+ "comment": "-Xvc Style used by Microsoft Visual C++",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "tasmmode",
+ "switch": "t",
+ "comment": "SciTech TASM compatible mode",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "g",
+ "comment": "Generate Debug Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "Werror",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "floatunderflow",
+ "switch": "w+float-underflow",
+ "comment": "float-underflow",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "macrodefaults",
+ "switch": "w-macro-defaults",
+ "comment": "Disable macro-defaults",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "user",
+ "switch": "w-user",
+ "comment": "Disable user",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "floatoverflow",
+ "switch": "w-float-overflow",
+ "comment": "Disable float-overflow",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "floatdenorm",
+ "switch": "w+float-denorm",
+ "comment": "float-denorm",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "numberoverflow",
+ "switch": "w-number-overflow",
+ "comment": "Disable number-overflow",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "macroselfref",
+ "switch": "w+macro-selfref",
+ "comment": "macro-selfref",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "floattoolong",
+ "switch": "w-float-toolong",
+ "comment": "Disable float-toolong",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "orphanlabels",
+ "switch": "w-orphan-labels",
+ "comment": "Disable orphan-labels",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssembledCodeListingFile",
+ "switch": "l",
+ "comment": "Assembled Code Listing File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "Z",
+ "comment": "Redirect Error Messages to File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IncludePaths",
+ "switch": "I",
+ "comment": "Include Paths",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "U",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFormat",
+ "switch": "o",
+ "comment": "Output File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v10_RC.json b/Templates/MSBuild/FlagTables/v10_RC.json
new file mode 100644
index 000000000..b8c0127d1
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v10_RC.json
@@ -0,0 +1,69 @@
+[
+ {
+ "name": "IgnoreStandardIncludePath",
+ "switch": "X",
+ "comment": "Ignore Standard Include Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "v",
+ "comment": "Show Progress",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NullTerminateStrings",
+ "switch": "n",
+ "comment": "Null Terminate Strings",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "u",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalIncludeDirectories",
+ "switch": "I",
+ "comment": "Additional Include Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ResourceOutputFileName",
+ "switch": "fo",
+ "comment": "Resource File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v11_CL.json b/Templates/MSBuild/FlagTables/v11_CL.json
new file mode 100644
index 000000000..b47ab2e98
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v11_CL.json
@@ -0,0 +1,1063 @@
+[
+ {
+ "name": "DebugInformationFormat",
+ "switch": "",
+ "comment": "None",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Z7",
+ "comment": "C7 compatible",
+ "value": "OldStyle",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Zi",
+ "comment": "Program Database",
+ "value": "ProgramDatabase",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "ZI",
+ "comment": "Program Database for Edit And Continue",
+ "value": "EditAndContinue",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "",
+ "comment": "No Common Language RunTime Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr",
+ "comment": "Common Language RunTime Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:pure",
+ "comment": "Pure MSIL Common Language RunTime Support",
+ "value": "Pure",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:safe",
+ "comment": "Safe MSIL Common Language RunTime Support",
+ "value": "Safe",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:oldSyntax",
+ "comment": "Common Language RunTime Support, Old Syntax",
+ "value": "OldSyntax",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W0",
+ "comment": "Turn Off All Warnings",
+ "value": "TurnOffAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W1",
+ "comment": "Level1",
+ "value": "Level1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W2",
+ "comment": "Level2",
+ "value": "Level2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W3",
+ "comment": "Level3",
+ "value": "Level3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W4",
+ "comment": "Level4",
+ "value": "Level4",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "Wall",
+ "comment": "EnableAllWarnings",
+ "value": "EnableAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Od",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O1",
+ "comment": "Minimize Size",
+ "value": "MinSpace",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O2",
+ "comment": "Maximize Speed",
+ "value": "MaxSpeed",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Ox",
+ "comment": "Full Optimization",
+ "value": "Full",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob0",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob1",
+ "comment": "Only __inline",
+ "value": "OnlyExplicitInline",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob2",
+ "comment": "Any Suitable",
+ "value": "AnySuitable",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Os",
+ "comment": "Favor small code",
+ "value": "Size",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Ot",
+ "comment": "Favor fast code",
+ "value": "Speed",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "",
+ "comment": "Neither",
+ "value": "Neither",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHa",
+ "comment": "Yes with SEH Exceptions",
+ "value": "Async",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHsc",
+ "comment": "Yes",
+ "value": "Sync",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHs",
+ "comment": "Yes with Extern C functions",
+ "value": "SyncCThrow",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCs",
+ "comment": "Stack Frames",
+ "value": "StackFrameRuntimeCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCu",
+ "comment": "Uninitialized variables",
+ "value": "UninitializedLocalUsageCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTC1",
+ "comment": "Both (/RTC1, equiv. to /RTCsu)",
+ "value": "EnableFastChecks",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MT",
+ "comment": "Multi-threaded",
+ "value": "MultiThreaded",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MTd",
+ "comment": "Multi-threaded Debug",
+ "value": "MultiThreadedDebug",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MD",
+ "comment": "Multi-threaded DLL",
+ "value": "MultiThreadedDLL",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MDd",
+ "comment": "Multi-threaded Debug DLL",
+ "value": "MultiThreadedDebugDLL",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp1",
+ "comment": "1 Byte",
+ "value": "1Byte",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp2",
+ "comment": "2 Bytes",
+ "value": "2Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp4",
+ "comment": "4 Byte",
+ "value": "4Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp8",
+ "comment": "8 Bytes",
+ "value": "8Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp16",
+ "comment": "16 Bytes",
+ "value": "16Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE",
+ "comment": "Streaming SIMD Extensions",
+ "value": "StreamingSIMDExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE2",
+ "comment": "Streaming SIMD Extensions 2",
+ "value": "StreamingSIMDExtensions2",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:AVX",
+ "comment": "Advanced Vector Extensions",
+ "value": "AdvancedVectorExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:IA32",
+ "comment": "No Enhanced Instructions",
+ "value": "NoExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:precise",
+ "comment": "Precise",
+ "value": "Precise",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:strict",
+ "comment": "Strict",
+ "value": "Strict",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:fast",
+ "comment": "Fast",
+ "value": "Fast",
+ "flags": []
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yc",
+ "comment": "Create",
+ "value": "Create",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yu",
+ "comment": "Use",
+ "value": "Use",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Y-",
+ "comment": "Not Using Precompiled Headers",
+ "value": "NotUsing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "",
+ "comment": "No Listing",
+ "value": "NoListing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FA",
+ "comment": "Assembly-Only Listing",
+ "value": "AssemblyCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAc",
+ "comment": "Assembly With Machine Code",
+ "value": "AssemblyAndMachineCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAs",
+ "comment": "Assembly With Source Code",
+ "value": "AssemblyAndSourceCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAcs",
+ "comment": "Assembly, Machine Code and Source",
+ "value": "All",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gd",
+ "comment": "__cdecl",
+ "value": "Cdecl",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gr",
+ "comment": "__fastcall",
+ "value": "FastCall",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gz",
+ "comment": "__stdcall",
+ "value": "StdCall",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TC",
+ "comment": "Compile as C Code",
+ "value": "CompileAsC",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TP",
+ "comment": "Compile as C++ Code",
+ "value": "CompileAsCpp",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:none",
+ "comment": "Do Not Send Report",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "Prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:queue",
+ "comment": "Queue For Next Login",
+ "value": "Queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:send",
+ "comment": "Send Automatically",
+ "value": "Send",
+ "flags": []
+ },
+ {
+ "name": "CompileAsWinRT",
+ "switch": "ZW",
+ "comment": "Consume Windows Runtime Extension",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WinRTNoStdLib",
+ "switch": "ZW:nostdlib",
+ "comment": "No Standard WinRT Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo-",
+ "comment": "Suppress Startup Banner",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX-",
+ "comment": "Treat Warnings As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SDLCheck",
+ "switch": "sdl-",
+ "comment": "SDL checks",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "SDLCheck",
+ "switch": "sdl",
+ "comment": "SDL checks",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MultiProcessorCompilation",
+ "switch": "MP",
+ "comment": "Multi-processor Compilation",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "IntrinsicFunctions",
+ "switch": "Oi",
+ "comment": "Enable Intrinsic Functions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy-",
+ "comment": "Omit Frame Pointers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy",
+ "comment": "Omit Frame Pointers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableFiberSafeOptimizations",
+ "switch": "GT",
+ "comment": "Enable Fiber-Safe Optimizations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WholeProgramOptimization",
+ "switch": "GL",
+ "comment": "Whole Program Optimization",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UndefineAllPreprocessorDefinitions",
+ "switch": "u",
+ "comment": "Undefine All Preprocessor Definitions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreStandardIncludePath",
+ "switch": "X",
+ "comment": "Ignore Standard Include Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessToFile",
+ "switch": "P",
+ "comment": "Preprocess to a File",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessSuppressLineNumbers",
+ "switch": "EP",
+ "comment": "Preprocess Suppress Line Numbers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessKeepComments",
+ "switch": "C",
+ "comment": "Keep Comments",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF-",
+ "comment": "Enable String Pooling",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF",
+ "comment": "Enable String Pooling",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm-",
+ "comment": "Enable Minimal Rebuild",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm",
+ "comment": "Enable Minimal Rebuild",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SmallerTypeCheck",
+ "switch": "RTCc",
+ "comment": "Smaller Type Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS-",
+ "comment": "Security Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS",
+ "comment": "Security Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy-",
+ "comment": "Enable Function-Level Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy",
+ "comment": "Enable Function-Level Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableParallelCodeGeneration",
+ "switch": "Qpar-",
+ "comment": "Enable Parallel Code Generation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableParallelCodeGeneration",
+ "switch": "Qpar",
+ "comment": "Enable Parallel Code Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except-",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CreateHotpatchableImage",
+ "switch": "hotpatch",
+ "comment": "Create Hotpatchable Image",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DisableLanguageExtensions",
+ "switch": "Za",
+ "comment": "Disable Language Extensions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t-",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope-",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR-",
+ "comment": "Enable Run-Time Type Information",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR",
+ "comment": "Enable Run-Time Type Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp-",
+ "comment": "Open MP Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp",
+ "comment": "Open MP Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ExpandAttributedSource",
+ "switch": "Fx",
+ "comment": "Expand Attributed Source",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseUnicodeForAssemblerListing",
+ "switch": "FAu",
+ "comment": "Use Unicode For Assembler Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateXMLDocumentationFiles",
+ "switch": "doc",
+ "comment": "Generate XML Documentation Files",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "BrowseInformation",
+ "switch": "FR",
+ "comment": "Enable Browse Information",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "ShowIncludes",
+ "switch": "showIncludes",
+ "comment": "Show Includes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze-",
+ "comment": "Enable Code Analysis",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze",
+ "comment": "Enable Code Analysis",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseFullPaths",
+ "switch": "FC",
+ "comment": "Use Full Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitDefaultLibName",
+ "switch": "Zl",
+ "comment": "Omit Default Library Name",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalIncludeDirectories",
+ "switch": "I",
+ "comment": "Additional Include Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalUsingDirectories",
+ "switch": "AI",
+ "comment": "Additional #using Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "U",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DisableSpecificWarnings",
+ "switch": "wd",
+ "comment": "Disable Specific Warnings",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedIncludeFiles",
+ "switch": "FI",
+ "comment": "Forced Include File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedUsingFiles",
+ "switch": "FU",
+ "comment": "Forced #using File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PREfastLog",
+ "switch": "analyze:log",
+ "comment": "Code Analysis Log",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ },
+ {
+ "name": "PREfastAdditionalPlugins",
+ "switch": "analyze:plugin",
+ "comment": "Additional Code Analysis Native plugins",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "TreatSpecificWarningsAsErrors",
+ "switch": "we",
+ "comment": "Treat Specific Warnings As Errors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PreprocessOutputPath",
+ "switch": "Fi",
+ "comment": "Preprocess Output Path",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yu",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yc",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderOutputFile",
+ "switch": "Fp",
+ "comment": "Precompiled Header Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "AssemblerListingLocation",
+ "switch": "Fa",
+ "comment": "ASM List Location",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ObjectFileName",
+ "switch": "Fo",
+ "comment": "Object File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDataBaseFileName",
+ "switch": "Fd",
+ "comment": "Program Database File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "XMLDocumentationFileName",
+ "switch": "doc",
+ "comment": "XML Documentation File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "BrowseInformationFile",
+ "switch": "FR",
+ "comment": "Browse Information File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ProcessorNumber",
+ "switch": "MP",
+ "comment": "Number of processors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v11_CSharp.json b/Templates/MSBuild/FlagTables/v11_CSharp.json
new file mode 100644
index 000000000..5989aea1e
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v11_CSharp.json
@@ -0,0 +1,574 @@
+[
+ {
+ "name": "ProjectName",
+ "switch": "out:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:exe",
+ "comment": "",
+ "value": "Exe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:winexe",
+ "comment": "",
+ "value": "Winexe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:library",
+ "comment": "",
+ "value": "Library",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:module",
+ "comment": "",
+ "value": "Module",
+ "flags": []
+ },
+ {
+ "name": "DocumentationFile",
+ "switch": "doc",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x86",
+ "comment": "",
+ "value": "x86",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:Itanium",
+ "comment": "",
+ "value": "Itanium",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x64",
+ "comment": "",
+ "value": "x64",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:arm",
+ "comment": "",
+ "value": "arm",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu32bitpreferred",
+ "comment": "",
+ "value": "anycpu32bitpreferred",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu",
+ "comment": "",
+ "value": "anycpu",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "mit alias",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "dateiliste",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AddModules",
+ "switch": "addmodule:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "Win32Resource",
+ "switch": "win32res:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationIcon",
+ "switch": "win32icon:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationManifest",
+ "switch": "win32manifest:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "NoWin32Manifest",
+ "switch": "nowin32manifest",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineDebug",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": [
+ "Continue"
+ ]
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:none",
+ "comment": "",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:full",
+ "comment": "",
+ "value": "full",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:pdbonly",
+ "comment": "",
+ "value": "pdbonly",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:0",
+ "comment": "",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:1",
+ "comment": "",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:2",
+ "comment": "",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "NoWarn",
+ "switch": "nowarn:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "CommaAppendable"
+ ]
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineConstants",
+ "switch": "define:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable",
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-1",
+ "comment": "",
+ "value": "ISO-1",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-2",
+ "comment": "",
+ "value": "ISO-2",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:5",
+ "comment": "",
+ "value": "5",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:6",
+ "comment": "",
+ "value": "6",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:default",
+ "comment": "",
+ "value": "default",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyOriginatorKeyFile",
+ "switch": "keyfile",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "KeyContainerName",
+ "switch": "keycontainer",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoLogo",
+ "switch": "nologo",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoConfig",
+ "switch": "noconfig",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "baseaddress:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "CodePage",
+ "switch": "codepage",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "Utf8Output",
+ "switch": "utf8output",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "MainEntryPoint",
+ "switch": "main:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "GenerateFullPaths",
+ "switch": "fullpaths",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FileAlignment",
+ "switch": "filealign",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "PdbFile",
+ "switch": "pdb:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SubsystemVersion",
+ "switch": "subsystemversion",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibPaths",
+ "switch": "lib:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:none",
+ "comment": "Do Not Send Report",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:queue",
+ "comment": "Queue For Next Login",
+ "value": "queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:send",
+ "comment": "Send Automatically",
+ "value": "send",
+ "flags": []
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v11_LIB.json b/Templates/MSBuild/FlagTables/v11_LIB.json
new file mode 100644
index 000000000..58a238c97
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v11_LIB.json
@@ -0,0 +1,297 @@
+[
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:PROMPT",
+ "comment": "PromptImmediately",
+ "value": "PromptImmediately",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:QUEUE",
+ "comment": "Queue For Next Login",
+ "value": "QueueForNextLogin",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:SEND",
+ "comment": "Send Error Report",
+ "value": "SendErrorReport",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:NONE",
+ "comment": "No Error Report",
+ "value": "NoErrorReport",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM",
+ "comment": "MachineARM",
+ "value": "MachineARM",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:EBC",
+ "comment": "MachineEBC",
+ "value": "MachineEBC",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:IA64",
+ "comment": "MachineIA64",
+ "value": "MachineIA64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS",
+ "comment": "MachineMIPS",
+ "value": "MachineMIPS",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS16",
+ "comment": "MachineMIPS16",
+ "value": "MachineMIPS16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU",
+ "comment": "MachineMIPSFPU",
+ "value": "MachineMIPSFPU",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU16",
+ "comment": "MachineMIPSFPU16",
+ "value": "MachineMIPSFPU16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:SH4",
+ "comment": "MachineSH4",
+ "value": "MachineSH4",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:THUMB",
+ "comment": "MachineTHUMB",
+ "value": "MachineTHUMB",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X64",
+ "comment": "MachineX64",
+ "value": "MachineX64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X86",
+ "comment": "MachineX86",
+ "value": "MachineX86",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:CONSOLE",
+ "comment": "Console",
+ "value": "Console",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWS",
+ "comment": "Windows",
+ "value": "Windows",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:NATIVE",
+ "comment": "Native",
+ "value": "Native",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_APPLICATION",
+ "comment": "EFI Application",
+ "value": "EFI Application",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+ "comment": "EFI Boot Service Driver",
+ "value": "EFI Boot Service Driver",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_ROM",
+ "comment": "EFI ROM",
+ "value": "EFI ROM",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+ "comment": "EFI Runtime",
+ "value": "EFI Runtime",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWSCE",
+ "comment": "WindowsCE",
+ "value": "WindowsCE",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:POSIX",
+ "comment": "POSIX",
+ "value": "POSIX",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "NOLOGO",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreAllDefaultLibraries",
+ "switch": "NODEFAULTLIB",
+ "comment": "Ignore All Default Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatLibWarningAsErrors",
+ "switch": "WX:NO",
+ "comment": "Treat Lib Warning As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatLibWarningAsErrors",
+ "switch": "WX",
+ "comment": "Treat Lib Warning As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Verbose",
+ "switch": "VERBOSE",
+ "comment": "Verbose",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG",
+ "comment": "Link Time Code Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibraryDirectories",
+ "switch": "LIBPATH:",
+ "comment": "Additional Library Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IgnoreSpecificDefaultLibraries",
+ "switch": "NODEFAULTLIB:",
+ "comment": "Ignore Specific Default Libraries",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ExportNamedFunctions",
+ "switch": "EXPORT:",
+ "comment": "Export Named Functions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "RemoveObjects",
+ "switch": "REMOVE:",
+ "comment": "Remove Objects",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFile",
+ "switch": "OUT:",
+ "comment": "Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ModuleDefinitionFile",
+ "switch": "DEF:",
+ "comment": "Module Definition File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ForceSymbolReferences",
+ "switch": "INCLUDE:",
+ "comment": "Force Symbol References",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "DisplayLibrary",
+ "switch": "LIST:",
+ "comment": "Display Library to standard output",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "Name",
+ "switch": "NAME:",
+ "comment": "Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v11_Link.json b/Templates/MSBuild/FlagTables/v11_Link.json
new file mode 100644
index 000000000..5d5c13f21
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v11_Link.json
@@ -0,0 +1,1272 @@
+[
+ {
+ "name": "ShowProgress",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE",
+ "comment": "Display all progress messages",
+ "value": "LinkVerbose",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:Lib",
+ "comment": "For Libraries Searched",
+ "value": "LinkVerboseLib",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:ICF",
+ "comment": "About COMDAT folding during optimized linking",
+ "value": "LinkVerboseICF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:REF",
+ "comment": "About data removed during optimized linking",
+ "value": "LinkVerboseREF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:SAFESEH",
+ "comment": "About Modules incompatible with SEH",
+ "value": "LinkVerboseSAFESEH",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:CLR",
+ "comment": "About linker activity related to managed code",
+ "value": "LinkVerboseCLR",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:MULTIPLE",
+ "comment": "Multiply Defined Symbol Only",
+ "value": "MultiplyDefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:UNRESOLVED",
+ "comment": "Undefined Symbol Only",
+ "value": "UndefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:5",
+ "comment": "X86 Image Only",
+ "value": "X86Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:6",
+ "comment": "X64 Image Only",
+ "value": "X64Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:16",
+ "comment": "Itanium Image Only",
+ "value": "ItaniumImage",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='asInvoker'",
+ "comment": "asInvoker",
+ "value": "AsInvoker",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='highestAvailable'",
+ "comment": "highestAvailable",
+ "value": "HighestAvailable",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='requireAdministrator'",
+ "comment": "requireAdministrator",
+ "value": "RequireAdministrator",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:CONSOLE",
+ "comment": "Console",
+ "value": "Console",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWS",
+ "comment": "Windows",
+ "value": "Windows",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:NATIVE",
+ "comment": "Native",
+ "value": "Native",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_APPLICATION",
+ "comment": "EFI Application",
+ "value": "EFI Application",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+ "comment": "EFI Boot Service Driver",
+ "value": "EFI Boot Service Driver",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_ROM",
+ "comment": "EFI ROM",
+ "value": "EFI ROM",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+ "comment": "EFI Runtime",
+ "value": "EFI Runtime",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:POSIX",
+ "comment": "POSIX",
+ "value": "POSIX",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "Driver",
+ "comment": "Driver",
+ "value": "Driver",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:UPONLY",
+ "comment": "UP Only",
+ "value": "UpOnly",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:WDM",
+ "comment": "WDM",
+ "value": "WDM",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG",
+ "comment": "Use Link Time Code Generation",
+ "value": "UseLinkTimeCodeGeneration",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGInstrument",
+ "comment": "Profile Guided Optimization - Instrument",
+ "value": "PGInstrument",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGOptimize",
+ "comment": "Profile Guided Optimization - Optimization",
+ "value": "PGOptimization",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGUpdate",
+ "comment": "Profile Guided Optimization - Update",
+ "value": "PGUpdate",
+ "flags": []
+ },
+ {
+ "name": "GenerateWindowsMetadata",
+ "switch": "WINMD",
+ "comment": "Yes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateWindowsMetadata",
+ "switch": "WINMD:NO",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA1",
+ "comment": "SHA1",
+ "value": "SHA1",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA256",
+ "comment": "SHA256",
+ "value": "SHA256",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA384",
+ "comment": "SHA384",
+ "value": "SHA384",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA512",
+ "comment": "SHA512",
+ "value": "SHA512",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM",
+ "comment": "MachineARM",
+ "value": "MachineARM",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:EBC",
+ "comment": "MachineEBC",
+ "value": "MachineEBC",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:IA64",
+ "comment": "MachineIA64",
+ "value": "MachineIA64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS",
+ "comment": "MachineMIPS",
+ "value": "MachineMIPS",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS16",
+ "comment": "MachineMIPS16",
+ "value": "MachineMIPS16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU",
+ "comment": "MachineMIPSFPU",
+ "value": "MachineMIPSFPU",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU16",
+ "comment": "MachineMIPSFPU16",
+ "value": "MachineMIPSFPU16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:SH4",
+ "comment": "MachineSH4",
+ "value": "MachineSH4",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:THUMB",
+ "comment": "MachineTHUMB",
+ "value": "MachineTHUMB",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X64",
+ "comment": "MachineX64",
+ "value": "MachineX64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X86",
+ "comment": "MachineX86",
+ "value": "MachineX86",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:MTA",
+ "comment": "MTA threading attribute",
+ "value": "MTAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:STA",
+ "comment": "STA threading attribute",
+ "value": "STAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:NONE",
+ "comment": "Default threading attribute",
+ "value": "DefaultThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:IJW",
+ "comment": "Force IJW image",
+ "value": "ForceIJWImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:PURE",
+ "comment": "Force Pure IL Image",
+ "value": "ForcePureILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:SAFE",
+ "comment": "Force Safe IL Image",
+ "value": "ForceSafeILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "",
+ "comment": "Default image type",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA1",
+ "comment": "SHA1",
+ "value": "SHA1",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA256",
+ "comment": "SHA256",
+ "value": "SHA256",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA384",
+ "comment": "SHA384",
+ "value": "SHA384",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA512",
+ "comment": "SHA512",
+ "value": "SHA512",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:PROMPT",
+ "comment": "PromptImmediately",
+ "value": "PromptImmediately",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:QUEUE",
+ "comment": "Queue For Next Login",
+ "value": "QueueForNextLogin",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:SEND",
+ "comment": "Send Error Report",
+ "value": "SendErrorReport",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:NONE",
+ "comment": "No Error Report",
+ "value": "NoErrorReport",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:NO",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:SYSTEMDLL",
+ "comment": "System Dlls Only",
+ "value": "SystemDlls",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL:NO",
+ "comment": "Enable Incremental Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL",
+ "comment": "Enable Incremental Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "NOLOGO",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:NOSTATUS",
+ "comment": "Link Status",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:STATUS",
+ "comment": "Link Status",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND:NO",
+ "comment": "Prevent Dll Binding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND",
+ "comment": "Prevent Dll Binding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX:NO",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreAllDefaultLibraries",
+ "switch": "NODEFAULTLIB",
+ "comment": "Ignore All Default Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST:NO",
+ "comment": "Generate Manifest",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST",
+ "comment": "Generate Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "ALLOWISOLATION:NO",
+ "comment": "Allow Isolation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "",
+ "comment": "Allow Isolation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableUAC",
+ "switch": "MANIFESTUAC:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "SpaceAppendable"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='true'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ManifestEmbed",
+ "switch": "manifest:embed",
+ "comment": "Embed Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG",
+ "comment": "Generate Debug Info",
+ "value": "true",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateMapFile",
+ "switch": "MAP",
+ "comment": "Generate Map File",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "MapExports",
+ "switch": "MAPINFO:EXPORTS",
+ "comment": "Map Exports",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG:DISABLE",
+ "comment": "Debuggable Assembly",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG",
+ "comment": "Debuggable Assembly",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE:NO",
+ "comment": "Enable Large Addresses",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE",
+ "comment": "Enable Large Addresses",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE:NO",
+ "comment": "Terminal Server",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE",
+ "comment": "Terminal Server",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromCD",
+ "switch": "SWAPRUN:CD",
+ "comment": "Swap Run From CD",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromNET",
+ "switch": "SWAPRUN:NET",
+ "comment": "Swap Run From Network",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:NOREF",
+ "comment": "References",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:REF",
+ "comment": "References",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:NOICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:ICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreEmbeddedIDL",
+ "switch": "IGNOREIDL",
+ "comment": "Ignore Embedded IDL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AppContainer",
+ "switch": "APPCONTAINER",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataLinkDelaySign",
+ "switch": "WINMDDELAYSIGN:NO",
+ "comment": "Windows Metadata Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataLinkDelaySign",
+ "switch": "WINMDDELAYSIGN",
+ "comment": "Windows Metadata Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoEntryPoint",
+ "switch": "NOENTRY",
+ "comment": "No Entry Point",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SetChecksum",
+ "switch": "RELEASE",
+ "comment": "Set Checksum",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE:NO",
+ "comment": "Randomized Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE",
+ "comment": "Randomized Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED:NO",
+ "comment": "Fixed Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED",
+ "comment": "Fixed Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT:NO",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TurnOffAssemblyGeneration",
+ "switch": "NOASSEMBLY",
+ "comment": "Turn Off Assembly Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportUnloadOfDelayLoadedDLL",
+ "switch": "DELAY:UNLOAD",
+ "comment": "Unload delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportNobindOfDelayLoadedDLL",
+ "switch": "DELAY:NOBIND",
+ "comment": "Nobind delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Profile",
+ "switch": "PROFILE",
+ "comment": "Profile",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN:NO",
+ "comment": "Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN",
+ "comment": "Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK:NO",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DetectOneDefinitionRule",
+ "switch": "ODR",
+ "comment": "Detect One Definition Rule violations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH:NO",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDLL",
+ "switch": "DLL",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibraryDirectories",
+ "switch": "LIBPATH:",
+ "comment": "Additional Library Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IgnoreSpecificDefaultLibraries",
+ "switch": "NODEFAULTLIB:",
+ "comment": "Ignore Specific Default Libraries",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AddModuleNamesToAssembly",
+ "switch": "ASSEMBLYMODULE:",
+ "comment": "Add Module to Assembly",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "EmbedManagedResourceFile",
+ "switch": "ASSEMBLYRESOURCE:",
+ "comment": "Embed Managed Resource File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForceSymbolReferences",
+ "switch": "INCLUDE:",
+ "comment": "Force Symbol References",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DelayLoadDLLs",
+ "switch": "DELAYLOAD:",
+ "comment": "Delay Loaded Dlls",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AssemblyLinkResource",
+ "switch": "ASSEMBLYLINKRESOURCE:",
+ "comment": "Assembly Link Resource",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalManifestDependencies",
+ "switch": "MANIFESTDEPENDENCY:",
+ "comment": "Additional Manifest Dependencies",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ManifestInput",
+ "switch": "manifestinput:",
+ "comment": "Manifest Input",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFile",
+ "switch": "OUT:",
+ "comment": "Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "Version",
+ "switch": "VERSION:",
+ "comment": "Version",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SpecifySectionAttributes",
+ "switch": "SECTION:",
+ "comment": "Specify Section Attributes",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MSDOSStubFileName",
+ "switch": "STUB:",
+ "comment": "MS-DOS Stub File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ModuleDefinitionFile",
+ "switch": "DEF:",
+ "comment": "Module Definition File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ManifestFile",
+ "switch": "ManifestFile:",
+ "comment": "Manifest File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDatabaseFile",
+ "switch": "PDB:",
+ "comment": "Generate Program Database File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StripPrivateSymbols",
+ "switch": "PDBSTRIPPED:",
+ "comment": "Strip Private Symbols",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MapFileName",
+ "switch": "MAP:",
+ "comment": "Map File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "HeapReserveSize",
+ "switch": "HEAP:",
+ "comment": "Heap Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "HeapCommitSize",
+ "switch": "HEAP",
+ "comment": "Heap Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "StackReserveSize",
+ "switch": "STACK:",
+ "comment": "Stack Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StackCommitSize",
+ "switch": "STACK",
+ "comment": "Stack Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "FunctionOrder",
+ "switch": "ORDER:@",
+ "comment": "Function Order",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProfileGuidedDatabase",
+ "switch": "PGD:",
+ "comment": "Profile Guided Database",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MidlCommandFile",
+ "switch": "MIDL:@",
+ "comment": "MIDL Commands",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergedIDLBaseFileName",
+ "switch": "IDLOUT:",
+ "comment": "Merged IDL Base File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryFile",
+ "switch": "TLBOUT:",
+ "comment": "Type Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataFile",
+ "switch": "WINMDFILE:",
+ "comment": "Windows Metadata File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataLinkKeyFile",
+ "switch": "WINMDKEYFILE:",
+ "comment": "Windows Metadata Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataKeyContainer",
+ "switch": "WINMDKEYCONTAINER:",
+ "comment": "Windows Metadata Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "EntryPointSymbol",
+ "switch": "ENTRY:",
+ "comment": "Entry Point",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "BASE:",
+ "comment": "Base Address",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ImportLibrary",
+ "switch": "IMPLIB:",
+ "comment": "Import Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergeSections",
+ "switch": "MERGE:",
+ "comment": "Merge Sections",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LinkKeyFile",
+ "switch": "KEYFILE:",
+ "comment": "Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "KeyContainer",
+ "switch": "KEYCONTAINER:",
+ "comment": "Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryResourceID",
+ "switch": "TLBID:",
+ "comment": "TypeLib Resource ID",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SectionAlignment",
+ "switch": "ALIGN:",
+ "comment": "SectionAlignment",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v11_MASM.json b/Templates/MSBuild/FlagTables/v11_MASM.json
new file mode 100644
index 000000000..4634306b1
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v11_MASM.json
@@ -0,0 +1,295 @@
+[
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cp",
+ "comment": "Preserves Identifier Case (/Cp)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cu",
+ "comment": "Maps all identifiers to upper case. (/Cu)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cx",
+ "comment": "Preserves case in public and extern symbols. (/Cx)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W0",
+ "comment": "Warning Level 0 (/W0)",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W1",
+ "comment": "Warning Level 1 (/W1)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W2",
+ "comment": "Warning Level 2 (/W2)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W3",
+ "comment": "Warning Level 3 (/W3)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp1",
+ "comment": "One Byte Boundary (/Zp1)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp2",
+ "comment": "Two Byte Boundary (/Zp2)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp4",
+ "comment": "Four Byte Boundary (/Zp4)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp8",
+ "comment": "Eight Byte Boundary (/Zp8)",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp16",
+ "comment": "Sixteen Byte Boundary (/Zp16)",
+ "value": "5",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gd",
+ "comment": "Use C-style Calling Convention (/Gd)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gz",
+ "comment": "Use stdcall Calling Convention (/Gz)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gc",
+ "comment": "Use Pascal Calling Convention (/Gc)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:prompt",
+ "comment": "Prompt to send report immediately (/errorReport:prompt)",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:queue",
+ "comment": "Prompt to send report at the next logon (/errorReport:queue)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:send",
+ "comment": "Automatically send report (/errorReport:send)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:none",
+ "comment": "Do not send report (/errorReport:none)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "NoLogo",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GeneratePreprocessedSourceListing",
+ "switch": "EP",
+ "comment": "Generate Preprocessed Source Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ListAllAvailableInformation",
+ "switch": "Sa",
+ "comment": "List All Available Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseSafeExceptionHandlers",
+ "switch": "safeseh",
+ "comment": "Use Safe Exception Handlers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AddFirstPassListing",
+ "switch": "Sf",
+ "comment": "Add First Pass Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableAssemblyGeneratedCodeListing",
+ "switch": "Sg",
+ "comment": "Enable Assembly Generated Code Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DisableSymbolTable",
+ "switch": "Sn",
+ "comment": "Disable Symbol Table",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableFalseConditionalsInListing",
+ "switch": "Sx",
+ "comment": "Enable False Conditionals In Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "WX",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MakeAllSymbolsPublic",
+ "switch": "Zf",
+ "comment": "Make All Symbols Public",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "Zi",
+ "comment": "Generate Debug Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableMASM51Compatibility",
+ "switch": "Zm",
+ "comment": "Enable MASM 5.1 Compatibility",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PerformSyntaxCheckOnly",
+ "switch": "Zs",
+ "comment": "Perform Syntax Check Only",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IncludePaths",
+ "switch": "I",
+ "comment": "Include Paths",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "BrowseFile",
+ "switch": "FR",
+ "comment": "Generate Browse Information File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ObjectFileName",
+ "switch": "Fo",
+ "comment": "Object File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "AssembledCodeListingFile",
+ "switch": "Fl",
+ "comment": "Assembled Code Listing File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v11_RC.json b/Templates/MSBuild/FlagTables/v11_RC.json
new file mode 100644
index 000000000..b8c0127d1
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v11_RC.json
@@ -0,0 +1,69 @@
+[
+ {
+ "name": "IgnoreStandardIncludePath",
+ "switch": "X",
+ "comment": "Ignore Standard Include Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "v",
+ "comment": "Show Progress",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NullTerminateStrings",
+ "switch": "n",
+ "comment": "Null Terminate Strings",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "u",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalIncludeDirectories",
+ "switch": "I",
+ "comment": "Additional Include Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ResourceOutputFileName",
+ "switch": "fo",
+ "comment": "Resource File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v12_CL.json b/Templates/MSBuild/FlagTables/v12_CL.json
new file mode 100644
index 000000000..771a5551c
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v12_CL.json
@@ -0,0 +1,1077 @@
+[
+ {
+ "name": "DebugInformationFormat",
+ "switch": "",
+ "comment": "None",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Z7",
+ "comment": "C7 compatible",
+ "value": "OldStyle",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Zi",
+ "comment": "Program Database",
+ "value": "ProgramDatabase",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "ZI",
+ "comment": "Program Database for Edit And Continue",
+ "value": "EditAndContinue",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "",
+ "comment": "No Common Language RunTime Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr",
+ "comment": "Common Language RunTime Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:pure",
+ "comment": "Pure MSIL Common Language RunTime Support",
+ "value": "Pure",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:safe",
+ "comment": "Safe MSIL Common Language RunTime Support",
+ "value": "Safe",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:oldSyntax",
+ "comment": "Common Language RunTime Support, Old Syntax",
+ "value": "OldSyntax",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W0",
+ "comment": "Turn Off All Warnings",
+ "value": "TurnOffAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W1",
+ "comment": "Level1",
+ "value": "Level1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W2",
+ "comment": "Level2",
+ "value": "Level2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W3",
+ "comment": "Level3",
+ "value": "Level3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W4",
+ "comment": "Level4",
+ "value": "Level4",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "Wall",
+ "comment": "EnableAllWarnings",
+ "value": "EnableAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "",
+ "comment": "Custom",
+ "value": "Custom",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Od",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O1",
+ "comment": "Minimize Size",
+ "value": "MinSpace",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O2",
+ "comment": "Maximize Speed",
+ "value": "MaxSpeed",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Ox",
+ "comment": "Full Optimization",
+ "value": "Full",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob0",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob1",
+ "comment": "Only __inline",
+ "value": "OnlyExplicitInline",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob2",
+ "comment": "Any Suitable",
+ "value": "AnySuitable",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Os",
+ "comment": "Favor small code",
+ "value": "Size",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Ot",
+ "comment": "Favor fast code",
+ "value": "Speed",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "",
+ "comment": "Neither",
+ "value": "Neither",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHa",
+ "comment": "Yes with SEH Exceptions",
+ "value": "Async",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHsc",
+ "comment": "Yes",
+ "value": "Sync",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHs",
+ "comment": "Yes with Extern C functions",
+ "value": "SyncCThrow",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCs",
+ "comment": "Stack Frames",
+ "value": "StackFrameRuntimeCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCu",
+ "comment": "Uninitialized variables",
+ "value": "UninitializedLocalUsageCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTC1",
+ "comment": "Both (/RTC1, equiv. to /RTCsu)",
+ "value": "EnableFastChecks",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MT",
+ "comment": "Multi-threaded",
+ "value": "MultiThreaded",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MTd",
+ "comment": "Multi-threaded Debug",
+ "value": "MultiThreadedDebug",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MD",
+ "comment": "Multi-threaded DLL",
+ "value": "MultiThreadedDLL",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MDd",
+ "comment": "Multi-threaded Debug DLL",
+ "value": "MultiThreadedDebugDLL",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp1",
+ "comment": "1 Byte",
+ "value": "1Byte",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp2",
+ "comment": "2 Bytes",
+ "value": "2Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp4",
+ "comment": "4 Byte",
+ "value": "4Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp8",
+ "comment": "8 Bytes",
+ "value": "8Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp16",
+ "comment": "16 Bytes",
+ "value": "16Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS-",
+ "comment": "Disable Security Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS",
+ "comment": "Enable Security Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE",
+ "comment": "Streaming SIMD Extensions",
+ "value": "StreamingSIMDExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE2",
+ "comment": "Streaming SIMD Extensions 2",
+ "value": "StreamingSIMDExtensions2",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:AVX",
+ "comment": "Advanced Vector Extensions",
+ "value": "AdvancedVectorExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:AVX2",
+ "comment": "Advanced Vector Extensions 2",
+ "value": "AdvancedVectorExtensions2",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:IA32",
+ "comment": "No Enhanced Instructions",
+ "value": "NoExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:precise",
+ "comment": "Precise",
+ "value": "Precise",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:strict",
+ "comment": "Strict",
+ "value": "Strict",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:fast",
+ "comment": "Fast",
+ "value": "Fast",
+ "flags": []
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yc",
+ "comment": "Create",
+ "value": "Create",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yu",
+ "comment": "Use",
+ "value": "Use",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Y-",
+ "comment": "Not Using Precompiled Headers",
+ "value": "NotUsing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "",
+ "comment": "No Listing",
+ "value": "NoListing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FA",
+ "comment": "Assembly-Only Listing",
+ "value": "AssemblyCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAc",
+ "comment": "Assembly With Machine Code",
+ "value": "AssemblyAndMachineCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAs",
+ "comment": "Assembly With Source Code",
+ "value": "AssemblyAndSourceCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAcs",
+ "comment": "Assembly, Machine Code and Source",
+ "value": "All",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gd",
+ "comment": "__cdecl",
+ "value": "Cdecl",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gr",
+ "comment": "__fastcall",
+ "value": "FastCall",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gz",
+ "comment": "__stdcall",
+ "value": "StdCall",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gv",
+ "comment": "__vectorcall",
+ "value": "VectorCall",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TC",
+ "comment": "Compile as C Code",
+ "value": "CompileAsC",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TP",
+ "comment": "Compile as C++ Code",
+ "value": "CompileAsCpp",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:none",
+ "comment": "Do Not Send Report",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "Prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:queue",
+ "comment": "Queue For Next Login",
+ "value": "Queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:send",
+ "comment": "Send Automatically",
+ "value": "Send",
+ "flags": []
+ },
+ {
+ "name": "CompileAsWinRT",
+ "switch": "ZW",
+ "comment": "Consume Windows Runtime Extension",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WinRTNoStdLib",
+ "switch": "ZW:nostdlib",
+ "comment": "No Standard WinRT Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX-",
+ "comment": "Treat Warnings As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SDLCheck",
+ "switch": "sdl-",
+ "comment": "SDL checks",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "SDLCheck",
+ "switch": "sdl",
+ "comment": "SDL checks",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MultiProcessorCompilation",
+ "switch": "MP",
+ "comment": "Multi-processor Compilation",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "IntrinsicFunctions",
+ "switch": "Oi",
+ "comment": "Enable Intrinsic Functions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy-",
+ "comment": "Omit Frame Pointers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy",
+ "comment": "Omit Frame Pointers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableFiberSafeOptimizations",
+ "switch": "GT",
+ "comment": "Enable Fiber-Safe Optimizations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WholeProgramOptimization",
+ "switch": "GL",
+ "comment": "Whole Program Optimization",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UndefineAllPreprocessorDefinitions",
+ "switch": "u",
+ "comment": "Undefine All Preprocessor Definitions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreStandardIncludePath",
+ "switch": "X",
+ "comment": "Ignore Standard Include Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessToFile",
+ "switch": "P",
+ "comment": "Preprocess to a File",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessSuppressLineNumbers",
+ "switch": "EP",
+ "comment": "Preprocess Suppress Line Numbers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessKeepComments",
+ "switch": "C",
+ "comment": "Keep Comments",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF-",
+ "comment": "Enable String Pooling",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF",
+ "comment": "Enable String Pooling",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm-",
+ "comment": "Enable Minimal Rebuild",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm",
+ "comment": "Enable Minimal Rebuild",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SmallerTypeCheck",
+ "switch": "RTCc",
+ "comment": "Smaller Type Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy-",
+ "comment": "Enable Function-Level Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy",
+ "comment": "Enable Function-Level Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableParallelCodeGeneration",
+ "switch": "Qpar-",
+ "comment": "Enable Parallel Code Generation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableParallelCodeGeneration",
+ "switch": "Qpar",
+ "comment": "Enable Parallel Code Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except-",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CreateHotpatchableImage",
+ "switch": "hotpatch",
+ "comment": "Create Hotpatchable Image",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DisableLanguageExtensions",
+ "switch": "Za",
+ "comment": "Disable Language Extensions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t-",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope-",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR-",
+ "comment": "Enable Run-Time Type Information",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR",
+ "comment": "Enable Run-Time Type Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp-",
+ "comment": "Open MP Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp",
+ "comment": "Open MP Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ExpandAttributedSource",
+ "switch": "Fx",
+ "comment": "Expand Attributed Source",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseUnicodeForAssemblerListing",
+ "switch": "FAu",
+ "comment": "Use Unicode For Assembler Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateXMLDocumentationFiles",
+ "switch": "doc",
+ "comment": "Generate XML Documentation Files",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "BrowseInformation",
+ "switch": "FR",
+ "comment": "Enable Browse Information",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "ShowIncludes",
+ "switch": "showIncludes",
+ "comment": "Show Includes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze-",
+ "comment": "Enable Code Analysis",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze",
+ "comment": "Enable Code Analysis",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseFullPaths",
+ "switch": "FC",
+ "comment": "Use Full Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitDefaultLibName",
+ "switch": "Zl",
+ "comment": "Omit Default Library Name",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalIncludeDirectories",
+ "switch": "I",
+ "comment": "Additional Include Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalUsingDirectories",
+ "switch": "AI",
+ "comment": "Additional #using Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "U",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DisableSpecificWarnings",
+ "switch": "wd",
+ "comment": "Disable Specific Warnings",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedIncludeFiles",
+ "switch": "FI",
+ "comment": "Forced Include File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedUsingFiles",
+ "switch": "FU",
+ "comment": "Forced #using File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PREfastLog",
+ "switch": "analyze:log",
+ "comment": "Code Analysis Log",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ },
+ {
+ "name": "PREfastAdditionalPlugins",
+ "switch": "analyze:plugin",
+ "comment": "Additional Code Analysis Native plugins",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "TreatSpecificWarningsAsErrors",
+ "switch": "we",
+ "comment": "Treat Specific Warnings As Errors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PreprocessOutputPath",
+ "switch": "Fi",
+ "comment": "Preprocess Output Path",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yu",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yc",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderOutputFile",
+ "switch": "Fp",
+ "comment": "Precompiled Header Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "AssemblerListingLocation",
+ "switch": "Fa",
+ "comment": "ASM List Location",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ObjectFileName",
+ "switch": "Fo",
+ "comment": "Object File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDataBaseFileName",
+ "switch": "Fd",
+ "comment": "Program Database File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "XMLDocumentationFileName",
+ "switch": "doc",
+ "comment": "XML Documentation File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "BrowseInformationFile",
+ "switch": "FR",
+ "comment": "Browse Information File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ProcessorNumber",
+ "switch": "MP",
+ "comment": "Number of processors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v12_CSharp.json b/Templates/MSBuild/FlagTables/v12_CSharp.json
new file mode 100644
index 000000000..5989aea1e
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v12_CSharp.json
@@ -0,0 +1,574 @@
+[
+ {
+ "name": "ProjectName",
+ "switch": "out:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:exe",
+ "comment": "",
+ "value": "Exe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:winexe",
+ "comment": "",
+ "value": "Winexe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:library",
+ "comment": "",
+ "value": "Library",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:module",
+ "comment": "",
+ "value": "Module",
+ "flags": []
+ },
+ {
+ "name": "DocumentationFile",
+ "switch": "doc",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x86",
+ "comment": "",
+ "value": "x86",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:Itanium",
+ "comment": "",
+ "value": "Itanium",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x64",
+ "comment": "",
+ "value": "x64",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:arm",
+ "comment": "",
+ "value": "arm",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu32bitpreferred",
+ "comment": "",
+ "value": "anycpu32bitpreferred",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu",
+ "comment": "",
+ "value": "anycpu",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "mit alias",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "dateiliste",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AddModules",
+ "switch": "addmodule:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "Win32Resource",
+ "switch": "win32res:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationIcon",
+ "switch": "win32icon:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationManifest",
+ "switch": "win32manifest:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "NoWin32Manifest",
+ "switch": "nowin32manifest",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineDebug",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": [
+ "Continue"
+ ]
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:none",
+ "comment": "",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:full",
+ "comment": "",
+ "value": "full",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:pdbonly",
+ "comment": "",
+ "value": "pdbonly",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:0",
+ "comment": "",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:1",
+ "comment": "",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:2",
+ "comment": "",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "NoWarn",
+ "switch": "nowarn:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "CommaAppendable"
+ ]
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineConstants",
+ "switch": "define:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable",
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-1",
+ "comment": "",
+ "value": "ISO-1",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-2",
+ "comment": "",
+ "value": "ISO-2",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:5",
+ "comment": "",
+ "value": "5",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:6",
+ "comment": "",
+ "value": "6",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:default",
+ "comment": "",
+ "value": "default",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyOriginatorKeyFile",
+ "switch": "keyfile",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "KeyContainerName",
+ "switch": "keycontainer",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoLogo",
+ "switch": "nologo",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoConfig",
+ "switch": "noconfig",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "baseaddress:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "CodePage",
+ "switch": "codepage",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "Utf8Output",
+ "switch": "utf8output",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "MainEntryPoint",
+ "switch": "main:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "GenerateFullPaths",
+ "switch": "fullpaths",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FileAlignment",
+ "switch": "filealign",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "PdbFile",
+ "switch": "pdb:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SubsystemVersion",
+ "switch": "subsystemversion",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibPaths",
+ "switch": "lib:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:none",
+ "comment": "Do Not Send Report",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:queue",
+ "comment": "Queue For Next Login",
+ "value": "queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:send",
+ "comment": "Send Automatically",
+ "value": "send",
+ "flags": []
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v12_LIB.json b/Templates/MSBuild/FlagTables/v12_LIB.json
new file mode 100644
index 000000000..58a238c97
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v12_LIB.json
@@ -0,0 +1,297 @@
+[
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:PROMPT",
+ "comment": "PromptImmediately",
+ "value": "PromptImmediately",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:QUEUE",
+ "comment": "Queue For Next Login",
+ "value": "QueueForNextLogin",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:SEND",
+ "comment": "Send Error Report",
+ "value": "SendErrorReport",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:NONE",
+ "comment": "No Error Report",
+ "value": "NoErrorReport",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM",
+ "comment": "MachineARM",
+ "value": "MachineARM",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:EBC",
+ "comment": "MachineEBC",
+ "value": "MachineEBC",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:IA64",
+ "comment": "MachineIA64",
+ "value": "MachineIA64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS",
+ "comment": "MachineMIPS",
+ "value": "MachineMIPS",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS16",
+ "comment": "MachineMIPS16",
+ "value": "MachineMIPS16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU",
+ "comment": "MachineMIPSFPU",
+ "value": "MachineMIPSFPU",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU16",
+ "comment": "MachineMIPSFPU16",
+ "value": "MachineMIPSFPU16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:SH4",
+ "comment": "MachineSH4",
+ "value": "MachineSH4",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:THUMB",
+ "comment": "MachineTHUMB",
+ "value": "MachineTHUMB",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X64",
+ "comment": "MachineX64",
+ "value": "MachineX64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X86",
+ "comment": "MachineX86",
+ "value": "MachineX86",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:CONSOLE",
+ "comment": "Console",
+ "value": "Console",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWS",
+ "comment": "Windows",
+ "value": "Windows",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:NATIVE",
+ "comment": "Native",
+ "value": "Native",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_APPLICATION",
+ "comment": "EFI Application",
+ "value": "EFI Application",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+ "comment": "EFI Boot Service Driver",
+ "value": "EFI Boot Service Driver",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_ROM",
+ "comment": "EFI ROM",
+ "value": "EFI ROM",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+ "comment": "EFI Runtime",
+ "value": "EFI Runtime",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWSCE",
+ "comment": "WindowsCE",
+ "value": "WindowsCE",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:POSIX",
+ "comment": "POSIX",
+ "value": "POSIX",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "NOLOGO",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreAllDefaultLibraries",
+ "switch": "NODEFAULTLIB",
+ "comment": "Ignore All Default Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatLibWarningAsErrors",
+ "switch": "WX:NO",
+ "comment": "Treat Lib Warning As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatLibWarningAsErrors",
+ "switch": "WX",
+ "comment": "Treat Lib Warning As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Verbose",
+ "switch": "VERBOSE",
+ "comment": "Verbose",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG",
+ "comment": "Link Time Code Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibraryDirectories",
+ "switch": "LIBPATH:",
+ "comment": "Additional Library Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IgnoreSpecificDefaultLibraries",
+ "switch": "NODEFAULTLIB:",
+ "comment": "Ignore Specific Default Libraries",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ExportNamedFunctions",
+ "switch": "EXPORT:",
+ "comment": "Export Named Functions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "RemoveObjects",
+ "switch": "REMOVE:",
+ "comment": "Remove Objects",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFile",
+ "switch": "OUT:",
+ "comment": "Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ModuleDefinitionFile",
+ "switch": "DEF:",
+ "comment": "Module Definition File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ForceSymbolReferences",
+ "switch": "INCLUDE:",
+ "comment": "Force Symbol References",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "DisplayLibrary",
+ "switch": "LIST:",
+ "comment": "Display Library to standard output",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "Name",
+ "switch": "NAME:",
+ "comment": "Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v12_Link.json b/Templates/MSBuild/FlagTables/v12_Link.json
new file mode 100644
index 000000000..5d5c13f21
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v12_Link.json
@@ -0,0 +1,1272 @@
+[
+ {
+ "name": "ShowProgress",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE",
+ "comment": "Display all progress messages",
+ "value": "LinkVerbose",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:Lib",
+ "comment": "For Libraries Searched",
+ "value": "LinkVerboseLib",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:ICF",
+ "comment": "About COMDAT folding during optimized linking",
+ "value": "LinkVerboseICF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:REF",
+ "comment": "About data removed during optimized linking",
+ "value": "LinkVerboseREF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:SAFESEH",
+ "comment": "About Modules incompatible with SEH",
+ "value": "LinkVerboseSAFESEH",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:CLR",
+ "comment": "About linker activity related to managed code",
+ "value": "LinkVerboseCLR",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:MULTIPLE",
+ "comment": "Multiply Defined Symbol Only",
+ "value": "MultiplyDefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:UNRESOLVED",
+ "comment": "Undefined Symbol Only",
+ "value": "UndefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:5",
+ "comment": "X86 Image Only",
+ "value": "X86Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:6",
+ "comment": "X64 Image Only",
+ "value": "X64Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:16",
+ "comment": "Itanium Image Only",
+ "value": "ItaniumImage",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='asInvoker'",
+ "comment": "asInvoker",
+ "value": "AsInvoker",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='highestAvailable'",
+ "comment": "highestAvailable",
+ "value": "HighestAvailable",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='requireAdministrator'",
+ "comment": "requireAdministrator",
+ "value": "RequireAdministrator",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:CONSOLE",
+ "comment": "Console",
+ "value": "Console",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWS",
+ "comment": "Windows",
+ "value": "Windows",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:NATIVE",
+ "comment": "Native",
+ "value": "Native",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_APPLICATION",
+ "comment": "EFI Application",
+ "value": "EFI Application",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+ "comment": "EFI Boot Service Driver",
+ "value": "EFI Boot Service Driver",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_ROM",
+ "comment": "EFI ROM",
+ "value": "EFI ROM",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+ "comment": "EFI Runtime",
+ "value": "EFI Runtime",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:POSIX",
+ "comment": "POSIX",
+ "value": "POSIX",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "Driver",
+ "comment": "Driver",
+ "value": "Driver",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:UPONLY",
+ "comment": "UP Only",
+ "value": "UpOnly",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:WDM",
+ "comment": "WDM",
+ "value": "WDM",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG",
+ "comment": "Use Link Time Code Generation",
+ "value": "UseLinkTimeCodeGeneration",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGInstrument",
+ "comment": "Profile Guided Optimization - Instrument",
+ "value": "PGInstrument",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGOptimize",
+ "comment": "Profile Guided Optimization - Optimization",
+ "value": "PGOptimization",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGUpdate",
+ "comment": "Profile Guided Optimization - Update",
+ "value": "PGUpdate",
+ "flags": []
+ },
+ {
+ "name": "GenerateWindowsMetadata",
+ "switch": "WINMD",
+ "comment": "Yes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateWindowsMetadata",
+ "switch": "WINMD:NO",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA1",
+ "comment": "SHA1",
+ "value": "SHA1",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA256",
+ "comment": "SHA256",
+ "value": "SHA256",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA384",
+ "comment": "SHA384",
+ "value": "SHA384",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA512",
+ "comment": "SHA512",
+ "value": "SHA512",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM",
+ "comment": "MachineARM",
+ "value": "MachineARM",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:EBC",
+ "comment": "MachineEBC",
+ "value": "MachineEBC",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:IA64",
+ "comment": "MachineIA64",
+ "value": "MachineIA64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS",
+ "comment": "MachineMIPS",
+ "value": "MachineMIPS",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS16",
+ "comment": "MachineMIPS16",
+ "value": "MachineMIPS16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU",
+ "comment": "MachineMIPSFPU",
+ "value": "MachineMIPSFPU",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU16",
+ "comment": "MachineMIPSFPU16",
+ "value": "MachineMIPSFPU16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:SH4",
+ "comment": "MachineSH4",
+ "value": "MachineSH4",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:THUMB",
+ "comment": "MachineTHUMB",
+ "value": "MachineTHUMB",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X64",
+ "comment": "MachineX64",
+ "value": "MachineX64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X86",
+ "comment": "MachineX86",
+ "value": "MachineX86",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:MTA",
+ "comment": "MTA threading attribute",
+ "value": "MTAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:STA",
+ "comment": "STA threading attribute",
+ "value": "STAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:NONE",
+ "comment": "Default threading attribute",
+ "value": "DefaultThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:IJW",
+ "comment": "Force IJW image",
+ "value": "ForceIJWImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:PURE",
+ "comment": "Force Pure IL Image",
+ "value": "ForcePureILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:SAFE",
+ "comment": "Force Safe IL Image",
+ "value": "ForceSafeILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "",
+ "comment": "Default image type",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA1",
+ "comment": "SHA1",
+ "value": "SHA1",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA256",
+ "comment": "SHA256",
+ "value": "SHA256",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA384",
+ "comment": "SHA384",
+ "value": "SHA384",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA512",
+ "comment": "SHA512",
+ "value": "SHA512",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:PROMPT",
+ "comment": "PromptImmediately",
+ "value": "PromptImmediately",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:QUEUE",
+ "comment": "Queue For Next Login",
+ "value": "QueueForNextLogin",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:SEND",
+ "comment": "Send Error Report",
+ "value": "SendErrorReport",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:NONE",
+ "comment": "No Error Report",
+ "value": "NoErrorReport",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:NO",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:SYSTEMDLL",
+ "comment": "System Dlls Only",
+ "value": "SystemDlls",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL:NO",
+ "comment": "Enable Incremental Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL",
+ "comment": "Enable Incremental Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "NOLOGO",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:NOSTATUS",
+ "comment": "Link Status",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:STATUS",
+ "comment": "Link Status",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND:NO",
+ "comment": "Prevent Dll Binding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND",
+ "comment": "Prevent Dll Binding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX:NO",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreAllDefaultLibraries",
+ "switch": "NODEFAULTLIB",
+ "comment": "Ignore All Default Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST:NO",
+ "comment": "Generate Manifest",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST",
+ "comment": "Generate Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "ALLOWISOLATION:NO",
+ "comment": "Allow Isolation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "",
+ "comment": "Allow Isolation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableUAC",
+ "switch": "MANIFESTUAC:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "SpaceAppendable"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='true'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ManifestEmbed",
+ "switch": "manifest:embed",
+ "comment": "Embed Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG",
+ "comment": "Generate Debug Info",
+ "value": "true",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateMapFile",
+ "switch": "MAP",
+ "comment": "Generate Map File",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "MapExports",
+ "switch": "MAPINFO:EXPORTS",
+ "comment": "Map Exports",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG:DISABLE",
+ "comment": "Debuggable Assembly",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG",
+ "comment": "Debuggable Assembly",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE:NO",
+ "comment": "Enable Large Addresses",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE",
+ "comment": "Enable Large Addresses",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE:NO",
+ "comment": "Terminal Server",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE",
+ "comment": "Terminal Server",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromCD",
+ "switch": "SWAPRUN:CD",
+ "comment": "Swap Run From CD",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromNET",
+ "switch": "SWAPRUN:NET",
+ "comment": "Swap Run From Network",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:NOREF",
+ "comment": "References",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:REF",
+ "comment": "References",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:NOICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:ICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreEmbeddedIDL",
+ "switch": "IGNOREIDL",
+ "comment": "Ignore Embedded IDL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AppContainer",
+ "switch": "APPCONTAINER",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataLinkDelaySign",
+ "switch": "WINMDDELAYSIGN:NO",
+ "comment": "Windows Metadata Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataLinkDelaySign",
+ "switch": "WINMDDELAYSIGN",
+ "comment": "Windows Metadata Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoEntryPoint",
+ "switch": "NOENTRY",
+ "comment": "No Entry Point",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SetChecksum",
+ "switch": "RELEASE",
+ "comment": "Set Checksum",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE:NO",
+ "comment": "Randomized Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE",
+ "comment": "Randomized Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED:NO",
+ "comment": "Fixed Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED",
+ "comment": "Fixed Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT:NO",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TurnOffAssemblyGeneration",
+ "switch": "NOASSEMBLY",
+ "comment": "Turn Off Assembly Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportUnloadOfDelayLoadedDLL",
+ "switch": "DELAY:UNLOAD",
+ "comment": "Unload delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportNobindOfDelayLoadedDLL",
+ "switch": "DELAY:NOBIND",
+ "comment": "Nobind delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Profile",
+ "switch": "PROFILE",
+ "comment": "Profile",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN:NO",
+ "comment": "Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN",
+ "comment": "Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK:NO",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DetectOneDefinitionRule",
+ "switch": "ODR",
+ "comment": "Detect One Definition Rule violations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH:NO",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDLL",
+ "switch": "DLL",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibraryDirectories",
+ "switch": "LIBPATH:",
+ "comment": "Additional Library Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IgnoreSpecificDefaultLibraries",
+ "switch": "NODEFAULTLIB:",
+ "comment": "Ignore Specific Default Libraries",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AddModuleNamesToAssembly",
+ "switch": "ASSEMBLYMODULE:",
+ "comment": "Add Module to Assembly",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "EmbedManagedResourceFile",
+ "switch": "ASSEMBLYRESOURCE:",
+ "comment": "Embed Managed Resource File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForceSymbolReferences",
+ "switch": "INCLUDE:",
+ "comment": "Force Symbol References",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DelayLoadDLLs",
+ "switch": "DELAYLOAD:",
+ "comment": "Delay Loaded Dlls",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AssemblyLinkResource",
+ "switch": "ASSEMBLYLINKRESOURCE:",
+ "comment": "Assembly Link Resource",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalManifestDependencies",
+ "switch": "MANIFESTDEPENDENCY:",
+ "comment": "Additional Manifest Dependencies",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ManifestInput",
+ "switch": "manifestinput:",
+ "comment": "Manifest Input",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFile",
+ "switch": "OUT:",
+ "comment": "Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "Version",
+ "switch": "VERSION:",
+ "comment": "Version",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SpecifySectionAttributes",
+ "switch": "SECTION:",
+ "comment": "Specify Section Attributes",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MSDOSStubFileName",
+ "switch": "STUB:",
+ "comment": "MS-DOS Stub File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ModuleDefinitionFile",
+ "switch": "DEF:",
+ "comment": "Module Definition File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ManifestFile",
+ "switch": "ManifestFile:",
+ "comment": "Manifest File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDatabaseFile",
+ "switch": "PDB:",
+ "comment": "Generate Program Database File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StripPrivateSymbols",
+ "switch": "PDBSTRIPPED:",
+ "comment": "Strip Private Symbols",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MapFileName",
+ "switch": "MAP:",
+ "comment": "Map File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "HeapReserveSize",
+ "switch": "HEAP:",
+ "comment": "Heap Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "HeapCommitSize",
+ "switch": "HEAP",
+ "comment": "Heap Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "StackReserveSize",
+ "switch": "STACK:",
+ "comment": "Stack Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StackCommitSize",
+ "switch": "STACK",
+ "comment": "Stack Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "FunctionOrder",
+ "switch": "ORDER:@",
+ "comment": "Function Order",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProfileGuidedDatabase",
+ "switch": "PGD:",
+ "comment": "Profile Guided Database",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MidlCommandFile",
+ "switch": "MIDL:@",
+ "comment": "MIDL Commands",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergedIDLBaseFileName",
+ "switch": "IDLOUT:",
+ "comment": "Merged IDL Base File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryFile",
+ "switch": "TLBOUT:",
+ "comment": "Type Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataFile",
+ "switch": "WINMDFILE:",
+ "comment": "Windows Metadata File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataLinkKeyFile",
+ "switch": "WINMDKEYFILE:",
+ "comment": "Windows Metadata Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataKeyContainer",
+ "switch": "WINMDKEYCONTAINER:",
+ "comment": "Windows Metadata Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "EntryPointSymbol",
+ "switch": "ENTRY:",
+ "comment": "Entry Point",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "BASE:",
+ "comment": "Base Address",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ImportLibrary",
+ "switch": "IMPLIB:",
+ "comment": "Import Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergeSections",
+ "switch": "MERGE:",
+ "comment": "Merge Sections",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LinkKeyFile",
+ "switch": "KEYFILE:",
+ "comment": "Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "KeyContainer",
+ "switch": "KEYCONTAINER:",
+ "comment": "Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryResourceID",
+ "switch": "TLBID:",
+ "comment": "TypeLib Resource ID",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SectionAlignment",
+ "switch": "ALIGN:",
+ "comment": "SectionAlignment",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v12_MASM.json b/Templates/MSBuild/FlagTables/v12_MASM.json
new file mode 100644
index 000000000..4634306b1
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v12_MASM.json
@@ -0,0 +1,295 @@
+[
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cp",
+ "comment": "Preserves Identifier Case (/Cp)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cu",
+ "comment": "Maps all identifiers to upper case. (/Cu)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cx",
+ "comment": "Preserves case in public and extern symbols. (/Cx)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W0",
+ "comment": "Warning Level 0 (/W0)",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W1",
+ "comment": "Warning Level 1 (/W1)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W2",
+ "comment": "Warning Level 2 (/W2)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W3",
+ "comment": "Warning Level 3 (/W3)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp1",
+ "comment": "One Byte Boundary (/Zp1)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp2",
+ "comment": "Two Byte Boundary (/Zp2)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp4",
+ "comment": "Four Byte Boundary (/Zp4)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp8",
+ "comment": "Eight Byte Boundary (/Zp8)",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp16",
+ "comment": "Sixteen Byte Boundary (/Zp16)",
+ "value": "5",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gd",
+ "comment": "Use C-style Calling Convention (/Gd)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gz",
+ "comment": "Use stdcall Calling Convention (/Gz)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gc",
+ "comment": "Use Pascal Calling Convention (/Gc)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:prompt",
+ "comment": "Prompt to send report immediately (/errorReport:prompt)",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:queue",
+ "comment": "Prompt to send report at the next logon (/errorReport:queue)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:send",
+ "comment": "Automatically send report (/errorReport:send)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:none",
+ "comment": "Do not send report (/errorReport:none)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "NoLogo",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GeneratePreprocessedSourceListing",
+ "switch": "EP",
+ "comment": "Generate Preprocessed Source Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ListAllAvailableInformation",
+ "switch": "Sa",
+ "comment": "List All Available Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseSafeExceptionHandlers",
+ "switch": "safeseh",
+ "comment": "Use Safe Exception Handlers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AddFirstPassListing",
+ "switch": "Sf",
+ "comment": "Add First Pass Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableAssemblyGeneratedCodeListing",
+ "switch": "Sg",
+ "comment": "Enable Assembly Generated Code Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DisableSymbolTable",
+ "switch": "Sn",
+ "comment": "Disable Symbol Table",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableFalseConditionalsInListing",
+ "switch": "Sx",
+ "comment": "Enable False Conditionals In Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "WX",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MakeAllSymbolsPublic",
+ "switch": "Zf",
+ "comment": "Make All Symbols Public",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "Zi",
+ "comment": "Generate Debug Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableMASM51Compatibility",
+ "switch": "Zm",
+ "comment": "Enable MASM 5.1 Compatibility",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PerformSyntaxCheckOnly",
+ "switch": "Zs",
+ "comment": "Perform Syntax Check Only",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IncludePaths",
+ "switch": "I",
+ "comment": "Include Paths",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "BrowseFile",
+ "switch": "FR",
+ "comment": "Generate Browse Information File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ObjectFileName",
+ "switch": "Fo",
+ "comment": "Object File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "AssembledCodeListingFile",
+ "switch": "Fl",
+ "comment": "Assembled Code Listing File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v12_RC.json b/Templates/MSBuild/FlagTables/v12_RC.json
new file mode 100644
index 000000000..b8c0127d1
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v12_RC.json
@@ -0,0 +1,69 @@
+[
+ {
+ "name": "IgnoreStandardIncludePath",
+ "switch": "X",
+ "comment": "Ignore Standard Include Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "v",
+ "comment": "Show Progress",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NullTerminateStrings",
+ "switch": "n",
+ "comment": "Null Terminate Strings",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "u",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalIncludeDirectories",
+ "switch": "I",
+ "comment": "Additional Include Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ResourceOutputFileName",
+ "switch": "fo",
+ "comment": "Resource File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v140_CL.json b/Templates/MSBuild/FlagTables/v140_CL.json
new file mode 100644
index 000000000..3dc9f353d
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v140_CL.json
@@ -0,0 +1,1184 @@
+[
+ {
+ "name": "DebugInformationFormat",
+ "switch": "",
+ "comment": "None",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Z7",
+ "comment": "C7 compatible",
+ "value": "OldStyle",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Zi",
+ "comment": "Program Database",
+ "value": "ProgramDatabase",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "ZI",
+ "comment": "Program Database for Edit And Continue",
+ "value": "EditAndContinue",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "",
+ "comment": "No Common Language RunTime Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr",
+ "comment": "Common Language RunTime Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:pure",
+ "comment": "Pure MSIL Common Language RunTime Support",
+ "value": "Pure",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:safe",
+ "comment": "Safe MSIL Common Language RunTime Support",
+ "value": "Safe",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W0",
+ "comment": "Turn Off All Warnings",
+ "value": "TurnOffAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W1",
+ "comment": "Level1",
+ "value": "Level1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W2",
+ "comment": "Level2",
+ "value": "Level2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W3",
+ "comment": "Level3",
+ "value": "Level3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W4",
+ "comment": "Level4",
+ "value": "Level4",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "Wall",
+ "comment": "EnableAllWarnings",
+ "value": "EnableAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "",
+ "comment": "Custom",
+ "value": "Custom",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Od",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O1",
+ "comment": "Minimize Size",
+ "value": "MinSpace",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O2",
+ "comment": "Maximize Speed",
+ "value": "MaxSpeed",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Ox",
+ "comment": "Full Optimization",
+ "value": "Full",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob0",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob1",
+ "comment": "Only __inline",
+ "value": "OnlyExplicitInline",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob2",
+ "comment": "Any Suitable",
+ "value": "AnySuitable",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Os",
+ "comment": "Favor small code",
+ "value": "Size",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Ot",
+ "comment": "Favor fast code",
+ "value": "Speed",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "",
+ "comment": "Neither",
+ "value": "Neither",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHa",
+ "comment": "Yes with SEH Exceptions",
+ "value": "Async",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHsc",
+ "comment": "Yes",
+ "value": "Sync",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHs",
+ "comment": "Yes with Extern C functions",
+ "value": "SyncCThrow",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCs",
+ "comment": "Stack Frames",
+ "value": "StackFrameRuntimeCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCu",
+ "comment": "Uninitialized variables",
+ "value": "UninitializedLocalUsageCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTC1",
+ "comment": "Both (/RTC1, equiv. to /RTCsu)",
+ "value": "EnableFastChecks",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MT",
+ "comment": "Multi-threaded",
+ "value": "MultiThreaded",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MTd",
+ "comment": "Multi-threaded Debug",
+ "value": "MultiThreadedDebug",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MD",
+ "comment": "Multi-threaded DLL",
+ "value": "MultiThreadedDLL",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MDd",
+ "comment": "Multi-threaded Debug DLL",
+ "value": "MultiThreadedDebugDLL",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp1",
+ "comment": "1 Byte",
+ "value": "1Byte",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp2",
+ "comment": "2 Bytes",
+ "value": "2Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp4",
+ "comment": "4 Byte",
+ "value": "4Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp8",
+ "comment": "8 Bytes",
+ "value": "8Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp16",
+ "comment": "16 Bytes",
+ "value": "16Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS-",
+ "comment": "Disable Security Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS",
+ "comment": "Enable Security Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ControlFlowGuard",
+ "switch": "guard:cf",
+ "comment": "Yes",
+ "value": "Guard",
+ "flags": []
+ },
+ {
+ "name": "ControlFlowGuard",
+ "switch": "",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE",
+ "comment": "Streaming SIMD Extensions",
+ "value": "StreamingSIMDExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE2",
+ "comment": "Streaming SIMD Extensions 2",
+ "value": "StreamingSIMDExtensions2",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:AVX",
+ "comment": "Advanced Vector Extensions",
+ "value": "AdvancedVectorExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:AVX2",
+ "comment": "Advanced Vector Extensions 2",
+ "value": "AdvancedVectorExtensions2",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:IA32",
+ "comment": "No Enhanced Instructions",
+ "value": "NoExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:precise",
+ "comment": "Precise",
+ "value": "Precise",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:strict",
+ "comment": "Strict",
+ "value": "Strict",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:fast",
+ "comment": "Fast",
+ "value": "Fast",
+ "flags": []
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yc",
+ "comment": "Create",
+ "value": "Create",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yu",
+ "comment": "Use",
+ "value": "Use",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Y-",
+ "comment": "Not Using Precompiled Headers",
+ "value": "NotUsing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "",
+ "comment": "No Listing",
+ "value": "NoListing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FA",
+ "comment": "Assembly-Only Listing",
+ "value": "AssemblyCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAc",
+ "comment": "Assembly With Machine Code",
+ "value": "AssemblyAndMachineCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAs",
+ "comment": "Assembly With Source Code",
+ "value": "AssemblyAndSourceCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAcs",
+ "comment": "Assembly, Machine Code and Source",
+ "value": "All",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gd",
+ "comment": "__cdecl",
+ "value": "Cdecl",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gr",
+ "comment": "__fastcall",
+ "value": "FastCall",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gz",
+ "comment": "__stdcall",
+ "value": "StdCall",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gv",
+ "comment": "__vectorcall",
+ "value": "VectorCall",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TC",
+ "comment": "Compile as C Code",
+ "value": "CompileAsC",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TP",
+ "comment": "Compile as C++ Code",
+ "value": "CompileAsCpp",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:none",
+ "comment": "Do Not Send Report",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "Prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:queue",
+ "comment": "Queue For Next Login",
+ "value": "Queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:send",
+ "comment": "Send Automatically",
+ "value": "Send",
+ "flags": []
+ },
+ {
+ "name": "CompileAsWinRT",
+ "switch": "ZW",
+ "comment": "Consume Windows Runtime Extension",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WinRTNoStdLib",
+ "switch": "ZW:nostdlib",
+ "comment": "No Standard WinRT Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX-",
+ "comment": "Treat Warnings As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SDLCheck",
+ "switch": "sdl-",
+ "comment": "SDL checks",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "SDLCheck",
+ "switch": "sdl",
+ "comment": "SDL checks",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MultiProcessorCompilation",
+ "switch": "MP",
+ "comment": "Multi-processor Compilation",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "IntrinsicFunctions",
+ "switch": "Oi",
+ "comment": "Enable Intrinsic Functions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy-",
+ "comment": "Omit Frame Pointers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy",
+ "comment": "Omit Frame Pointers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableFiberSafeOptimizations",
+ "switch": "GT",
+ "comment": "Enable Fiber-Safe Optimizations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WholeProgramOptimization",
+ "switch": "GL",
+ "comment": "Whole Program Optimization",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UndefineAllPreprocessorDefinitions",
+ "switch": "u",
+ "comment": "Undefine All Preprocessor Definitions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreStandardIncludePath",
+ "switch": "X",
+ "comment": "Ignore Standard Include Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessToFile",
+ "switch": "P",
+ "comment": "Preprocess to a File",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessSuppressLineNumbers",
+ "switch": "EP",
+ "comment": "Preprocess Suppress Line Numbers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessKeepComments",
+ "switch": "C",
+ "comment": "Keep Comments",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF-",
+ "comment": "Enable String Pooling",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF",
+ "comment": "Enable String Pooling",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm-",
+ "comment": "Enable Minimal Rebuild",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm",
+ "comment": "Enable Minimal Rebuild",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SmallerTypeCheck",
+ "switch": "RTCc",
+ "comment": "Smaller Type Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy-",
+ "comment": "Enable Function-Level Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy",
+ "comment": "Enable Function-Level Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableParallelCodeGeneration",
+ "switch": "Qpar-",
+ "comment": "Enable Parallel Code Generation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableParallelCodeGeneration",
+ "switch": "Qpar",
+ "comment": "Enable Parallel Code Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except-",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CreateHotpatchableImage",
+ "switch": "hotpatch",
+ "comment": "Create Hotpatchable Image",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DisableLanguageExtensions",
+ "switch": "Za",
+ "comment": "Disable Language Extensions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t-",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope-",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RemoveUnreferencedCodeData",
+ "switch": "Zc:inline-",
+ "comment": "Remove unreferenced code and data",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RemoveUnreferencedCodeData",
+ "switch": "Zc:inline",
+ "comment": "Remove unreferenced code and data",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnforceTypeConversionRules",
+ "switch": "Zc:rvalueCast-",
+ "comment": "Enforce type conversion rules",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnforceTypeConversionRules",
+ "switch": "Zc:rvalueCast",
+ "comment": "Enforce type conversion rules",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR-",
+ "comment": "Enable Run-Time Type Information",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR",
+ "comment": "Enable Run-Time Type Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp-",
+ "comment": "Open MP Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp",
+ "comment": "Open MP Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ExpandAttributedSource",
+ "switch": "Fx",
+ "comment": "Expand Attributed Source",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseUnicodeForAssemblerListing",
+ "switch": "FAu",
+ "comment": "Use Unicode For Assembler Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateXMLDocumentationFiles",
+ "switch": "doc",
+ "comment": "Generate XML Documentation Files",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "BrowseInformation",
+ "switch": "FR",
+ "comment": "Enable Browse Information",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "ShowIncludes",
+ "switch": "showIncludes",
+ "comment": "Show Includes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze-",
+ "comment": "Enable Code Analysis",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze",
+ "comment": "Enable Code Analysis",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseFullPaths",
+ "switch": "FC",
+ "comment": "Use Full Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitDefaultLibName",
+ "switch": "Zl",
+ "comment": "Omit Default Library Name",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalIncludeDirectories",
+ "switch": "I",
+ "comment": "Additional Include Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalUsingDirectories",
+ "switch": "AI",
+ "comment": "Additional #using Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "U",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DisableSpecificWarnings",
+ "switch": "wd",
+ "comment": "Disable Specific Warnings",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedIncludeFiles",
+ "switch": "FI",
+ "comment": "Forced Include File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedUsingFiles",
+ "switch": "FU",
+ "comment": "Forced #using File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PREfastLog",
+ "switch": "analyze:log",
+ "comment": "Code Analysis Log",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ },
+ {
+ "name": "PREfastAdditionalPlugins",
+ "switch": "analyze:plugin",
+ "comment": "Additional Code Analysis Native plugins",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "TreatSpecificWarningsAsErrors",
+ "switch": "we",
+ "comment": "Treat Specific Warnings As Errors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "WarningVersion",
+ "switch": "Wv:",
+ "comment": "Warning Version",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "PreprocessOutputPath",
+ "switch": "Fi",
+ "comment": "Preprocess Output Path",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yu",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yc",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderOutputFile",
+ "switch": "Fp",
+ "comment": "Precompiled Header Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "AssemblerListingLocation",
+ "switch": "Fa",
+ "comment": "ASM List Location",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ObjectFileName",
+ "switch": "Fo",
+ "comment": "Object File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDataBaseFileName",
+ "switch": "Fd",
+ "comment": "Program Database File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "XMLDocumentationFileName",
+ "switch": "doc",
+ "comment": "XML Documentation File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "BrowseInformationFile",
+ "switch": "FR",
+ "comment": "Browse Information File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ProcessorNumber",
+ "switch": "MP",
+ "comment": "Number of processors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=c++98",
+ "comment": "C++03",
+ "value": "c++98",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=c++11",
+ "comment": "C++11",
+ "value": "c++11",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=c++1y",
+ "comment": "C++14",
+ "value": "c++1y",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=c++14",
+ "comment": "C++14",
+ "value": "c++1y",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=gnu++98",
+ "comment": "C++03 (GNU Dialect)",
+ "value": "gnu++98",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=gnu++11",
+ "comment": "C++11 (GNU Dialect)",
+ "value": "gnu++11",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=gnu++1y",
+ "comment": "C++14 (GNU Dialect)",
+ "value": "gnu++1y",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=gnu++14",
+ "comment": "C++14 (GNU Dialect)",
+ "value": "gnu++1y",
+ "flags": []
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v140_CSharp.json b/Templates/MSBuild/FlagTables/v140_CSharp.json
new file mode 100644
index 000000000..5989aea1e
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v140_CSharp.json
@@ -0,0 +1,574 @@
+[
+ {
+ "name": "ProjectName",
+ "switch": "out:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:exe",
+ "comment": "",
+ "value": "Exe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:winexe",
+ "comment": "",
+ "value": "Winexe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:library",
+ "comment": "",
+ "value": "Library",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:module",
+ "comment": "",
+ "value": "Module",
+ "flags": []
+ },
+ {
+ "name": "DocumentationFile",
+ "switch": "doc",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x86",
+ "comment": "",
+ "value": "x86",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:Itanium",
+ "comment": "",
+ "value": "Itanium",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x64",
+ "comment": "",
+ "value": "x64",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:arm",
+ "comment": "",
+ "value": "arm",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu32bitpreferred",
+ "comment": "",
+ "value": "anycpu32bitpreferred",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu",
+ "comment": "",
+ "value": "anycpu",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "mit alias",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "dateiliste",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AddModules",
+ "switch": "addmodule:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "Win32Resource",
+ "switch": "win32res:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationIcon",
+ "switch": "win32icon:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationManifest",
+ "switch": "win32manifest:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "NoWin32Manifest",
+ "switch": "nowin32manifest",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineDebug",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": [
+ "Continue"
+ ]
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:none",
+ "comment": "",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:full",
+ "comment": "",
+ "value": "full",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:pdbonly",
+ "comment": "",
+ "value": "pdbonly",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:0",
+ "comment": "",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:1",
+ "comment": "",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:2",
+ "comment": "",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "NoWarn",
+ "switch": "nowarn:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "CommaAppendable"
+ ]
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineConstants",
+ "switch": "define:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable",
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-1",
+ "comment": "",
+ "value": "ISO-1",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-2",
+ "comment": "",
+ "value": "ISO-2",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:5",
+ "comment": "",
+ "value": "5",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:6",
+ "comment": "",
+ "value": "6",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:default",
+ "comment": "",
+ "value": "default",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyOriginatorKeyFile",
+ "switch": "keyfile",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "KeyContainerName",
+ "switch": "keycontainer",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoLogo",
+ "switch": "nologo",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoConfig",
+ "switch": "noconfig",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "baseaddress:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "CodePage",
+ "switch": "codepage",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "Utf8Output",
+ "switch": "utf8output",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "MainEntryPoint",
+ "switch": "main:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "GenerateFullPaths",
+ "switch": "fullpaths",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FileAlignment",
+ "switch": "filealign",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "PdbFile",
+ "switch": "pdb:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SubsystemVersion",
+ "switch": "subsystemversion",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibPaths",
+ "switch": "lib:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:none",
+ "comment": "Do Not Send Report",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:queue",
+ "comment": "Queue For Next Login",
+ "value": "queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:send",
+ "comment": "Send Automatically",
+ "value": "send",
+ "flags": []
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v140_Link.json b/Templates/MSBuild/FlagTables/v140_Link.json
new file mode 100644
index 000000000..3fb072c50
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v140_Link.json
@@ -0,0 +1,1316 @@
+[
+ {
+ "name": "ShowProgress",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE",
+ "comment": "Display all progress messages",
+ "value": "LinkVerbose",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:Lib",
+ "comment": "For Libraries Searched",
+ "value": "LinkVerboseLib",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:ICF",
+ "comment": "About COMDAT folding during optimized linking",
+ "value": "LinkVerboseICF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:REF",
+ "comment": "About data removed during optimized linking",
+ "value": "LinkVerboseREF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:SAFESEH",
+ "comment": "About Modules incompatible with SEH",
+ "value": "LinkVerboseSAFESEH",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:CLR",
+ "comment": "About linker activity related to managed code",
+ "value": "LinkVerboseCLR",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:MULTIPLE",
+ "comment": "Multiply Defined Symbol Only",
+ "value": "MultiplyDefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:UNRESOLVED",
+ "comment": "Undefined Symbol Only",
+ "value": "UndefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:5",
+ "comment": "X86 Image Only",
+ "value": "X86Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:6",
+ "comment": "X64 Image Only",
+ "value": "X64Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:16",
+ "comment": "Itanium Image Only",
+ "value": "ItaniumImage",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='asInvoker'",
+ "comment": "asInvoker",
+ "value": "AsInvoker",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='highestAvailable'",
+ "comment": "highestAvailable",
+ "value": "HighestAvailable",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='requireAdministrator'",
+ "comment": "requireAdministrator",
+ "value": "RequireAdministrator",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG",
+ "comment": "Optimize for debugging",
+ "value": "true",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG:FASTLINK",
+ "comment": "Optimize for faster linking",
+ "value": "DebugFastLink",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG:FULL",
+ "comment": "Optimize for debugging",
+ "value": "true",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG:NONE",
+ "comment": "Produces no debugging information",
+ "value": "false",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "SubSystem",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:CONSOLE",
+ "comment": "Console",
+ "value": "Console",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWS",
+ "comment": "Windows",
+ "value": "Windows",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:NATIVE",
+ "comment": "Native",
+ "value": "Native",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_APPLICATION",
+ "comment": "EFI Application",
+ "value": "EFI Application",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+ "comment": "EFI Boot Service Driver",
+ "value": "EFI Boot Service Driver",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_ROM",
+ "comment": "EFI ROM",
+ "value": "EFI ROM",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+ "comment": "EFI Runtime",
+ "value": "EFI Runtime",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:POSIX",
+ "comment": "POSIX",
+ "value": "POSIX",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "Driver",
+ "comment": "Driver",
+ "value": "Driver",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:UPONLY",
+ "comment": "UP Only",
+ "value": "UpOnly",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:WDM",
+ "comment": "WDM",
+ "value": "WDM",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:incremental",
+ "comment": "Use Fast Link Time Code Generation",
+ "value": "UseFastLinkTimeCodeGeneration",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG",
+ "comment": "Use Link Time Code Generation",
+ "value": "UseLinkTimeCodeGeneration",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGInstrument",
+ "comment": "Profile Guided Optimization - Instrument",
+ "value": "PGInstrument",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGOptimize",
+ "comment": "Profile Guided Optimization - Optimization",
+ "value": "PGOptimization",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGUpdate",
+ "comment": "Profile Guided Optimization - Update",
+ "value": "PGUpdate",
+ "flags": []
+ },
+ {
+ "name": "GenerateWindowsMetadata",
+ "switch": "WINMD",
+ "comment": "Yes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateWindowsMetadata",
+ "switch": "WINMD:NO",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA1",
+ "comment": "SHA1",
+ "value": "SHA1",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA256",
+ "comment": "SHA256",
+ "value": "SHA256",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA384",
+ "comment": "SHA384",
+ "value": "SHA384",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA512",
+ "comment": "SHA512",
+ "value": "SHA512",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM",
+ "comment": "MachineARM",
+ "value": "MachineARM",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:EBC",
+ "comment": "MachineEBC",
+ "value": "MachineEBC",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:IA64",
+ "comment": "MachineIA64",
+ "value": "MachineIA64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS",
+ "comment": "MachineMIPS",
+ "value": "MachineMIPS",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS16",
+ "comment": "MachineMIPS16",
+ "value": "MachineMIPS16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU",
+ "comment": "MachineMIPSFPU",
+ "value": "MachineMIPSFPU",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU16",
+ "comment": "MachineMIPSFPU16",
+ "value": "MachineMIPSFPU16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:SH4",
+ "comment": "MachineSH4",
+ "value": "MachineSH4",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:THUMB",
+ "comment": "MachineTHUMB",
+ "value": "MachineTHUMB",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X64",
+ "comment": "MachineX64",
+ "value": "MachineX64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X86",
+ "comment": "MachineX86",
+ "value": "MachineX86",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:MTA",
+ "comment": "MTA threading attribute",
+ "value": "MTAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:STA",
+ "comment": "STA threading attribute",
+ "value": "STAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:NONE",
+ "comment": "Default threading attribute",
+ "value": "DefaultThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:IJW",
+ "comment": "Force IJW image",
+ "value": "ForceIJWImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:PURE",
+ "comment": "Force Pure IL Image",
+ "value": "ForcePureILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:SAFE",
+ "comment": "Force Safe IL Image",
+ "value": "ForceSafeILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "",
+ "comment": "Default image type",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA1",
+ "comment": "SHA1",
+ "value": "SHA1",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA256",
+ "comment": "SHA256",
+ "value": "SHA256",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA384",
+ "comment": "SHA384",
+ "value": "SHA384",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA512",
+ "comment": "SHA512",
+ "value": "SHA512",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:PROMPT",
+ "comment": "PromptImmediately",
+ "value": "PromptImmediately",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:QUEUE",
+ "comment": "Queue For Next Login",
+ "value": "QueueForNextLogin",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:SEND",
+ "comment": "Send Error Report",
+ "value": "SendErrorReport",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:NONE",
+ "comment": "No Error Report",
+ "value": "NoErrorReport",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:NO",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:SYSTEMDLL",
+ "comment": "System Dlls Only",
+ "value": "SystemDlls",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL:NO",
+ "comment": "Enable Incremental Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL",
+ "comment": "Enable Incremental Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "NOLOGO",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:NOSTATUS",
+ "comment": "Link Status",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:STATUS",
+ "comment": "Link Status",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND:NO",
+ "comment": "Prevent Dll Binding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND",
+ "comment": "Prevent Dll Binding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX:NO",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreAllDefaultLibraries",
+ "switch": "NODEFAULTLIB",
+ "comment": "Ignore All Default Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST:NO",
+ "comment": "Generate Manifest",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST",
+ "comment": "Generate Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "ALLOWISOLATION:NO",
+ "comment": "Allow Isolation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "",
+ "comment": "Allow Isolation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableUAC",
+ "switch": "MANIFESTUAC:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "SpaceAppendable"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='true'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ManifestEmbed",
+ "switch": "manifest:embed",
+ "comment": "Embed Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateMapFile",
+ "switch": "MAP",
+ "comment": "Generate Map File",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "MapExports",
+ "switch": "MAPINFO:EXPORTS",
+ "comment": "Map Exports",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG:DISABLE",
+ "comment": "Debuggable Assembly",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG",
+ "comment": "Debuggable Assembly",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE:NO",
+ "comment": "Enable Large Addresses",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE",
+ "comment": "Enable Large Addresses",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE:NO",
+ "comment": "Terminal Server",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE",
+ "comment": "Terminal Server",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromCD",
+ "switch": "SWAPRUN:CD",
+ "comment": "Swap Run From CD",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromNET",
+ "switch": "SWAPRUN:NET",
+ "comment": "Swap Run From Network",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:NOREF",
+ "comment": "References",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:REF",
+ "comment": "References",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:NOICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:ICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreEmbeddedIDL",
+ "switch": "IGNOREIDL",
+ "comment": "Ignore Embedded IDL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AppContainer",
+ "switch": "APPCONTAINER",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataLinkDelaySign",
+ "switch": "WINMDDELAYSIGN:NO",
+ "comment": "Windows Metadata Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataLinkDelaySign",
+ "switch": "WINMDDELAYSIGN",
+ "comment": "Windows Metadata Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoEntryPoint",
+ "switch": "NOENTRY",
+ "comment": "No Entry Point",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SetChecksum",
+ "switch": "RELEASE",
+ "comment": "Set Checksum",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE:NO",
+ "comment": "Randomized Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE",
+ "comment": "Randomized Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED:NO",
+ "comment": "Fixed Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED",
+ "comment": "Fixed Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT:NO",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TurnOffAssemblyGeneration",
+ "switch": "NOASSEMBLY",
+ "comment": "Turn Off Assembly Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportUnloadOfDelayLoadedDLL",
+ "switch": "DELAY:UNLOAD",
+ "comment": "Unload delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportNobindOfDelayLoadedDLL",
+ "switch": "DELAY:NOBIND",
+ "comment": "Nobind delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Profile",
+ "switch": "PROFILE",
+ "comment": "Profile",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN:NO",
+ "comment": "Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN",
+ "comment": "Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK:NO",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DetectOneDefinitionRule",
+ "switch": "ODR",
+ "comment": "Detect One Definition Rule violations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH:NO",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDLL",
+ "switch": "DLL",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibraryDirectories",
+ "switch": "LIBPATH:",
+ "comment": "Additional Library Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "Natvis",
+ "switch": "NATVIS:",
+ "comment": "Natvis files",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IgnoreSpecificDefaultLibraries",
+ "switch": "NODEFAULTLIB:",
+ "comment": "Ignore Specific Default Libraries",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AddModuleNamesToAssembly",
+ "switch": "ASSEMBLYMODULE:",
+ "comment": "Add Module to Assembly",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "EmbedManagedResourceFile",
+ "switch": "ASSEMBLYRESOURCE:",
+ "comment": "Embed Managed Resource File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForceSymbolReferences",
+ "switch": "INCLUDE:",
+ "comment": "Force Symbol References",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DelayLoadDLLs",
+ "switch": "DELAYLOAD:",
+ "comment": "Delay Loaded Dlls",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AssemblyLinkResource",
+ "switch": "ASSEMBLYLINKRESOURCE:",
+ "comment": "Assembly Link Resource",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalManifestDependencies",
+ "switch": "MANIFESTDEPENDENCY:",
+ "comment": "Additional Manifest Dependencies",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ManifestInput",
+ "switch": "manifestinput:",
+ "comment": "Manifest Input",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFile",
+ "switch": "OUT:",
+ "comment": "Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "Version",
+ "switch": "VERSION:",
+ "comment": "Version",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SpecifySectionAttributes",
+ "switch": "SECTION:",
+ "comment": "Specify Section Attributes",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MSDOSStubFileName",
+ "switch": "STUB:",
+ "comment": "MS-DOS Stub File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ModuleDefinitionFile",
+ "switch": "DEF:",
+ "comment": "Module Definition File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ManifestFile",
+ "switch": "ManifestFile:",
+ "comment": "Manifest File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDatabaseFile",
+ "switch": "PDB:",
+ "comment": "Generate Program Database File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StripPrivateSymbols",
+ "switch": "PDBSTRIPPED:",
+ "comment": "Strip Private Symbols",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MapFileName",
+ "switch": "MAP:",
+ "comment": "Map File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "HeapReserveSize",
+ "switch": "HEAP:",
+ "comment": "Heap Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "HeapCommitSize",
+ "switch": "HEAP",
+ "comment": "Heap Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "StackReserveSize",
+ "switch": "STACK:",
+ "comment": "Stack Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StackCommitSize",
+ "switch": "STACK",
+ "comment": "Stack Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "FunctionOrder",
+ "switch": "ORDER:@",
+ "comment": "Function Order",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProfileGuidedDatabase",
+ "switch": "PGD:",
+ "comment": "Profile Guided Database",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MidlCommandFile",
+ "switch": "MIDL:@",
+ "comment": "MIDL Commands",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergedIDLBaseFileName",
+ "switch": "IDLOUT:",
+ "comment": "Merged IDL Base File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryFile",
+ "switch": "TLBOUT:",
+ "comment": "Type Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataFile",
+ "switch": "WINMDFILE:",
+ "comment": "Windows Metadata File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataLinkKeyFile",
+ "switch": "WINMDKEYFILE:",
+ "comment": "Windows Metadata Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataKeyContainer",
+ "switch": "WINMDKEYCONTAINER:",
+ "comment": "Windows Metadata Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "EntryPointSymbol",
+ "switch": "ENTRY:",
+ "comment": "Entry Point",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "BASE:",
+ "comment": "Base Address",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ImportLibrary",
+ "switch": "IMPLIB:",
+ "comment": "Import Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergeSections",
+ "switch": "MERGE:",
+ "comment": "Merge Sections",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LinkKeyFile",
+ "switch": "KEYFILE:",
+ "comment": "Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "KeyContainer",
+ "switch": "KEYCONTAINER:",
+ "comment": "Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryResourceID",
+ "switch": "TLBID:",
+ "comment": "TypeLib Resource ID",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SectionAlignment",
+ "switch": "ALIGN:",
+ "comment": "SectionAlignment",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v141_CL.json b/Templates/MSBuild/FlagTables/v141_CL.json
new file mode 100644
index 000000000..01fafe48d
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v141_CL.json
@@ -0,0 +1,1268 @@
+[
+ {
+ "name": "DebugInformationFormat",
+ "switch": "",
+ "comment": "None",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Z7",
+ "comment": "C7 compatible",
+ "value": "OldStyle",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Zi",
+ "comment": "Program Database",
+ "value": "ProgramDatabase",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "ZI",
+ "comment": "Program Database for Edit And Continue",
+ "value": "EditAndContinue",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "",
+ "comment": "No Common Language RunTime Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr",
+ "comment": "Common Language RunTime Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:pure",
+ "comment": "Pure MSIL Common Language RunTime Support",
+ "value": "Pure",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:safe",
+ "comment": "Safe MSIL Common Language RunTime Support",
+ "value": "Safe",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W0",
+ "comment": "Turn Off All Warnings",
+ "value": "TurnOffAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W1",
+ "comment": "Level1",
+ "value": "Level1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W2",
+ "comment": "Level2",
+ "value": "Level2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W3",
+ "comment": "Level3",
+ "value": "Level3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W4",
+ "comment": "Level4",
+ "value": "Level4",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "Wall",
+ "comment": "EnableAllWarnings",
+ "value": "EnableAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "DiagnosticsFormat",
+ "switch": "diagnostics:caret",
+ "comment": "Caret",
+ "value": "Caret",
+ "flags": []
+ },
+ {
+ "name": "DiagnosticsFormat",
+ "switch": "diagnostics:column",
+ "comment": "Column Info",
+ "value": "Column",
+ "flags": []
+ },
+ {
+ "name": "DiagnosticsFormat",
+ "switch": "diagnostics:classic",
+ "comment": "Classic",
+ "value": "Classic",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "",
+ "comment": "Custom",
+ "value": "Custom",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Od",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O1",
+ "comment": "Maximum Optimization (Favor Size)",
+ "value": "MinSpace",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O2",
+ "comment": "Maximum Optimization (Favor Speed)",
+ "value": "MaxSpeed",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Ox",
+ "comment": "Optimizations (Favor Speed)",
+ "value": "Full",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob0",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob1",
+ "comment": "Only __inline",
+ "value": "OnlyExplicitInline",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob2",
+ "comment": "Any Suitable",
+ "value": "AnySuitable",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Os",
+ "comment": "Favor small code",
+ "value": "Size",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Ot",
+ "comment": "Favor fast code",
+ "value": "Speed",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "",
+ "comment": "Neither",
+ "value": "Neither",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHa",
+ "comment": "Yes with SEH Exceptions",
+ "value": "Async",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHsc",
+ "comment": "Yes",
+ "value": "Sync",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHs",
+ "comment": "Yes with Extern C functions",
+ "value": "SyncCThrow",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCs",
+ "comment": "Stack Frames",
+ "value": "StackFrameRuntimeCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCu",
+ "comment": "Uninitialized variables",
+ "value": "UninitializedLocalUsageCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTC1",
+ "comment": "Both (/RTC1, equiv. to /RTCsu)",
+ "value": "EnableFastChecks",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MT",
+ "comment": "Multi-threaded",
+ "value": "MultiThreaded",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MTd",
+ "comment": "Multi-threaded Debug",
+ "value": "MultiThreadedDebug",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MD",
+ "comment": "Multi-threaded DLL",
+ "value": "MultiThreadedDLL",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MDd",
+ "comment": "Multi-threaded Debug DLL",
+ "value": "MultiThreadedDebugDLL",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp1",
+ "comment": "1 Byte",
+ "value": "1Byte",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp2",
+ "comment": "2 Bytes",
+ "value": "2Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp4",
+ "comment": "4 Byte",
+ "value": "4Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp8",
+ "comment": "8 Bytes",
+ "value": "8Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp16",
+ "comment": "16 Bytes",
+ "value": "16Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS-",
+ "comment": "Disable Security Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS",
+ "comment": "Enable Security Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ControlFlowGuard",
+ "switch": "guard:cf",
+ "comment": "Yes",
+ "value": "Guard",
+ "flags": []
+ },
+ {
+ "name": "ControlFlowGuard",
+ "switch": "",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE",
+ "comment": "Streaming SIMD Extensions",
+ "value": "StreamingSIMDExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE2",
+ "comment": "Streaming SIMD Extensions 2",
+ "value": "StreamingSIMDExtensions2",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:AVX",
+ "comment": "Advanced Vector Extensions",
+ "value": "AdvancedVectorExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:AVX2",
+ "comment": "Advanced Vector Extensions 2",
+ "value": "AdvancedVectorExtensions2",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:IA32",
+ "comment": "No Enhanced Instructions",
+ "value": "NoExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:precise",
+ "comment": "Precise",
+ "value": "Precise",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:strict",
+ "comment": "Strict",
+ "value": "Strict",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:fast",
+ "comment": "Fast",
+ "value": "Fast",
+ "flags": []
+ },
+ {
+ "name": "SpectreMitigation",
+ "switch": "Qspectre",
+ "comment": "Spectre mitigations",
+ "value": "Spectre",
+ "flags": []
+ },
+ {
+ "name": "LanguageStandard",
+ "switch": "std:c++14",
+ "comment": "ISO C++14 Standard",
+ "value": "stdcpp14",
+ "flags": []
+ },
+ {
+ "name": "LanguageStandard",
+ "switch": "std:c++17",
+ "comment": "ISO C++17 Standard",
+ "value": "stdcpp17",
+ "flags": []
+ },
+ {
+ "name": "LanguageStandard",
+ "switch": "std:c++latest",
+ "comment": "ISO C++ Latest Draft Standard",
+ "value": "stdcpplatest",
+ "flags": []
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yc",
+ "comment": "Create",
+ "value": "Create",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yu",
+ "comment": "Use",
+ "value": "Use",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Y-",
+ "comment": "Not Using Precompiled Headers",
+ "value": "NotUsing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "",
+ "comment": "No Listing",
+ "value": "NoListing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FA",
+ "comment": "Assembly-Only Listing",
+ "value": "AssemblyCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAc",
+ "comment": "Assembly With Machine Code",
+ "value": "AssemblyAndMachineCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAs",
+ "comment": "Assembly With Source Code",
+ "value": "AssemblyAndSourceCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAcs",
+ "comment": "Assembly, Machine Code and Source",
+ "value": "All",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gd",
+ "comment": "__cdecl",
+ "value": "Cdecl",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gr",
+ "comment": "__fastcall",
+ "value": "FastCall",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gz",
+ "comment": "__stdcall",
+ "value": "StdCall",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gv",
+ "comment": "__vectorcall",
+ "value": "VectorCall",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TC",
+ "comment": "Compile as C Code",
+ "value": "CompileAsC",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TP",
+ "comment": "Compile as C++ Code",
+ "value": "CompileAsCpp",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:none",
+ "comment": "Do Not Send Report",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "Prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:queue",
+ "comment": "Queue For Next Login",
+ "value": "Queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:send",
+ "comment": "Send Automatically",
+ "value": "Send",
+ "flags": []
+ },
+ {
+ "name": "CompileAsWinRT",
+ "switch": "ZW",
+ "comment": "Consume Windows Runtime Extension",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WinRTNoStdLib",
+ "switch": "ZW:nostdlib",
+ "comment": "No Standard WinRT Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX-",
+ "comment": "Treat Warnings As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SDLCheck",
+ "switch": "sdl-",
+ "comment": "SDL checks",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "SDLCheck",
+ "switch": "sdl",
+ "comment": "SDL checks",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MultiProcessorCompilation",
+ "switch": "MP",
+ "comment": "Multi-processor Compilation",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "IntrinsicFunctions",
+ "switch": "Oi",
+ "comment": "Enable Intrinsic Functions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy-",
+ "comment": "Omit Frame Pointers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy",
+ "comment": "Omit Frame Pointers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableFiberSafeOptimizations",
+ "switch": "GT",
+ "comment": "Enable Fiber-Safe Optimizations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WholeProgramOptimization",
+ "switch": "GL",
+ "comment": "Whole Program Optimization",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UndefineAllPreprocessorDefinitions",
+ "switch": "u",
+ "comment": "Undefine All Preprocessor Definitions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreStandardIncludePath",
+ "switch": "X",
+ "comment": "Ignore Standard Include Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessToFile",
+ "switch": "P",
+ "comment": "Preprocess to a File",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessSuppressLineNumbers",
+ "switch": "EP",
+ "comment": "Preprocess Suppress Line Numbers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessKeepComments",
+ "switch": "C",
+ "comment": "Keep Comments",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF-",
+ "comment": "Enable String Pooling",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF",
+ "comment": "Enable String Pooling",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm-",
+ "comment": "Enable Minimal Rebuild",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm",
+ "comment": "Enable Minimal Rebuild",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SmallerTypeCheck",
+ "switch": "RTCc",
+ "comment": "Smaller Type Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy-",
+ "comment": "Enable Function-Level Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy",
+ "comment": "Enable Function-Level Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableParallelCodeGeneration",
+ "switch": "Qpar-",
+ "comment": "Enable Parallel Code Generation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableParallelCodeGeneration",
+ "switch": "Qpar",
+ "comment": "Enable Parallel Code Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except-",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CreateHotpatchableImage",
+ "switch": "hotpatch",
+ "comment": "Create Hotpatchable Image",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DisableLanguageExtensions",
+ "switch": "Za",
+ "comment": "Disable Language Extensions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ConformanceMode",
+ "switch": "permissive-",
+ "comment": "Conformance mode enabled",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ConformanceMode",
+ "switch": "permissive",
+ "comment": "Conformance mode disabled",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t-",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope-",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RemoveUnreferencedCodeData",
+ "switch": "Zc:inline-",
+ "comment": "Remove unreferenced code and data",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RemoveUnreferencedCodeData",
+ "switch": "Zc:inline",
+ "comment": "Remove unreferenced code and data",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnforceTypeConversionRules",
+ "switch": "Zc:rvalueCast-",
+ "comment": "Enforce type conversion rules",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnforceTypeConversionRules",
+ "switch": "Zc:rvalueCast",
+ "comment": "Enforce type conversion rules",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR-",
+ "comment": "Enable Run-Time Type Information",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR",
+ "comment": "Enable Run-Time Type Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp-",
+ "comment": "Open MP Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp",
+ "comment": "Open MP Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableModules",
+ "switch": "experimental:module",
+ "comment": "Enable C++ Modules (experimental)",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ExpandAttributedSource",
+ "switch": "Fx",
+ "comment": "Expand Attributed Source",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseUnicodeForAssemblerListing",
+ "switch": "FAu",
+ "comment": "Use Unicode For Assembler Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateXMLDocumentationFiles",
+ "switch": "doc",
+ "comment": "Generate XML Documentation Files",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "BrowseInformation",
+ "switch": "FR",
+ "comment": "Enable Browse Information",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "ShowIncludes",
+ "switch": "showIncludes",
+ "comment": "Show Includes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze-",
+ "comment": "Enable Code Analysis",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze",
+ "comment": "Enable Code Analysis",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseFullPaths",
+ "switch": "FC",
+ "comment": "Use Full Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitDefaultLibName",
+ "switch": "Zl",
+ "comment": "Omit Default Library Name",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalIncludeDirectories",
+ "switch": "I",
+ "comment": "Additional Include Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalUsingDirectories",
+ "switch": "AI",
+ "comment": "Additional #using Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "U",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DisableSpecificWarnings",
+ "switch": "wd",
+ "comment": "Disable Specific Warnings",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedIncludeFiles",
+ "switch": "FI",
+ "comment": "Forced Include File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedUsingFiles",
+ "switch": "FU",
+ "comment": "Forced #using File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PREfastLog",
+ "switch": "analyze:log",
+ "comment": "Code Analysis Log",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ },
+ {
+ "name": "PREfastAdditionalPlugins",
+ "switch": "analyze:plugin",
+ "comment": "Additional Code Analysis Native plugins",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "TreatSpecificWarningsAsErrors",
+ "switch": "we",
+ "comment": "Treat Specific Warnings As Errors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "WarningVersion",
+ "switch": "Wv:",
+ "comment": "Warning Version",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "PreprocessOutputPath",
+ "switch": "Fi",
+ "comment": "Preprocess Output Path",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yu",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yc",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderOutputFile",
+ "switch": "Fp",
+ "comment": "Precompiled Header Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "AssemblerListingLocation",
+ "switch": "Fa",
+ "comment": "ASM List Location",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ObjectFileName",
+ "switch": "Fo",
+ "comment": "Object File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDataBaseFileName",
+ "switch": "Fd",
+ "comment": "Program Database File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "XMLDocumentationFileName",
+ "switch": "doc",
+ "comment": "XML Documentation File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "BrowseInformationFile",
+ "switch": "FR",
+ "comment": "Browse Information File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ProcessorNumber",
+ "switch": "MP",
+ "comment": "Number of processors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=c++98",
+ "comment": "C++03",
+ "value": "c++98",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=c++11",
+ "comment": "C++11",
+ "value": "c++11",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=c++1y",
+ "comment": "C++14",
+ "value": "c++1y",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=c++14",
+ "comment": "C++14",
+ "value": "c++1y",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=gnu++98",
+ "comment": "C++03 (GNU Dialect)",
+ "value": "gnu++98",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=gnu++11",
+ "comment": "C++11 (GNU Dialect)",
+ "value": "gnu++11",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=gnu++1y",
+ "comment": "C++14 (GNU Dialect)",
+ "value": "gnu++1y",
+ "flags": []
+ },
+ {
+ "name": "CppLanguageStandard",
+ "switch": "std=gnu++14",
+ "comment": "C++14 (GNU Dialect)",
+ "value": "gnu++1y",
+ "flags": []
+ },
+ {
+ "name": "SupportJustMyCode",
+ "switch": "JMC-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "SupportJustMyCode",
+ "switch": "JMC",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v141_CSharp.json b/Templates/MSBuild/FlagTables/v141_CSharp.json
new file mode 100644
index 000000000..5989aea1e
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v141_CSharp.json
@@ -0,0 +1,574 @@
+[
+ {
+ "name": "ProjectName",
+ "switch": "out:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:exe",
+ "comment": "",
+ "value": "Exe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:winexe",
+ "comment": "",
+ "value": "Winexe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:library",
+ "comment": "",
+ "value": "Library",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:module",
+ "comment": "",
+ "value": "Module",
+ "flags": []
+ },
+ {
+ "name": "DocumentationFile",
+ "switch": "doc",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x86",
+ "comment": "",
+ "value": "x86",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:Itanium",
+ "comment": "",
+ "value": "Itanium",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x64",
+ "comment": "",
+ "value": "x64",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:arm",
+ "comment": "",
+ "value": "arm",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu32bitpreferred",
+ "comment": "",
+ "value": "anycpu32bitpreferred",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu",
+ "comment": "",
+ "value": "anycpu",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "mit alias",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "dateiliste",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AddModules",
+ "switch": "addmodule:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "Win32Resource",
+ "switch": "win32res:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationIcon",
+ "switch": "win32icon:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationManifest",
+ "switch": "win32manifest:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "NoWin32Manifest",
+ "switch": "nowin32manifest",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineDebug",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": [
+ "Continue"
+ ]
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:none",
+ "comment": "",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:full",
+ "comment": "",
+ "value": "full",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:pdbonly",
+ "comment": "",
+ "value": "pdbonly",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:0",
+ "comment": "",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:1",
+ "comment": "",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:2",
+ "comment": "",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "NoWarn",
+ "switch": "nowarn:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "CommaAppendable"
+ ]
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineConstants",
+ "switch": "define:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable",
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-1",
+ "comment": "",
+ "value": "ISO-1",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-2",
+ "comment": "",
+ "value": "ISO-2",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:5",
+ "comment": "",
+ "value": "5",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:6",
+ "comment": "",
+ "value": "6",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:default",
+ "comment": "",
+ "value": "default",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyOriginatorKeyFile",
+ "switch": "keyfile",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "KeyContainerName",
+ "switch": "keycontainer",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoLogo",
+ "switch": "nologo",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoConfig",
+ "switch": "noconfig",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "baseaddress:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "CodePage",
+ "switch": "codepage",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "Utf8Output",
+ "switch": "utf8output",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "MainEntryPoint",
+ "switch": "main:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "GenerateFullPaths",
+ "switch": "fullpaths",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FileAlignment",
+ "switch": "filealign",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "PdbFile",
+ "switch": "pdb:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SubsystemVersion",
+ "switch": "subsystemversion",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibPaths",
+ "switch": "lib:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:none",
+ "comment": "Do Not Send Report",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:queue",
+ "comment": "Queue For Next Login",
+ "value": "queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:send",
+ "comment": "Send Automatically",
+ "value": "send",
+ "flags": []
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v141_Link.json b/Templates/MSBuild/FlagTables/v141_Link.json
new file mode 100644
index 000000000..66ee76fcb
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v141_Link.json
@@ -0,0 +1,1323 @@
+[
+ {
+ "name": "ShowProgress",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE",
+ "comment": "Display all progress messages",
+ "value": "LinkVerbose",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:Lib",
+ "comment": "For Libraries Searched",
+ "value": "LinkVerboseLib",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:ICF",
+ "comment": "About COMDAT folding during optimized linking",
+ "value": "LinkVerboseICF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:REF",
+ "comment": "About data removed during optimized linking",
+ "value": "LinkVerboseREF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:SAFESEH",
+ "comment": "About Modules incompatible with SEH",
+ "value": "LinkVerboseSAFESEH",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:CLR",
+ "comment": "About linker activity related to managed code",
+ "value": "LinkVerboseCLR",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:MULTIPLE",
+ "comment": "Multiply Defined Symbol Only",
+ "value": "MultiplyDefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:UNRESOLVED",
+ "comment": "Undefined Symbol Only",
+ "value": "UndefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:5",
+ "comment": "X86 Image Only",
+ "value": "X86Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:6",
+ "comment": "X64 Image Only",
+ "value": "X64Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:16",
+ "comment": "Itanium Image Only",
+ "value": "ItaniumImage",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='asInvoker'",
+ "comment": "asInvoker",
+ "value": "AsInvoker",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='highestAvailable'",
+ "comment": "highestAvailable",
+ "value": "HighestAvailable",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='requireAdministrator'",
+ "comment": "requireAdministrator",
+ "value": "RequireAdministrator",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG",
+ "comment": "Generate Debug Information",
+ "value": "true",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG:FASTLINK",
+ "comment": "Generate Debug Information optimized for faster links",
+ "value": "DebugFastLink",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG:FULL",
+ "comment": "Generate Debug Information optimized for sharing and publishing",
+ "value": "DebugFull",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG:NONE",
+ "comment": "Produces no debugging information",
+ "value": "false",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "SubSystem",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:CONSOLE",
+ "comment": "Console",
+ "value": "Console",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWS",
+ "comment": "Windows",
+ "value": "Windows",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:NATIVE",
+ "comment": "Native",
+ "value": "Native",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_APPLICATION",
+ "comment": "EFI Application",
+ "value": "EFI Application",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+ "comment": "EFI Boot Service Driver",
+ "value": "EFI Boot Service Driver",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_ROM",
+ "comment": "EFI ROM",
+ "value": "EFI ROM",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+ "comment": "EFI Runtime",
+ "value": "EFI Runtime",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:POSIX",
+ "comment": "POSIX",
+ "value": "POSIX",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "Driver",
+ "comment": "Driver",
+ "value": "Driver",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:UPONLY",
+ "comment": "UP Only",
+ "value": "UpOnly",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:WDM",
+ "comment": "WDM",
+ "value": "WDM",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:incremental",
+ "comment": "Use Fast Link Time Code Generation",
+ "value": "UseFastLinkTimeCodeGeneration",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG",
+ "comment": "Use Link Time Code Generation",
+ "value": "UseLinkTimeCodeGeneration",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGInstrument",
+ "comment": "Profile Guided Optimization - Instrument",
+ "value": "PGInstrument",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGOptimize",
+ "comment": "Profile Guided Optimization - Optimization",
+ "value": "PGOptimization",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGUpdate",
+ "comment": "Profile Guided Optimization - Update",
+ "value": "PGUpdate",
+ "flags": []
+ },
+ {
+ "name": "GenerateWindowsMetadata",
+ "switch": "WINMD",
+ "comment": "Yes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateWindowsMetadata",
+ "switch": "WINMD:NO",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA1",
+ "comment": "SHA1",
+ "value": "SHA1",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA256",
+ "comment": "SHA256",
+ "value": "SHA256",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA384",
+ "comment": "SHA384",
+ "value": "SHA384",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA512",
+ "comment": "SHA512",
+ "value": "SHA512",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM",
+ "comment": "MachineARM",
+ "value": "MachineARM",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM64",
+ "comment": "MachineARM64",
+ "value": "MachineARM64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:EBC",
+ "comment": "MachineEBC",
+ "value": "MachineEBC",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:IA64",
+ "comment": "MachineIA64",
+ "value": "MachineIA64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS",
+ "comment": "MachineMIPS",
+ "value": "MachineMIPS",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS16",
+ "comment": "MachineMIPS16",
+ "value": "MachineMIPS16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU",
+ "comment": "MachineMIPSFPU",
+ "value": "MachineMIPSFPU",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU16",
+ "comment": "MachineMIPSFPU16",
+ "value": "MachineMIPSFPU16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:SH4",
+ "comment": "MachineSH4",
+ "value": "MachineSH4",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:THUMB",
+ "comment": "MachineTHUMB",
+ "value": "MachineTHUMB",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X64",
+ "comment": "MachineX64",
+ "value": "MachineX64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X86",
+ "comment": "MachineX86",
+ "value": "MachineX86",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:MTA",
+ "comment": "MTA threading attribute",
+ "value": "MTAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:STA",
+ "comment": "STA threading attribute",
+ "value": "STAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:NONE",
+ "comment": "Default threading attribute",
+ "value": "DefaultThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:IJW",
+ "comment": "Force IJW image",
+ "value": "ForceIJWImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:PURE",
+ "comment": "Force Pure IL Image",
+ "value": "ForcePureILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:SAFE",
+ "comment": "Force Safe IL Image",
+ "value": "ForceSafeILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "",
+ "comment": "Default image type",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA1",
+ "comment": "SHA1",
+ "value": "SHA1",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA256",
+ "comment": "SHA256",
+ "value": "SHA256",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA384",
+ "comment": "SHA384",
+ "value": "SHA384",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA512",
+ "comment": "SHA512",
+ "value": "SHA512",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:PROMPT",
+ "comment": "PromptImmediately",
+ "value": "PromptImmediately",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:QUEUE",
+ "comment": "Queue For Next Login",
+ "value": "QueueForNextLogin",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:SEND",
+ "comment": "Send Error Report",
+ "value": "SendErrorReport",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:NONE",
+ "comment": "No Error Report",
+ "value": "NoErrorReport",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:NO",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:SYSTEMDLL",
+ "comment": "System Dlls Only",
+ "value": "SystemDlls",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL:NO",
+ "comment": "Enable Incremental Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL",
+ "comment": "Enable Incremental Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "NOLOGO",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:NOSTATUS",
+ "comment": "Link Status",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:STATUS",
+ "comment": "Link Status",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND:NO",
+ "comment": "Prevent Dll Binding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND",
+ "comment": "Prevent Dll Binding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX:NO",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreAllDefaultLibraries",
+ "switch": "NODEFAULTLIB",
+ "comment": "Ignore All Default Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST:NO",
+ "comment": "Generate Manifest",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST",
+ "comment": "Generate Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "ALLOWISOLATION:NO",
+ "comment": "Allow Isolation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "",
+ "comment": "Allow Isolation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableUAC",
+ "switch": "MANIFESTUAC:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "SpaceAppendable"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='true'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ManifestEmbed",
+ "switch": "manifest:embed",
+ "comment": "Embed Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateMapFile",
+ "switch": "MAP",
+ "comment": "Generate Map File",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "MapExports",
+ "switch": "MAPINFO:EXPORTS",
+ "comment": "Map Exports",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG:DISABLE",
+ "comment": "Debuggable Assembly",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG",
+ "comment": "Debuggable Assembly",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE:NO",
+ "comment": "Enable Large Addresses",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE",
+ "comment": "Enable Large Addresses",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE:NO",
+ "comment": "Terminal Server",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE",
+ "comment": "Terminal Server",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromCD",
+ "switch": "SWAPRUN:CD",
+ "comment": "Swap Run From CD",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromNET",
+ "switch": "SWAPRUN:NET",
+ "comment": "Swap Run From Network",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:NOREF",
+ "comment": "References",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:REF",
+ "comment": "References",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:NOICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:ICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreEmbeddedIDL",
+ "switch": "IGNOREIDL",
+ "comment": "Ignore Embedded IDL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AppContainer",
+ "switch": "APPCONTAINER",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataLinkDelaySign",
+ "switch": "WINMDDELAYSIGN:NO",
+ "comment": "Windows Metadata Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataLinkDelaySign",
+ "switch": "WINMDDELAYSIGN",
+ "comment": "Windows Metadata Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoEntryPoint",
+ "switch": "NOENTRY",
+ "comment": "No Entry Point",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SetChecksum",
+ "switch": "RELEASE",
+ "comment": "Set Checksum",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE:NO",
+ "comment": "Randomized Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE",
+ "comment": "Randomized Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED:NO",
+ "comment": "Fixed Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED",
+ "comment": "Fixed Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT:NO",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TurnOffAssemblyGeneration",
+ "switch": "NOASSEMBLY",
+ "comment": "Turn Off Assembly Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportUnloadOfDelayLoadedDLL",
+ "switch": "DELAY:UNLOAD",
+ "comment": "Unload delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportNobindOfDelayLoadedDLL",
+ "switch": "DELAY:NOBIND",
+ "comment": "Nobind delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Profile",
+ "switch": "PROFILE",
+ "comment": "Profile",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN:NO",
+ "comment": "Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN",
+ "comment": "Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK:NO",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DetectOneDefinitionRule",
+ "switch": "ODR",
+ "comment": "Detect One Definition Rule violations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH:NO",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDLL",
+ "switch": "DLL",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibraryDirectories",
+ "switch": "LIBPATH:",
+ "comment": "Additional Library Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "Natvis",
+ "switch": "NATVIS:",
+ "comment": "Natvis files",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IgnoreSpecificDefaultLibraries",
+ "switch": "NODEFAULTLIB:",
+ "comment": "Ignore Specific Default Libraries",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AddModuleNamesToAssembly",
+ "switch": "ASSEMBLYMODULE:",
+ "comment": "Add Module to Assembly",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "EmbedManagedResourceFile",
+ "switch": "ASSEMBLYRESOURCE:",
+ "comment": "Embed Managed Resource File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForceSymbolReferences",
+ "switch": "INCLUDE:",
+ "comment": "Force Symbol References",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DelayLoadDLLs",
+ "switch": "DELAYLOAD:",
+ "comment": "Delay Loaded Dlls",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AssemblyLinkResource",
+ "switch": "ASSEMBLYLINKRESOURCE:",
+ "comment": "Assembly Link Resource",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalManifestDependencies",
+ "switch": "MANIFESTDEPENDENCY:",
+ "comment": "Additional Manifest Dependencies",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ManifestInput",
+ "switch": "manifestinput:",
+ "comment": "Manifest Input",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFile",
+ "switch": "OUT:",
+ "comment": "Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "Version",
+ "switch": "VERSION:",
+ "comment": "Version",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SpecifySectionAttributes",
+ "switch": "SECTION:",
+ "comment": "Specify Section Attributes",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MSDOSStubFileName",
+ "switch": "STUB:",
+ "comment": "MS-DOS Stub File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ModuleDefinitionFile",
+ "switch": "DEF:",
+ "comment": "Module Definition File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ManifestFile",
+ "switch": "ManifestFile:",
+ "comment": "Manifest File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDatabaseFile",
+ "switch": "PDB:",
+ "comment": "Generate Program Database File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StripPrivateSymbols",
+ "switch": "PDBSTRIPPED:",
+ "comment": "Strip Private Symbols",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MapFileName",
+ "switch": "MAP:",
+ "comment": "Map File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "HeapReserveSize",
+ "switch": "HEAP:",
+ "comment": "Heap Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "HeapCommitSize",
+ "switch": "HEAP",
+ "comment": "Heap Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "StackReserveSize",
+ "switch": "STACK:",
+ "comment": "Stack Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StackCommitSize",
+ "switch": "STACK",
+ "comment": "Stack Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "FunctionOrder",
+ "switch": "ORDER:@",
+ "comment": "Function Order",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProfileGuidedDatabase",
+ "switch": "PGD:",
+ "comment": "Profile Guided Database",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MidlCommandFile",
+ "switch": "MIDL:@",
+ "comment": "MIDL Commands",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergedIDLBaseFileName",
+ "switch": "IDLOUT:",
+ "comment": "Merged IDL Base File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryFile",
+ "switch": "TLBOUT:",
+ "comment": "Type Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataFile",
+ "switch": "WINMDFILE:",
+ "comment": "Windows Metadata File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataLinkKeyFile",
+ "switch": "WINMDKEYFILE:",
+ "comment": "Windows Metadata Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataKeyContainer",
+ "switch": "WINMDKEYCONTAINER:",
+ "comment": "Windows Metadata Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "EntryPointSymbol",
+ "switch": "ENTRY:",
+ "comment": "Entry Point",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "BASE:",
+ "comment": "Base Address",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ImportLibrary",
+ "switch": "IMPLIB:",
+ "comment": "Import Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergeSections",
+ "switch": "MERGE:",
+ "comment": "Merge Sections",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LinkKeyFile",
+ "switch": "KEYFILE:",
+ "comment": "Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "KeyContainer",
+ "switch": "KEYCONTAINER:",
+ "comment": "Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryResourceID",
+ "switch": "TLBID:",
+ "comment": "TypeLib Resource ID",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SectionAlignment",
+ "switch": "ALIGN:",
+ "comment": "SectionAlignment",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v142_CL.json b/Templates/MSBuild/FlagTables/v142_CL.json
new file mode 100644
index 000000000..95b9d14f6
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v142_CL.json
@@ -0,0 +1,1212 @@
+[
+ {
+ "name": "DebugInformationFormat",
+ "switch": "",
+ "comment": "None",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Z7",
+ "comment": "C7 compatible",
+ "value": "OldStyle",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "Zi",
+ "comment": "Program Database",
+ "value": "ProgramDatabase",
+ "flags": []
+ },
+ {
+ "name": "DebugInformationFormat",
+ "switch": "ZI",
+ "comment": "Program Database for Edit And Continue",
+ "value": "EditAndContinue",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "",
+ "comment": "No Common Language RunTime Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr",
+ "comment": "Common Language RunTime Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:pure",
+ "comment": "Pure MSIL Common Language RunTime Support",
+ "value": "Pure",
+ "flags": []
+ },
+ {
+ "name": "CompileAsManaged",
+ "switch": "clr:safe",
+ "comment": "Safe MSIL Common Language RunTime Support",
+ "value": "Safe",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W0",
+ "comment": "Turn Off All Warnings",
+ "value": "TurnOffAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W1",
+ "comment": "Level1",
+ "value": "Level1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W2",
+ "comment": "Level2",
+ "value": "Level2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W3",
+ "comment": "Level3",
+ "value": "Level3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W4",
+ "comment": "Level4",
+ "value": "Level4",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "Wall",
+ "comment": "EnableAllWarnings",
+ "value": "EnableAllWarnings",
+ "flags": []
+ },
+ {
+ "name": "DiagnosticsFormat",
+ "switch": "diagnostics:caret",
+ "comment": "Caret",
+ "value": "Caret",
+ "flags": []
+ },
+ {
+ "name": "DiagnosticsFormat",
+ "switch": "diagnostics:column",
+ "comment": "Column Info",
+ "value": "Column",
+ "flags": []
+ },
+ {
+ "name": "DiagnosticsFormat",
+ "switch": "diagnostics:classic",
+ "comment": "Classic",
+ "value": "Classic",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "",
+ "comment": "Custom",
+ "value": "Custom",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Od",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O1",
+ "comment": "Maximum Optimization (Favor Size)",
+ "value": "MinSpace",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "O2",
+ "comment": "Maximum Optimization (Favor Speed)",
+ "value": "MaxSpeed",
+ "flags": []
+ },
+ {
+ "name": "Optimization",
+ "switch": "Ox",
+ "comment": "Optimizations (Favor Speed)",
+ "value": "Full",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob0",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob1",
+ "comment": "Only __inline",
+ "value": "OnlyExplicitInline",
+ "flags": []
+ },
+ {
+ "name": "InlineFunctionExpansion",
+ "switch": "Ob2",
+ "comment": "Any Suitable",
+ "value": "AnySuitable",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Os",
+ "comment": "Favor small code",
+ "value": "Size",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "Ot",
+ "comment": "Favor fast code",
+ "value": "Speed",
+ "flags": []
+ },
+ {
+ "name": "FavorSizeOrSpeed",
+ "switch": "",
+ "comment": "Neither",
+ "value": "Neither",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHa",
+ "comment": "Yes with SEH Exceptions",
+ "value": "Async",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHsc",
+ "comment": "Yes",
+ "value": "Sync",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "EHs",
+ "comment": "Yes with Extern C functions",
+ "value": "SyncCThrow",
+ "flags": []
+ },
+ {
+ "name": "ExceptionHandling",
+ "switch": "",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCs",
+ "comment": "Stack Frames",
+ "value": "StackFrameRuntimeCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTCu",
+ "comment": "Uninitialized variables",
+ "value": "UninitializedLocalUsageCheck",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "RTC1",
+ "comment": "Both (/RTC1, equiv. to /RTCsu)",
+ "value": "EnableFastChecks",
+ "flags": []
+ },
+ {
+ "name": "BasicRuntimeChecks",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MT",
+ "comment": "Multi-threaded",
+ "value": "MultiThreaded",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MTd",
+ "comment": "Multi-threaded Debug",
+ "value": "MultiThreadedDebug",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MD",
+ "comment": "Multi-threaded DLL",
+ "value": "MultiThreadedDLL",
+ "flags": []
+ },
+ {
+ "name": "RuntimeLibrary",
+ "switch": "MDd",
+ "comment": "Multi-threaded Debug DLL",
+ "value": "MultiThreadedDebugDLL",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp1",
+ "comment": "1 Byte",
+ "value": "1Byte",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp2",
+ "comment": "2 Bytes",
+ "value": "2Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp4",
+ "comment": "4 Byte",
+ "value": "4Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp8",
+ "comment": "8 Bytes",
+ "value": "8Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "Zp16",
+ "comment": "16 Bytes",
+ "value": "16Bytes",
+ "flags": []
+ },
+ {
+ "name": "StructMemberAlignment",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS-",
+ "comment": "Disable Security Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "BufferSecurityCheck",
+ "switch": "GS",
+ "comment": "Enable Security Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ControlFlowGuard",
+ "switch": "guard:cf",
+ "comment": "Yes",
+ "value": "Guard",
+ "flags": []
+ },
+ {
+ "name": "ControlFlowGuard",
+ "switch": "",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE",
+ "comment": "Streaming SIMD Extensions",
+ "value": "StreamingSIMDExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:SSE2",
+ "comment": "Streaming SIMD Extensions 2",
+ "value": "StreamingSIMDExtensions2",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:AVX",
+ "comment": "Advanced Vector Extensions",
+ "value": "AdvancedVectorExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:AVX2",
+ "comment": "Advanced Vector Extensions 2",
+ "value": "AdvancedVectorExtensions2",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "arch:IA32",
+ "comment": "No Enhanced Instructions",
+ "value": "NoExtensions",
+ "flags": []
+ },
+ {
+ "name": "EnableEnhancedInstructionSet",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:precise",
+ "comment": "Precise",
+ "value": "Precise",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:strict",
+ "comment": "Strict",
+ "value": "Strict",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointModel",
+ "switch": "fp:fast",
+ "comment": "Fast",
+ "value": "Fast",
+ "flags": []
+ },
+ {
+ "name": "SpectreMitigation",
+ "switch": "Qspectre-",
+ "comment": "Spectre mitigations disabled",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "SpectreMitigation",
+ "switch": "Qspectre",
+ "comment": "Spectre mitigations enabled",
+ "value": "Spectre",
+ "flags": []
+ },
+ {
+ "name": "LanguageStandard",
+ "switch": "std:c++14",
+ "comment": "ISO C++14 Standard",
+ "value": "stdcpp14",
+ "flags": []
+ },
+ {
+ "name": "LanguageStandard",
+ "switch": "std:c++17",
+ "comment": "ISO C++17 Standard",
+ "value": "stdcpp17",
+ "flags": []
+ },
+ {
+ "name": "LanguageStandard",
+ "switch": "std:c++latest",
+ "comment": "Preview - Features from the Latest C++ Working Draft",
+ "value": "stdcpplatest",
+ "flags": []
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yc",
+ "comment": "Create",
+ "value": "Create",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Yu",
+ "comment": "Use",
+ "value": "Use",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeader",
+ "switch": "Y-",
+ "comment": "Not Using Precompiled Headers",
+ "value": "NotUsing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "",
+ "comment": "No Listing",
+ "value": "NoListing",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FA",
+ "comment": "Assembly-Only Listing",
+ "value": "AssemblyCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAc",
+ "comment": "Assembly With Machine Code",
+ "value": "AssemblyAndMachineCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAs",
+ "comment": "Assembly With Source Code",
+ "value": "AssemblyAndSourceCode",
+ "flags": []
+ },
+ {
+ "name": "AssemblerOutput",
+ "switch": "FAcs",
+ "comment": "Assembly, Machine Code and Source",
+ "value": "All",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gd",
+ "comment": "__cdecl",
+ "value": "Cdecl",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gr",
+ "comment": "__fastcall",
+ "value": "FastCall",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gz",
+ "comment": "__stdcall",
+ "value": "StdCall",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gv",
+ "comment": "__vectorcall",
+ "value": "VectorCall",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TC",
+ "comment": "Compile as C Code",
+ "value": "CompileAsC",
+ "flags": []
+ },
+ {
+ "name": "CompileAs",
+ "switch": "TP",
+ "comment": "Compile as C++ Code",
+ "value": "CompileAsCpp",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:none",
+ "comment": "Do Not Send Report",
+ "value": "None",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "Prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:queue",
+ "comment": "Queue For Next Login",
+ "value": "Queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:send",
+ "comment": "Send Automatically",
+ "value": "Send",
+ "flags": []
+ },
+ {
+ "name": "SupportJustMyCode",
+ "switch": "JMC-",
+ "comment": "Support Just My Code Debugging",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "SupportJustMyCode",
+ "switch": "JMC",
+ "comment": "Support Just My Code Debugging",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CompileAsWinRT",
+ "switch": "ZW",
+ "comment": "Consume Windows Runtime Extension",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WinRTNoStdLib",
+ "switch": "ZW:nostdlib",
+ "comment": "No Standard WinRT Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX-",
+ "comment": "Treat Warnings As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningAsError",
+ "switch": "WX",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SDLCheck",
+ "switch": "sdl-",
+ "comment": "SDL checks",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "SDLCheck",
+ "switch": "sdl",
+ "comment": "SDL checks",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MultiProcessorCompilation",
+ "switch": "MP",
+ "comment": "Multi-processor Compilation",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "IntrinsicFunctions",
+ "switch": "Oi",
+ "comment": "Enable Intrinsic Functions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy-",
+ "comment": "Omit Frame Pointers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OmitFramePointers",
+ "switch": "Oy",
+ "comment": "Omit Frame Pointers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableFiberSafeOptimizations",
+ "switch": "GT",
+ "comment": "Enable Fiber-Safe Optimizations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WholeProgramOptimization",
+ "switch": "GL",
+ "comment": "Whole Program Optimization",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UndefineAllPreprocessorDefinitions",
+ "switch": "u",
+ "comment": "Undefine All Preprocessor Definitions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreStandardIncludePath",
+ "switch": "X",
+ "comment": "Ignore Standard Include Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessToFile",
+ "switch": "P",
+ "comment": "Preprocess to a File",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessSuppressLineNumbers",
+ "switch": "EP",
+ "comment": "Preprocess Suppress Line Numbers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessKeepComments",
+ "switch": "C",
+ "comment": "Keep Comments",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF-",
+ "comment": "Enable String Pooling",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "StringPooling",
+ "switch": "GF",
+ "comment": "Enable String Pooling",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm-",
+ "comment": "Enable Minimal Rebuild",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "MinimalRebuild",
+ "switch": "Gm",
+ "comment": "Enable Minimal Rebuild",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SmallerTypeCheck",
+ "switch": "RTCc",
+ "comment": "Smaller Type Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy-",
+ "comment": "Enable Function-Level Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FunctionLevelLinking",
+ "switch": "Gy",
+ "comment": "Enable Function-Level Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableParallelCodeGeneration",
+ "switch": "Qpar-",
+ "comment": "Enable Parallel Code Generation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableParallelCodeGeneration",
+ "switch": "Qpar",
+ "comment": "Enable Parallel Code Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except-",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FloatingPointExceptions",
+ "switch": "fp:except",
+ "comment": "Enable Floating Point Exceptions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CreateHotpatchableImage",
+ "switch": "hotpatch",
+ "comment": "Create Hotpatchable Image",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DisableLanguageExtensions",
+ "switch": "Za",
+ "comment": "Disable Language Extensions",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ConformanceMode",
+ "switch": "permissive-",
+ "comment": "Conformance mode enabled",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ConformanceMode",
+ "switch": "permissive",
+ "comment": "Conformance mode disabled",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t-",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWChar_tAsBuiltInType",
+ "switch": "Zc:wchar_t",
+ "comment": "Treat WChar_t As Built in Type",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope-",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ForceConformanceInForLoopScope",
+ "switch": "Zc:forScope",
+ "comment": "Force Conformance in For Loop Scope",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RemoveUnreferencedCodeData",
+ "switch": "Zc:inline-",
+ "comment": "Remove unreferenced code and data",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RemoveUnreferencedCodeData",
+ "switch": "Zc:inline",
+ "comment": "Remove unreferenced code and data",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnforceTypeConversionRules",
+ "switch": "Zc:rvalueCast-",
+ "comment": "Enforce type conversion rules",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnforceTypeConversionRules",
+ "switch": "Zc:rvalueCast",
+ "comment": "Enforce type conversion rules",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR-",
+ "comment": "Enable Run-Time Type Information",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RuntimeTypeInfo",
+ "switch": "GR",
+ "comment": "Enable Run-Time Type Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp-",
+ "comment": "Open MP Support",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OpenMPSupport",
+ "switch": "openmp",
+ "comment": "Open MP Support",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableModules",
+ "switch": "experimental:module",
+ "comment": "Enable C++ Modules (experimental)",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ExpandAttributedSource",
+ "switch": "Fx",
+ "comment": "Expand Attributed Source",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseUnicodeForAssemblerListing",
+ "switch": "FAu",
+ "comment": "Use Unicode For Assembler Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateXMLDocumentationFiles",
+ "switch": "doc",
+ "comment": "Generate XML Documentation Files",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "BrowseInformation",
+ "switch": "FR",
+ "comment": "Enable Browse Information",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "ShowIncludes",
+ "switch": "showIncludes",
+ "comment": "Show Includes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze-",
+ "comment": "Enable Code Analysis",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnablePREfast",
+ "switch": "analyze",
+ "comment": "Enable Code Analysis",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseFullPaths",
+ "switch": "FC",
+ "comment": "Use Full Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OmitDefaultLibName",
+ "switch": "Zl",
+ "comment": "Omit Default Library Name",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalIncludeDirectories",
+ "switch": "I",
+ "comment": "Additional Include Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalUsingDirectories",
+ "switch": "AI",
+ "comment": "Additional #using Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "U",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DisableSpecificWarnings",
+ "switch": "wd",
+ "comment": "Disable Specific Warnings",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedIncludeFiles",
+ "switch": "FI",
+ "comment": "Forced Include File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForcedUsingFiles",
+ "switch": "FU",
+ "comment": "Forced #using File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "PREfastLog",
+ "switch": "analyze:log",
+ "comment": "Code Analysis Log",
+ "value": "",
+ "flags": [
+ "UserFollowing"
+ ]
+ },
+ {
+ "name": "PREfastAdditionalPlugins",
+ "switch": "analyze:plugin",
+ "comment": "Additional Code Analysis Native plugins",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "TreatSpecificWarningsAsErrors",
+ "switch": "we",
+ "comment": "Treat Specific Warnings As Errors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "WarningVersion",
+ "switch": "Wv:",
+ "comment": "Warning Version",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "PreprocessOutputPath",
+ "switch": "Fi",
+ "comment": "Preprocess Output Path",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yu",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderFile",
+ "switch": "Yc",
+ "comment": "Precompiled Header File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "PrecompiledHeaderOutputFile",
+ "switch": "Fp",
+ "comment": "Precompiled Header Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "AssemblerListingLocation",
+ "switch": "Fa",
+ "comment": "ASM List Location",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ObjectFileName",
+ "switch": "Fo",
+ "comment": "Object File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDataBaseFileName",
+ "switch": "Fd",
+ "comment": "Program Database File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "XMLDocumentationFileName",
+ "switch": "doc",
+ "comment": "XML Documentation File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "BrowseInformationFile",
+ "switch": "FR",
+ "comment": "Browse Information File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ProcessorNumber",
+ "switch": "MP",
+ "comment": "Number of processors",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v142_CSharp.json b/Templates/MSBuild/FlagTables/v142_CSharp.json
new file mode 100644
index 000000000..5989aea1e
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v142_CSharp.json
@@ -0,0 +1,574 @@
+[
+ {
+ "name": "ProjectName",
+ "switch": "out:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:exe",
+ "comment": "",
+ "value": "Exe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:winexe",
+ "comment": "",
+ "value": "Winexe",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:library",
+ "comment": "",
+ "value": "Library",
+ "flags": []
+ },
+ {
+ "name": "OutputType",
+ "switch": "target:module",
+ "comment": "",
+ "value": "Module",
+ "flags": []
+ },
+ {
+ "name": "DocumentationFile",
+ "switch": "doc",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x86",
+ "comment": "",
+ "value": "x86",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:Itanium",
+ "comment": "",
+ "value": "Itanium",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:x64",
+ "comment": "",
+ "value": "x64",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:arm",
+ "comment": "",
+ "value": "arm",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu32bitpreferred",
+ "comment": "",
+ "value": "anycpu32bitpreferred",
+ "flags": []
+ },
+ {
+ "name": "Platform",
+ "switch": "platform:anycpu",
+ "comment": "",
+ "value": "anycpu",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "mit alias",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "References",
+ "switch": "reference:",
+ "comment": "dateiliste",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AddModules",
+ "switch": "addmodule:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "Win32Resource",
+ "switch": "win32res:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationIcon",
+ "switch": "win32icon:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "ApplicationManifest",
+ "switch": "win32manifest:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "NoWin32Manifest",
+ "switch": "nowin32manifest",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineDebug",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": [
+ "Continue"
+ ]
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DebugSymbols",
+ "switch": "debug+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:none",
+ "comment": "",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:full",
+ "comment": "",
+ "value": "full",
+ "flags": []
+ },
+ {
+ "name": "DebugType",
+ "switch": "debug:pdbonly",
+ "comment": "",
+ "value": "pdbonly",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "Optimize",
+ "switch": "optimize+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror-",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningsAsErrors",
+ "switch": "warnaserror+",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:0",
+ "comment": "",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:1",
+ "comment": "",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:2",
+ "comment": "",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "warn:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "NoWarn",
+ "switch": "nowarn:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "CommaAppendable"
+ ]
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CheckForOverflowUnderflow",
+ "switch": "checked+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowUnsafeBlocks",
+ "switch": "unsafe+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DefineConstants",
+ "switch": "define:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "SemicolonAppendable",
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-1",
+ "comment": "",
+ "value": "ISO-1",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:ISO-2",
+ "comment": "",
+ "value": "ISO-2",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:3",
+ "comment": "",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:4",
+ "comment": "",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:5",
+ "comment": "",
+ "value": "5",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:6",
+ "comment": "",
+ "value": "6",
+ "flags": []
+ },
+ {
+ "name": "LangVersion",
+ "switch": "langversion:default",
+ "comment": "",
+ "value": "default",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DelaySign",
+ "switch": "delaysign+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyOriginatorKeyFile",
+ "switch": "keyfile",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "KeyContainerName",
+ "switch": "keycontainer",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoLogo",
+ "switch": "nologo",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoConfig",
+ "switch": "noconfig",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "baseaddress:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "CodePage",
+ "switch": "codepage",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "Utf8Output",
+ "switch": "utf8output",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "MainEntryPoint",
+ "switch": "main:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "GenerateFullPaths",
+ "switch": "fullpaths",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FileAlignment",
+ "switch": "filealign",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "PdbFile",
+ "switch": "pdb:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib-",
+ "comment": "",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "NoStandardLib",
+ "switch": "nostdlib+",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SubsystemVersion",
+ "switch": "subsystemversion",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibPaths",
+ "switch": "lib:",
+ "comment": "",
+ "value": "",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:none",
+ "comment": "Do Not Send Report",
+ "value": "none",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:prompt",
+ "comment": "Prompt Immediately",
+ "value": "prompt",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:queue",
+ "comment": "Queue For Next Login",
+ "value": "queue",
+ "flags": []
+ },
+ {
+ "name": "ErrorReport",
+ "switch": "errorreport:send",
+ "comment": "Send Automatically",
+ "value": "send",
+ "flags": []
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v142_Link.json b/Templates/MSBuild/FlagTables/v142_Link.json
new file mode 100644
index 000000000..66ee76fcb
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v142_Link.json
@@ -0,0 +1,1323 @@
+[
+ {
+ "name": "ShowProgress",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE",
+ "comment": "Display all progress messages",
+ "value": "LinkVerbose",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:Lib",
+ "comment": "For Libraries Searched",
+ "value": "LinkVerboseLib",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:ICF",
+ "comment": "About COMDAT folding during optimized linking",
+ "value": "LinkVerboseICF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:REF",
+ "comment": "About data removed during optimized linking",
+ "value": "LinkVerboseREF",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:SAFESEH",
+ "comment": "About Modules incompatible with SEH",
+ "value": "LinkVerboseSAFESEH",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "VERBOSE:CLR",
+ "comment": "About linker activity related to managed code",
+ "value": "LinkVerboseCLR",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:MULTIPLE",
+ "comment": "Multiply Defined Symbol Only",
+ "value": "MultiplyDefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "ForceFileOutput",
+ "switch": "FORCE:UNRESOLVED",
+ "comment": "Undefined Symbol Only",
+ "value": "UndefinedSymbolOnly",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:5",
+ "comment": "X86 Image Only",
+ "value": "X86Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:6",
+ "comment": "X64 Image Only",
+ "value": "X64Image",
+ "flags": []
+ },
+ {
+ "name": "CreateHotPatchableImage",
+ "switch": "FUNCTIONPADMIN:16",
+ "comment": "Itanium Image Only",
+ "value": "ItaniumImage",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='asInvoker'",
+ "comment": "asInvoker",
+ "value": "AsInvoker",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='highestAvailable'",
+ "comment": "highestAvailable",
+ "value": "HighestAvailable",
+ "flags": []
+ },
+ {
+ "name": "UACExecutionLevel",
+ "switch": "level='requireAdministrator'",
+ "comment": "requireAdministrator",
+ "value": "RequireAdministrator",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG",
+ "comment": "Generate Debug Information",
+ "value": "true",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG:FASTLINK",
+ "comment": "Generate Debug Information optimized for faster links",
+ "value": "DebugFastLink",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG:FULL",
+ "comment": "Generate Debug Information optimized for sharing and publishing",
+ "value": "DebugFull",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "DEBUG:NONE",
+ "comment": "Produces no debugging information",
+ "value": "false",
+ "flags": [
+ "CaseInsensitive"
+ ]
+ },
+ {
+ "name": "SubSystem",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:CONSOLE",
+ "comment": "Console",
+ "value": "Console",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWS",
+ "comment": "Windows",
+ "value": "Windows",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:NATIVE",
+ "comment": "Native",
+ "value": "Native",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_APPLICATION",
+ "comment": "EFI Application",
+ "value": "EFI Application",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+ "comment": "EFI Boot Service Driver",
+ "value": "EFI Boot Service Driver",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_ROM",
+ "comment": "EFI ROM",
+ "value": "EFI ROM",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+ "comment": "EFI Runtime",
+ "value": "EFI Runtime",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:POSIX",
+ "comment": "POSIX",
+ "value": "POSIX",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "Driver",
+ "comment": "Driver",
+ "value": "Driver",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:UPONLY",
+ "comment": "UP Only",
+ "value": "UpOnly",
+ "flags": []
+ },
+ {
+ "name": "Driver",
+ "switch": "DRIVER:WDM",
+ "comment": "WDM",
+ "value": "WDM",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "",
+ "comment": "Default",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:incremental",
+ "comment": "Use Fast Link Time Code Generation",
+ "value": "UseFastLinkTimeCodeGeneration",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG",
+ "comment": "Use Link Time Code Generation",
+ "value": "UseLinkTimeCodeGeneration",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGInstrument",
+ "comment": "Profile Guided Optimization - Instrument",
+ "value": "PGInstrument",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGOptimize",
+ "comment": "Profile Guided Optimization - Optimization",
+ "value": "PGOptimization",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG:PGUpdate",
+ "comment": "Profile Guided Optimization - Update",
+ "value": "PGUpdate",
+ "flags": []
+ },
+ {
+ "name": "GenerateWindowsMetadata",
+ "switch": "WINMD",
+ "comment": "Yes",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateWindowsMetadata",
+ "switch": "WINMD:NO",
+ "comment": "No",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA1",
+ "comment": "SHA1",
+ "value": "SHA1",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA256",
+ "comment": "SHA256",
+ "value": "SHA256",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA384",
+ "comment": "SHA384",
+ "value": "SHA384",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataSignHash",
+ "switch": "WINMDSIGNHASH:SHA512",
+ "comment": "SHA512",
+ "value": "SHA512",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "",
+ "comment": "Not Set",
+ "value": "NotSet",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM",
+ "comment": "MachineARM",
+ "value": "MachineARM",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM64",
+ "comment": "MachineARM64",
+ "value": "MachineARM64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:EBC",
+ "comment": "MachineEBC",
+ "value": "MachineEBC",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:IA64",
+ "comment": "MachineIA64",
+ "value": "MachineIA64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS",
+ "comment": "MachineMIPS",
+ "value": "MachineMIPS",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS16",
+ "comment": "MachineMIPS16",
+ "value": "MachineMIPS16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU",
+ "comment": "MachineMIPSFPU",
+ "value": "MachineMIPSFPU",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU16",
+ "comment": "MachineMIPSFPU16",
+ "value": "MachineMIPSFPU16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:SH4",
+ "comment": "MachineSH4",
+ "value": "MachineSH4",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:THUMB",
+ "comment": "MachineTHUMB",
+ "value": "MachineTHUMB",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X64",
+ "comment": "MachineX64",
+ "value": "MachineX64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X86",
+ "comment": "MachineX86",
+ "value": "MachineX86",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:MTA",
+ "comment": "MTA threading attribute",
+ "value": "MTAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:STA",
+ "comment": "STA threading attribute",
+ "value": "STAThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRThreadAttribute",
+ "switch": "CLRTHREADATTRIBUTE:NONE",
+ "comment": "Default threading attribute",
+ "value": "DefaultThreadingAttribute",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:IJW",
+ "comment": "Force IJW image",
+ "value": "ForceIJWImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:PURE",
+ "comment": "Force Pure IL Image",
+ "value": "ForcePureILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "CLRIMAGETYPE:SAFE",
+ "comment": "Force Safe IL Image",
+ "value": "ForceSafeILImage",
+ "flags": []
+ },
+ {
+ "name": "CLRImageType",
+ "switch": "",
+ "comment": "Default image type",
+ "value": "Default",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA1",
+ "comment": "SHA1",
+ "value": "SHA1",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA256",
+ "comment": "SHA256",
+ "value": "SHA256",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA384",
+ "comment": "SHA384",
+ "value": "SHA384",
+ "flags": []
+ },
+ {
+ "name": "SignHash",
+ "switch": "CLRSIGNHASH:SHA512",
+ "comment": "SHA512",
+ "value": "SHA512",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:PROMPT",
+ "comment": "PromptImmediately",
+ "value": "PromptImmediately",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:QUEUE",
+ "comment": "Queue For Next Login",
+ "value": "QueueForNextLogin",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:SEND",
+ "comment": "Send Error Report",
+ "value": "SendErrorReport",
+ "flags": []
+ },
+ {
+ "name": "LinkErrorReporting",
+ "switch": "ERRORREPORT:NONE",
+ "comment": "No Error Report",
+ "value": "NoErrorReport",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError",
+ "comment": "Enabled",
+ "value": "Enabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:NO",
+ "comment": "Disabled",
+ "value": "Disabled",
+ "flags": []
+ },
+ {
+ "name": "CLRSupportLastError",
+ "switch": "CLRSupportLastError:SYSTEMDLL",
+ "comment": "System Dlls Only",
+ "value": "SystemDlls",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL:NO",
+ "comment": "Enable Incremental Linking",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkIncremental",
+ "switch": "INCREMENTAL",
+ "comment": "Enable Incremental Linking",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "NOLOGO",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:NOSTATUS",
+ "comment": "Link Status",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkStatus",
+ "switch": "LTCG:STATUS",
+ "comment": "Link Status",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND:NO",
+ "comment": "Prevent Dll Binding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "PreventDllBinding",
+ "switch": "ALLOWBIND",
+ "comment": "Prevent Dll Binding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX:NO",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatLinkerWarningAsErrors",
+ "switch": "WX",
+ "comment": "Treat Linker Warning As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreAllDefaultLibraries",
+ "switch": "NODEFAULTLIB",
+ "comment": "Ignore All Default Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST:NO",
+ "comment": "Generate Manifest",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "GenerateManifest",
+ "switch": "MANIFEST",
+ "comment": "Generate Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "ALLOWISOLATION:NO",
+ "comment": "Allow Isolation",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AllowIsolation",
+ "switch": "",
+ "comment": "Allow Isolation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableUAC",
+ "switch": "MANIFESTUAC:",
+ "comment": "",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired",
+ "SpaceAppendable"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='false'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "UACUIAccess",
+ "switch": "uiAccess='true'",
+ "comment": "UAC Bypass UI Protection",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ManifestEmbed",
+ "switch": "manifest:embed",
+ "comment": "Embed Manifest",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateMapFile",
+ "switch": "MAP",
+ "comment": "Generate Map File",
+ "value": "true",
+ "flags": [
+ "UserValue",
+ "UserIgnored",
+ "Continue"
+ ]
+ },
+ {
+ "name": "MapExports",
+ "switch": "MAPINFO:EXPORTS",
+ "comment": "Map Exports",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG:DISABLE",
+ "comment": "Debuggable Assembly",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "AssemblyDebug",
+ "switch": "ASSEMBLYDEBUG",
+ "comment": "Debuggable Assembly",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE:NO",
+ "comment": "Enable Large Addresses",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LargeAddressAware",
+ "switch": "LARGEADDRESSAWARE",
+ "comment": "Enable Large Addresses",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE:NO",
+ "comment": "Terminal Server",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TerminalServerAware",
+ "switch": "TSAWARE",
+ "comment": "Terminal Server",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromCD",
+ "switch": "SWAPRUN:CD",
+ "comment": "Swap Run From CD",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SwapRunFromNET",
+ "switch": "SWAPRUN:NET",
+ "comment": "Swap Run From Network",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:NOREF",
+ "comment": "References",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "OptimizeReferences",
+ "switch": "OPT:REF",
+ "comment": "References",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:NOICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "EnableCOMDATFolding",
+ "switch": "OPT:ICF",
+ "comment": "Enable COMDAT Folding",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreEmbeddedIDL",
+ "switch": "IGNOREIDL",
+ "comment": "Ignore Embedded IDL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AppContainer",
+ "switch": "APPCONTAINER",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataLinkDelaySign",
+ "switch": "WINMDDELAYSIGN:NO",
+ "comment": "Windows Metadata Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "WindowsMetadataLinkDelaySign",
+ "switch": "WINMDDELAYSIGN",
+ "comment": "Windows Metadata Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NoEntryPoint",
+ "switch": "NOENTRY",
+ "comment": "No Entry Point",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SetChecksum",
+ "switch": "RELEASE",
+ "comment": "Set Checksum",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE:NO",
+ "comment": "Randomized Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "RandomizedBaseAddress",
+ "switch": "DYNAMICBASE",
+ "comment": "Randomized Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED:NO",
+ "comment": "Fixed Base Address",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "FixedBaseAddress",
+ "switch": "FIXED",
+ "comment": "Fixed Base Address",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT:NO",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "DataExecutionPrevention",
+ "switch": "NXCOMPAT",
+ "comment": "Data Execution Prevention (DEP)",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TurnOffAssemblyGeneration",
+ "switch": "NOASSEMBLY",
+ "comment": "Turn Off Assembly Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportUnloadOfDelayLoadedDLL",
+ "switch": "DELAY:UNLOAD",
+ "comment": "Unload delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SupportNobindOfDelayLoadedDLL",
+ "switch": "DELAY:NOBIND",
+ "comment": "Nobind delay loaded DLL",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Profile",
+ "switch": "PROFILE",
+ "comment": "Profile",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN:NO",
+ "comment": "Delay Sign",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "LinkDelaySign",
+ "switch": "DELAYSIGN",
+ "comment": "Delay Sign",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK:NO",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "CLRUnmanagedCodeCheck",
+ "switch": "CLRUNMANAGEDCODECHECK",
+ "comment": "CLR Unmanaged Code Check",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DetectOneDefinitionRule",
+ "switch": "ODR",
+ "comment": "Detect One Definition Rule violations",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH:NO",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "ImageHasSafeExceptionHandlers",
+ "switch": "SAFESEH",
+ "comment": "Image Has Safe Exception Handlers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkDLL",
+ "switch": "DLL",
+ "comment": "",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibraryDirectories",
+ "switch": "LIBPATH:",
+ "comment": "Additional Library Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "Natvis",
+ "switch": "NATVIS:",
+ "comment": "Natvis files",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IgnoreSpecificDefaultLibraries",
+ "switch": "NODEFAULTLIB:",
+ "comment": "Ignore Specific Default Libraries",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AddModuleNamesToAssembly",
+ "switch": "ASSEMBLYMODULE:",
+ "comment": "Add Module to Assembly",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "EmbedManagedResourceFile",
+ "switch": "ASSEMBLYRESOURCE:",
+ "comment": "Embed Managed Resource File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ForceSymbolReferences",
+ "switch": "INCLUDE:",
+ "comment": "Force Symbol References",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "DelayLoadDLLs",
+ "switch": "DELAYLOAD:",
+ "comment": "Delay Loaded Dlls",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AssemblyLinkResource",
+ "switch": "ASSEMBLYLINKRESOURCE:",
+ "comment": "Assembly Link Resource",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalManifestDependencies",
+ "switch": "MANIFESTDEPENDENCY:",
+ "comment": "Additional Manifest Dependencies",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ManifestInput",
+ "switch": "manifestinput:",
+ "comment": "Manifest Input",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFile",
+ "switch": "OUT:",
+ "comment": "Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "Version",
+ "switch": "VERSION:",
+ "comment": "Version",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SpecifySectionAttributes",
+ "switch": "SECTION:",
+ "comment": "Specify Section Attributes",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MSDOSStubFileName",
+ "switch": "STUB:",
+ "comment": "MS-DOS Stub File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ModuleDefinitionFile",
+ "switch": "DEF:",
+ "comment": "Module Definition File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ManifestFile",
+ "switch": "ManifestFile:",
+ "comment": "Manifest File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProgramDatabaseFile",
+ "switch": "PDB:",
+ "comment": "Generate Program Database File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StripPrivateSymbols",
+ "switch": "PDBSTRIPPED:",
+ "comment": "Strip Private Symbols",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MapFileName",
+ "switch": "MAP:",
+ "comment": "Map File Name",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "HeapReserveSize",
+ "switch": "HEAP:",
+ "comment": "Heap Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "HeapCommitSize",
+ "switch": "HEAP",
+ "comment": "Heap Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "StackReserveSize",
+ "switch": "STACK:",
+ "comment": "Stack Reserve Size",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "StackCommitSize",
+ "switch": "STACK",
+ "comment": "Stack Commit Size",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "UserRequired"
+ ]
+ },
+ {
+ "name": "FunctionOrder",
+ "switch": "ORDER:@",
+ "comment": "Function Order",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ProfileGuidedDatabase",
+ "switch": "PGD:",
+ "comment": "Profile Guided Database",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MidlCommandFile",
+ "switch": "MIDL:@",
+ "comment": "MIDL Commands",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergedIDLBaseFileName",
+ "switch": "IDLOUT:",
+ "comment": "Merged IDL Base File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryFile",
+ "switch": "TLBOUT:",
+ "comment": "Type Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataFile",
+ "switch": "WINMDFILE:",
+ "comment": "Windows Metadata File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataLinkKeyFile",
+ "switch": "WINMDKEYFILE:",
+ "comment": "Windows Metadata Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "WindowsMetadataKeyContainer",
+ "switch": "WINMDKEYCONTAINER:",
+ "comment": "Windows Metadata Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "EntryPointSymbol",
+ "switch": "ENTRY:",
+ "comment": "Entry Point",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "BaseAddress",
+ "switch": "BASE:",
+ "comment": "Base Address",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ImportLibrary",
+ "switch": "IMPLIB:",
+ "comment": "Import Library",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "MergeSections",
+ "switch": "MERGE:",
+ "comment": "Merge Sections",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "LinkKeyFile",
+ "switch": "KEYFILE:",
+ "comment": "Key File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "KeyContainer",
+ "switch": "KEYCONTAINER:",
+ "comment": "Key Container",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "TypeLibraryResourceID",
+ "switch": "TLBID:",
+ "comment": "TypeLib Resource ID",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "SectionAlignment",
+ "switch": "ALIGN:",
+ "comment": "SectionAlignment",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v14_LIB.json b/Templates/MSBuild/FlagTables/v14_LIB.json
new file mode 100644
index 000000000..5990ed1b7
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v14_LIB.json
@@ -0,0 +1,304 @@
+[
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:PROMPT",
+ "comment": "PromptImmediately",
+ "value": "PromptImmediately",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:QUEUE",
+ "comment": "Queue For Next Login",
+ "value": "QueueForNextLogin",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:SEND",
+ "comment": "Send Error Report",
+ "value": "SendErrorReport",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "ERRORREPORT:NONE",
+ "comment": "No Error Report",
+ "value": "NoErrorReport",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM",
+ "comment": "MachineARM",
+ "value": "MachineARM",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:ARM64",
+ "comment": "MachineARM64",
+ "value": "MachineARM64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:EBC",
+ "comment": "MachineEBC",
+ "value": "MachineEBC",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:IA64",
+ "comment": "MachineIA64",
+ "value": "MachineIA64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS",
+ "comment": "MachineMIPS",
+ "value": "MachineMIPS",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPS16",
+ "comment": "MachineMIPS16",
+ "value": "MachineMIPS16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU",
+ "comment": "MachineMIPSFPU",
+ "value": "MachineMIPSFPU",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:MIPSFPU16",
+ "comment": "MachineMIPSFPU16",
+ "value": "MachineMIPSFPU16",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:SH4",
+ "comment": "MachineSH4",
+ "value": "MachineSH4",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:THUMB",
+ "comment": "MachineTHUMB",
+ "value": "MachineTHUMB",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X64",
+ "comment": "MachineX64",
+ "value": "MachineX64",
+ "flags": []
+ },
+ {
+ "name": "TargetMachine",
+ "switch": "MACHINE:X86",
+ "comment": "MachineX86",
+ "value": "MachineX86",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:CONSOLE",
+ "comment": "Console",
+ "value": "Console",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWS",
+ "comment": "Windows",
+ "value": "Windows",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:NATIVE",
+ "comment": "Native",
+ "value": "Native",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_APPLICATION",
+ "comment": "EFI Application",
+ "value": "EFI Application",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER",
+ "comment": "EFI Boot Service Driver",
+ "value": "EFI Boot Service Driver",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_ROM",
+ "comment": "EFI ROM",
+ "value": "EFI ROM",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:EFI_RUNTIME_DRIVER",
+ "comment": "EFI Runtime",
+ "value": "EFI Runtime",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:WINDOWSCE",
+ "comment": "WindowsCE",
+ "value": "WindowsCE",
+ "flags": []
+ },
+ {
+ "name": "SubSystem",
+ "switch": "SUBSYSTEM:POSIX",
+ "comment": "POSIX",
+ "value": "POSIX",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "NOLOGO",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "IgnoreAllDefaultLibraries",
+ "switch": "NODEFAULTLIB",
+ "comment": "Ignore All Default Libraries",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatLibWarningAsErrors",
+ "switch": "WX:NO",
+ "comment": "Treat Lib Warning As Errors",
+ "value": "false",
+ "flags": []
+ },
+ {
+ "name": "TreatLibWarningAsErrors",
+ "switch": "WX",
+ "comment": "Treat Lib Warning As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "Verbose",
+ "switch": "VERBOSE",
+ "comment": "Verbose",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "LinkTimeCodeGeneration",
+ "switch": "LTCG",
+ "comment": "Link Time Code Generation",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AdditionalLibraryDirectories",
+ "switch": "LIBPATH:",
+ "comment": "Additional Library Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IgnoreSpecificDefaultLibraries",
+ "switch": "NODEFAULTLIB:",
+ "comment": "Ignore Specific Default Libraries",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ExportNamedFunctions",
+ "switch": "EXPORT:",
+ "comment": "Export Named Functions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "RemoveObjects",
+ "switch": "REMOVE:",
+ "comment": "Remove Objects",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "OutputFile",
+ "switch": "OUT:",
+ "comment": "Output File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ModuleDefinitionFile",
+ "switch": "DEF:",
+ "comment": "Module Definition File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "ForceSymbolReferences",
+ "switch": "INCLUDE:",
+ "comment": "Force Symbol References",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "DisplayLibrary",
+ "switch": "LIST:",
+ "comment": "Display Library to standard output",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "Name",
+ "switch": "NAME:",
+ "comment": "Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v14_MASM.json b/Templates/MSBuild/FlagTables/v14_MASM.json
new file mode 100644
index 000000000..4634306b1
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v14_MASM.json
@@ -0,0 +1,295 @@
+[
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cp",
+ "comment": "Preserves Identifier Case (/Cp)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cu",
+ "comment": "Maps all identifiers to upper case. (/Cu)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "PreserveIdentifierCase",
+ "switch": "Cx",
+ "comment": "Preserves case in public and extern symbols. (/Cx)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W0",
+ "comment": "Warning Level 0 (/W0)",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W1",
+ "comment": "Warning Level 1 (/W1)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W2",
+ "comment": "Warning Level 2 (/W2)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "WarningLevel",
+ "switch": "W3",
+ "comment": "Warning Level 3 (/W3)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp1",
+ "comment": "One Byte Boundary (/Zp1)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp2",
+ "comment": "Two Byte Boundary (/Zp2)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp4",
+ "comment": "Four Byte Boundary (/Zp4)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp8",
+ "comment": "Eight Byte Boundary (/Zp8)",
+ "value": "4",
+ "flags": []
+ },
+ {
+ "name": "PackAlignmentBoundary",
+ "switch": "Zp16",
+ "comment": "Sixteen Byte Boundary (/Zp16)",
+ "value": "5",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "",
+ "comment": "Default",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gd",
+ "comment": "Use C-style Calling Convention (/Gd)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gz",
+ "comment": "Use stdcall Calling Convention (/Gz)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "CallingConvention",
+ "switch": "Gc",
+ "comment": "Use Pascal Calling Convention (/Gc)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:prompt",
+ "comment": "Prompt to send report immediately (/errorReport:prompt)",
+ "value": "0",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:queue",
+ "comment": "Prompt to send report at the next logon (/errorReport:queue)",
+ "value": "1",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:send",
+ "comment": "Automatically send report (/errorReport:send)",
+ "value": "2",
+ "flags": []
+ },
+ {
+ "name": "ErrorReporting",
+ "switch": "errorReport:none",
+ "comment": "Do not send report (/errorReport:none)",
+ "value": "3",
+ "flags": []
+ },
+ {
+ "name": "NoLogo",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GeneratePreprocessedSourceListing",
+ "switch": "EP",
+ "comment": "Generate Preprocessed Source Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ListAllAvailableInformation",
+ "switch": "Sa",
+ "comment": "List All Available Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "UseSafeExceptionHandlers",
+ "switch": "safeseh",
+ "comment": "Use Safe Exception Handlers",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "AddFirstPassListing",
+ "switch": "Sf",
+ "comment": "Add First Pass Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableAssemblyGeneratedCodeListing",
+ "switch": "Sg",
+ "comment": "Enable Assembly Generated Code Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "DisableSymbolTable",
+ "switch": "Sn",
+ "comment": "Disable Symbol Table",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableFalseConditionalsInListing",
+ "switch": "Sx",
+ "comment": "Enable False Conditionals In Listing",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "TreatWarningsAsErrors",
+ "switch": "WX",
+ "comment": "Treat Warnings As Errors",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "MakeAllSymbolsPublic",
+ "switch": "Zf",
+ "comment": "Make All Symbols Public",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "GenerateDebugInformation",
+ "switch": "Zi",
+ "comment": "Generate Debug Information",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "EnableMASM51Compatibility",
+ "switch": "Zm",
+ "comment": "Enable MASM 5.1 Compatibility",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PerformSyntaxCheckOnly",
+ "switch": "Zs",
+ "comment": "Perform Syntax Check Only",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "IncludePaths",
+ "switch": "I",
+ "comment": "Include Paths",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "BrowseFile",
+ "switch": "FR",
+ "comment": "Generate Browse Information File",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ObjectFileName",
+ "switch": "Fo",
+ "comment": "Object File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ },
+ {
+ "name": "AssembledCodeListingFile",
+ "switch": "Fl",
+ "comment": "Assembled Code Listing File",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Templates/MSBuild/FlagTables/v14_RC.json b/Templates/MSBuild/FlagTables/v14_RC.json
new file mode 100644
index 000000000..b8c0127d1
--- /dev/null
+++ b/Templates/MSBuild/FlagTables/v14_RC.json
@@ -0,0 +1,69 @@
+[
+ {
+ "name": "IgnoreStandardIncludePath",
+ "switch": "X",
+ "comment": "Ignore Standard Include Paths",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "ShowProgress",
+ "switch": "v",
+ "comment": "Show Progress",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "SuppressStartupBanner",
+ "switch": "nologo",
+ "comment": "Suppress Startup Banner",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "NullTerminateStrings",
+ "switch": "n",
+ "comment": "Null Terminate Strings",
+ "value": "true",
+ "flags": []
+ },
+ {
+ "name": "PreprocessorDefinitions",
+ "switch": "D",
+ "comment": "Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "UndefinePreprocessorDefinitions",
+ "switch": "u",
+ "comment": "Undefine Preprocessor Definitions",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "AdditionalIncludeDirectories",
+ "switch": "I",
+ "comment": "Additional Include Directories",
+ "value": "",
+ "flags": [
+ "UserValue",
+ "SemicolonAppendable"
+ ]
+ },
+ {
+ "name": "ResourceOutputFileName",
+ "switch": "fo",
+ "comment": "Resource File Name",
+ "value": "",
+ "flags": [
+ "UserValue"
+ ]
+ }
+]
diff --git a/Tests/CMakeCommands/add_compile_definitions/CMakeLists.txt b/Tests/CMakeCommands/add_compile_definitions/CMakeLists.txt
new file mode 100644
index 000000000..2eb887e00
--- /dev/null
+++ b/Tests/CMakeCommands/add_compile_definitions/CMakeLists.txt
@@ -0,0 +1,15 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(add_compile_definitions LANGUAGES CXX)
+
+add_compile_definitions(TEST_DEFINITION
+ $<$<COMPILE_LANGUAGE:CXX>:LANG_$<COMPILE_LANGUAGE>>
+ $<$<EQUAL:0,1>:UNEXPECTED_DEFINITION>)
+
+add_executable(add_compile_definitions main.cpp)
+
+add_library(imp UNKNOWN IMPORTED)
+get_target_property(_res imp COMPILE_DEFINITIONS)
+if (_res)
+ message(SEND_ERROR "add_compile_definitions populated the COMPILE_DEFINITIONS target property")
+endif()
diff --git a/Tests/CMakeCommands/add_compile_definitions/main.cpp b/Tests/CMakeCommands/add_compile_definitions/main.cpp
new file mode 100644
index 000000000..41ff25f4c
--- /dev/null
+++ b/Tests/CMakeCommands/add_compile_definitions/main.cpp
@@ -0,0 +1,17 @@
+
+#ifndef TEST_DEFINITION
+# error Expected TEST_DEFINITION
+#endif
+
+#ifndef LANG_CXX
+# error Expected LANG_CXX
+#endif
+
+#ifdef UNPEXTED_DEFINITION
+# error Unexpected UNPEXTED_DEFINITION
+#endif
+
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/add_link_options/CMakeLists.txt b/Tests/CMakeCommands/add_link_options/CMakeLists.txt
new file mode 100644
index 000000000..bb7dcbbfc
--- /dev/null
+++ b/Tests/CMakeCommands/add_link_options/CMakeLists.txt
@@ -0,0 +1,20 @@
+cmake_minimum_required(VERSION 3.11)
+
+project(add_link_options LANGUAGES C)
+
+
+add_link_options(-LINK_FLAG)
+
+add_executable(add_link_options EXCLUDE_FROM_ALL LinkOptionsExe.c)
+
+get_target_property(result add_link_options LINK_OPTIONS)
+if (NOT result MATCHES "-LINK_FLAG")
+ message(SEND_ERROR "add_link_options not populated the LINK_OPTIONS target property")
+endif()
+
+
+add_library(imp UNKNOWN IMPORTED)
+get_target_property(result imp LINK_OPTIONS)
+if (result)
+ message(FATAL_ERROR "add_link_options populated the LINK_OPTIONS target property")
+endif()
diff --git a/Tests/CMakeCommands/add_link_options/LinkOptionsExe.c b/Tests/CMakeCommands/add_link_options/LinkOptionsExe.c
new file mode 100644
index 000000000..8488f4e58
--- /dev/null
+++ b/Tests/CMakeCommands/add_link_options/LinkOptionsExe.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/link_directories/CMakeLists.txt b/Tests/CMakeCommands/link_directories/CMakeLists.txt
new file mode 100644
index 000000000..60c07b638
--- /dev/null
+++ b/Tests/CMakeCommands/link_directories/CMakeLists.txt
@@ -0,0 +1,30 @@
+cmake_minimum_required(VERSION 3.12)
+
+project(link_directories LANGUAGES C)
+
+
+link_directories(/A)
+link_directories(BEFORE /B)
+
+set(CMAKE_LINK_DIRECTORIES_BEFORE ON)
+link_directories(/C)
+
+get_directory_property(result LINK_DIRECTORIES)
+if (NOT result MATCHES "/C;/B;/A")
+ message(SEND_ERROR "link_directories not populated the LINK_DIRECTORIES directory property")
+endif()
+
+
+add_executable(link_directories EXCLUDE_FROM_ALL LinkDirectoriesExe.c)
+
+get_target_property(result link_directories LINK_DIRECTORIES)
+if (NOT result MATCHES "/C;/B;/A")
+ message(SEND_ERROR "link_directories not populated the LINK_DIRECTORIES target property")
+endif()
+
+
+add_library(imp UNKNOWN IMPORTED)
+get_target_property(result imp LINK_DIRECTORIES)
+if (result)
+ message(FATAL_ERROR "link_directories populated the LINK_DIRECTORIES target property")
+endif()
diff --git a/Tests/CMakeCommands/link_directories/LinkDirectoriesExe.c b/Tests/CMakeCommands/link_directories/LinkDirectoriesExe.c
new file mode 100644
index 000000000..8488f4e58
--- /dev/null
+++ b/Tests/CMakeCommands/link_directories/LinkDirectoriesExe.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/target_link_directories/CMakeLists.txt b/Tests/CMakeCommands/target_link_directories/CMakeLists.txt
new file mode 100644
index 000000000..bc7b9b212
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_directories/CMakeLists.txt
@@ -0,0 +1,40 @@
+
+cmake_minimum_required(VERSION 3.12)
+
+project(target_link_directories LANGUAGES C)
+
+add_library(target_link_directories SHARED LinkDirectoriesLib.c)
+# Test no items
+target_link_directories(target_link_directories PRIVATE)
+
+add_library(target_link_directories_2 SHARED EXCLUDE_FROM_ALL LinkDirectoriesLib.c)
+target_link_directories(target_link_directories_2 PRIVATE /private/dir INTERFACE /interface/dir)
+get_target_property(result target_link_directories_2 LINK_DIRECTORIES)
+if (NOT result MATCHES "/private/dir")
+ message(SEND_ERROR "${result} target_link_directories not populated the LINK_DIRECTORIES target property")
+endif()
+get_target_property(result target_link_directories_2 INTERFACE_LINK_DIRECTORIES)
+if (NOT result MATCHES "/interface/dir")
+ message(SEND_ERROR "target_link_directories not populated the INTERFACE_LINK_DIRECTORIES target property of shared library")
+endif()
+
+add_library(target_link_directories_3 STATIC EXCLUDE_FROM_ALL LinkDirectoriesLib.c)
+target_link_directories(target_link_directories_3 INTERFACE /interface/dir)
+get_target_property(result target_link_directories_3 INTERFACE_LINK_DIRECTORIES)
+if (NOT result MATCHES "/interface/dir")
+ message(SEND_ERROR "target_link_directories not populated the INTERFACE_LINK_DIRECTORIES target property of static library")
+endif()
+
+add_library(target_link_directories_4 SHARED EXCLUDE_FROM_ALL LinkDirectoriesLib.c)
+target_link_directories(target_link_directories_4 PRIVATE relative/dir)
+get_target_property(result target_link_directories_4 LINK_DIRECTORIES)
+if (NOT result MATCHES "${CMAKE_CURRENT_SOURCE_DIR}/relative/dir")
+ message(SEND_ERROR "target_link_directories not populated the LINK_DIRECTORIES with relative path")
+endif()
+
+add_subdirectory(subdir)
+target_link_directories(target_link_directories_5 PRIVATE relative/dir)
+get_target_property(result target_link_directories_5 LINK_DIRECTORIES)
+if (NOT result MATCHES "${CMAKE_CURRENT_SOURCE_DIR}/relative/dir")
+ message(SEND_ERROR "target_link_directories not populated the LINK_DIRECTORIES with relative path")
+endif()
diff --git a/Tests/CMakeCommands/target_link_directories/LinkDirectoriesLib.c b/Tests/CMakeCommands/target_link_directories/LinkDirectoriesLib.c
new file mode 100644
index 000000000..9bbd24cd8
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_directories/LinkDirectoriesLib.c
@@ -0,0 +1,7 @@
+#if defined(_WIN32)
+__declspec(dllexport)
+#endif
+ int flags_lib(void)
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/target_link_directories/subdir/CMakeLists.txt b/Tests/CMakeCommands/target_link_directories/subdir/CMakeLists.txt
new file mode 100644
index 000000000..7e7ad2a97
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_directories/subdir/CMakeLists.txt
@@ -0,0 +1,2 @@
+
+add_library(target_link_directories_5 SHARED EXCLUDE_FROM_ALL ../LinkDirectoriesLib.c)
diff --git a/Tests/CMakeCommands/target_link_libraries/SubDirA/CMakeLists.txt b/Tests/CMakeCommands/target_link_libraries/SubDirA/CMakeLists.txt
new file mode 100644
index 000000000..4dae10395
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_libraries/SubDirA/CMakeLists.txt
@@ -0,0 +1,15 @@
+add_executable(SubDirA SubDirA.c)
+
+# Link to a target imported in this directory that would not normally
+# be visible to the directory in which TopDir is defined.
+target_link_libraries(TopDir PUBLIC SameNameImported)
+
+# Link SubDirA to a target imported in this directory that has the same
+# name as a target imported in SubDirB's directory. SubDirB will also
+# tell us to link its copy. At compile time we verify both are linked.
+target_link_libraries(SubDirA PRIVATE SameNameImported)
+
+# Import a target with the same name as a target imported in SubDirB.
+# Distinguish this copy by having a unique usage requirement.
+add_library(SameNameImported IMPORTED INTERFACE)
+target_compile_definitions(SameNameImported INTERFACE DEF_SameNameImportedSubDirA)
diff --git a/Tests/CMakeCommands/target_link_libraries/SubDirA/SubDirA.c b/Tests/CMakeCommands/target_link_libraries/SubDirA/SubDirA.c
new file mode 100644
index 000000000..4706bb94e
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_libraries/SubDirA/SubDirA.c
@@ -0,0 +1,14 @@
+#ifndef DEF_SameNameImportedSubDirA
+# error "DEF_SameNameImportedSubDirA is not defined but should be!"
+#endif
+#ifndef DEF_SameNameImportedSubDirB
+# error "DEF_SameNameImportedSubDirB is not defined but should be!"
+#endif
+#ifdef DEF_TopDirImported
+# error "DEF_TopDirImported is defined but should not be!"
+#endif
+
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/target_link_libraries/SubDirB/CMakeLists.txt b/Tests/CMakeCommands/target_link_libraries/SubDirB/CMakeLists.txt
new file mode 100644
index 000000000..7c918e699
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_libraries/SubDirB/CMakeLists.txt
@@ -0,0 +1,15 @@
+add_executable(SubDirB SubDirB.c)
+
+# Link to a target imported in this directory that would not normally
+# be visible to the directory in which TopDir is defined.
+target_link_libraries(TopDir PUBLIC SameNameImported)
+
+# Link SubDirA to a target imported in this directory that has the same
+# name as a target imported in SubDirA's directory. We verify when
+# compiling SubDirA that it sees our target and its own.
+target_link_libraries(SubDirA PRIVATE SameNameImported)
+
+# Import a target with the same name as a target imported in SubDirA.
+# Distinguish this copy by having a unique usage requirement.
+add_library(SameNameImported IMPORTED INTERFACE)
+target_compile_definitions(SameNameImported INTERFACE DEF_SameNameImportedSubDirB)
diff --git a/Tests/CMakeCommands/target_link_libraries/SubDirB/SubDirB.c b/Tests/CMakeCommands/target_link_libraries/SubDirB/SubDirB.c
new file mode 100644
index 000000000..6e567298c
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_libraries/SubDirB/SubDirB.c
@@ -0,0 +1,14 @@
+#ifdef DEF_SameNameImportedSubDirA
+# error "DEF_SameNameImportedSubDirA is defined but should not be!"
+#endif
+#ifdef DEF_SameNameImportedSubDirB
+# error "DEF_SameNameImportedSubDirB is defined but should not be!"
+#endif
+#ifndef DEF_TopDirImported
+# error "DEF_TopDirImported is not defined but should be!"
+#endif
+
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/target_link_libraries/SubDirC/CMakeLists.txt b/Tests/CMakeCommands/target_link_libraries/SubDirC/CMakeLists.txt
new file mode 100644
index 000000000..54bcc5174
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_libraries/SubDirC/CMakeLists.txt
@@ -0,0 +1,9 @@
+add_library(SubDirC STATIC SubDirC.c)
+
+add_library(SubDirC1 INTERFACE)
+target_compile_definitions(SubDirC1 INTERFACE DEF_SubDirC1)
+
+add_library(SubDirC2 INTERFACE)
+target_compile_definitions(SubDirC2 INTERFACE DEF_SubDirC2)
+
+target_link_libraries(SubDirC PRIVATE SubDirC1)
diff --git a/Tests/CMakeCommands/target_link_libraries/SubDirC/SubDirC.c b/Tests/CMakeCommands/target_link_libraries/SubDirC/SubDirC.c
new file mode 100644
index 000000000..c5536dccd
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_libraries/SubDirC/SubDirC.c
@@ -0,0 +1,11 @@
+#ifndef DEF_SubDirC1
+# error "DEF_SubDirC1 not defined"
+#endif
+#ifndef DEF_SubDirC2
+# error "DEF_SubDirC2 not defined"
+#endif
+
+int SubDirC(void)
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/target_link_libraries/TopDir.c b/Tests/CMakeCommands/target_link_libraries/TopDir.c
new file mode 100644
index 000000000..d8066e5ca
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_libraries/TopDir.c
@@ -0,0 +1,20 @@
+#ifndef DEF_SameNameImportedSubDirA
+# error "DEF_SameNameImportedSubDirA is not defined but should be!"
+#endif
+#ifndef DEF_SameNameImportedSubDirB
+# error "DEF_SameNameImportedSubDirB is not defined but should be!"
+#endif
+#ifdef DEF_TopDirImported
+# error "DEF_TopDirImported is defined but should not be!"
+#endif
+#ifdef DEF_SubDirC1
+# error "DEF_SubDirC1 defined but should not be"
+#endif
+#ifdef DEF_SubDirC2
+# error "DEF_SubDirC2 defined but should not be"
+#endif
+
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/target_link_options/CMakeLists.txt b/Tests/CMakeCommands/target_link_options/CMakeLists.txt
new file mode 100644
index 000000000..e84d0410e
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_options/CMakeLists.txt
@@ -0,0 +1,34 @@
+
+cmake_minimum_required(VERSION 3.11)
+
+project(target_link_options LANGUAGES C)
+
+add_library(target_link_options SHARED LinkOptionsLib.c)
+# Test no items
+target_link_options(target_link_options PRIVATE)
+
+add_library(target_link_options_2 SHARED EXCLUDE_FROM_ALL LinkOptionsLib.c)
+target_link_options(target_link_options_2 PRIVATE -PRIVATE_FLAG INTERFACE -INTERFACE_FLAG)
+get_target_property(result target_link_options_2 LINK_OPTIONS)
+if (NOT result MATCHES "-PRIVATE_FLAG")
+ message(SEND_ERROR "target_link_options not populated the LINK_OPTIONS target property")
+endif()
+get_target_property(result target_link_options_2 INTERFACE_LINK_OPTIONS)
+if (NOT result MATCHES "-INTERFACE_FLAG")
+ message(SEND_ERROR "target_link_options not populated the INTERFACE_LINK_OPTIONS target property of shared library")
+endif()
+
+add_library(target_link_options_3 STATIC EXCLUDE_FROM_ALL LinkOptionsLib.c)
+target_link_options(target_link_options_3 INTERFACE -INTERFACE_FLAG)
+get_target_property(result target_link_options_3 INTERFACE_LINK_OPTIONS)
+if (NOT result MATCHES "-INTERFACE_FLAG")
+ message(SEND_ERROR "target_link_options not populated the INTERFACE_LINK_OPTIONS target property of static library")
+endif()
+
+add_library(target_link_options_4 SHARED EXCLUDE_FROM_ALL LinkOptionsLib.c)
+target_link_options(target_link_options_4 PRIVATE -PRIVATE_FLAG)
+target_link_options(target_link_options_4 BEFORE PRIVATE -BEFORE_PRIVATE_FLAG)
+get_target_property(result target_link_options_4 LINK_OPTIONS)
+if (NOT result MATCHES "-BEFORE_PRIVATE_FLAG.*-PRIVATE_FLAG")
+ message(SEND_ERROR "target_link_options not managing correctly 'BEFORE' keyword")
+endif()
diff --git a/Tests/CMakeCommands/target_link_options/LinkOptionsLib.c b/Tests/CMakeCommands/target_link_options/LinkOptionsLib.c
new file mode 100644
index 000000000..9bbd24cd8
--- /dev/null
+++ b/Tests/CMakeCommands/target_link_options/LinkOptionsLib.c
@@ -0,0 +1,7 @@
+#if defined(_WIN32)
+__declspec(dllexport)
+#endif
+ int flags_lib(void)
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/target_sources/CMakeLists.txt b/Tests/CMakeCommands/target_sources/CMakeLists.txt
new file mode 100644
index 000000000..ab14855c7
--- /dev/null
+++ b/Tests/CMakeCommands/target_sources/CMakeLists.txt
@@ -0,0 +1,36 @@
+
+cmake_minimum_required(VERSION 3.12)
+cmake_policy(SET CMP0076 NEW)
+
+project(target_sources)
+
+add_library(target_sources_lib)
+target_compile_definitions(target_sources_lib PRIVATE "-DIS_LIB")
+add_subdirectory(subdir)
+
+set(subdir_fullpath "${CMAKE_CURRENT_LIST_DIR}/subdir")
+
+get_property(target_sources_lib_property TARGET target_sources_lib PROPERTY SOURCES)
+if (NOT "$<1:${subdir_fullpath}/subdir_empty_1.cpp>" IN_LIST target_sources_lib_property)
+ message(SEND_ERROR "target_sources_lib: Generator expression to absolute sub directory file not found")
+endif()
+if (NOT "$<1:${subdir_fullpath}/../empty_1.cpp>" IN_LIST target_sources_lib_property)
+ message(SEND_ERROR "target_sources_lib: Generator expression to absolute main directory file not found")
+endif()
+if (NOT "${subdir_fullpath}/subdir_empty_2.cpp" IN_LIST target_sources_lib_property)
+ message(SEND_ERROR "target_sources_lib: Relative sub directory file not converted to absolute")
+endif()
+if (NOT "$<1:empty_2.cpp>" IN_LIST target_sources_lib_property)
+ message(SEND_ERROR "target_sources_lib: Generator expression to relative main directory file not found")
+endif()
+if (NOT "${subdir_fullpath}/../empty_3.cpp" IN_LIST target_sources_lib_property)
+ message(SEND_ERROR "target_sources_lib: Relative main directory file not converted to absolute")
+endif()
+
+add_executable(target_sources main.cpp)
+target_link_libraries(target_sources target_sources_lib)
+
+get_property(target_sources_property TARGET target_sources PROPERTY SOURCES)
+if (NOT "main.cpp" IN_LIST target_sources_property)
+ message(SEND_ERROR "target_sources: Relative main directory file converted to absolute")
+endif()
diff --git a/Tests/CMakeCommands/target_sources/empty_1.cpp b/Tests/CMakeCommands/target_sources/empty_1.cpp
new file mode 100644
index 000000000..01e5b07ae
--- /dev/null
+++ b/Tests/CMakeCommands/target_sources/empty_1.cpp
@@ -0,0 +1,21 @@
+#ifdef IS_LIB
+
+# ifdef _WIN32
+__declspec(dllexport)
+# endif
+ int internal_empty_1()
+{
+ return 0;
+}
+
+#else
+
+# ifdef _WIN32
+__declspec(dllexport)
+# endif
+ int empty_1()
+{
+ return 0;
+}
+
+#endif
diff --git a/Tests/CMakeCommands/target_sources/empty_2.cpp b/Tests/CMakeCommands/target_sources/empty_2.cpp
new file mode 100644
index 000000000..48ae8bb23
--- /dev/null
+++ b/Tests/CMakeCommands/target_sources/empty_2.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty_2()
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/target_sources/empty_3.cpp b/Tests/CMakeCommands/target_sources/empty_3.cpp
new file mode 100644
index 000000000..bd3a6d1c8
--- /dev/null
+++ b/Tests/CMakeCommands/target_sources/empty_3.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty_3()
+{
+ return 0;
+}
diff --git a/Tests/CMakeCommands/target_sources/main.cpp b/Tests/CMakeCommands/target_sources/main.cpp
new file mode 100644
index 000000000..622771cb9
--- /dev/null
+++ b/Tests/CMakeCommands/target_sources/main.cpp
@@ -0,0 +1,16 @@
+#include <iostream>
+
+int empty_1();
+int subdir_empty_1();
+int subdir_empty_2();
+
+int main()
+{
+ int e1 = empty_1();
+ int se1 = subdir_empty_1();
+ int se2 = subdir_empty_2();
+
+ std::cout << e1 << " " << se1 << " " << se2 << std::endl;
+
+ return 0;
+}
diff --git a/Tests/CMakeCommands/target_sources/subdir/CMakeLists.txt b/Tests/CMakeCommands/target_sources/subdir/CMakeLists.txt
new file mode 100644
index 000000000..f749f1d7a
--- /dev/null
+++ b/Tests/CMakeCommands/target_sources/subdir/CMakeLists.txt
@@ -0,0 +1,6 @@
+
+target_sources(target_sources_lib PUBLIC $<1:${CMAKE_CURRENT_LIST_DIR}/subdir_empty_1.cpp>
+ $<1:${CMAKE_CURRENT_LIST_DIR}/../empty_1.cpp>
+ subdir_empty_2.cpp
+ PRIVATE $<1:empty_2.cpp>
+ ../empty_3.cpp)
diff --git a/Tests/CMakeCommands/target_sources/subdir/subdir_empty_1.cpp b/Tests/CMakeCommands/target_sources/subdir/subdir_empty_1.cpp
new file mode 100644
index 000000000..3c61321a1
--- /dev/null
+++ b/Tests/CMakeCommands/target_sources/subdir/subdir_empty_1.cpp
@@ -0,0 +1,21 @@
+#ifdef IS_LIB
+
+# ifdef _WIN32
+__declspec(dllexport)
+# endif
+ int internal_subdir_empty_1()
+{
+ return 0;
+}
+
+#else
+
+# ifdef _WIN32
+__declspec(dllexport)
+# endif
+ int subdir_empty_1()
+{
+ return 0;
+}
+
+#endif
diff --git a/Tests/CMakeCommands/target_sources/subdir/subdir_empty_2.cpp b/Tests/CMakeCommands/target_sources/subdir/subdir_empty_2.cpp
new file mode 100644
index 000000000..47fa73697
--- /dev/null
+++ b/Tests/CMakeCommands/target_sources/subdir/subdir_empty_2.cpp
@@ -0,0 +1,21 @@
+#ifdef IS_LIB
+
+# ifdef _WIN32
+__declspec(dllexport)
+# endif
+ int internal_subdir_empty_2()
+{
+ return 0;
+}
+
+#else
+
+# ifdef _WIN32
+__declspec(dllexport)
+# endif
+ int subdir_empty_2()
+{
+ return 0;
+}
+
+#endif
diff --git a/Tests/CMakeLib/testAffinity.cxx b/Tests/CMakeLib/testAffinity.cxx
new file mode 100644
index 000000000..4b8228092
--- /dev/null
+++ b/Tests/CMakeLib/testAffinity.cxx
@@ -0,0 +1,18 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmAffinity.h"
+
+#include <cstddef>
+#include <iostream>
+#include <set>
+
+int main()
+{
+ std::set<size_t> cpus = cmAffinity::GetProcessorsAvailable();
+ if (!cpus.empty()) {
+ std::cout << "CPU affinity mask count is '" << cpus.size() << "'.\n";
+ } else {
+ std::cout << "CPU affinity not supported on this platform.\n";
+ }
+ return 0;
+}
diff --git a/Tests/CMakeLib/testArgumentParser.cxx b/Tests/CMakeLib/testArgumentParser.cxx
new file mode 100644
index 000000000..788fecee6
--- /dev/null
+++ b/Tests/CMakeLib/testArgumentParser.cxx
@@ -0,0 +1,148 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#include "cmArgumentParser.h"
+
+#include "cm_static_string_view.hxx"
+#include "cm_string_view.hxx"
+
+#include <initializer_list>
+#include <iostream>
+#include <string>
+#include <vector>
+
+namespace {
+
+struct Result
+{
+ bool Option1 = false;
+ bool Option2 = false;
+
+ std::string String1;
+ std::string String2;
+
+ std::vector<std::string> List1;
+ std::vector<std::string> List2;
+ std::vector<std::string> List3;
+
+ std::vector<std::vector<std::string>> Multi1;
+ std::vector<std::vector<std::string>> Multi2;
+ std::vector<std::vector<std::string>> Multi3;
+};
+
+std::initializer_list<cm::string_view> const args = {
+ /* clang-format off */
+ "OPTION_1", // option
+ "STRING_1", // string arg missing value
+ "STRING_2", "foo", "bar", // string arg + unparsed value
+ "LIST_1", // list arg missing values
+ "LIST_2", "foo", "bar", // list arg with 2 elems
+ "LIST_3", "bar", // list arg ...
+ "LIST_3", "foo", // ... with continuation
+ "MULTI_2", // multi list with 0 lists
+ "MULTI_3", "foo", "bar", // multi list with first list with two elems
+ "MULTI_3", "bar", "foo", // multi list with second list with two elems
+ /* clang-format on */
+};
+
+bool verifyResult(Result const& result,
+ std::vector<std::string> const& unparsedArguments,
+ std::vector<std::string> const& keywordsMissingValue)
+{
+ static std::vector<std::string> const foobar = { "foo", "bar" };
+ static std::vector<std::string> const barfoo = { "bar", "foo" };
+ static std::vector<std::string> const missing = { "STRING_1", "LIST_1" };
+
+#define ASSERT_TRUE(x) \
+ do { \
+ if (!(x)) { \
+ std::cout << "ASSERT_TRUE(" #x ") failed on line " << __LINE__ << "\n"; \
+ return false; \
+ } \
+ } while (false)
+
+ ASSERT_TRUE(result.Option1);
+ ASSERT_TRUE(!result.Option2);
+
+ ASSERT_TRUE(result.String1.empty());
+ ASSERT_TRUE(result.String2 == "foo");
+
+ ASSERT_TRUE(result.List1.empty());
+ ASSERT_TRUE(result.List2 == foobar);
+ ASSERT_TRUE(result.List3 == barfoo);
+
+ ASSERT_TRUE(result.Multi1.empty());
+ ASSERT_TRUE(result.Multi2.size() == 1);
+ ASSERT_TRUE(result.Multi2[0].empty());
+ ASSERT_TRUE(result.Multi3.size() == 2);
+ ASSERT_TRUE(result.Multi3[0] == foobar);
+ ASSERT_TRUE(result.Multi3[1] == barfoo);
+
+ ASSERT_TRUE(unparsedArguments.size() == 1);
+ ASSERT_TRUE(unparsedArguments[0] == "bar");
+ ASSERT_TRUE(keywordsMissingValue == missing);
+
+ return true;
+}
+
+bool testArgumentParserDynamic()
+{
+ Result result;
+ std::vector<std::string> unparsedArguments;
+ std::vector<std::string> keywordsMissingValue;
+
+ cmArgumentParser<void>{}
+ .Bind("OPTION_1"_s, result.Option1)
+ .Bind("OPTION_2"_s, result.Option2)
+ .Bind("STRING_1"_s, result.String1)
+ .Bind("STRING_2"_s, result.String2)
+ .Bind("LIST_1"_s, result.List1)
+ .Bind("LIST_2"_s, result.List2)
+ .Bind("LIST_3"_s, result.List3)
+ .Bind("MULTI_1"_s, result.Multi1)
+ .Bind("MULTI_2"_s, result.Multi2)
+ .Bind("MULTI_3"_s, result.Multi3)
+ .Parse(args, &unparsedArguments, &keywordsMissingValue);
+
+ return verifyResult(result, unparsedArguments, keywordsMissingValue);
+}
+
+bool testArgumentParserStatic()
+{
+ static auto const parser = //
+ cmArgumentParser<Result>{}
+ .Bind("OPTION_1"_s, &Result::Option1)
+ .Bind("OPTION_2"_s, &Result::Option2)
+ .Bind("STRING_1"_s, &Result::String1)
+ .Bind("STRING_2"_s, &Result::String2)
+ .Bind("LIST_1"_s, &Result::List1)
+ .Bind("LIST_2"_s, &Result::List2)
+ .Bind("LIST_3"_s, &Result::List3)
+ .Bind("MULTI_1"_s, &Result::Multi1)
+ .Bind("MULTI_2"_s, &Result::Multi2)
+ .Bind("MULTI_3"_s, &Result::Multi3);
+
+ std::vector<std::string> unparsedArguments;
+ std::vector<std::string> keywordsMissingValue;
+ Result const result =
+ parser.Parse(args, &unparsedArguments, &keywordsMissingValue);
+
+ return verifyResult(result, unparsedArguments, keywordsMissingValue);
+}
+
+} // namespace
+
+int testArgumentParser(int /*unused*/, char* /*unused*/ [])
+{
+ if (!testArgumentParserDynamic()) {
+ std::cout << "While executing testArgumentParserDynamic().\n";
+ return -1;
+ }
+
+ if (!testArgumentParserStatic()) {
+ std::cout << "While executing testArgumentParserStatic().\n";
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/Tests/CMakeLib/testRange.cxx b/Tests/CMakeLib/testRange.cxx
new file mode 100644
index 000000000..b26b07b8c
--- /dev/null
+++ b/Tests/CMakeLib/testRange.cxx
@@ -0,0 +1,45 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#include "cmRange.h"
+
+#include <iostream>
+#include <string>
+#include <vector>
+
+#define ASSERT_TRUE(x) \
+ do { \
+ if (!(x)) { \
+ std::cout << "ASSERT_TRUE(" #x ") failed on line " << __LINE__ << "\n"; \
+ return -1; \
+ } \
+ } while (false)
+
+int testRange(int /*unused*/, char* /*unused*/ [])
+{
+ std::vector<int> const testData = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+
+ ASSERT_TRUE(!cmMakeRange(testData).empty());
+ ASSERT_TRUE(cmMakeRange(testData).size() == 10);
+
+ ASSERT_TRUE(!cmMakeRange(testData).advance(5).empty());
+ ASSERT_TRUE(cmMakeRange(testData).advance(5).size() == 5);
+
+ ASSERT_TRUE(cmMakeRange(testData).advance(5).retreat(5).empty());
+ ASSERT_TRUE(cmMakeRange(testData).advance(5).retreat(5).size() == 0);
+
+ ASSERT_TRUE(cmMakeRange(testData).any_of([](int n) { return n % 3 == 0; }));
+ ASSERT_TRUE(cmMakeRange(testData).all_of([](int n) { return n < 11; }));
+ ASSERT_TRUE(cmMakeRange(testData).none_of([](int n) { return n > 11; }));
+
+ std::vector<int> const evenData = { 2, 4, 6, 8, 10 };
+ ASSERT_TRUE(cmMakeRange(testData).filter([](int n) { return n % 2 == 0; }) ==
+ cmMakeRange(evenData));
+
+ std::vector<std::string> const stringRange = { "1", "2", "3", "4", "5" };
+ ASSERT_TRUE(cmMakeRange(testData)
+ .transform([](int n) { return std::to_string(n); })
+ .retreat(5) == cmMakeRange(stringRange));
+
+ return 0;
+}
diff --git a/Tests/CMakeLib/testString.cxx b/Tests/CMakeLib/testString.cxx
new file mode 100644
index 000000000..af5e41ed3
--- /dev/null
+++ b/Tests/CMakeLib/testString.cxx
@@ -0,0 +1,1347 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#include "cmString.hxx"
+
+#include "cm_static_string_view.hxx"
+#include "cm_string_view.hxx"
+
+#include <cstring>
+#include <iostream>
+#include <iterator>
+#include <sstream>
+#include <stdexcept>
+#include <string>
+#include <type_traits>
+#include <utility>
+
+#define ASSERT_TRUE(x) \
+ do { \
+ if (!(x)) { \
+ std::cout << "ASSERT_TRUE(" #x ") failed on line " << __LINE__ << "\n"; \
+ return false; \
+ } \
+ } while (false)
+
+static bool testConstructDefault()
+{
+ std::cout << "testConstructDefault()\n";
+ cm::String str;
+ cm::String const& str_const = str;
+ ASSERT_TRUE(bool(str_const) == false);
+ ASSERT_TRUE(str_const.data() == nullptr);
+ ASSERT_TRUE(str_const.size() == 0);
+ ASSERT_TRUE(str_const.empty());
+ ASSERT_TRUE(str_const.is_stable());
+ ASSERT_TRUE(str.c_str() == nullptr);
+ ASSERT_TRUE(str.str().empty());
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static bool testFromNullPtr(cm::String str)
+{
+ cm::String const& str_const = str;
+ ASSERT_TRUE(bool(str_const) == false);
+ ASSERT_TRUE(str_const.data() == nullptr);
+ ASSERT_TRUE(str_const.size() == 0);
+ ASSERT_TRUE(str_const.empty());
+ ASSERT_TRUE(str_const.is_stable());
+ ASSERT_TRUE(str.c_str() == nullptr);
+ ASSERT_TRUE(str.str().empty());
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static bool testConstructFromNullPtr()
+{
+ std::cout << "testConstructFromNullPtr()\n";
+ return testFromNullPtr(nullptr);
+}
+
+static bool testAssignFromNullPtr()
+{
+ std::cout << "testAssignFromNullPtr()\n";
+ cm::String str;
+ str = nullptr;
+ return testFromNullPtr(str);
+}
+
+static bool testFromCStrNull(cm::String str)
+{
+ cm::String const& str_const = str;
+ ASSERT_TRUE(bool(str_const) == false);
+ ASSERT_TRUE(str_const.data() == nullptr);
+ ASSERT_TRUE(str_const.size() == 0);
+ ASSERT_TRUE(str_const.empty());
+ ASSERT_TRUE(str_const.is_stable());
+ ASSERT_TRUE(str.c_str() == nullptr);
+ ASSERT_TRUE(str.str().empty());
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static bool testConstructFromCStrNull()
+{
+ std::cout << "testConstructFromCStrNull()\n";
+ const char* null = nullptr;
+ return testFromCStrNull(null);
+}
+
+static bool testAssignFromCStrNull()
+{
+ std::cout << "testAssignFromCStrNull()\n";
+ const char* null = nullptr;
+ cm::String str;
+ str = null;
+ return testFromCStrNull(str);
+}
+
+static char const charArray[] = "abc";
+
+static bool testFromCharArray(cm::String str)
+{
+ cm::String const& str_const = str;
+ ASSERT_TRUE(str_const.data() != charArray);
+ ASSERT_TRUE(str_const.size() == sizeof(charArray) - 1);
+ ASSERT_TRUE(str_const.is_stable());
+ ASSERT_TRUE(str.c_str() != charArray);
+ ASSERT_TRUE(str.is_stable());
+ cm::String substr = str.substr(1);
+ cm::String const& substr_const = substr;
+ ASSERT_TRUE(substr_const.data() != &charArray[1]);
+ ASSERT_TRUE(substr_const.size() == 2);
+ ASSERT_TRUE(!substr_const.is_stable());
+ ASSERT_TRUE(substr.c_str() != &charArray[1]);
+ ASSERT_TRUE(!substr.is_stable());
+ return true;
+}
+
+static bool testConstructFromCharArray()
+{
+ std::cout << "testConstructFromCharArray()\n";
+ return testFromCharArray(charArray);
+}
+
+static bool testAssignFromCharArray()
+{
+ std::cout << "testAssignFromCharArray()\n";
+ cm::String str;
+ str = charArray;
+ return testFromCharArray(str);
+}
+
+static const char* cstr = "abc";
+
+static bool testFromCStr(cm::String const& str)
+{
+ ASSERT_TRUE(str.data() != cstr);
+ ASSERT_TRUE(str.size() == 3);
+ ASSERT_TRUE(std::strncmp(str.data(), cstr, 3) == 0);
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static bool testConstructFromCStr()
+{
+ std::cout << "testConstructFromCStr()\n";
+ return testFromCStr(cstr);
+}
+
+static bool testAssignFromCStr()
+{
+ std::cout << "testAssignFromCStr()\n";
+ cm::String str;
+ str = cstr;
+ return testFromCStr(str);
+}
+
+static const std::string stdstr = "abc";
+
+static bool testFromStdString(cm::String const& str)
+{
+#if defined(_GLIBCXX_USE_CXX11_ABI) && _GLIBCXX_USE_CXX11_ABI
+ // It would be nice to check this everywhere, but several platforms
+ // still use a CoW implementation even in C++11.
+ ASSERT_TRUE(str.data() != stdstr.data());
+#endif
+ ASSERT_TRUE(str.size() == 3);
+ ASSERT_TRUE(std::strncmp(str.data(), stdstr.data(), 3) == 0);
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static bool testConstructFromStdString()
+{
+ std::cout << "testConstructFromStdString()\n";
+ return testFromStdString(stdstr);
+}
+
+static bool testAssignFromStdString()
+{
+ std::cout << "testAssignFromStdString()\n";
+ cm::String str;
+ str = stdstr;
+ return testFromStdString(str);
+}
+
+static bool testConstructFromView()
+{
+ std::cout << "testConstructFromView()\n";
+ cm::string_view view = cstr;
+ return testFromCStr(view);
+}
+
+static bool testAssignFromView()
+{
+ std::cout << "testAssignFromView()\n";
+ cm::string_view view = cstr;
+ cm::String str;
+ str = view;
+ return testFromCStr(str);
+}
+
+static bool testFromChar(cm::String const& str)
+{
+ ASSERT_TRUE(str.size() == 1);
+ ASSERT_TRUE(std::strncmp(str.data(), "a", 1) == 0);
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static bool testConstructFromChar()
+{
+ std::cout << "testConstructFromChar()\n";
+ return testFromChar('a');
+}
+
+static bool testAssignFromChar()
+{
+ std::cout << "testAssignFromChar()\n";
+ cm::String str;
+ str = 'a';
+ return testFromChar(str);
+}
+
+static bool testConstructFromInitList()
+{
+ std::cout << "testConstructFromInitList()\n";
+ cm::String const str{ 'a', 'b', 'c' };
+ ASSERT_TRUE(str.size() == 3);
+ ASSERT_TRUE(std::strncmp(str.data(), "abc", 3) == 0);
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static bool testAssignFromInitList()
+{
+ std::cout << "testAssignFromInitList()\n";
+ cm::String str;
+ str = { 'a', 'b', 'c' };
+ ASSERT_TRUE(str.size() == 3);
+ ASSERT_TRUE(std::strncmp(str.data(), "abc", 3) == 0);
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static bool testConstructFromBuffer()
+{
+ std::cout << "testConstructFromBuffer()\n";
+ cm::String const str(cstr, 3);
+ return testFromCStr(str);
+}
+
+static bool testConstructFromInputIterator()
+{
+ std::cout << "testConstructFromInputIterator()\n";
+ cm::String const str(cstr, cstr + 3);
+ ASSERT_TRUE(str.data() != cstr);
+ ASSERT_TRUE(str.size() == 3);
+ ASSERT_TRUE(std::strncmp(str.data(), cstr, 3) == 0);
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static bool testConstructFromN()
+{
+ std::cout << "testConstructFromN()\n";
+ cm::String const str(3, 'a');
+ ASSERT_TRUE(str.size() == 3);
+ ASSERT_TRUE(std::strncmp(str.data(), "aaa", 3) == 0);
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static const auto staticStringView = "abc"_s;
+
+static bool testFromStaticStringView(cm::String str)
+{
+ cm::String const& str_const = str;
+ ASSERT_TRUE(str_const.data() == staticStringView.data());
+ ASSERT_TRUE(str_const.size() == staticStringView.size());
+ ASSERT_TRUE(!str_const.is_stable());
+ ASSERT_TRUE(str.c_str() == staticStringView);
+ ASSERT_TRUE(!str.is_stable());
+ cm::String substr = str.substr(1);
+ cm::String const& substr_const = substr;
+ ASSERT_TRUE(substr_const.data() == &staticStringView[1]);
+ ASSERT_TRUE(substr_const.size() == 2);
+ ASSERT_TRUE(!substr_const.is_stable());
+ ASSERT_TRUE(substr.c_str() == &staticStringView[1]);
+ ASSERT_TRUE(!substr.is_stable());
+ return true;
+}
+
+static bool testConstructFromStaticStringView()
+{
+ std::cout << "testConstructFromStaticStringView()\n";
+ return testFromStaticStringView(staticStringView);
+}
+
+static bool testAssignFromStaticStringView()
+{
+ std::cout << "testAssignFromStaticStringView()\n";
+ cm::String str;
+ str = staticStringView;
+ return testFromStaticStringView(str);
+}
+
+static bool testConstructCopy()
+{
+ std::cout << "testConstructCopy()\n";
+ cm::String s1 = std::string("abc");
+ cm::String s2 = s1;
+ ASSERT_TRUE(s1.data() == s2.data());
+ ASSERT_TRUE(s1.size() == 3);
+ ASSERT_TRUE(s2.size() == 3);
+ ASSERT_TRUE(std::strncmp(s2.data(), "abc", 3) == 0);
+ ASSERT_TRUE(s1.is_stable());
+ ASSERT_TRUE(s2.is_stable());
+ return true;
+}
+
+static bool testConstructMove()
+{
+ std::cout << "testConstructMove()\n";
+ cm::String s1 = std::string("abc");
+ cm::String s2 = std::move(s1);
+ ASSERT_TRUE(s1.data() == nullptr);
+ ASSERT_TRUE(s1.size() == 0);
+ ASSERT_TRUE(s2.size() == 3);
+ ASSERT_TRUE(std::strncmp(s2.data(), "abc", 3) == 0);
+ ASSERT_TRUE(s1.is_stable());
+ ASSERT_TRUE(s2.is_stable());
+ return true;
+}
+
+static bool testAssignCopy()
+{
+ std::cout << "testAssignCopy()\n";
+ cm::String s1 = std::string("abc");
+ cm::String s2;
+ s2 = s1;
+ ASSERT_TRUE(s1.data() == s2.data());
+ ASSERT_TRUE(s1.size() == 3);
+ ASSERT_TRUE(s2.size() == 3);
+ ASSERT_TRUE(std::strncmp(s2.data(), "abc", 3) == 0);
+ ASSERT_TRUE(s1.is_stable());
+ ASSERT_TRUE(s2.is_stable());
+ return true;
+}
+
+static bool testAssignMove()
+{
+ std::cout << "testAssignMove()\n";
+ cm::String s1 = std::string("abc");
+ cm::String s2;
+ s2 = std::move(s1);
+ ASSERT_TRUE(s1.data() == nullptr);
+ ASSERT_TRUE(s1.size() == 0);
+ ASSERT_TRUE(s2.size() == 3);
+ ASSERT_TRUE(std::strncmp(s2.data(), "abc", 3) == 0);
+ ASSERT_TRUE(s1.is_stable());
+ ASSERT_TRUE(s2.is_stable());
+ return true;
+}
+
+static bool testOperatorBool()
+{
+ std::cout << "testOperatorBool()\n";
+ cm::String str;
+ ASSERT_TRUE(!str);
+ str = "";
+ ASSERT_TRUE(str);
+ str = static_cast<const char*>(nullptr);
+ ASSERT_TRUE(!str);
+ str = std::string();
+ ASSERT_TRUE(str);
+ str = nullptr;
+ ASSERT_TRUE(!str);
+ return true;
+}
+
+static bool testOperatorIndex()
+{
+ std::cout << "testOperatorIndex()\n";
+ cm::String str = "abc";
+ ASSERT_TRUE(str[0] == 'a');
+ ASSERT_TRUE(str[1] == 'b');
+ ASSERT_TRUE(str[2] == 'c');
+ return true;
+}
+
+static bool testOperatorPlusEqual()
+{
+ std::cout << "testOperatorPlusEqual()\n";
+ cm::String str = "a";
+ str += "b";
+ {
+ const char* c = "c";
+ str += c;
+ }
+ str += 'd';
+ str += std::string("e");
+ str += cm::string_view("f", 1);
+ str += cm::String("g");
+ ASSERT_TRUE(str.size() == 7);
+ ASSERT_TRUE(std::strncmp(str.data(), "abcdefg", 7) == 0);
+ ASSERT_TRUE(str.is_stable());
+ return true;
+}
+
+static bool testOperatorCompare()
+{
+ std::cout << "testOperatorCompare()\n";
+ cm::String str = "b";
+ {
+ ASSERT_TRUE(str == "b");
+ ASSERT_TRUE("b" == str);
+ ASSERT_TRUE(str != "a");
+ ASSERT_TRUE("a" != str);
+ ASSERT_TRUE(str < "c");
+ ASSERT_TRUE("a" < str);
+ ASSERT_TRUE(str > "a");
+ ASSERT_TRUE("c" > str);
+ ASSERT_TRUE(str <= "b");
+ ASSERT_TRUE("b" <= str);
+ ASSERT_TRUE(str >= "b");
+ ASSERT_TRUE("b" >= str);
+ }
+ {
+ const char* a = "a";
+ const char* b = "b";
+ const char* c = "c";
+ ASSERT_TRUE(str == b);
+ ASSERT_TRUE(b == str);
+ ASSERT_TRUE(str != a);
+ ASSERT_TRUE(a != str);
+ ASSERT_TRUE(str < c);
+ ASSERT_TRUE(a < str);
+ ASSERT_TRUE(str > a);
+ ASSERT_TRUE(c > str);
+ ASSERT_TRUE(str <= b);
+ ASSERT_TRUE(b <= str);
+ ASSERT_TRUE(str >= b);
+ ASSERT_TRUE(b >= str);
+ }
+ {
+ ASSERT_TRUE(str == 'b');
+ ASSERT_TRUE('b' == str);
+ ASSERT_TRUE(str != 'a');
+ ASSERT_TRUE('a' != str);
+ ASSERT_TRUE(str < 'c');
+ ASSERT_TRUE('a' < str);
+ ASSERT_TRUE(str > 'a');
+ ASSERT_TRUE('c' > str);
+ ASSERT_TRUE(str <= 'b');
+ ASSERT_TRUE('b' <= str);
+ ASSERT_TRUE(str >= 'b');
+ ASSERT_TRUE('b' >= str);
+ }
+ {
+ std::string const a = "a";
+ std::string const b = "b";
+ std::string const c = "c";
+ ASSERT_TRUE(str == b);
+ ASSERT_TRUE(b == str);
+ ASSERT_TRUE(str != a);
+ ASSERT_TRUE(a != str);
+ ASSERT_TRUE(str < c);
+ ASSERT_TRUE(a < str);
+ ASSERT_TRUE(str > a);
+ ASSERT_TRUE(c > str);
+ ASSERT_TRUE(str <= b);
+ ASSERT_TRUE(b <= str);
+ ASSERT_TRUE(str >= b);
+ ASSERT_TRUE(b >= str);
+ }
+ {
+ cm::string_view const a("a", 1);
+ cm::string_view const b("b", 1);
+ cm::string_view const c("c", 1);
+ ASSERT_TRUE(str == b);
+ ASSERT_TRUE(b == str);
+ ASSERT_TRUE(str != a);
+ ASSERT_TRUE(a != str);
+ ASSERT_TRUE(str < c);
+ ASSERT_TRUE(a < str);
+ ASSERT_TRUE(str > a);
+ ASSERT_TRUE(c > str);
+ ASSERT_TRUE(str <= b);
+ ASSERT_TRUE(b <= str);
+ ASSERT_TRUE(str >= b);
+ ASSERT_TRUE(b >= str);
+ }
+ {
+ cm::String const a("a");
+ cm::String const b("b");
+ cm::String const c("c");
+ ASSERT_TRUE(str == b);
+ ASSERT_TRUE(b == str);
+ ASSERT_TRUE(str != a);
+ ASSERT_TRUE(a != str);
+ ASSERT_TRUE(str < c);
+ ASSERT_TRUE(a < str);
+ ASSERT_TRUE(str > a);
+ ASSERT_TRUE(c > str);
+ ASSERT_TRUE(str <= b);
+ ASSERT_TRUE(b <= str);
+ ASSERT_TRUE(str >= b);
+ ASSERT_TRUE(b >= str);
+ }
+ return true;
+}
+
+static bool testOperatorStream()
+{
+ std::cout << "testOperatorStream()\n";
+ std::ostringstream ss;
+ ss << "a" << cm::String("b") << 'c';
+ ASSERT_TRUE(ss.str() == "abc");
+ return true;
+}
+
+static bool testOperatorStdStringPlusEqual()
+{
+ std::cout << "testOperatorStdStringPlusEqual()\n";
+ std::string s = "a";
+ s += cm::String("b");
+ ASSERT_TRUE(s == "ab");
+ return true;
+}
+
+static bool testMethod_borrow()
+{
+ std::cout << "testMethod_borrow()\n";
+ std::string s = "abc";
+ cm::String str = cm::String::borrow(s);
+ ASSERT_TRUE(str.data() == s.data());
+ ASSERT_TRUE(str.size() == s.size());
+ ASSERT_TRUE(str == s);
+ return true;
+}
+
+static bool testMethod_view()
+{
+ std::cout << "testMethod_view()\n";
+ cm::String str;
+ ASSERT_TRUE(str.view().data() == nullptr);
+ ASSERT_TRUE(str.view().size() == 0);
+ str = charArray;
+ ASSERT_TRUE(str.view().data() != charArray);
+ ASSERT_TRUE(str.view().size() == sizeof(charArray) - 1);
+ str = std::string("abc");
+ ASSERT_TRUE(str.view().size() == 3);
+ ASSERT_TRUE(strncmp(str.view().data(), "abc", 3) == 0);
+ return true;
+}
+
+static bool testMethod_empty()
+{
+ std::cout << "testMethod_empty()\n";
+ cm::String str;
+ ASSERT_TRUE(str.empty());
+ str = "";
+ ASSERT_TRUE(str.empty());
+ str = "abc";
+ ASSERT_TRUE(!str.empty());
+ str = std::string();
+ ASSERT_TRUE(str.empty());
+ str = std::string("abc");
+ ASSERT_TRUE(!str.empty());
+ return true;
+}
+
+static bool testMethod_length()
+{
+ std::cout << "testMethod_length()\n";
+ cm::String str;
+ ASSERT_TRUE(str.length() == 0);
+ str = "";
+ ASSERT_TRUE(str.length() == 0);
+ str = "abc";
+ ASSERT_TRUE(str.length() == 3);
+ str = std::string();
+ ASSERT_TRUE(str.length() == 0);
+ str = std::string("abc");
+ ASSERT_TRUE(str.length() == 3);
+ return true;
+}
+
+static bool testMethod_at()
+{
+ std::cout << "testMethod_at()\n";
+ cm::String str = "abc";
+ ASSERT_TRUE(str.at(0) == 'a');
+ ASSERT_TRUE(str.at(1) == 'b');
+ ASSERT_TRUE(str.at(2) == 'c');
+ bool except_out_of_range = false;
+ try {
+ str.at(3);
+ } catch (std::out_of_range&) {
+ except_out_of_range = true;
+ }
+ ASSERT_TRUE(except_out_of_range);
+ return true;
+}
+
+static bool testMethod_front_back()
+{
+ std::cout << "testMethod_front_back()\n";
+ cm::String str = "abc";
+ ASSERT_TRUE(str.front() == 'a');
+ ASSERT_TRUE(str.back() == 'c');
+ return true;
+}
+
+static bool testMethodIterators()
+{
+ std::cout << "testMethodIterators()\n";
+ cm::String str = "abc";
+ ASSERT_TRUE(*str.begin() == 'a');
+ ASSERT_TRUE(*(str.end() - 1) == 'c');
+ ASSERT_TRUE(str.end() - str.begin() == 3);
+ ASSERT_TRUE(*str.cbegin() == 'a');
+ ASSERT_TRUE(*(str.cend() - 1) == 'c');
+ ASSERT_TRUE(str.cend() - str.cbegin() == 3);
+ ASSERT_TRUE(*str.rbegin() == 'c');
+ ASSERT_TRUE(*(str.rend() - 1) == 'a');
+ ASSERT_TRUE(str.rend() - str.rbegin() == 3);
+ ASSERT_TRUE(*str.crbegin() == 'c');
+ ASSERT_TRUE(*(str.crend() - 1) == 'a');
+ ASSERT_TRUE(str.crend() - str.crbegin() == 3);
+ return true;
+}
+
+static bool testMethod_clear()
+{
+ std::cout << "testMethod_clear()\n";
+ cm::String str = "abc";
+ ASSERT_TRUE(!str.empty());
+ str.clear();
+ ASSERT_TRUE(str.empty());
+ return true;
+}
+
+static bool testMethod_insert()
+{
+ std::cout << "testMethod_insert()\n";
+ cm::String str = "abc";
+ str.insert(1, 2, 'd').insert(0, 1, '_');
+ ASSERT_TRUE(str.size() == 6);
+ ASSERT_TRUE(std::strncmp(str.data(), "_addbc", 6) == 0);
+ return true;
+}
+
+static bool testMethod_erase()
+{
+ std::cout << "testMethod_erase()\n";
+ cm::String str = "abcdefg";
+ str.erase(5).erase(1, 2);
+ ASSERT_TRUE(str.size() == 3);
+ ASSERT_TRUE(std::strncmp(str.data(), "ade", 3) == 0);
+ return true;
+}
+
+static bool testMethod_push_back()
+{
+ std::cout << "testMethod_push_back()\n";
+ cm::String str = "abc";
+ str.push_back('d');
+ ASSERT_TRUE(str == "abcd");
+ return true;
+}
+
+static bool testMethod_pop_back()
+{
+ std::cout << "testMethod_pop_back()\n";
+ cm::String str = "abc";
+ str.pop_back();
+ ASSERT_TRUE(str == "ab");
+ return true;
+}
+
+static bool testMethod_replace()
+{
+ std::cout << "testMethod_replace()\n";
+ {
+ cm::String str = "abcd";
+ const char* bc = "bc";
+ ASSERT_TRUE(str.replace(1, 2, "BC") == "aBCd");
+ ASSERT_TRUE(str.replace(1, 2, bc) == "abcd");
+ ASSERT_TRUE(str.replace(1, 2, 'x') == "axd");
+ ASSERT_TRUE(str.replace(1, 1, std::string("bc")) == "abcd");
+ ASSERT_TRUE(str.replace(1, 2, cm::string_view("BC", 2)) == "aBCd");
+ ASSERT_TRUE(str.replace(1, 2, cm::String("bc")) == "abcd");
+ }
+ {
+ cm::String str = "abcd";
+ const char* bc = "bc";
+ ASSERT_TRUE(str.replace(str.begin() + 1, str.begin() + 3, "BC") == "aBCd");
+ ASSERT_TRUE(str.replace(str.begin() + 1, str.begin() + 3, bc) == "abcd");
+ ASSERT_TRUE(str.replace(str.begin() + 1, str.begin() + 3, 'x') == "axd");
+ ASSERT_TRUE(str.replace(str.begin() + 1, str.begin() + 2,
+ std::string("bc")) == "abcd");
+ ASSERT_TRUE(str.replace(str.begin() + 1, str.begin() + 3,
+ cm::string_view("BC", 2)) == "aBCd");
+ ASSERT_TRUE(str.replace(str.begin() + 1, str.begin() + 3,
+ cm::String("bc")) == "abcd");
+ }
+ {
+ cm::String str = "abcd";
+ const char* bc = "_bc";
+ ASSERT_TRUE(str.replace(1, 2, "_BC_", 1, 2) == "aBCd");
+ ASSERT_TRUE(str.replace(1, 2, bc, 1) == "abcd");
+ ASSERT_TRUE(str.replace(1, 2, 'x', 0) == "axd");
+ ASSERT_TRUE(str.replace(1, 1, std::string("_bc_"), 1, 2) == "abcd");
+ ASSERT_TRUE(str.replace(1, 2, cm::string_view("_BC", 3), 1) == "aBCd");
+ ASSERT_TRUE(str.replace(1, 2, cm::String("_bc_"), 1, 2) == "abcd");
+ }
+ {
+ cm::String str = "abcd";
+ const char* bc = "_bc_";
+ ASSERT_TRUE(str.replace(1, 2, 2, 'x') == "axxd");
+ ASSERT_TRUE(str.replace(str.begin() + 1, str.begin() + 3, 2, 'y') ==
+ "ayyd");
+ ASSERT_TRUE(
+ str.replace(str.begin() + 1, str.begin() + 3, bc + 1, bc + 3) == "abcd");
+ }
+ return true;
+}
+
+static bool testMethod_copy()
+{
+ std::cout << "testMethod_copy()\n";
+ cm::String str = "abc";
+ char dest[2];
+ cm::String::size_type n = str.copy(dest, 2, 1);
+ ASSERT_TRUE(n == 2);
+ ASSERT_TRUE(std::strncmp(dest, "bc", 2) == 0);
+ n = str.copy(dest, 2);
+ ASSERT_TRUE(n == 2);
+ ASSERT_TRUE(std::strncmp(dest, "ab", 2) == 0);
+ return true;
+}
+
+static bool testMethod_resize()
+{
+ std::cout << "testMethod_resize()\n";
+ cm::String str = "abc";
+ str.resize(3);
+ ASSERT_TRUE(str == "abc");
+ str.resize(2);
+ ASSERT_TRUE(str == "ab");
+ str.resize(3, 'c');
+ ASSERT_TRUE(str == "abc");
+ return true;
+}
+
+static bool testMethod_swap()
+{
+ std::cout << "testMethod_swap()\n";
+ cm::String str1 = std::string("1");
+ cm::String str2 = std::string("2");
+ str1.swap(str2);
+ ASSERT_TRUE(str1 == "2");
+ ASSERT_TRUE(str2 == "1");
+ return true;
+}
+
+static bool testMethod_substr_AtEnd(cm::String str)
+{
+ cm::String substr = str.substr(1);
+ ASSERT_TRUE(substr.data() == str.data() + 1);
+ ASSERT_TRUE(substr.size() == 2);
+ ASSERT_TRUE(!substr.is_stable());
+
+ // c_str() at the end of the buffer does not internally mutate.
+ ASSERT_TRUE(std::strcmp(substr.c_str(), "bc") == 0);
+ ASSERT_TRUE(substr.c_str() == str.data() + 1);
+ ASSERT_TRUE(substr.data() == str.data() + 1);
+ ASSERT_TRUE(substr.size() == 2);
+ ASSERT_TRUE(!substr.is_stable());
+
+ // str() internally mutates.
+ ASSERT_TRUE(substr.str() == "bc");
+ ASSERT_TRUE(substr.is_stable());
+ ASSERT_TRUE(substr.data() != str.data() + 1);
+ ASSERT_TRUE(substr.size() == 2);
+ ASSERT_TRUE(substr.c_str() != str.data() + 1);
+ ASSERT_TRUE(std::strcmp(substr.c_str(), "bc") == 0);
+ return true;
+}
+
+static bool testMethod_substr_AtEndBorrowed()
+{
+ std::cout << "testMethod_substr_AtEndBorrowed()\n";
+ return testMethod_substr_AtEnd("abc"_s);
+}
+
+static bool testMethod_substr_AtEndOwned()
+{
+ std::cout << "testMethod_substr_AtEndOwned()\n";
+ return testMethod_substr_AtEnd(std::string("abc"));
+}
+
+static bool testMethod_substr_AtStart(cm::String str)
+{
+ {
+ cm::String substr = str.substr(0, 2);
+ ASSERT_TRUE(substr.data() == str.data());
+ ASSERT_TRUE(substr.size() == 2);
+
+ // c_str() not at the end of the buffer internally mutates.
+ const char* substr_c = substr.c_str();
+ ASSERT_TRUE(std::strcmp(substr_c, "ab") == 0);
+ ASSERT_TRUE(substr_c != str.data());
+ ASSERT_TRUE(substr.data() != str.data());
+ ASSERT_TRUE(substr.size() == 2);
+ ASSERT_TRUE(substr.is_stable());
+
+ // str() does not need to internally mutate after c_str() did so
+ ASSERT_TRUE(substr.str() == "ab");
+ ASSERT_TRUE(substr.is_stable());
+ ASSERT_TRUE(substr.data() == substr_c);
+ ASSERT_TRUE(substr.size() == 2);
+ ASSERT_TRUE(substr.c_str() == substr_c);
+ }
+
+ {
+ cm::String substr = str.substr(0, 2);
+ ASSERT_TRUE(substr.data() == str.data());
+ ASSERT_TRUE(substr.size() == 2);
+ ASSERT_TRUE(!substr.is_stable());
+
+ // str() internally mutates.
+ ASSERT_TRUE(substr.str() == "ab");
+ ASSERT_TRUE(substr.is_stable());
+ ASSERT_TRUE(substr.data() != str.data());
+ ASSERT_TRUE(substr.size() == 2);
+ ASSERT_TRUE(substr.c_str() != str.data());
+
+ // c_str() does not internally after str() did so
+ const char* substr_c = substr.c_str();
+ ASSERT_TRUE(std::strcmp(substr_c, "ab") == 0);
+ ASSERT_TRUE(substr_c == substr.data());
+ ASSERT_TRUE(substr.size() == 2);
+ ASSERT_TRUE(substr.is_stable());
+ }
+
+ return true;
+}
+
+static bool testMethod_substr_AtStartBorrowed()
+{
+ std::cout << "testMethod_substr_AtStartBorrowed()\n";
+ return testMethod_substr_AtStart("abc"_s);
+}
+
+static bool testMethod_substr_AtStartOwned()
+{
+ std::cout << "testMethod_substr_AtStartOwned()\n";
+ return testMethod_substr_AtStart(std::string("abc"));
+}
+
+static bool testMethod_compare()
+{
+ std::cout << "testMethod_compare()\n";
+ cm::String str = "b";
+ ASSERT_TRUE(str.compare("a") > 0);
+ ASSERT_TRUE(str.compare("b") == 0);
+ ASSERT_TRUE(str.compare("c") < 0);
+ {
+ const char* a = "a";
+ const char* b = "b";
+ const char* c = "c";
+ ASSERT_TRUE(str.compare(a) > 0);
+ ASSERT_TRUE(str.compare(b) == 0);
+ ASSERT_TRUE(str.compare(c) < 0);
+ }
+ ASSERT_TRUE(str.compare('a') > 0);
+ ASSERT_TRUE(str.compare('b') == 0);
+ ASSERT_TRUE(str.compare('c') < 0);
+ ASSERT_TRUE(str.compare(std::string("a")) > 0);
+ ASSERT_TRUE(str.compare(std::string("b")) == 0);
+ ASSERT_TRUE(str.compare(std::string("c")) < 0);
+ ASSERT_TRUE(str.compare(cm::string_view("a_", 1)) > 0);
+ ASSERT_TRUE(str.compare(cm::string_view("b_", 1)) == 0);
+ ASSERT_TRUE(str.compare(cm::string_view("c_", 1)) < 0);
+ ASSERT_TRUE(str.compare(cm::String("a")) > 0);
+ ASSERT_TRUE(str.compare(cm::String("b")) == 0);
+ ASSERT_TRUE(str.compare(cm::String("c")) < 0);
+ ASSERT_TRUE(str.compare(0, 1, cm::string_view("a", 1)) > 0);
+ ASSERT_TRUE(str.compare(1, 0, cm::string_view("", 0)) == 0);
+ ASSERT_TRUE(str.compare(0, 1, cm::string_view("ac", 2), 1, 1) < 0);
+ ASSERT_TRUE(str.compare(1, 0, "") == 0);
+ ASSERT_TRUE(str.compare(1, 0, "_", 0) == 0);
+ return true;
+}
+
+static bool testMethod_find()
+{
+ std::cout << "testMethod_find()\n";
+ cm::String str = "abcabc";
+ ASSERT_TRUE(str.find("a") == 0);
+ ASSERT_TRUE(str.find("a", 1) == 3);
+ {
+ const char* a = "a";
+ ASSERT_TRUE(str.find(a) == 0);
+ ASSERT_TRUE(str.find(a, 1) == 3);
+ }
+ ASSERT_TRUE(str.find('a') == 0);
+ ASSERT_TRUE(str.find('a', 1) == 3);
+ ASSERT_TRUE(str.find(std::string("a")) == 0);
+ ASSERT_TRUE(str.find(std::string("a"), 1) == 3);
+ ASSERT_TRUE(str.find(cm::string_view("a_", 1)) == 0);
+ ASSERT_TRUE(str.find(cm::string_view("a_", 1), 1) == 3);
+ ASSERT_TRUE(str.find(cm::String("a")) == 0);
+ ASSERT_TRUE(str.find(cm::String("a"), 1) == 3);
+ ASSERT_TRUE(str.find("ab_", 1, 2) == 3);
+ return true;
+}
+
+static bool testMethod_rfind()
+{
+ std::cout << "testMethod_rfind()\n";
+ cm::String str = "abcabc";
+ ASSERT_TRUE(str.rfind("a") == 3);
+ ASSERT_TRUE(str.rfind("a", 1) == 0);
+ {
+ const char* a = "a";
+ ASSERT_TRUE(str.rfind(a) == 3);
+ ASSERT_TRUE(str.rfind(a, 1) == 0);
+ }
+ ASSERT_TRUE(str.rfind('a') == 3);
+ ASSERT_TRUE(str.rfind('a', 1) == 0);
+ ASSERT_TRUE(str.rfind(std::string("a")) == 3);
+ ASSERT_TRUE(str.rfind(std::string("a"), 1) == 0);
+ ASSERT_TRUE(str.rfind(cm::string_view("a_", 1)) == 3);
+ ASSERT_TRUE(str.rfind(cm::string_view("a_", 1), 1) == 0);
+ ASSERT_TRUE(str.rfind(cm::String("a")) == 3);
+ ASSERT_TRUE(str.rfind(cm::String("a"), 1) == 0);
+ ASSERT_TRUE(str.rfind("ab_", 1, 2) == 0);
+ return true;
+}
+
+static bool testMethod_find_first_of()
+{
+ std::cout << "testMethod_find_first_of()\n";
+ cm::String str = "abcabc";
+ ASSERT_TRUE(str.find_first_of("_a") == 0);
+ ASSERT_TRUE(str.find_first_of("_a", 1) == 3);
+ {
+ const char* a = "_a";
+ ASSERT_TRUE(str.find_first_of(a) == 0);
+ ASSERT_TRUE(str.find_first_of(a, 1) == 3);
+ }
+ ASSERT_TRUE(str.find_first_of('a') == 0);
+ ASSERT_TRUE(str.find_first_of('a', 1) == 3);
+ ASSERT_TRUE(str.find_first_of(std::string("_a")) == 0);
+ ASSERT_TRUE(str.find_first_of(std::string("_a"), 1) == 3);
+ ASSERT_TRUE(str.find_first_of(cm::string_view("ba_", 1)) == 1);
+ ASSERT_TRUE(str.find_first_of(cm::string_view("ba_", 1), 2) == 4);
+ ASSERT_TRUE(str.find_first_of(cm::String("ab")) == 0);
+ ASSERT_TRUE(str.find_first_of(cm::String("ab"), 2) == 3);
+ ASSERT_TRUE(str.find_first_of("_ab", 1, 2) == 3);
+ return true;
+}
+
+static bool testMethod_find_first_not_of()
+{
+ std::cout << "testMethod_find_first_not_of()\n";
+ cm::String str = "abcabc";
+ ASSERT_TRUE(str.find_first_not_of("_a") == 1);
+ ASSERT_TRUE(str.find_first_not_of("_a", 2) == 2);
+ {
+ const char* a = "_a";
+ ASSERT_TRUE(str.find_first_not_of(a) == 1);
+ ASSERT_TRUE(str.find_first_not_of(a, 2) == 2);
+ }
+ ASSERT_TRUE(str.find_first_not_of('a') == 1);
+ ASSERT_TRUE(str.find_first_not_of('a', 2) == 2);
+ ASSERT_TRUE(str.find_first_not_of(std::string("_a")) == 1);
+ ASSERT_TRUE(str.find_first_not_of(std::string("_a"), 2) == 2);
+ ASSERT_TRUE(str.find_first_not_of(cm::string_view("ba_", 1)) == 0);
+ ASSERT_TRUE(str.find_first_not_of(cm::string_view("ba_", 1), 1) == 2);
+ ASSERT_TRUE(str.find_first_not_of(cm::String("_a")) == 1);
+ ASSERT_TRUE(str.find_first_not_of(cm::String("_a"), 2) == 2);
+ ASSERT_TRUE(str.find_first_not_of("_bca", 1, 3) == 3);
+ return true;
+}
+
+static bool testMethod_find_last_of()
+{
+ std::cout << "testMethod_find_last_of()\n";
+ cm::String str = "abcabc";
+ ASSERT_TRUE(str.find_last_of("_a") == 3);
+ ASSERT_TRUE(str.find_last_of("_a", 1) == 0);
+ {
+ const char* a = "_a";
+ ASSERT_TRUE(str.find_last_of(a) == 3);
+ ASSERT_TRUE(str.find_last_of(a, 1) == 0);
+ }
+ ASSERT_TRUE(str.find_last_of('a') == 3);
+ ASSERT_TRUE(str.find_last_of('a', 1) == 0);
+ ASSERT_TRUE(str.find_last_of(std::string("_a")) == 3);
+ ASSERT_TRUE(str.find_last_of(std::string("_a"), 1) == 0);
+ ASSERT_TRUE(str.find_last_of(cm::string_view("ba_", 1)) == 4);
+ ASSERT_TRUE(str.find_last_of(cm::string_view("ba_", 1), 2) == 1);
+ ASSERT_TRUE(str.find_last_of(cm::String("ab")) == 4);
+ ASSERT_TRUE(str.find_last_of(cm::String("ab"), 2) == 1);
+ ASSERT_TRUE(str.find_last_of("_ab", 1, 2) == 0);
+ return true;
+}
+
+static bool testMethod_find_last_not_of()
+{
+ std::cout << "testMethod_find_last_not_of()\n";
+ cm::String str = "abcabc";
+ ASSERT_TRUE(str.find_last_not_of("_a") == 5);
+ ASSERT_TRUE(str.find_last_not_of("_a", 1) == 1);
+ {
+ const char* a = "_a";
+ ASSERT_TRUE(str.find_last_not_of(a) == 5);
+ ASSERT_TRUE(str.find_last_not_of(a, 1) == 1);
+ }
+ ASSERT_TRUE(str.find_last_not_of('a') == 5);
+ ASSERT_TRUE(str.find_last_not_of('a', 1) == 1);
+ ASSERT_TRUE(str.find_last_not_of(std::string("_a")) == 5);
+ ASSERT_TRUE(str.find_last_not_of(std::string("_a"), 1) == 1);
+ ASSERT_TRUE(str.find_last_not_of(cm::string_view("cb_", 1)) == 4);
+ ASSERT_TRUE(str.find_last_not_of(cm::string_view("cb_", 1), 2) == 1);
+ ASSERT_TRUE(str.find_last_not_of(cm::String("_a")) == 5);
+ ASSERT_TRUE(str.find_last_not_of(cm::String("_a"), 1) == 1);
+ ASSERT_TRUE(str.find_last_not_of("cb_", 2, 2) == 0);
+ return true;
+}
+
+static bool testAddition()
+{
+ std::cout << "testAddition()\n";
+ {
+ ASSERT_TRUE(cm::String("a") + "b" == "ab");
+ ASSERT_TRUE("ab" == "a" + cm::String("b"));
+ ASSERT_TRUE("a" + cm::String("b") + "c" == "abc");
+ ASSERT_TRUE("abc" == "a" + cm::String("b") + "c");
+ ASSERT_TRUE("a" + (cm::String("b") + "c") + "d" == "abcd");
+ ASSERT_TRUE("abcd" == "a" + (cm::String("b") + "c") + "d");
+ }
+ {
+ ASSERT_TRUE(cm::String("a"_s) + "b"_s == "ab"_s);
+ ASSERT_TRUE("ab"_s == "a"_s + cm::String("b"_s));
+ ASSERT_TRUE("a"_s + cm::String("b"_s) + "c"_s == "abc"_s);
+ ASSERT_TRUE("abc"_s == "a"_s + cm::String("b"_s) + "c"_s);
+ ASSERT_TRUE("a"_s + (cm::String("b"_s) + "c"_s) + "d"_s == "abcd"_s);
+ ASSERT_TRUE("abcd"_s == "a"_s + (cm::String("b"_s) + "c"_s) + "d"_s);
+ }
+ {
+ const char* a = "a";
+ const char* b = "b";
+ const char* ab = "ab";
+ ASSERT_TRUE(cm::String(a) + b == ab);
+ ASSERT_TRUE(ab == a + cm::String(b));
+ const char* c = "c";
+ const char* abc = "abc";
+ ASSERT_TRUE(a + cm::String(b) + c == abc);
+ ASSERT_TRUE(abc == a + cm::String(b) + c);
+ const char* d = "d";
+ const char* abcd = "abcd";
+ ASSERT_TRUE(a + (cm::String(b) + c) + d == abcd);
+ ASSERT_TRUE(abcd == a + (cm::String(b) + c) + d);
+ }
+ {
+ ASSERT_TRUE(cm::String('a') + 'b' == "ab");
+ ASSERT_TRUE("ab" == 'a' + cm::String('b'));
+ ASSERT_TRUE('a' + cm::String('b') + 'c' == "abc");
+ ASSERT_TRUE("abc" == 'a' + cm::String('b') + 'c');
+ ASSERT_TRUE('a' + (cm::String('b') + 'c') + 'd' == "abcd");
+ ASSERT_TRUE("abcd" == 'a' + (cm::String('b') + 'c') + 'd');
+ }
+ {
+ std::string a = "a";
+ std::string b = "b";
+ std::string ab = "ab";
+ ASSERT_TRUE(cm::String(a) + b == ab);
+ ASSERT_TRUE(ab == a + cm::String(b));
+ std::string c = "c";
+ std::string abc = "abc";
+ ASSERT_TRUE(a + cm::String(b) + c == abc);
+ ASSERT_TRUE(abc == a + cm::String(b) + c);
+ std::string d = "d";
+ std::string abcd = "abcd";
+ ASSERT_TRUE(a + (cm::String(b) + c) + d == abcd);
+ ASSERT_TRUE(abcd == a + (cm::String(b) + c) + d);
+ }
+ {
+ cm::string_view a("a", 1);
+ cm::string_view b("b", 1);
+ cm::string_view ab("ab", 2);
+ ASSERT_TRUE(cm::String(a) + b == ab);
+ ASSERT_TRUE(ab == a + cm::String(b));
+ cm::string_view c("c", 1);
+ cm::string_view abc("abc", 3);
+ ASSERT_TRUE(a + cm::String(b) + c == abc);
+ ASSERT_TRUE(abc == a + cm::String(b) + c);
+ cm::string_view d("d", 1);
+ cm::string_view abcd("abcd", 4);
+ ASSERT_TRUE(a + (cm::String(b) + c) + d == abcd);
+ ASSERT_TRUE(abcd == a + (cm::String(b) + c) + d);
+ }
+ {
+ cm::String a = "a";
+ cm::String b = "b";
+ cm::String ab = "ab";
+ ASSERT_TRUE(a + b == ab);
+ ASSERT_TRUE(ab == a + b);
+ cm::String c = "c";
+ cm::String abc = "abc";
+ ASSERT_TRUE(a + cm::String(b) + c == abc);
+ ASSERT_TRUE(abc == a + cm::String(b) + c);
+ cm::String d = "d";
+ cm::String abcd = "abcd";
+ ASSERT_TRUE(a + (cm::String(b) + c) + d == abcd);
+ ASSERT_TRUE(abcd == a + (cm::String(b) + c) + d);
+ }
+ {
+ cm::String str;
+ str += "a" + cm::String("b") + 'c';
+ ASSERT_TRUE(str == "abc");
+ ASSERT_TRUE(str.is_stable());
+ }
+ {
+ std::string s;
+ s += "a" + cm::String("b") + 'c';
+ ASSERT_TRUE(s == "abc");
+ }
+ {
+ std::ostringstream ss;
+ ss << ("a" + cm::String("b") + 'c');
+ ASSERT_TRUE(ss.str() == "abc");
+ }
+ return true;
+}
+
+static bool testStability()
+{
+ std::cout << "testStability()\n";
+ cm::String str = "abc"_s;
+ ASSERT_TRUE(!str.is_stable());
+ ASSERT_TRUE(str.str_if_stable() == nullptr);
+ str.stabilize();
+ ASSERT_TRUE(str.is_stable());
+ std::string const* str_if_stable = str.str_if_stable();
+ ASSERT_TRUE(str_if_stable != nullptr);
+ ASSERT_TRUE(*str_if_stable == "abc");
+ str.stabilize();
+ ASSERT_TRUE(str.is_stable());
+ ASSERT_TRUE(str.str_if_stable() == str_if_stable);
+ return true;
+}
+
+int testString(int /*unused*/, char* /*unused*/ [])
+{
+ if (!testConstructDefault()) {
+ return 1;
+ }
+ if (!testConstructFromNullPtr()) {
+ return 1;
+ }
+ if (!testConstructFromCStrNull()) {
+ return 1;
+ }
+ if (!testConstructFromCharArray()) {
+ return 1;
+ }
+ if (!testConstructFromCStr()) {
+ return 1;
+ }
+ if (!testConstructFromStdString()) {
+ return 1;
+ }
+ if (!testConstructFromView()) {
+ return 1;
+ }
+ if (!testConstructFromChar()) {
+ return 1;
+ }
+ if (!testConstructFromInitList()) {
+ return 1;
+ }
+ if (!testConstructFromBuffer()) {
+ return 1;
+ }
+ if (!testConstructFromInputIterator()) {
+ return 1;
+ }
+ if (!testConstructFromN()) {
+ return 1;
+ }
+ if (!testConstructFromStaticStringView()) {
+ return 1;
+ }
+ if (!testConstructCopy()) {
+ return 1;
+ }
+ if (!testConstructMove()) {
+ return 1;
+ }
+ if (!testAssignCopy()) {
+ return 1;
+ }
+ if (!testAssignMove()) {
+ return 1;
+ }
+ if (!testAssignFromChar()) {
+ return 1;
+ }
+ if (!testAssignFromView()) {
+ return 1;
+ }
+ if (!testAssignFromStdString()) {
+ return 1;
+ }
+ if (!testAssignFromCStr()) {
+ return 1;
+ }
+ if (!testAssignFromCharArray()) {
+ return 1;
+ }
+ if (!testAssignFromCStrNull()) {
+ return 1;
+ }
+ if (!testAssignFromNullPtr()) {
+ return 1;
+ }
+ if (!testAssignFromInitList()) {
+ return 1;
+ }
+ if (!testAssignFromStaticStringView()) {
+ return 1;
+ }
+ if (!testOperatorBool()) {
+ return 1;
+ }
+ if (!testOperatorIndex()) {
+ return 1;
+ }
+ if (!testOperatorPlusEqual()) {
+ return 1;
+ }
+ if (!testOperatorCompare()) {
+ return 1;
+ }
+ if (!testOperatorStream()) {
+ return 1;
+ }
+ if (!testOperatorStdStringPlusEqual()) {
+ return 1;
+ }
+ if (!testMethod_borrow()) {
+ return 1;
+ }
+ if (!testMethod_view()) {
+ return 1;
+ }
+ if (!testMethod_empty()) {
+ return 1;
+ }
+ if (!testMethod_length()) {
+ return 1;
+ }
+ if (!testMethod_at()) {
+ return 1;
+ }
+ if (!testMethod_front_back()) {
+ return 1;
+ }
+ if (!testMethod_clear()) {
+ return 1;
+ }
+ if (!testMethod_insert()) {
+ return 1;
+ }
+ if (!testMethod_erase()) {
+ return 1;
+ }
+ if (!testMethod_push_back()) {
+ return 1;
+ }
+ if (!testMethod_pop_back()) {
+ return 1;
+ }
+ if (!testMethod_replace()) {
+ return 1;
+ }
+ if (!testMethod_copy()) {
+ return 1;
+ }
+ if (!testMethod_resize()) {
+ return 1;
+ }
+ if (!testMethod_swap()) {
+ return 1;
+ }
+ if (!testMethodIterators()) {
+ return 1;
+ }
+ if (!testMethod_substr_AtEndBorrowed()) {
+ return 1;
+ }
+ if (!testMethod_substr_AtEndOwned()) {
+ return 1;
+ }
+ if (!testMethod_substr_AtStartBorrowed()) {
+ return 1;
+ }
+ if (!testMethod_substr_AtStartOwned()) {
+ return 1;
+ }
+ if (!testMethod_compare()) {
+ return 1;
+ }
+ if (!testMethod_find()) {
+ return 1;
+ }
+ if (!testMethod_rfind()) {
+ return 1;
+ }
+ if (!testMethod_find_first_of()) {
+ return 1;
+ }
+ if (!testMethod_find_first_not_of()) {
+ return 1;
+ }
+ if (!testMethod_find_last_of()) {
+ return 1;
+ }
+ if (!testMethod_find_last_not_of()) {
+ return 1;
+ }
+ if (!testAddition()) {
+ return 1;
+ }
+ if (!testStability()) {
+ return 1;
+ }
+ return 0;
+}
diff --git a/Tests/CMakeLib/testUVProcessChain.cxx b/Tests/CMakeLib/testUVProcessChain.cxx
new file mode 100644
index 000000000..72ae60203
--- /dev/null
+++ b/Tests/CMakeLib/testUVProcessChain.cxx
@@ -0,0 +1,335 @@
+#include "cmUVProcessChain.h"
+
+#include "cmAlgorithms.h"
+#include "cmGetPipes.h"
+#include "cmUVHandlePtr.h"
+#include "cmUVStreambuf.h"
+
+#include "cm_uv.h"
+
+#include <algorithm>
+#include <functional>
+#include <iostream>
+#include <sstream>
+#include <string>
+#include <vector>
+
+#include <csignal>
+
+struct ExpectedStatus
+{
+ bool Finished;
+ bool MatchExitStatus;
+ bool MatchTermSignal;
+ cmUVProcessChain::Status Status;
+};
+
+static const std::vector<ExpectedStatus> status1 = {
+ { false, false, false, { 0, 0 } },
+ { false, false, false, { 0, 0 } },
+ { false, false, false, { 0, 0 } },
+};
+
+static const std::vector<ExpectedStatus> status2 = {
+ { true, true, true, { 0, 0 } },
+ { false, false, false, { 0, 0 } },
+ { false, false, false, { 0, 0 } },
+};
+
+static const std::vector<ExpectedStatus> status3 = {
+ { true, true, true, { 0, 0 } },
+ { true, true, true, { 1, 0 } },
+#ifdef _WIN32
+ { true, true, true, { 2, 0 } },
+#else
+ { true, false, true, { 0, SIGABRT } },
+#endif
+};
+
+bool operator==(const cmUVProcessChain::Status* actual,
+ const ExpectedStatus& expected)
+{
+ if (!expected.Finished) {
+ return !actual;
+ } else if (!actual) {
+ return false;
+ }
+ if (expected.MatchExitStatus &&
+ expected.Status.ExitStatus != actual->ExitStatus) {
+ return false;
+ }
+ if (expected.MatchTermSignal &&
+ expected.Status.TermSignal != actual->TermSignal) {
+ return false;
+ }
+ return true;
+}
+
+bool resultsMatch(const std::vector<const cmUVProcessChain::Status*>& actual,
+ const std::vector<ExpectedStatus>& expected)
+{
+ return actual.size() == expected.size() &&
+ std::equal(actual.begin(), actual.end(), expected.begin());
+}
+
+std::string getInput(std::istream& input)
+{
+ char buffer[1024];
+ std::ostringstream str;
+ do {
+ input.read(buffer, 1024);
+ str.write(buffer, input.gcount());
+ } while (input.gcount() > 0);
+ return str.str();
+}
+
+template <typename T>
+std::function<std::ostream&(std::ostream&)> printExpected(bool match,
+ const T& value)
+{
+ return [match, value](std::ostream& stream) -> std::ostream& {
+ if (match) {
+ stream << value;
+ } else {
+ stream << "*";
+ }
+ return stream;
+ };
+}
+
+std::ostream& operator<<(
+ std::ostream& stream,
+ const std::function<std::ostream&(std::ostream&)>& func)
+{
+ return func(stream);
+}
+
+void printResults(const std::vector<const cmUVProcessChain::Status*>& actual,
+ const std::vector<ExpectedStatus>& expected)
+{
+ std::cout << "Expected: " << std::endl;
+ for (auto const& e : expected) {
+ if (e.Finished) {
+ std::cout << " ExitStatus: "
+ << printExpected(e.MatchExitStatus, e.Status.ExitStatus)
+ << ", TermSignal: "
+ << printExpected(e.MatchTermSignal, e.Status.TermSignal)
+ << std::endl;
+ } else {
+ std::cout << " null" << std::endl;
+ }
+ }
+ std::cout << "Actual:" << std::endl;
+ for (auto const& a : actual) {
+ if (a) {
+ std::cout << " ExitStatus: " << a->ExitStatus
+ << ", TermSignal: " << a->TermSignal << std::endl;
+ } else {
+ std::cout << " null" << std::endl;
+ }
+ }
+}
+
+bool checkExecution(cmUVProcessChainBuilder& builder,
+ std::unique_ptr<cmUVProcessChain>& chain)
+{
+ std::vector<const cmUVProcessChain::Status*> status;
+
+ chain = cm::make_unique<cmUVProcessChain>(builder.Start());
+ if (!chain->Valid()) {
+ std::cout << "Valid() returned false, should be true" << std::endl;
+ return false;
+ }
+ status = chain->GetStatus();
+ if (!resultsMatch(status, status1)) {
+ std::cout << "GetStatus() did not produce expected output" << std::endl;
+ printResults(status, status1);
+ return false;
+ }
+
+ if (chain->Wait(6000)) {
+ std::cout << "Wait() returned true, should be false" << std::endl;
+ return false;
+ }
+ status = chain->GetStatus();
+ if (!resultsMatch(status, status2)) {
+ std::cout << "GetStatus() did not produce expected output" << std::endl;
+ printResults(status, status2);
+ return false;
+ }
+
+ if (!chain->Wait()) {
+ std::cout << "Wait() returned false, should be true" << std::endl;
+ return false;
+ }
+ status = chain->GetStatus();
+ if (!resultsMatch(status, status3)) {
+ std::cout << "GetStatus() did not produce expected output" << std::endl;
+ printResults(status, status3);
+ return false;
+ }
+
+ return true;
+}
+
+bool checkOutput(std::istream& outputStream, std::istream& errorStream)
+{
+ std::string output = getInput(outputStream);
+ if (output != "HELO WRD!") {
+ std::cout << "Output was \"" << output << "\", expected \"HELO WRD!\""
+ << std::endl;
+ return false;
+ }
+
+ std::string error = getInput(errorStream);
+ if (error.length() != 3 || error.find('1') == std::string::npos ||
+ error.find('2') == std::string::npos ||
+ error.find('3') == std::string::npos) {
+ std::cout << "Error was \"" << error << "\", expected \"123\""
+ << std::endl;
+ return false;
+ }
+
+ return true;
+}
+
+bool testUVProcessChainBuiltin(const char* helperCommand)
+{
+ cmUVProcessChainBuilder builder;
+ std::unique_ptr<cmUVProcessChain> chain;
+ builder.AddCommand({ helperCommand, "echo" })
+ .AddCommand({ helperCommand, "capitalize" })
+ .AddCommand({ helperCommand, "dedup" })
+ .SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
+ .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
+
+ if (!checkExecution(builder, chain)) {
+ return false;
+ }
+
+ if (!chain->OutputStream()) {
+ std::cout << "OutputStream() was null, expecting not null" << std::endl;
+ return false;
+ }
+ if (!chain->ErrorStream()) {
+ std::cout << "ErrorStream() was null, expecting not null" << std::endl;
+ return false;
+ }
+
+ if (!checkOutput(*chain->OutputStream(), *chain->ErrorStream())) {
+ return false;
+ }
+
+ return true;
+}
+
+bool testUVProcessChainExternal(const char* helperCommand)
+{
+ cmUVProcessChainBuilder builder;
+ std::unique_ptr<cmUVProcessChain> chain;
+ int outputPipe[2], errorPipe[2];
+ cm::uv_pipe_ptr outputInPipe, outputOutPipe, errorInPipe, errorOutPipe;
+
+ if (cmGetPipes(outputPipe) < 0) {
+ std::cout << "Error creating pipes" << std::endl;
+ return false;
+ }
+ if (cmGetPipes(errorPipe) < 0) {
+ std::cout << "Error creating pipes" << std::endl;
+ return false;
+ }
+
+ builder.AddCommand({ helperCommand, "echo" })
+ .AddCommand({ helperCommand, "capitalize" })
+ .AddCommand({ helperCommand, "dedup" })
+ .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT, outputPipe[1])
+ .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR, errorPipe[1]);
+
+ if (!checkExecution(builder, chain)) {
+ return false;
+ }
+
+ if (chain->OutputStream()) {
+ std::cout << "OutputStream() was not null, expecting null" << std::endl;
+ return false;
+ }
+ if (chain->ErrorStream()) {
+ std::cout << "ErrorStream() was not null, expecting null" << std::endl;
+ return false;
+ }
+
+ outputOutPipe.init(chain->GetLoop(), 0);
+ uv_pipe_open(outputOutPipe, outputPipe[1]);
+ outputOutPipe.reset();
+
+ errorOutPipe.init(chain->GetLoop(), 0);
+ uv_pipe_open(errorOutPipe, errorPipe[1]);
+ errorOutPipe.reset();
+
+ outputInPipe.init(chain->GetLoop(), 0);
+ uv_pipe_open(outputInPipe, outputPipe[0]);
+ cmUVStreambuf outputBuf;
+ outputBuf.open(outputInPipe);
+ std::istream outputStream(&outputBuf);
+
+ errorInPipe.init(chain->GetLoop(), 0);
+ uv_pipe_open(errorInPipe, errorPipe[0]);
+ cmUVStreambuf errorBuf;
+ errorBuf.open(errorInPipe);
+ std::istream errorStream(&errorBuf);
+
+ if (!checkOutput(outputStream, errorStream)) {
+ return false;
+ }
+
+ return true;
+}
+
+bool testUVProcessChainNone(const char* helperCommand)
+{
+ cmUVProcessChainBuilder builder;
+ std::unique_ptr<cmUVProcessChain> chain;
+ builder.AddCommand({ helperCommand, "echo" })
+ .AddCommand({ helperCommand, "capitalize" })
+ .AddCommand({ helperCommand, "dedup" });
+
+ if (!checkExecution(builder, chain)) {
+ return false;
+ }
+
+ if (chain->OutputStream()) {
+ std::cout << "OutputStream() was not null, expecting null" << std::endl;
+ return false;
+ }
+ if (chain->ErrorStream()) {
+ std::cout << "ErrorStream() was not null, expecting null" << std::endl;
+ return false;
+ }
+
+ return true;
+}
+
+int testUVProcessChain(int argc, char** const argv)
+{
+ if (argc < 2) {
+ std::cout << "Invalid arguments.\n";
+ return -1;
+ }
+
+ if (!testUVProcessChainBuiltin(argv[1])) {
+ std::cout << "While executing testUVProcessChainBuiltin().\n";
+ return -1;
+ }
+
+ if (!testUVProcessChainExternal(argv[1])) {
+ std::cout << "While executing testUVProcessChainExternal().\n";
+ return -1;
+ }
+
+ if (!testUVProcessChainNone(argv[1])) {
+ std::cout << "While executing testUVProcessChainNone().\n";
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/Tests/CMakeLib/testUVProcessChainHelper.cxx b/Tests/CMakeLib/testUVProcessChainHelper.cxx
new file mode 100644
index 000000000..263665d59
--- /dev/null
+++ b/Tests/CMakeLib/testUVProcessChainHelper.cxx
@@ -0,0 +1,72 @@
+#include <chrono>
+#include <iostream>
+#include <set>
+#include <sstream>
+#include <string>
+#include <thread>
+
+#include <cctype>
+#include <cstdlib>
+
+std::string getStdin()
+{
+ char buffer[1024];
+ std::ostringstream str;
+ do {
+ std::cin.read(buffer, 1024);
+ str.write(buffer, std::cin.gcount());
+ } while (std::cin.gcount() > 0);
+ return str.str();
+}
+
+int main(int argc, char** argv)
+{
+ if (argc < 2) {
+ return -1;
+ }
+
+ std::string command = argv[1];
+ if (command == "echo") {
+ std::this_thread::sleep_for(std::chrono::milliseconds(3000));
+ std::cout << "HELLO world!" << std::flush;
+ std::cerr << "1" << std::flush;
+ return 0;
+ }
+ if (command == "capitalize") {
+ std::this_thread::sleep_for(std::chrono::milliseconds(9000));
+ std::string input = getStdin();
+ for (auto& c : input) {
+ c = static_cast<char>(std::toupper(c));
+ }
+ std::cout << input << std::flush;
+ std::cerr << "2" << std::flush;
+ return 1;
+ }
+ if (command == "dedup") {
+ // Use a nested scope to free all resources before aborting below.
+ {
+ std::string input = getStdin();
+ std::set<char> seen;
+ std::string output;
+ for (auto c : input) {
+ if (!seen.count(c)) {
+ seen.insert(c);
+ output += c;
+ }
+ }
+ std::cout << output << std::flush;
+ std::cerr << "3" << std::flush;
+ }
+
+ // On Windows, the exit code of abort() is different between debug and
+ // release builds, and does not yield a term_signal in libuv in either
+ // case. For the sake of simplicity, we just return another non-zero code.
+#ifdef _WIN32
+ return 2;
+#else
+ std::abort();
+#endif
+ }
+
+ return -1;
+}
diff --git a/Tests/CMakeLib/testUVRAII.cxx b/Tests/CMakeLib/testUVRAII.cxx
new file mode 100644
index 000000000..2aeaf2c02
--- /dev/null
+++ b/Tests/CMakeLib/testUVRAII.cxx
@@ -0,0 +1,230 @@
+#include "cmUVHandlePtr.h"
+
+#include <chrono>
+#include <iostream>
+#include <thread>
+#include <utility>
+
+#include "cm_uv.h"
+
+static void signal_reset_fn(uv_async_t* handle)
+{
+ auto ptr = static_cast<cm::uv_async_ptr*>(handle->data);
+ ptr->reset();
+}
+
+// A common pattern is to use an async signal to shutdown the server.
+static bool testAsyncShutdown()
+{
+ uv_loop_t Loop;
+ auto err = uv_loop_init(&Loop);
+ if (err != 0) {
+ std::cerr << "Could not init loop" << std::endl;
+ return false;
+ }
+
+ {
+ cm::uv_async_ptr signal;
+ signal.init(Loop, &signal_reset_fn, &signal);
+
+ std::thread([&] {
+ std::this_thread::sleep_for(std::chrono::seconds(2));
+ signal.send();
+ })
+ .detach();
+
+ if (uv_run(&Loop, UV_RUN_DEFAULT) != 0) {
+ std::cerr << "Unclean exit state in testAsyncDtor" << std::endl;
+ return false;
+ }
+
+ if (signal.get()) {
+ std::cerr << "Loop exited with signal not being cleaned up" << std::endl;
+ return false;
+ }
+ }
+
+ uv_loop_close(&Loop);
+
+ return true;
+}
+
+static void signal_fn(uv_async_t*)
+{
+}
+
+// Async dtor is sort of a pain; since it locks a mutex we must be sure its
+// dtor always calls reset otherwise the mutex is deleted then locked.
+static bool testAsyncDtor()
+{
+ uv_loop_t Loop;
+ auto err = uv_loop_init(&Loop);
+ if (err != 0) {
+ std::cerr << "Could not init loop" << std::endl;
+ return false;
+ }
+
+ {
+ cm::uv_async_ptr signal;
+ signal.init(Loop, signal_fn);
+ }
+
+ if (uv_run(&Loop, UV_RUN_DEFAULT) != 0) {
+ std::cerr << "Unclean exit state in testAsyncDtor" << std::endl;
+ return false;
+ }
+
+ uv_loop_close(&Loop);
+
+ return true;
+}
+
+// Async needs a relatively stateful deleter; make sure that is properly
+// accounted for and doesn't try to hold on to invalid state when it is
+// moved
+static bool testAsyncMove()
+{
+ uv_loop_t Loop;
+ auto err = uv_loop_init(&Loop);
+ if (err != 0) {
+ std::cerr << "Could not init loop" << std::endl;
+ return false;
+ }
+
+ {
+ cm::uv_async_ptr signal;
+ {
+ cm::uv_async_ptr signalTmp;
+ signalTmp.init(Loop, signal_fn);
+ signal = std::move(signalTmp);
+ }
+ }
+
+ if (uv_run(&Loop, UV_RUN_DEFAULT) != 0) {
+ std::cerr << "Unclean exit state in testAsyncDtor" << std::endl;
+ return false;
+ }
+
+ uv_loop_close(&Loop);
+ return true;
+}
+
+// When a type is castable to another uv type (pipe -> stream) here,
+// and the deleter is convertible as well, we should allow moves from
+// one type to the other.
+static bool testCrossAssignment()
+{
+ uv_loop_t Loop;
+ auto err = uv_loop_init(&Loop);
+ if (err != 0) {
+ std::cerr << "Could not init loop" << std::endl;
+ return false;
+ }
+
+ {
+ cm::uv_pipe_ptr pipe;
+ pipe.init(Loop, 0);
+
+ cm::uv_stream_ptr stream = std::move(pipe);
+ if (pipe.get()) {
+ std::cerr << "Move should be sure to invalidate the previous ptr"
+ << std::endl;
+ return false;
+ }
+ cm::uv_handle_ptr handle = std::move(stream);
+ if (stream.get()) {
+ std::cerr << "Move should be sure to invalidate the previous ptr"
+ << std::endl;
+ return false;
+ }
+ }
+
+ if (uv_run(&Loop, UV_RUN_DEFAULT) != 0) {
+ std::cerr << "Unclean exit state in testCrossAssignment" << std::endl;
+ return false;
+ }
+
+ uv_loop_close(&Loop);
+ return true;
+}
+
+// This test can't fail at run time; but this makes sure we have all our move
+// ctors created correctly.
+static bool testAllMoves()
+{
+ using namespace cm;
+ struct allTypes
+ {
+ uv_stream_ptr _7;
+ uv_timer_ptr _8;
+ uv_tty_ptr _9;
+ uv_process_ptr _11;
+ uv_pipe_ptr _12;
+ uv_async_ptr _13;
+ uv_signal_ptr _14;
+ uv_handle_ptr _15;
+ };
+
+ allTypes a;
+ allTypes b(std::move(a));
+ allTypes c = std::move(b);
+ return true;
+};
+
+static bool testLoopReset()
+{
+ bool closed = false;
+ cm::uv_loop_ptr loop;
+ loop.init();
+
+ uv_timer_t timer;
+ uv_timer_init(loop, &timer);
+ timer.data = &closed;
+ uv_close(reinterpret_cast<uv_handle_t*>(&timer), [](uv_handle_t* handle) {
+ auto closedPtr = static_cast<bool*>(handle->data);
+ *closedPtr = true;
+ });
+
+ loop.reset();
+ if (!closed) {
+ std::cerr << "uv_loop_ptr did not finish" << std::endl;
+ return false;
+ }
+
+ return true;
+};
+
+static bool testLoopDestructor()
+{
+ bool closed = false;
+
+ uv_timer_t timer;
+ {
+ cm::uv_loop_ptr loop;
+ loop.init();
+
+ uv_timer_init(loop, &timer);
+ timer.data = &closed;
+ uv_close(reinterpret_cast<uv_handle_t*>(&timer), [](uv_handle_t* handle) {
+ auto closedPtr = static_cast<bool*>(handle->data);
+ *closedPtr = true;
+ });
+ }
+
+ if (!closed) {
+ std::cerr << "uv_loop_ptr did not finish" << std::endl;
+ return false;
+ }
+
+ return true;
+};
+
+int testUVRAII(int, char** const)
+{
+ if ((testAsyncShutdown() &&
+ testAsyncDtor() & testAsyncMove() & testCrossAssignment() &
+ testAllMoves() & testLoopReset() & testLoopDestructor()) == 0) {
+ return -1;
+ }
+ return 0;
+}
diff --git a/Tests/CMakeLib/testUVStreambuf.cxx b/Tests/CMakeLib/testUVStreambuf.cxx
new file mode 100644
index 000000000..39655f372
--- /dev/null
+++ b/Tests/CMakeLib/testUVStreambuf.cxx
@@ -0,0 +1,457 @@
+#include "cmUVStreambuf.h"
+
+#include "cmGetPipes.h"
+#include "cmUVHandlePtr.h"
+
+#include "cm_uv.h"
+
+#include <iostream>
+#include <string>
+#include <vector>
+
+#include <cstring>
+
+#include <stdint.h>
+
+#define TEST_STR_LINE_1 "This string must be exactly 128 characters long so"
+#define TEST_STR_LINE_2 "that we can test CMake's std::streambuf integration"
+#define TEST_STR_LINE_3 "with libuv's uv_stream_t."
+#define TEST_STR TEST_STR_LINE_1 "\n" TEST_STR_LINE_2 "\n" TEST_STR_LINE_3
+
+bool writeDataToStreamPipe(uv_loop_t& loop, cm::uv_pipe_ptr& inputPipe,
+ char* outputData, unsigned int outputDataLength,
+ const char* /* unused */)
+{
+ int err;
+
+ // Create the pipe
+ int pipeHandles[2];
+ if (cmGetPipes(pipeHandles) < 0) {
+ std::cout << "Could not open pipe" << std::endl;
+ return false;
+ }
+
+ cm::uv_pipe_ptr outputPipe;
+ inputPipe.init(loop, 0);
+ outputPipe.init(loop, 0);
+ uv_pipe_open(inputPipe, pipeHandles[0]);
+ uv_pipe_open(outputPipe, pipeHandles[1]);
+
+ // Write data for reading
+ uv_write_t writeReq;
+ struct WriteCallbackData
+ {
+ bool Finished = false;
+ int Status;
+ } writeData;
+ writeReq.data = &writeData;
+ uv_buf_t outputBuf;
+ outputBuf.base = outputData;
+ outputBuf.len = outputDataLength;
+ if ((err = uv_write(&writeReq, outputPipe, &outputBuf, 1,
+ [](uv_write_t* req, int status) {
+ auto data = static_cast<WriteCallbackData*>(req->data);
+ data->Finished = true;
+ data->Status = status;
+ })) < 0) {
+ std::cout << "Could not write to pipe: " << uv_strerror(err) << std::endl;
+ return false;
+ }
+ while (!writeData.Finished) {
+ uv_run(&loop, UV_RUN_ONCE);
+ }
+ if (writeData.Status < 0) {
+ std::cout << "Status is " << uv_strerror(writeData.Status)
+ << ", should be 0" << std::endl;
+ return false;
+ }
+
+ return true;
+}
+
+bool writeDataToStreamProcess(uv_loop_t& loop, cm::uv_pipe_ptr& inputPipe,
+ char* outputData, unsigned int /* unused */,
+ const char* cmakeCommand)
+{
+ int err;
+
+ inputPipe.init(loop, 0);
+ std::vector<std::string> arguments = { cmakeCommand, "-E", "echo_append",
+ outputData };
+ std::vector<const char*> processArgs;
+ for (auto const& arg : arguments) {
+ processArgs.push_back(arg.c_str());
+ }
+ processArgs.push_back(nullptr);
+ std::vector<uv_stdio_container_t> stdio(3);
+ stdio[0].flags = UV_IGNORE;
+ stdio[0].data.stream = nullptr;
+ stdio[1].flags =
+ static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE);
+ stdio[1].data.stream = inputPipe;
+ stdio[2].flags = UV_IGNORE;
+ stdio[2].data.stream = nullptr;
+
+ struct ProcessExitData
+ {
+ bool Finished = false;
+ int64_t ExitStatus;
+ int TermSignal;
+ } exitData;
+ cm::uv_process_ptr process;
+ auto options = uv_process_options_t();
+ options.file = cmakeCommand;
+ options.args = const_cast<char**>(processArgs.data());
+ options.flags = UV_PROCESS_WINDOWS_HIDE;
+ options.stdio = stdio.data();
+ options.stdio_count = static_cast<int>(stdio.size());
+ options.exit_cb = [](uv_process_t* handle, int64_t exitStatus,
+ int termSignal) {
+ auto data = static_cast<ProcessExitData*>(handle->data);
+ data->Finished = true;
+ data->ExitStatus = exitStatus;
+ data->TermSignal = termSignal;
+ };
+ if ((err = process.spawn(loop, options, &exitData)) < 0) {
+ std::cout << "Could not spawn process: " << uv_strerror(err) << std::endl;
+ return false;
+ }
+ while (!exitData.Finished) {
+ uv_run(&loop, UV_RUN_ONCE);
+ }
+ if (exitData.ExitStatus != 0) {
+ std::cout << "Process exit status is " << exitData.ExitStatus
+ << ", should be 0" << std::endl;
+ return false;
+ }
+ if (exitData.TermSignal != 0) {
+ std::cout << "Process term signal is " << exitData.TermSignal
+ << ", should be 0" << std::endl;
+ return false;
+ }
+
+ return true;
+}
+
+bool testUVStreambufRead(
+ bool (*cb)(uv_loop_t& loop, cm::uv_pipe_ptr& inputPipe, char* outputData,
+ unsigned int outputDataLength, const char* cmakeCommand),
+ const char* cmakeCommand)
+{
+ char outputData[] = TEST_STR;
+ bool success = false;
+ cm::uv_loop_ptr loop;
+ loop.init();
+ cm::uv_pipe_ptr inputPipe;
+ std::vector<char> inputData(128);
+ std::streamsize readLen;
+ std::string line;
+ cm::uv_timer_ptr timer;
+
+ // Create the streambuf
+ cmUVStreambuf inputBuf(64);
+ std::istream inputStream(&inputBuf);
+ if (inputBuf.is_open()) {
+ std::cout << "is_open() is true, should be false" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != -1) {
+ std::cout << "in_avail() returned " << readLen << ", should be -1"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) {
+ std::cout << "sgetn() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+
+ // Perform first read test - read all the data
+ if (!cb(*loop, inputPipe, outputData, 128, cmakeCommand)) {
+ goto end;
+ }
+ inputBuf.open(inputPipe);
+ if (!inputBuf.is_open()) {
+ std::cout << "is_open() is false, should be true" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != 0) {
+ std::cout << "in_avail() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 128) {
+ std::cout << "sgetn() returned " << readLen << ", should be 128"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != 0) {
+ std::cout << "in_avail() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+ if (std::memcmp(inputData.data(), outputData, 128)) {
+ std::cout << "Read data does not match write data" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) {
+ std::cout << "sgetn() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != -1) {
+ std::cout << "in_avail() returned " << readLen << ", should be -1"
+ << std::endl;
+ goto end;
+ }
+ inputData.assign(128, char{});
+ inputBuf.close();
+ if (inputBuf.is_open()) {
+ std::cout << "is_open() is true, should be false" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) {
+ std::cout << "sgetn() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != -1) {
+ std::cout << "in_avail() returned " << readLen << ", should be -1"
+ << std::endl;
+ goto end;
+ }
+
+ // Perform second read test - read some data and then close
+ if (!cb(*loop, inputPipe, outputData, 128, cmakeCommand)) {
+ goto end;
+ }
+ inputBuf.open(inputPipe);
+ if (!inputBuf.is_open()) {
+ std::cout << "is_open() is false, should be true" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != 0) {
+ std::cout << "in_avail() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 64)) != 64) {
+ std::cout << "sgetn() returned " << readLen << ", should be 64"
+ << std::endl;
+ goto end;
+ }
+ if (std::memcmp(inputData.data(), outputData, 64)) {
+ std::cout << "Read data does not match write data" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != 8) {
+ std::cout << "in_avail() returned " << readLen << ", should be 8"
+ << std::endl;
+ goto end;
+ }
+ inputData.assign(128, char{});
+ inputBuf.close();
+ if (inputBuf.is_open()) {
+ std::cout << "is_open() is true, should be false" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != -1) {
+ std::cout << "in_avail() returned " << readLen << ", should be -1"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) {
+ std::cout << "sgetn() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+
+ // Perform third read test - read line by line
+ if (!cb(*loop, inputPipe, outputData, 128, cmakeCommand)) {
+ goto end;
+ }
+ inputBuf.open(inputPipe);
+ if (!inputBuf.is_open()) {
+ std::cout << "is_open() is false, should be true" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != 0) {
+ std::cout << "in_avail() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+
+ if (!std::getline(inputStream, line)) {
+ std::cout << "getline returned false, should be true" << std::endl;
+ goto end;
+ }
+ if (line != TEST_STR_LINE_1) {
+ std::cout << "Line 1 is \"" << line
+ << "\", should be \"" TEST_STR_LINE_1 "\"" << std::endl;
+ goto end;
+ }
+
+ if (!std::getline(inputStream, line)) {
+ std::cout << "getline returned false, should be true" << std::endl;
+ goto end;
+ }
+ if (line != TEST_STR_LINE_2) {
+ std::cout << "Line 2 is \"" << line
+ << "\", should be \"" TEST_STR_LINE_2 "\"" << std::endl;
+ goto end;
+ }
+
+ if (!std::getline(inputStream, line)) {
+ std::cout << "getline returned false, should be true" << std::endl;
+ goto end;
+ }
+ if (line != TEST_STR_LINE_3) {
+ std::cout << "Line 3 is \"" << line
+ << "\", should be \"" TEST_STR_LINE_3 "\"" << std::endl;
+ goto end;
+ }
+
+ if (std::getline(inputStream, line)) {
+ std::cout << "getline returned true, should be false" << std::endl;
+ goto end;
+ }
+
+ inputBuf.close();
+ if (inputBuf.is_open()) {
+ std::cout << "is_open() is true, should be false" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != -1) {
+ std::cout << "in_avail() returned " << readLen << ", should be -1"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) {
+ std::cout << "sgetn() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+
+ // Perform fourth read test - run the event loop outside of underflow()
+ if (!cb(*loop, inputPipe, outputData, 128, cmakeCommand)) {
+ goto end;
+ }
+ inputBuf.open(inputPipe);
+ if (!inputBuf.is_open()) {
+ std::cout << "is_open() is false, should be true" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != 0) {
+ std::cout << "in_avail() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+ uv_run(loop, UV_RUN_DEFAULT);
+ if ((readLen = inputBuf.in_avail()) != 72) {
+ std::cout << "in_avail() returned " << readLen << ", should be 72"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 128) {
+ std::cout << "sgetn() returned " << readLen << ", should be 128"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != 0) {
+ std::cout << "in_avail() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) {
+ std::cout << "sgetn() returned " << readLen << ", should be 128"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != -1) {
+ std::cout << "in_avail() returned " << readLen << ", should be -1"
+ << std::endl;
+ goto end;
+ }
+
+ inputBuf.close();
+ if (inputBuf.is_open()) {
+ std::cout << "is_open() is true, should be false" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != -1) {
+ std::cout << "in_avail() returned " << readLen << ", should be -1"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) {
+ std::cout << "sgetn() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+
+ // Perform fifth read test - close the streambuf in the middle of a read
+ timer.init(*loop, &inputBuf);
+ if (!cb(*loop, inputPipe, outputData, 128, cmakeCommand)) {
+ goto end;
+ }
+ inputBuf.open(inputPipe);
+ if (!inputBuf.is_open()) {
+ std::cout << "is_open() is false, should be true" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != 0) {
+ std::cout << "in_avail() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+ uv_timer_start(timer,
+ [](uv_timer_t* handle) {
+ auto buf = static_cast<cmUVStreambuf*>(handle->data);
+ buf->close();
+ },
+ 0, 0);
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) {
+ std::cout << "sgetn() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+ if (inputBuf.is_open()) {
+ std::cout << "is_open() is true, should be false" << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.in_avail()) != -1) {
+ std::cout << "in_avail() returned " << readLen << ", should be -1"
+ << std::endl;
+ goto end;
+ }
+ if ((readLen = inputBuf.sgetn(inputData.data(), 128)) != 0) {
+ std::cout << "sgetn() returned " << readLen << ", should be 0"
+ << std::endl;
+ goto end;
+ }
+
+ success = true;
+
+end:
+ return success;
+}
+
+int testUVStreambuf(int argc, char** const argv)
+{
+ if (argc < 2) {
+ std::cout << "Invalid arguments.\n";
+ return -1;
+ }
+
+ if (!testUVStreambufRead(writeDataToStreamPipe, argv[1])) {
+ std::cout << "While executing testUVStreambufRead() with pipe.\n";
+ return -1;
+ }
+
+ if (!testUVStreambufRead(writeDataToStreamProcess, argv[1])) {
+ std::cout << "While executing testUVStreambufRead() with process.\n";
+ return -1;
+ }
+
+ return 0;
+}
diff --git a/Tests/CMakeOnly/ProjectIncludeAny/CMakeLists.txt b/Tests/CMakeOnly/ProjectIncludeAny/CMakeLists.txt
new file mode 100644
index 000000000..ffce488f4
--- /dev/null
+++ b/Tests/CMakeOnly/ProjectIncludeAny/CMakeLists.txt
@@ -0,0 +1,4 @@
+project(ProjectInclude LANGUAGES NONE)
+if(NOT AUTO_INCLUDE)
+ message(FATAL_ERROR "include file not found")
+endif()
diff --git a/Tests/CMakeOnly/ProjectIncludeBefore/CMakeLists.txt b/Tests/CMakeOnly/ProjectIncludeBefore/CMakeLists.txt
new file mode 100644
index 000000000..5cd9cba2c
--- /dev/null
+++ b/Tests/CMakeOnly/ProjectIncludeBefore/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(FOO TRUE)
+project(ProjectInclude LANGUAGES NONE)
+if(NOT AUTO_INCLUDE)
+ message(FATAL_ERROR "include file not found")
+endif()
diff --git a/Tests/CMakeOnly/ProjectIncludeBefore/include.cmake b/Tests/CMakeOnly/ProjectIncludeBefore/include.cmake
new file mode 100644
index 000000000..0a4799df3
--- /dev/null
+++ b/Tests/CMakeOnly/ProjectIncludeBefore/include.cmake
@@ -0,0 +1,9 @@
+if(NOT FOO)
+ message(FATAL_ERROR "FOO is not set")
+endif()
+
+if(NOT "${PROJECT_NAME}" STREQUAL "")
+ message(FATAL_ERROR "PROJECT_NAME should be empty")
+endif()
+
+set(AUTO_INCLUDE TRUE)
diff --git a/Tests/CMakeServerLib/CMakeLists.txt b/Tests/CMakeServerLib/CMakeLists.txt
new file mode 100644
index 000000000..2c23c2dbe
--- /dev/null
+++ b/Tests/CMakeServerLib/CMakeLists.txt
@@ -0,0 +1,21 @@
+include_directories(
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMake_BINARY_DIR}/Source
+ ${CMake_SOURCE_DIR}/Source
+ )
+
+set(CMakeServerLib_TESTS
+ testServerBuffering.cpp
+ )
+
+create_test_sourcelist(CMakeLib_TEST_SRCS CMakeServerLibTests.cxx ${CMakeServerLib_TESTS})
+add_executable(CMakeServerLibTests ${CMakeLib_TEST_SRCS})
+target_link_libraries(CMakeServerLibTests CMakeLib CMakeServerLib)
+
+SET_PROPERTY(TARGET CMakeServerLibTests PROPERTY C_CLANG_TIDY "")
+SET_PROPERTY(TARGET CMakeServerLibTests PROPERTY CXX_CLANG_TIDY "")
+
+foreach(testfile ${CMakeServerLib_TESTS})
+ get_filename_component(test "${testfile}" NAME_WE)
+ 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..7330eadf7
--- /dev/null
+++ b/Tests/CMakeServerLib/testServerBuffering.cpp
@@ -0,0 +1,85 @@
+#include "cmConnection.h"
+#include "cmServerConnection.h"
+#include <iostream>
+#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 (auto& messageChar : fullMessage) {
+ rawBuffer += messageChar;
+ 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/CPackUseDefaultVersion/CMakeLists.txt b/Tests/CPackUseDefaultVersion/CMakeLists.txt
new file mode 100644
index 000000000..9f21f3afb
--- /dev/null
+++ b/Tests/CPackUseDefaultVersion/CMakeLists.txt
@@ -0,0 +1,6 @@
+cmake_minimum_required(VERSION 3.2)
+project(CPackUseProjectVersion NONE)
+
+include(CPack)
+
+message("CPACK_PACKAGE_VERSION=${CPACK_PACKAGE_VERSION}")
diff --git a/Tests/CPackUseProjectVersion/CMakeLists.txt b/Tests/CPackUseProjectVersion/CMakeLists.txt
new file mode 100644
index 000000000..d4770ae75
--- /dev/null
+++ b/Tests/CPackUseProjectVersion/CMakeLists.txt
@@ -0,0 +1,6 @@
+cmake_minimum_required(VERSION 3.2)
+project(CPackUseProjectVersion VERSION 1.2.3 LANGUAGES NONE)
+
+include(CPack)
+
+message("CPACK_PACKAGE_VERSION=${CPACK_PACKAGE_VERSION}")
diff --git a/Tests/CPackUseShortProjectVersion/CMakeLists.txt b/Tests/CPackUseShortProjectVersion/CMakeLists.txt
new file mode 100644
index 000000000..855bc6401
--- /dev/null
+++ b/Tests/CPackUseShortProjectVersion/CMakeLists.txt
@@ -0,0 +1,6 @@
+cmake_minimum_required(VERSION 3.2)
+project(CPackUseProjectVersion VERSION 2 LANGUAGES NONE)
+
+include(CPack)
+
+message("CPACK_PACKAGE_VERSION=${CPACK_PACKAGE_VERSION}")
diff --git a/Tests/CSharpLinkFromCxx/CMakeLists.txt b/Tests/CSharpLinkFromCxx/CMakeLists.txt
new file mode 100644
index 000000000..9a1a99379
--- /dev/null
+++ b/Tests/CSharpLinkFromCxx/CMakeLists.txt
@@ -0,0 +1,19 @@
+# Take a C# shared library and link it to a managed C++ shared library
+cmake_minimum_required(VERSION 3.10)
+project (CSharpLinkFromCxx CXX CSharp)
+
+add_library(CSharpLibrary SHARED UsefulCSharpClass.cs)
+
+# we have to change the default flags for the
+# managed C++ project to build
+string(REPLACE "/EHsc" "" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS})
+string(REPLACE "/RTC1" "" CMAKE_CXX_FLAGS_DEBUG ${CMAKE_CXX_FLAGS_DEBUG})
+
+# The C# project is a dependency of the C++/CLI project
+add_library(ManagedCppLibrary SHARED UsefulManagedCppClass.cpp UsefulManagedCppClass.hpp)
+target_compile_options(ManagedCppLibrary PRIVATE "/clr")
+target_link_libraries(ManagedCppLibrary PUBLIC CSharpLibrary)
+
+# Main executable for the test framework
+add_executable(CSharpLinkFromCxx CSharpLinkFromCxx.cs)
+target_link_libraries(CSharpLinkFromCxx PRIVATE ManagedCppLibrary)
diff --git a/Tests/CSharpLinkFromCxx/CSharpLinkFromCxx.cs b/Tests/CSharpLinkFromCxx/CSharpLinkFromCxx.cs
new file mode 100644
index 000000000..31a74ebf6
--- /dev/null
+++ b/Tests/CSharpLinkFromCxx/CSharpLinkFromCxx.cs
@@ -0,0 +1,16 @@
+using System;
+using CSharpLibrary;
+
+namespace CSharpLinkFromCxx
+{
+ internal class CSharpLinkFromCxx
+ {
+ public static void Main(string[] args)
+ {
+ Console.WriteLine("Starting test for CSharpLinkFromCxx");
+
+ var useful = new UsefulManagedCppClass();
+ useful.RunTest();
+ }
+ }
+}
diff --git a/Tests/CSharpLinkFromCxx/UsefulCSharpClass.cs b/Tests/CSharpLinkFromCxx/UsefulCSharpClass.cs
new file mode 100644
index 000000000..749e57dc2
--- /dev/null
+++ b/Tests/CSharpLinkFromCxx/UsefulCSharpClass.cs
@@ -0,0 +1,12 @@
+using System;
+
+namespace CSharpLibrary
+{
+ public class UsefulCSharpClass
+ {
+ public string GetSomethingUseful()
+ {
+ return "Something Useful";
+ }
+ }
+}
diff --git a/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.cpp b/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.cpp
new file mode 100644
index 000000000..94688125b
--- /dev/null
+++ b/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.cpp
@@ -0,0 +1,15 @@
+#include "UsefulManagedCppClass.hpp"
+
+namespace CSharpLibrary
+{
+ UsefulManagedCppClass::UsefulManagedCppClass()
+ {
+ auto useful = gcnew UsefulCSharpClass();
+ m_usefulString = useful->GetSomethingUseful();
+ }
+
+ void UsefulManagedCppClass::RunTest()
+ {
+ Console::WriteLine("Printing from Managed CPP Class: " + m_usefulString);
+ }
+}
diff --git a/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.hpp b/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.hpp
new file mode 100644
index 000000000..def7cea0c
--- /dev/null
+++ b/Tests/CSharpLinkFromCxx/UsefulManagedCppClass.hpp
@@ -0,0 +1,16 @@
+using namespace System;
+
+namespace CSharpLibrary
+{
+ public ref class UsefulManagedCppClass
+ {
+ public:
+
+ UsefulManagedCppClass();
+ void RunTest();
+
+ private:
+
+ String^ m_usefulString;
+ };
+}
diff --git a/Tests/CSharpLinkToCxx/cpp_static.cpp b/Tests/CSharpLinkToCxx/cpp_static.cpp
new file mode 100644
index 000000000..9af2b6ea3
--- /dev/null
+++ b/Tests/CSharpLinkToCxx/cpp_static.cpp
@@ -0,0 +1,3 @@
+void cpp_static()
+{
+}
diff --git a/Tests/CSharpOnly/empty.cs b/Tests/CSharpOnly/empty.cs
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/CSharpOnly/empty.cs
diff --git a/Tests/CSharpOnly/empty.txt b/Tests/CSharpOnly/empty.txt
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/CSharpOnly/empty.txt
diff --git a/Tests/CheckSwift.cmake b/Tests/CheckSwift.cmake
new file mode 100644
index 000000000..fcbae7ef9
--- /dev/null
+++ b/Tests/CheckSwift.cmake
@@ -0,0 +1,61 @@
+if(NOT CMAKE_GENERATOR MATCHES "Xcode|Ninja")
+ set(CMAKE_Swift_COMPILER "")
+ return()
+endif()
+
+if(NOT DEFINED CMAKE_Swift_COMPILER)
+ set(_desc "Looking for a Swift compiler")
+ message(STATUS ${_desc})
+
+ file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/CheckSwift)
+
+ file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/CheckSwift/CMakeLists.txt"
+ "cmake_minimum_required(VERSION 3.14)
+project(CheckSwift Swift)
+file(WRITE \"\${CMAKE_CURRENT_BINARY_DIR}/result.cmake\"
+ \"set(CMAKE_Swift_COMPILER \\\"\${CMAKE_Swift_COMPILER}\\\")\\n\"
+ \"set(CMAKE_Swift_FLAGS \\\"\${CMAKE_Swift_FLAGS}\\\")\\n\")
+")
+
+ if(CMAKE_GENERATOR_INSTANCE)
+ set(_D_CMAKE_GENERATOR_INSTANCE "-DCMAKE_GENERATOR_INSTANCE:INTERNAL=${CMAKE_GENERATOR_INSTANCE}")
+ else()
+ set(_D_CMAKE_GENERATOR_INSTANCE "")
+ endif()
+
+ execute_process(WORKING_DIRECTORY
+ ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/CheckSwift
+ COMMAND
+ ${CMAKE_COMMAND} . -G ${CMAKE_GENERATOR}
+ -A "${CMAKE_GENERATOR_PLATFORM}"
+ -T "${CMAKE_GENERATOR_TOOLSET}"
+ ${_D_CMAKE_GENERATOR_INSTANCE}
+ TIMEOUT
+ 60
+ OUTPUT_VARIABLE
+ output
+ ERROR_VARIABLE
+ output
+ RESULT_VARIABLE
+ result)
+
+ include(${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/CheckSwift/result.cmake
+ OPTIONAL)
+ if(CMAKE_Swift_COMPILER AND "${result}" STREQUAL "0")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+ "${_desc} passed with the following output:\n"
+ "${output}\n")
+ else()
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+ "${_desc} failed with the following output:\n"
+ "${output}\n")
+ endif()
+
+ message(STATUS "${_desc} - ${CMAKE_Swift_COMPILER}")
+
+ set(CMAKE_Swift_COMPILER "${CMAKE_Swift_COMPILER}" CACHE FILEPATH "Swift compiler")
+ set(CMAKE_Swift_FLAGS "${CMAKE_Swift_FLAGS}" CACHE STRING "Swift flags")
+
+ mark_as_advanced(CMAKE_Swift_COMPILER)
+ mark_as_advanced(CMAKE_Swift_FLAGS)
+endif()
diff --git a/Tests/CommandLength/CMakeLists.txt b/Tests/CommandLength/CMakeLists.txt
new file mode 100644
index 000000000..68360518b
--- /dev/null
+++ b/Tests/CommandLength/CMakeLists.txt
@@ -0,0 +1,17 @@
+cmake_minimum_required(VERSION 3.10)
+project(CommandLength C)
+
+add_executable(CommandLength test.c)
+add_custom_command(TARGET CommandLength POST_BUILD VERBATIM
+ COMMAND ${CMAKE_COMMAND} -E make_directory log)
+
+set(msg "xxxx $$$$ yyyy")
+set(msg "${msg} ${msg}")
+set(msg "${msg} ${msg}")
+set(msg "${msg} ${msg}")
+set(msg "${msg} ${msg}")
+foreach(i RANGE 1 1000)
+ add_custom_command(TARGET CommandLength POST_BUILD VERBATIM
+ COMMAND ${CMAKE_COMMAND} -E echo "${i} ${msg}" > log/${i}
+ )
+endforeach()
diff --git a/Tests/CommandLength/test.c b/Tests/CommandLength/test.c
new file mode 100644
index 000000000..f8b643afb
--- /dev/null
+++ b/Tests/CommandLength/test.c
@@ -0,0 +1,4 @@
+int main()
+{
+ return 0;
+}
diff --git a/Tests/Contracts/Home.cmake b/Tests/Contracts/Home.cmake
new file mode 100644
index 000000000..8b05e8190
--- /dev/null
+++ b/Tests/Contracts/Home.cmake
@@ -0,0 +1,19 @@
+# Find a home in which to build.
+if(NOT DEFINED HOME)
+ if(DEFINED ENV{CTEST_REAL_HOME})
+ set(HOME "$ENV{CTEST_REAL_HOME}")
+ else()
+ set(HOME "$ENV{HOME}")
+ endif()
+
+ if(NOT HOME AND WIN32)
+ # Try for USERPROFILE as HOME equivalent:
+ string(REPLACE "\\" "/" HOME "$ENV{USERPROFILE}")
+
+ # But just use root of SystemDrive if USERPROFILE contains any spaces:
+ # (Default on XP and earlier...)
+ if(HOME MATCHES " ")
+ string(REPLACE "\\" "/" HOME "$ENV{SystemDrive}")
+ endif()
+ endif()
+endif()
diff --git a/Tests/Contracts/PLplot/CMakeLists.txt b/Tests/Contracts/PLplot/CMakeLists.txt
new file mode 100644
index 000000000..8e95ba36a
--- /dev/null
+++ b/Tests/Contracts/PLplot/CMakeLists.txt
@@ -0,0 +1,18 @@
+cmake_minimum_required(VERSION 3.9)
+project(PLplotDriver NONE)
+include(ExternalProject)
+include(${CMAKE_CURRENT_SOURCE_DIR}/../Home.cmake)
+set(PLplot_PREFIX "${HOME}/.cmake/Contracts/PLplot")
+file(REMOVE_RECURSE "${PLplot_PREFIX}")
+separate_arguments(PLplot_CMAKE_ARGS UNIX_COMMAND "${PLplot_CMAKE_FLAGS}")
+if(NOT PLplot_GIT_TAG)
+ set(PLplot_GIT_TAG "plplot-5.13.0")
+endif()
+ExternalProject_Add(PLplot
+ GIT_REPOSITORY "https://git.code.sf.net/p/plplot/plplot"
+ GIT_TAG "${PLplot_GIT_TAG}"
+ PREFIX "${PLplot_PREFIX}"
+ CMAKE_ARGS
+ -DCMAKE_INSTALL_PREFIX=<INSTALL_DIR>
+ ${PLplot_CMAKE_ARGS}
+ )
diff --git a/Tests/Contracts/PLplot/Configure.cmake b/Tests/Contracts/PLplot/Configure.cmake
new file mode 100644
index 000000000..83591d4fc
--- /dev/null
+++ b/Tests/Contracts/PLplot/Configure.cmake
@@ -0,0 +1,4 @@
+set(Contracts.PLplot_BUILD_OPTIONS
+ -DPLplot_CMAKE_FLAGS=${CMake_TEST_CONTRACT_PLplot_CMAKE_FLAGS}
+ -DPLplot_GIT_TAG=${CMake_TEST_CONTRACT_PLplot_GIT_TAG}
+ )
diff --git a/Tests/Contracts/Trilinos/Configure.cmake b/Tests/Contracts/Trilinos/Configure.cmake
new file mode 100644
index 000000000..d62eb7917
--- /dev/null
+++ b/Tests/Contracts/Trilinos/Configure.cmake
@@ -0,0 +1,7 @@
+# ValidateBuild.cmake is configured into this location when the test is built:
+set(dir "${CMAKE_CURRENT_BINARY_DIR}/Contracts/${project}")
+
+set(exe "${CMAKE_COMMAND}")
+set(args -P "${dir}/ValidateBuild.cmake")
+
+set(CMake_TEST_CONTRACT_Trilinos_RUN_TEST ${exe} ${args})
diff --git a/Tests/Contracts/VTK/Configure.cmake b/Tests/Contracts/VTK/Configure.cmake
new file mode 100644
index 000000000..037d75ab2
--- /dev/null
+++ b/Tests/Contracts/VTK/Configure.cmake
@@ -0,0 +1,3 @@
+set(exe "$ENV{HOME}/.cmake/Contracts/VTK/VTK-build/bin/vtkCommonCoreCxxTests")
+set(args otherArrays)
+set(CMake_TEST_CONTRACT_VTK_RUN_TEST ${exe} ${args})
diff --git a/Tests/Cuda/MixedStandardLevels/CMakeLists.txt b/Tests/Cuda/MixedStandardLevels/CMakeLists.txt
new file mode 100644
index 000000000..b399662a7
--- /dev/null
+++ b/Tests/Cuda/MixedStandardLevels/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.7)
+project(MixedStandardLevels CXX CUDA)
+
+string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_30,code=compute_30")
+
+set(CMAKE_CXX_STANDARD 11)
+
+add_executable(MixedStandardLevels main.cu)
+target_compile_features(MixedStandardLevels PUBLIC cxx_std_11)
+
+if(APPLE)
+ # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime.
+ set_property(TARGET MixedStandardLevels PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES})
+endif()
diff --git a/Tests/Cuda/MixedStandardLevels/main.cu b/Tests/Cuda/MixedStandardLevels/main.cu
new file mode 100644
index 000000000..d57c05a66
--- /dev/null
+++ b/Tests/Cuda/MixedStandardLevels/main.cu
@@ -0,0 +1,10 @@
+
+#include <type_traits>
+
+int main(int argc, char** argv)
+{
+ // Verify that issue #17519 Setting CXX_STANDARD breaks CUDA_STANDARD
+ // selection via cxx_std_11 has been corrected
+ using returnv = std::integral_constant<int, 0>;
+ return returnv::value;
+}
diff --git a/Tests/Cuda/NotEnabled/CMakeLists.txt b/Tests/Cuda/NotEnabled/CMakeLists.txt
new file mode 100644
index 000000000..968751b65
--- /dev/null
+++ b/Tests/Cuda/NotEnabled/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.7)
+project(CudaNotEnabled CXX)
+
+add_library(HasCudaProps lib.cxx)
+
+target_compile_features(HasCudaProps PUBLIC cxx_std_11)
+#Verify that setting this variables in a project that doesn't have CUDA
+#enabled allow for the project to configure and build correctly.
+#Tests the fix for #19432
+set_property(TARGET HasCudaProps PROPERTY CUDA_SEPARABLE_COMPILATION ON)
+set_property(TARGET HasCudaProps PROPERTY CUDA_RESOLVE_DEVICE_SYMBOLS ON)
+
+add_executable(CudaNotEnabled main.cxx)
+target_link_libraries(CudaNotEnabled PRIVATE HasCudaProps)
diff --git a/Tests/Cuda/NotEnabled/lib.cxx b/Tests/Cuda/NotEnabled/lib.cxx
new file mode 100644
index 000000000..5dae5a3f5
--- /dev/null
+++ b/Tests/Cuda/NotEnabled/lib.cxx
@@ -0,0 +1,5 @@
+
+int cxx_function(int input)
+{
+ return input;
+}
diff --git a/Tests/Cuda/NotEnabled/main.cxx b/Tests/Cuda/NotEnabled/main.cxx
new file mode 100644
index 000000000..a644207a1
--- /dev/null
+++ b/Tests/Cuda/NotEnabled/main.cxx
@@ -0,0 +1,9 @@
+
+#include <type_traits>
+
+int main(int argc, char** argv)
+{
+ // make sure we have c++11 enabled
+ using returnv = std::integral_constant<int, 0>;
+ return returnv::value;
+}
diff --git a/Tests/Cuda/ObjectLibrary/Conflicts/CMakeLists.txt b/Tests/Cuda/ObjectLibrary/Conflicts/CMakeLists.txt
new file mode 100644
index 000000000..1602f8a2a
--- /dev/null
+++ b/Tests/Cuda/ObjectLibrary/Conflicts/CMakeLists.txt
@@ -0,0 +1,2 @@
+
+add_library(CudaConflicts OBJECT static.cu)
diff --git a/Tests/Cuda/ObjectLibrary/Conflicts/static.cu b/Tests/Cuda/ObjectLibrary/Conflicts/static.cu
new file mode 100644
index 000000000..586e8c62b
--- /dev/null
+++ b/Tests/Cuda/ObjectLibrary/Conflicts/static.cu
@@ -0,0 +1,17 @@
+
+#include <cuda.h>
+#include <cuda_runtime.h>
+#include <iostream>
+
+int __host__ cu2_sq_func(int x)
+{
+ cudaError_t err;
+ int nDevices = 0;
+ err = cudaGetDeviceCount(&nDevices);
+ if (err != cudaSuccess) {
+ std::cerr << "nDevices: " << nDevices << std::endl;
+ std::cerr << "err: " << err << std::endl;
+ return 1;
+ }
+ return x * x;
+}
diff --git a/Tests/Cuda/ProperDeviceLibraries/CMakeLists.txt b/Tests/Cuda/ProperDeviceLibraries/CMakeLists.txt
new file mode 100644
index 000000000..cb47b09b4
--- /dev/null
+++ b/Tests/Cuda/ProperDeviceLibraries/CMakeLists.txt
@@ -0,0 +1,45 @@
+cmake_minimum_required(VERSION 3.13)
+project(ProperDeviceLibraries CXX CUDA)
+
+string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_35,code=compute_35 -gencode arch=compute_35,code=sm_35")
+set(CMAKE_CUDA_STANDARD 11)
+
+set(THREADS_PREFER_PTHREAD_FLAG ON)
+find_package(Threads)
+
+add_executable(ProperDeviceLibraries main.cu)
+set_target_properties(ProperDeviceLibraries
+ PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
+
+add_library(UseThreadsMixed SHARED use_pthreads.cxx use_pthreads.cu)
+target_link_libraries(UseThreadsMixed Threads::Threads)
+
+add_library(UseThreadsCuda SHARED use_pthreads.cu)
+target_link_libraries(UseThreadsCuda Threads::Threads)
+
+target_link_libraries(ProperDeviceLibraries PRIVATE UseThreadsMixed UseThreadsCuda)
+
+if(THREADS_HAVE_PTHREAD_ARG AND CMAKE_USE_PTHREADS_INIT)
+ add_library(UseExplicitPThreadsFlag SHARED use_pthreads.cu)
+ target_compile_options(UseExplicitPThreadsFlag PUBLIC "-Xcompiler=-pthread")
+ target_link_libraries(UseExplicitPThreadsFlag PUBLIC "-pthread")
+
+ add_library(UseExplicitLThreadsFlag SHARED use_pthreads.cu)
+ target_compile_options(UseExplicitLThreadsFlag PUBLIC "-Xcompiler=-pthread")
+ target_link_libraries(UseExplicitLThreadsFlag PUBLIC "-lpthread")
+
+ add_library(UseExplicitLongThreadsFlag SHARED use_pthreads.cu)
+ target_link_libraries(UseExplicitLongThreadsFlag PUBLIC "--library pthread")
+
+ target_link_libraries(ProperDeviceLibraries PRIVATE UseExplicitPThreadsFlag UseExplicitLThreadsFlag UseExplicitLongThreadsFlag)
+endif()
+
+if(CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 10.0.0)
+ #CUDA 10 removed the cublas_device library
+ target_link_libraries(ProperDeviceLibraries PRIVATE cublas_device)
+endif()
+
+if(APPLE)
+ # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime.
+ set_property(TARGET ProperDeviceLibraries PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES})
+endif()
diff --git a/Tests/Cuda/ProperDeviceLibraries/main.cu b/Tests/Cuda/ProperDeviceLibraries/main.cu
new file mode 100644
index 000000000..8ceb0ccb4
--- /dev/null
+++ b/Tests/Cuda/ProperDeviceLibraries/main.cu
@@ -0,0 +1,92 @@
+
+#include <cublas_v2.h>
+#include <cuda_runtime.h>
+#include <iostream>
+
+#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)
+
+# include <pthread.h>
+static int verify_linking_to_pthread()
+{
+ return static_cast<int>(pthread_self());
+}
+#endif
+
+// this test only makes sense for versions of CUDA that ships
+// static libraries that have separable compilation device symbols
+#if __CUDACC_VER_MAJOR__ <= 9
+__global__ void deviceCublasSgemm(int n, float alpha, float beta,
+ const float* d_A, const float* d_B,
+ float* d_C)
+{
+ cublasHandle_t cnpHandle;
+ cublasStatus_t status = cublasCreate(&cnpHandle);
+
+ if (status != CUBLAS_STATUS_SUCCESS) {
+ return;
+ }
+
+ // Call function defined in the cublas_device system static library.
+ // This way we can verify that we properly pass system libraries to the
+ // device link line
+ status = cublasSgemm(cnpHandle, CUBLAS_OP_N, CUBLAS_OP_N, n, n, n, &alpha,
+ d_A, n, d_B, n, &beta, d_C, n);
+
+ cublasDestroy(cnpHandle);
+}
+#endif
+
+int choose_cuda_device()
+{
+ int nDevices = 0;
+ cudaError_t err = cudaGetDeviceCount(&nDevices);
+ if (err != cudaSuccess) {
+ std::cerr << "Failed to retrieve the number of CUDA enabled devices"
+ << std::endl;
+ return 1;
+ }
+ for (int i = 0; i < nDevices; ++i) {
+ cudaDeviceProp prop;
+ cudaError_t err = cudaGetDeviceProperties(&prop, i);
+ if (err != cudaSuccess) {
+ std::cerr << "Could not retrieve properties from CUDA device " << i
+ << std::endl;
+ return 1;
+ }
+
+ if (prop.major > 3 || (prop.major == 3 && prop.minor >= 5)) {
+ err = cudaSetDevice(i);
+ if (err != cudaSuccess) {
+ std::cout << "Could not select CUDA device " << i << std::endl;
+ } else {
+ return 0;
+ }
+ }
+ }
+
+ std::cout << "Could not find a CUDA enabled card supporting compute >=3.5"
+ << std::endl;
+ return 1;
+}
+
+int main(int argc, char** argv)
+{
+ int ret = choose_cuda_device();
+ if (ret) {
+ return 0;
+ }
+
+#if __CUDACC_VER_MAJOR__ <= 9
+ // initial values that will make sure that the cublasSgemm won't actually
+ // do any work
+ int n = 0;
+ float alpha = 1;
+ float beta = 1;
+ float* d_A = nullptr;
+ float* d_B = nullptr;
+ float* d_C = nullptr;
+ deviceCublasSgemm<<<1, 1>>>(n, alpha, beta, d_A, d_B, d_C);
+#endif
+
+ return 0;
+}
diff --git a/Tests/Cuda/ProperDeviceLibraries/use_pthreads.cu b/Tests/Cuda/ProperDeviceLibraries/use_pthreads.cu
new file mode 100644
index 000000000..c57b8a828
--- /dev/null
+++ b/Tests/Cuda/ProperDeviceLibraries/use_pthreads.cu
@@ -0,0 +1,9 @@
+
+#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)
+
+# include <pthread.h>
+static int verify_linking_to_pthread_cuda()
+{
+ return static_cast<int>(pthread_self());
+}
+#endif
diff --git a/Tests/Cuda/ProperDeviceLibraries/use_pthreads.cxx b/Tests/Cuda/ProperDeviceLibraries/use_pthreads.cxx
new file mode 100644
index 000000000..dc7c208a4
--- /dev/null
+++ b/Tests/Cuda/ProperDeviceLibraries/use_pthreads.cxx
@@ -0,0 +1,9 @@
+
+#if defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)
+
+# include <pthread.h>
+static int verify_linking_to_pthread_cxx()
+{
+ return static_cast<int>(pthread_self());
+}
+#endif
diff --git a/Tests/CudaOnly/CircularLinkLine/CMakeLists.txt b/Tests/CudaOnly/CircularLinkLine/CMakeLists.txt
new file mode 100644
index 000000000..5e6f7abc6
--- /dev/null
+++ b/Tests/CudaOnly/CircularLinkLine/CMakeLists.txt
@@ -0,0 +1,34 @@
+cmake_minimum_required(VERSION 3.7)
+project (CircularLinkLine CUDA)
+
+#Goal for this example:
+# Verify that we de-duplicate the device link line
+# Verify that a de-duplicated link line still works with circular static libraries
+
+string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_30,code=[compute_30]")
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CUDA_STANDARD 11)
+
+add_library(CUDACircularDeviceLinking1 STATIC file1.cu)
+add_library(CUDACircularDeviceLinking2 STATIC file2.cu)
+add_library(CUDACircularDeviceLinking3 STATIC file3.cu)
+add_executable(CudaOnlyCircularLinkLine main.cu)
+
+target_link_libraries(CUDACircularDeviceLinking1 PUBLIC CUDACircularDeviceLinking2)
+target_link_libraries(CUDACircularDeviceLinking2 PUBLIC CUDACircularDeviceLinking3)
+target_link_libraries(CUDACircularDeviceLinking3 PUBLIC CUDACircularDeviceLinking1)
+
+target_link_libraries(CudaOnlyCircularLinkLine PRIVATE CUDACircularDeviceLinking3)
+
+
+set_target_properties(CUDACircularDeviceLinking1
+ PROPERTIES
+ CUDA_SEPARABLE_COMPILATION ON)
+
+set_target_properties(CUDACircularDeviceLinking2
+ PROPERTIES
+ CUDA_SEPARABLE_COMPILATION ON)
+
+set_target_properties(CUDACircularDeviceLinking3
+ PROPERTIES
+ CUDA_SEPARABLE_COMPILATION ON)
diff --git a/Tests/CudaOnly/CircularLinkLine/file1.cu b/Tests/CudaOnly/CircularLinkLine/file1.cu
new file mode 100644
index 000000000..88ac4e3cb
--- /dev/null
+++ b/Tests/CudaOnly/CircularLinkLine/file1.cu
@@ -0,0 +1,6 @@
+
+extern __device__ int file2_func(int);
+int __device__ file1_func(int x)
+{
+ return file2_func(x);
+}
diff --git a/Tests/CudaOnly/CircularLinkLine/file2.cu b/Tests/CudaOnly/CircularLinkLine/file2.cu
new file mode 100644
index 000000000..b32dbffe4
--- /dev/null
+++ b/Tests/CudaOnly/CircularLinkLine/file2.cu
@@ -0,0 +1,6 @@
+
+extern __device__ int file3_func(int);
+int __device__ file2_func(int x)
+{
+ return x + file3_func(x);
+}
diff --git a/Tests/CudaOnly/CircularLinkLine/file3.cu b/Tests/CudaOnly/CircularLinkLine/file3.cu
new file mode 100644
index 000000000..7f67187ed
--- /dev/null
+++ b/Tests/CudaOnly/CircularLinkLine/file3.cu
@@ -0,0 +1,8 @@
+
+extern __device__ int file1_func(int);
+int __device__ file3_func(int x)
+{
+ if (x > 0)
+ return file1_func(-x);
+ return x;
+}
diff --git a/Tests/CudaOnly/CircularLinkLine/main.cu b/Tests/CudaOnly/CircularLinkLine/main.cu
new file mode 100644
index 000000000..1c19e8dc3
--- /dev/null
+++ b/Tests/CudaOnly/CircularLinkLine/main.cu
@@ -0,0 +1,5 @@
+
+int main(int argc, char** argv)
+{
+ return 0;
+}
diff --git a/Tests/CudaOnly/DontResolveDeviceSymbols/CMakeLists.txt b/Tests/CudaOnly/DontResolveDeviceSymbols/CMakeLists.txt
new file mode 100644
index 000000000..619008902
--- /dev/null
+++ b/Tests/CudaOnly/DontResolveDeviceSymbols/CMakeLists.txt
@@ -0,0 +1,50 @@
+cmake_minimum_required(VERSION 3.13)
+project (DontResolveDeviceSymbols CUDA)
+
+# Find nm and dumpbin
+if(CMAKE_NM)
+ set(dump_command ${CMAKE_NM})
+ set(dump_args --defined-only)
+ set(symbol_name cudaRegisterLinkedBinary)
+else()
+ include(GetPrerequisites)
+ message(STATUS "calling list_prerequisites to find dumpbin")
+ list_prerequisites("${CMAKE_COMMAND}" 0 0 0)
+ if(gp_dumpbin)
+ set(dump_command ${gp_dumpbin})
+ set(dump_args /SYMBOLS)
+ set(symbol_name nv_fatb)
+ endif()
+endif()
+
+
+#Goal for this example:
+# Build a static library that defines multiple methods and kernels that
+# use each other.
+# Don't resolve the device symbols in the static library
+# Don't resolve the device symbols in the executable library
+# Verify that we can't use those device symbols from anything
+string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_30,code=[compute_30] -gencode arch=compute_50,code=\\\"compute_50\\\"")
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CUDA_STANDARD 11)
+
+add_library(CUDANoDeviceResolve SHARED file1.cu)
+set_target_properties(CUDANoDeviceResolve
+ PROPERTIES
+ CUDA_SEPARABLE_COMPILATION ON
+ CUDA_RESOLVE_DEVICE_SYMBOLS OFF
+ POSITION_INDEPENDENT_CODE ON)
+if(MSVC)
+ target_link_options(CUDANoDeviceResolve PRIVATE "/FORCE:UNRESOLVED")
+endif()
+
+if(dump_command)
+add_custom_command(TARGET CUDANoDeviceResolve POST_BUILD
+ COMMAND ${CMAKE_COMMAND}
+ -DDUMP_COMMAND=${dump_command}
+ -DDUMP_ARGS=${dump_args}
+ -DSYMBOL_NAME=${symbol_name}
+ -DTEST_LIBRARY_PATH=$<TARGET_FILE:CUDANoDeviceResolve>
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/verify.cmake
+ )
+endif()
diff --git a/Tests/CudaOnly/DontResolveDeviceSymbols/file1.cu b/Tests/CudaOnly/DontResolveDeviceSymbols/file1.cu
new file mode 100644
index 000000000..3924f67c6
--- /dev/null
+++ b/Tests/CudaOnly/DontResolveDeviceSymbols/file1.cu
@@ -0,0 +1,69 @@
+
+#include <iostream>
+
+static __global__ void file1_kernel(int in, int* out)
+{
+ *out = in * in;
+}
+
+int choose_cuda_device()
+{
+ int nDevices = 0;
+ cudaError_t err = cudaGetDeviceCount(&nDevices);
+ if (err != cudaSuccess) {
+ std::cerr << "Failed to retrieve the number of CUDA enabled devices"
+ << std::endl;
+ return 1;
+ }
+ for (int i = 0; i < nDevices; ++i) {
+ cudaDeviceProp prop;
+ cudaError_t err = cudaGetDeviceProperties(&prop, i);
+ if (err != cudaSuccess) {
+ std::cerr << "Could not retrieve properties from CUDA device " << i
+ << std::endl;
+ return 1;
+ }
+ std::cout << "prop.major: " << prop.major << std::endl;
+ if (prop.major >= 3) {
+ err = cudaSetDevice(i);
+ if (err != cudaSuccess) {
+ std::cout << "Could not select CUDA device " << i << std::endl;
+ } else {
+ return 0;
+ }
+ }
+ }
+
+ std::cout << "Could not find a CUDA enabled card supporting compute >=3.0"
+ << std::endl;
+
+ return 1;
+}
+
+int file1_launch_kernel()
+{
+ int ret = choose_cuda_device();
+ if (ret) {
+ return 0;
+ }
+
+ int input = 4;
+
+ int* output;
+ cudaError_t err = cudaMallocManaged(&output, sizeof(int));
+ cudaDeviceSynchronize();
+ if (err != cudaSuccess) {
+ return 1;
+ }
+
+ file1_kernel<<<1, 1>>>(input, output);
+ cudaDeviceSynchronize();
+ err = cudaGetLastError();
+ std::cout << err << " " << cudaGetErrorString(err) << std::endl;
+ if (err == cudaSuccess) {
+ // This kernel launch should failed as the device linking never occured
+ std::cerr << "file1_kernel: kernel launch should have failed" << std::endl;
+ return 1;
+ }
+ return 0;
+}
diff --git a/Tests/CudaOnly/DontResolveDeviceSymbols/main.cu b/Tests/CudaOnly/DontResolveDeviceSymbols/main.cu
new file mode 100644
index 000000000..84a7a19eb
--- /dev/null
+++ b/Tests/CudaOnly/DontResolveDeviceSymbols/main.cu
@@ -0,0 +1,7 @@
+
+#include <iostream>
+
+int main(int argc, char** argv)
+{
+ return 0;
+}
diff --git a/Tests/CudaOnly/DontResolveDeviceSymbols/verify.cmake b/Tests/CudaOnly/DontResolveDeviceSymbols/verify.cmake
new file mode 100644
index 000000000..9bb426da0
--- /dev/null
+++ b/Tests/CudaOnly/DontResolveDeviceSymbols/verify.cmake
@@ -0,0 +1,14 @@
+execute_process(COMMAND ${DUMP_COMMAND} ${DUMP_ARGS} ${TEST_LIBRARY_PATH}
+ RESULT_VARIABLE RESULT
+ OUTPUT_VARIABLE OUTPUT
+ ERROR_VARIABLE ERROR
+)
+
+if(NOT "${RESULT}" STREQUAL "0")
+ message(FATAL_ERROR "${DUMP_COMMAND} failed [${RESULT}] [${OUTPUT}] [${ERROR}]")
+endif()
+
+if("${OUTPUT}" MATCHES "${SYMBOL_NAME}")
+ message(FATAL_ERROR
+ "The '${SYMBOL_NAME}' symbol is defined; device linking occurred!")
+endif()
diff --git a/Tests/CudaOnly/GPUDebugFlag/CMakeLists.txt b/Tests/CudaOnly/GPUDebugFlag/CMakeLists.txt
new file mode 100644
index 000000000..fbef15f9e
--- /dev/null
+++ b/Tests/CudaOnly/GPUDebugFlag/CMakeLists.txt
@@ -0,0 +1,23 @@
+
+cmake_minimum_required(VERSION 3.7)
+project (GPUDebugFlag CUDA)
+
+#Goal for this example:
+#verify that -G enables gpu debug flags
+string(APPEND CMAKE_CUDA_FLAGS " -gencode=arch=compute_30,code=compute_30")
+string(APPEND CMAKE_CUDA_FLAGS " -G")
+set(CMAKE_CUDA_STANDARD 11)
+
+add_executable(CudaOnlyGPUDebugFlag main.cu)
+
+if(CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 9.0.0)
+ #CUDA's __CUDACC_DEBUG__ define was added in 9.0
+ #so if we are below 9.0.0 we will manually add the define so that the test
+ #passes
+ target_compile_definitions(CudaOnlyGPUDebugFlag PRIVATE "__CUDACC_DEBUG__")
+endif()
+
+if(APPLE)
+ # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime.
+ set_property(TARGET CudaOnlyGPUDebugFlag PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES})
+endif()
diff --git a/Tests/CudaOnly/GPUDebugFlag/main.cu b/Tests/CudaOnly/GPUDebugFlag/main.cu
new file mode 100644
index 000000000..1f3fc129f
--- /dev/null
+++ b/Tests/CudaOnly/GPUDebugFlag/main.cu
@@ -0,0 +1,71 @@
+#include <cuda.h>
+#include <cuda_runtime.h>
+#include <iostream>
+
+static __global__ void debug_kernel(bool* has_debug)
+{
+// Verify using the return code if we have GPU debug flag enabled
+#if defined(__CUDACC__) && defined(__CUDACC_DEBUG__)
+ *has_debug = true;
+#else
+ *has_debug = false;
+#endif
+}
+
+int choose_cuda_device()
+{
+ int nDevices = 0;
+ cudaError_t err = cudaGetDeviceCount(&nDevices);
+ if (err != cudaSuccess) {
+ std::cerr << "Failed to retrieve the number of CUDA enabled devices"
+ << std::endl;
+ return 1;
+ }
+ for (int i = 0; i < nDevices; ++i) {
+ cudaDeviceProp prop;
+ cudaError_t err = cudaGetDeviceProperties(&prop, i);
+ if (err != cudaSuccess) {
+ std::cerr << "Could not retrieve properties from CUDA device " << i
+ << std::endl;
+ return 1;
+ }
+ if (prop.major >= 3) {
+ err = cudaSetDevice(i);
+ if (err != cudaSuccess) {
+ std::cout << "Could not select CUDA device " << i << std::endl;
+ } else {
+ return 0;
+ }
+ }
+ }
+
+ std::cout << "Could not find a CUDA enabled card supporting compute >=3.0"
+ << std::endl;
+
+ return 1;
+}
+
+int main(int argc, char** argv)
+{
+ bool* has_debug;
+ cudaError_t err = cudaMallocManaged(&has_debug, sizeof(bool));
+ if (err != cudaSuccess) {
+ std::cerr << "cudaMallocManaged failed:\n"
+ << " " << cudaGetErrorString(err) << std::endl;
+ return 1;
+ }
+
+ debug_kernel<<<1, 1>>>(has_debug);
+ err = cudaDeviceSynchronize();
+ if (err != cudaSuccess) {
+ std::cerr << "debug_kernel: kernel launch shouldn't have failed\n"
+ << "reason:\t" << cudaGetErrorString(err) << std::endl;
+ return 1;
+ }
+ if (*has_debug == false) {
+ std::cerr << "debug_kernel: kernel not compiled with device debug"
+ << std::endl;
+ return 1;
+ }
+ return 0;
+}
diff --git a/Tests/CudaOnly/PDB/CMakeLists.txt b/Tests/CudaOnly/PDB/CMakeLists.txt
new file mode 100644
index 000000000..6ecf98935
--- /dev/null
+++ b/Tests/CudaOnly/PDB/CMakeLists.txt
@@ -0,0 +1,19 @@
+cmake_minimum_required(VERSION 3.11)
+project (PDB CUDA)
+
+add_executable(CudaOnlyPDB main.cu)
+set_target_properties(CudaOnlyPDB PROPERTIES
+ PDB_NAME LinkPDBName
+ PDB_OUTPUT_DIRECTORY LinkPDBDir
+ COMPILE_PDB_NAME CompPDBName
+ COMPILE_PDB_OUTPUT_DIRECTORY CompPDBDir
+ )
+
+set(pdbs
+ ${CMAKE_CURRENT_BINARY_DIR}/CompPDBDir/${CMAKE_CFG_INTDIR}/CompPDBName.pdb
+ ${CMAKE_CURRENT_BINARY_DIR}/LinkPDBDir/${CMAKE_CFG_INTDIR}/LinkPDBName.pdb
+ )
+add_custom_command(TARGET CudaOnlyPDB POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -Dconfig=$<CONFIG> "-Dpdbs=${pdbs}"
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/check_pdbs.cmake
+ )
diff --git a/Tests/CudaOnly/PDB/check_pdbs.cmake b/Tests/CudaOnly/PDB/check_pdbs.cmake
new file mode 100644
index 000000000..5e01ca722
--- /dev/null
+++ b/Tests/CudaOnly/PDB/check_pdbs.cmake
@@ -0,0 +1,10 @@
+if(NOT "${config}" MATCHES "[Dd][Ee][Bb]")
+ return()
+endif()
+foreach(pdb ${pdbs})
+ if(EXISTS "${pdb}")
+ message(STATUS "PDB Exists: ${pdb}")
+ else()
+ message(SEND_ERROR "PDB MISSING:\n ${pdb}")
+ endif()
+endforeach()
diff --git a/Tests/CudaOnly/PDB/main.cu b/Tests/CudaOnly/PDB/main.cu
new file mode 100644
index 000000000..f8b643afb
--- /dev/null
+++ b/Tests/CudaOnly/PDB/main.cu
@@ -0,0 +1,4 @@
+int main()
+{
+ return 0;
+}
diff --git a/Tests/CudaOnly/WithDefs/inc_cuda/inc_cuda.h b/Tests/CudaOnly/WithDefs/inc_cuda/inc_cuda.h
new file mode 100644
index 000000000..e228b5867
--- /dev/null
+++ b/Tests/CudaOnly/WithDefs/inc_cuda/inc_cuda.h
@@ -0,0 +1 @@
+#define INC_CUDA
diff --git a/Tests/ExportImport/Export/SubDirLinkA/CMakeLists.txt b/Tests/ExportImport/Export/SubDirLinkA/CMakeLists.txt
new file mode 100644
index 000000000..1c3c9dccc
--- /dev/null
+++ b/Tests/ExportImport/Export/SubDirLinkA/CMakeLists.txt
@@ -0,0 +1,6 @@
+add_library(SubDirLinkAImported IMPORTED INTERFACE)
+target_compile_definitions(SubDirLinkAImported INTERFACE DEF_SubDirLinkAImportedForExport)
+
+target_link_libraries(TopDirLib PUBLIC SubDirLinkAImported)
+
+add_library(SubDirLinkA STATIC SubDirLinkA.c)
diff --git a/Tests/ExportImport/Export/SubDirLinkA/SubDirLinkA.c b/Tests/ExportImport/Export/SubDirLinkA/SubDirLinkA.c
new file mode 100644
index 000000000..abf76f556
--- /dev/null
+++ b/Tests/ExportImport/Export/SubDirLinkA/SubDirLinkA.c
@@ -0,0 +1,11 @@
+#ifdef DEF_SubDirLinkAImportedForExport
+# error "DEF_SubDirLinkAImportedForExport is defined but should not be!"
+#endif
+#ifndef DEF_SubDirLinkBImportedForExport
+# error "DEF_SubDirLinkBImportedForExport is not defined but should be!"
+#endif
+
+int testSubDirLinkA(void)
+{
+ return 0;
+}
diff --git a/Tests/ExportImport/Export/SubDirLinkB/CMakeLists.txt b/Tests/ExportImport/Export/SubDirLinkB/CMakeLists.txt
new file mode 100644
index 000000000..22e168ff8
--- /dev/null
+++ b/Tests/ExportImport/Export/SubDirLinkB/CMakeLists.txt
@@ -0,0 +1,4 @@
+add_library(SubDirLinkBImported IMPORTED INTERFACE)
+target_compile_definitions(SubDirLinkBImported INTERFACE DEF_SubDirLinkBImportedForExport)
+
+target_link_libraries(SubDirLinkA PUBLIC SubDirLinkBImported)
diff --git a/Tests/ExportImport/Export/testLib9.c b/Tests/ExportImport/Export/testLib9.c
new file mode 100644
index 000000000..2f6f8ebc7
--- /dev/null
+++ b/Tests/ExportImport/Export/testLib9.c
@@ -0,0 +1,15 @@
+#ifndef testLib9ObjPub_USED
+# error "testLib9ObjPub_USED not defined!"
+#endif
+#ifndef testLib9ObjPriv_USED
+# error "testLib9ObjPriv_USED not defined!"
+#endif
+#ifdef testLib9ObjIface_USED
+# error "testLib9ObjIface_USED defined but should not be!"
+#endif
+int testLib9ObjPub(void);
+int testLib9ObjPriv(void);
+int testLib9(void)
+{
+ return (testLib9ObjPub() + testLib9ObjPriv());
+}
diff --git a/Tests/ExportImport/Export/testLib9ObjIface.c b/Tests/ExportImport/Export/testLib9ObjIface.c
new file mode 100644
index 000000000..e75440a28
--- /dev/null
+++ b/Tests/ExportImport/Export/testLib9ObjIface.c
@@ -0,0 +1,11 @@
+/* Duplicate symbols from other sources to verify that this source
+ is not included when the object library is used. */
+int testLib9ObjMissing(void);
+int testLib9ObjPub(void)
+{
+ return testLib9ObjMissing();
+}
+int testLib9ObjPriv(void)
+{
+ return testLib9ObjMissing();
+}
diff --git a/Tests/ExportImport/Export/testLib9ObjPriv.c b/Tests/ExportImport/Export/testLib9ObjPriv.c
new file mode 100644
index 000000000..6fa63ccde
--- /dev/null
+++ b/Tests/ExportImport/Export/testLib9ObjPriv.c
@@ -0,0 +1,4 @@
+int testLib9ObjPriv(void)
+{
+ return 0;
+}
diff --git a/Tests/ExportImport/Export/testLib9ObjPub.c b/Tests/ExportImport/Export/testLib9ObjPub.c
new file mode 100644
index 000000000..66e2624b0
--- /dev/null
+++ b/Tests/ExportImport/Export/testLib9ObjPub.c
@@ -0,0 +1,4 @@
+int testLib9ObjPub(void)
+{
+ return 0;
+}
diff --git a/Tests/ExportImport/Export/testTopDirLib.c b/Tests/ExportImport/Export/testTopDirLib.c
new file mode 100644
index 000000000..1ec68de1f
--- /dev/null
+++ b/Tests/ExportImport/Export/testTopDirLib.c
@@ -0,0 +1,11 @@
+#ifndef DEF_SubDirLinkAImportedForExport
+# error "DEF_SubDirLinkAImportedForExport is not defined but should be!"
+#endif
+#ifdef DEF_SubDirLinkBImportedForExport
+# error "DEF_SubDirLinkBImportedForExport is defined but should not be!"
+#endif
+
+int testTopDirLib(void)
+{
+ return 0;
+}
diff --git a/Tests/ExportImport/Import/A/SubDirLink.c b/Tests/ExportImport/Import/A/SubDirLink.c
new file mode 100644
index 000000000..eb4b8609a
--- /dev/null
+++ b/Tests/ExportImport/Import/A/SubDirLink.c
@@ -0,0 +1,14 @@
+#ifndef DEF_SubDirLinkAImportedForImport
+# error "DEF_SubDirLinkAImportedForImport is not defined but should be!"
+#endif
+#ifndef DEF_SubDirLinkBImportedForImport
+# error "DEF_SubDirLinkBImportedForImport is not defined but should be!"
+#endif
+
+extern int testTopDirLib(void);
+extern int testSubDirLinkA(void);
+
+int main(void)
+{
+ return (testTopDirLib() + testSubDirLinkA() + 0);
+}
diff --git a/Tests/ExportImport/Import/A/imp_testLib9.c b/Tests/ExportImport/Import/A/imp_testLib9.c
new file mode 100644
index 000000000..e014857ec
--- /dev/null
+++ b/Tests/ExportImport/Import/A/imp_testLib9.c
@@ -0,0 +1,16 @@
+#ifndef testLib9ObjPub_USED
+# error "testLib9ObjPub_USED not defined!"
+#endif
+#ifdef testLib9ObjPriv_USED
+# error "testLib9ObjPriv_USED defined but should not be!"
+#endif
+#ifndef testLib9ObjIface_USED
+# error "testLib9ObjIface_USED not defined!"
+#endif
+
+int testLib9(void);
+
+int main()
+{
+ return testLib9();
+}
diff --git a/Tests/ExportImport/Import/A/imp_testLinkOptions.cpp b/Tests/ExportImport/Import/A/imp_testLinkOptions.cpp
new file mode 100644
index 000000000..2b18b2e09
--- /dev/null
+++ b/Tests/ExportImport/Import/A/imp_testLinkOptions.cpp
@@ -0,0 +1,8 @@
+
+#include "testSharedLibRequired.h"
+
+int foo()
+{
+ TestSharedLibRequired req;
+ return req.foo();
+}
diff --git a/Tests/ExternalProjectLocal/Step5/CMakeLists.txt b/Tests/ExternalProjectLocal/Step5/CMakeLists.txt
new file mode 100644
index 000000000..93b3880f0
--- /dev/null
+++ b/Tests/ExternalProjectLocal/Step5/CMakeLists.txt
@@ -0,0 +1,71 @@
+cmake_minimum_required (VERSION 2.6)
+project (Tutorial)
+
+# The version number.
+set (Tutorial_VERSION_MAJOR 1)
+set (Tutorial_VERSION_MINOR 0)
+
+# does this system provide the log and exp functions?
+include (${CMAKE_ROOT}/Modules/CheckFunctionExists.cmake)
+check_function_exists (log HAVE_LOG)
+check_function_exists (exp HAVE_EXP)
+
+# should we use our own math functions
+option(USE_MYMATH "Use tutorial provided math implementation" ON)
+
+# configure a header file to pass some of the CMake settings
+# to the source code
+configure_file (
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ )
+
+# add the binary tree to the search path for include files
+# so that we will find TutorialConfig.h
+include_directories ("${PROJECT_BINARY_DIR}")
+
+# add the MathFunctions library?
+if (USE_MYMATH)
+ include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
+ add_subdirectory (MathFunctions)
+ set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
+endif ()
+
+# add the executable
+add_executable (Tutorial tutorial.cxx)
+target_link_libraries (Tutorial ${EXTRA_LIBS})
+
+# add the install targets
+install (TARGETS Tutorial DESTINATION bin)
+install (FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ DESTINATION include)
+
+# enable testing
+enable_testing ()
+
+# does the application run
+add_test (TutorialRuns Tutorial 25)
+
+# does the usage message work?
+add_test (TutorialUsage Tutorial)
+set_tests_properties (TutorialUsage
+ PROPERTIES
+ PASS_REGULAR_EXPRESSION "Usage:.*number"
+ )
+
+#define a macro to simplify adding tests
+macro (do_test arg result)
+ add_test (TutorialComp${arg} Tutorial ${arg})
+ set_tests_properties (TutorialComp${arg}
+ PROPERTIES PASS_REGULAR_EXPRESSION ${result}
+ )
+endmacro ()
+
+# do a bunch of result based tests
+do_test (4 "4 is 2")
+do_test (9 "9 is 3")
+do_test (5 "5 is 2.236")
+do_test (7 "7 is 2.645")
+do_test (25 "25 is 5")
+do_test (-25 "-25 is 0")
+do_test (0.0001 "0.0001 is 0.01")
diff --git a/Tests/ExternalProjectLocal/Step5/MathFunctions/CMakeLists.txt b/Tests/ExternalProjectLocal/Step5/MathFunctions/CMakeLists.txt
new file mode 100644
index 000000000..453a46332
--- /dev/null
+++ b/Tests/ExternalProjectLocal/Step5/MathFunctions/CMakeLists.txt
@@ -0,0 +1,17 @@
+# first we add the executable that generates the table
+# add the binary tree directory to the search path for include files
+include_directories( ${CMAKE_CURRENT_BINARY_DIR} )
+
+add_executable(MakeTable MakeTable.cxx )
+# add the command to generate the source code
+add_custom_command (
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ DEPENDS MakeTable
+ )
+
+# add the main library
+add_library(MathFunctions mysqrt.cxx ${CMAKE_CURRENT_BINARY_DIR}/Table.h )
+
+install (TARGETS MathFunctions DESTINATION bin)
+install (FILES MathFunctions.h DESTINATION include)
diff --git a/Tests/ExternalProjectLocal/Step5/MathFunctions/MakeTable.cxx b/Tests/ExternalProjectLocal/Step5/MathFunctions/MakeTable.cxx
new file mode 100644
index 000000000..cebd50fcc
--- /dev/null
+++ b/Tests/ExternalProjectLocal/Step5/MathFunctions/MakeTable.cxx
@@ -0,0 +1,32 @@
+// A simple program that builds a sqrt table
+#include <math.h>
+#include <stdio.h>
+
+int main(int argc, char* argv[])
+{
+ int i;
+ double result;
+
+ // make sure we have enough arguments
+ if (argc < 2) {
+ return 1;
+ }
+
+ // open the output file
+ FILE* fout = fopen(argv[1], "w");
+ if (!fout) {
+ return 1;
+ }
+
+ // create a source file with a table of square roots
+ fprintf(fout, "double sqrtTable[] = {\n");
+ for (i = 0; i < 10; ++i) {
+ result = sqrt(static_cast<double>(i));
+ fprintf(fout, "%g,\n", result);
+ }
+
+ // close the table with a zero
+ fprintf(fout, "0};\n");
+ fclose(fout);
+ return 0;
+}
diff --git a/Tests/ExternalProjectLocal/Step5/MathFunctions/MathFunctions.h b/Tests/ExternalProjectLocal/Step5/MathFunctions/MathFunctions.h
new file mode 100644
index 000000000..cd36bccff
--- /dev/null
+++ b/Tests/ExternalProjectLocal/Step5/MathFunctions/MathFunctions.h
@@ -0,0 +1 @@
+double mysqrt(double x);
diff --git a/Tests/ExternalProjectLocal/Step5/MathFunctions/mysqrt.cxx b/Tests/ExternalProjectLocal/Step5/MathFunctions/mysqrt.cxx
new file mode 100644
index 000000000..458ed63a1
--- /dev/null
+++ b/Tests/ExternalProjectLocal/Step5/MathFunctions/mysqrt.cxx
@@ -0,0 +1,40 @@
+#include "MathFunctions.h"
+#include "TutorialConfig.h"
+#include <stdio.h>
+
+// include the generated table
+#include "Table.h"
+
+#include <math.h>
+
+// a hack square root calculation using simple operations
+double mysqrt(double x)
+{
+ if (x <= 0) {
+ return 0;
+ }
+
+ double result;
+
+ // if we have both log and exp then use them
+ double delta;
+
+ // use the table to help find an initial value
+ result = x;
+ if (x >= 1 && x < 10) {
+ result = sqrtTable[static_cast<int>(x)];
+ }
+
+ // do ten iterations
+ int i;
+ for (i = 0; i < 10; ++i) {
+ if (result <= 0) {
+ result = 0.1;
+ }
+ delta = x - (result * result);
+ result = result + 0.5 * delta / result;
+ fprintf(stdout, "Computing sqrt of %g to be %g\n", x, result);
+ }
+
+ return result;
+}
diff --git a/Tests/ExternalProjectLocal/Step5/TutorialConfig.h.in b/Tests/ExternalProjectLocal/Step5/TutorialConfig.h.in
new file mode 100644
index 000000000..e97ce24ea
--- /dev/null
+++ b/Tests/ExternalProjectLocal/Step5/TutorialConfig.h.in
@@ -0,0 +1,8 @@
+// the configured options and settings for Tutorial
+#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
+#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
+#cmakedefine USE_MYMATH
+
+// does the platform provide exp and log functions?
+#cmakedefine HAVE_LOG
+#cmakedefine HAVE_EXP
diff --git a/Tests/ExternalProjectLocal/Step5/tutorial.cxx b/Tests/ExternalProjectLocal/Step5/tutorial.cxx
new file mode 100644
index 000000000..37f6ac456
--- /dev/null
+++ b/Tests/ExternalProjectLocal/Step5/tutorial.cxx
@@ -0,0 +1,33 @@
+// A simple program that computes the square root of a number
+#include "TutorialConfig.h"
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifdef USE_MYMATH
+# include "MathFunctions.h"
+#endif
+
+int main(int argc, char* argv[])
+{
+ if (argc < 2) {
+ fprintf(stdout, "%s Version %d.%d\n", argv[0], Tutorial_VERSION_MAJOR,
+ Tutorial_VERSION_MINOR);
+ fprintf(stdout, "Usage: %s number\n", argv[0]);
+ return 1;
+ }
+
+ double inputValue = atof(argv[1]);
+ double outputValue = 0;
+
+ if (inputValue >= 0) {
+#ifdef USE_MYMATH
+ outputValue = mysqrt(inputValue);
+#else
+ outputValue = sqrt(inputValue);
+#endif
+ }
+
+ fprintf(stdout, "The square root of %g is %g\n", inputValue, outputValue);
+ return 0;
+}
diff --git a/Tests/ExternalProjectSourceSubdirNotCMake/CMakeLists.txt b/Tests/ExternalProjectSourceSubdirNotCMake/CMakeLists.txt
new file mode 100644
index 000000000..f64df1a77
--- /dev/null
+++ b/Tests/ExternalProjectSourceSubdirNotCMake/CMakeLists.txt
@@ -0,0 +1,20 @@
+cmake_minimum_required(VERSION 3.6)
+project(ExternalProjectSourceSubdirNotCMake NONE)
+include(ExternalProject)
+
+find_program(MAKE_EXECUTABLE
+ NAMES gmake make)
+
+if (NOT MAKE_EXECUTABLE)
+ message("No `make` executable found; skipping")
+ return ()
+endif ()
+
+ExternalProject_Add(Example
+ SOURCE_SUBDIR subdir
+ BUILD_IN_SOURCE 1
+ SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Example
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND "${MAKE_EXECUTABLE}"
+ INSTALL_COMMAND ""
+ )
diff --git a/Tests/ExternalProjectSourceSubdirNotCMake/Example/subdir/Makefile b/Tests/ExternalProjectSourceSubdirNotCMake/Example/subdir/Makefile
new file mode 100644
index 000000000..cab3b8f4b
--- /dev/null
+++ b/Tests/ExternalProjectSourceSubdirNotCMake/Example/subdir/Makefile
@@ -0,0 +1,2 @@
+all:
+ echo "complete"
diff --git a/Tests/FindALSA/CMakeLists.txt b/Tests/FindALSA/CMakeLists.txt
new file mode 100644
index 000000000..891f7a43a
--- /dev/null
+++ b/Tests/FindALSA/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindALSA.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindALSA/Test"
+ "${CMake_BINARY_DIR}/Tests/FindALSA/Test"
+ ${build_generator_args}
+ --build-project TestFindALSA
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindALSA/Test/CMakeLists.txt b/Tests/FindALSA/Test/CMakeLists.txt
new file mode 100644
index 000000000..2829740cf
--- /dev/null
+++ b/Tests/FindALSA/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindALSA C)
+include(CTest)
+
+find_package(ALSA REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_ALSA_VERSION="${ALSA_VERSION_STRING}")
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt ALSA::ALSA)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${ALSA_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${ALSA_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindALSA/Test/main.c b/Tests/FindALSA/Test/main.c
new file mode 100644
index 000000000..d3303d076
--- /dev/null
+++ b/Tests/FindALSA/Test/main.c
@@ -0,0 +1,10 @@
+#include <alsa/global.h>
+#include <stdio.h>
+#include <string.h>
+
+int main()
+{
+ printf("Found ALSA version %s, expected version %s\n",
+ snd_asoundlib_version(), CMAKE_EXPECTED_ALSA_VERSION);
+ return strcmp(snd_asoundlib_version(), CMAKE_EXPECTED_ALSA_VERSION);
+}
diff --git a/Tests/FindBoost/TestFail/CMakeLists.txt b/Tests/FindBoost/TestFail/CMakeLists.txt
new file mode 100644
index 000000000..7c14a5990
--- /dev/null
+++ b/Tests/FindBoost/TestFail/CMakeLists.txt
@@ -0,0 +1,18 @@
+cmake_minimum_required(VERSION 3.1)
+project(TestFindBoost CXX)
+include(CTest)
+
+find_package(Boost REQUIRED COMPONENTS foobar filesystem thread)
+
+add_executable(test_boost_tgt main.cxx)
+target_link_libraries(test_boost_tgt
+ Boost::dynamic_linking
+ Boost::disable_autolinking
+ Boost::filesystem
+ Boost::thread)
+add_test(NAME test_boost_tgt COMMAND test_boost_tgt)
+
+add_executable(test_boost_var main.cxx)
+target_include_directories(test_boost_var PRIVATE ${Boost_INCLUDE_DIRS})
+target_link_libraries(test_boost_var PRIVATE ${Boost_FILESYSTEM_LIBRARIES} ${Boost_SYSTEM_LIBRARIES} ${Boost_THREAD_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})
+add_test(NAME test_boost_var COMMAND test_boost_var)
diff --git a/Tests/FindBoost/TestFail/main.cxx b/Tests/FindBoost/TestFail/main.cxx
new file mode 100644
index 000000000..6e8b5da63
--- /dev/null
+++ b/Tests/FindBoost/TestFail/main.cxx
@@ -0,0 +1,24 @@
+#include <boost/filesystem.hpp>
+#include <boost/thread.hpp>
+
+namespace {
+
+boost::mutex m1;
+boost::recursive_mutex m2;
+
+void threadmain()
+{
+ boost::lock_guard<boost::mutex> lock1(m1);
+ boost::lock_guard<boost::recursive_mutex> lock2(m2);
+
+ boost::filesystem::path p(boost::filesystem::current_path());
+}
+}
+
+int main()
+{
+ boost::thread foo(threadmain);
+ foo.join();
+
+ return 0;
+}
diff --git a/Tests/FindBoost/TestPython/CMakeLists.txt b/Tests/FindBoost/TestPython/CMakeLists.txt
new file mode 100644
index 000000000..4d137ca0d
--- /dev/null
+++ b/Tests/FindBoost/TestPython/CMakeLists.txt
@@ -0,0 +1,17 @@
+cmake_minimum_required(VERSION 3.14)
+project(TestFindBoostPython CXX)
+include(CTest)
+
+find_package(Boost OPTIONAL_COMPONENTS python27 python34 python35 python36 python37)
+
+set(FAILTEST TRUE)
+foreach (v IN ITEMS 27 34 35 36 37)
+ if (Boost_PYTHON${v}_FOUND)
+ set(FAILTEST FALSE)
+ break()
+ endif ()
+endforeach ()
+
+if (FAILTEST)
+ message(FATAL_ERROR "No Boost Python module found")
+endif ()
diff --git a/Tests/FindCURL/CMakeLists.txt b/Tests/FindCURL/CMakeLists.txt
new file mode 100644
index 000000000..0cfd629c9
--- /dev/null
+++ b/Tests/FindCURL/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindCURL.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindCURL/Test"
+ "${CMake_BINARY_DIR}/Tests/FindCURL/Test"
+ ${build_generator_args}
+ --build-project TestFindCURL
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindCURL/Test/CMakeLists.txt b/Tests/FindCURL/Test/CMakeLists.txt
new file mode 100644
index 000000000..cbf2866b0
--- /dev/null
+++ b/Tests/FindCURL/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindCURL C)
+include(CTest)
+
+find_package(CURL REQUIRED COMPONENTS HTTP)
+
+add_definitions(-DCMAKE_EXPECTED_CURL_VERSION="${CURL_VERSION_STRING}")
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt CURL::libcurl)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${CURL_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${CURL_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindCURL/Test/main.c b/Tests/FindCURL/Test/main.c
new file mode 100644
index 000000000..263775f95
--- /dev/null
+++ b/Tests/FindCURL/Test/main.c
@@ -0,0 +1,17 @@
+#include <curl/curl.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+int main()
+{
+ struct curl_slist* slist;
+
+ curl_global_init(0);
+
+ slist = curl_slist_append(NULL, "CMake");
+ curl_slist_free_all(slist);
+
+ curl_global_cleanup();
+
+ return 0;
+}
diff --git a/Tests/FindCups/CMakeLists.txt b/Tests/FindCups/CMakeLists.txt
new file mode 100644
index 000000000..5be1ac106
--- /dev/null
+++ b/Tests/FindCups/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindCups.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindCups/Test"
+ "${CMake_BINARY_DIR}/Tests/FindCups/Test"
+ ${build_generator_args}
+ --build-project FindCups
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindCups/Test/CMakeLists.txt b/Tests/FindCups/Test/CMakeLists.txt
new file mode 100644
index 000000000..9e90553fb
--- /dev/null
+++ b/Tests/FindCups/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindCups C)
+include(CTest)
+
+find_package(Cups REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_CUPS_VERSION="${CUPS_VERSION_STRING}")
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt Cups::Cups)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${CUPS_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${CUPS_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindCups/Test/main.c b/Tests/FindCups/Test/main.c
new file mode 100644
index 000000000..b69d621f7
--- /dev/null
+++ b/Tests/FindCups/Test/main.c
@@ -0,0 +1,12 @@
+#include <cups/cups.h>
+
+int main()
+{
+ int num_options = 0;
+ cups_option_t* options = NULL;
+
+ num_options = cupsAddOption(CUPS_COPIES, "1", num_options, &options);
+ cupsFreeOptions(num_options, options);
+
+ return 0;
+}
diff --git a/Tests/FindDoxygen/AllTarget/CMakeLists.txt b/Tests/FindDoxygen/AllTarget/CMakeLists.txt
new file mode 100644
index 000000000..69aa518c7
--- /dev/null
+++ b/Tests/FindDoxygen/AllTarget/CMakeLists.txt
@@ -0,0 +1,42 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindDoxygen VERSION 1.0 LANGUAGES NONE)
+enable_testing()
+
+find_package(Doxygen REQUIRED)
+
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/main.cpp [[
+/**
+ * \file
+ * \brief One C++ file w/ sample Doxygen comment just to produce any docs...
+ */
+]])
+
+set(DOXYGEN_OUTPUT_DIRECTORY outDirWithout)
+file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/${DOXYGEN_OUTPUT_DIRECTORY})
+doxygen_add_docs(docsNoAll ${CMAKE_CURRENT_BINARY_DIR}/main.cpp)
+
+set(DOXYGEN_OUTPUT_DIRECTORY outDirWith)
+file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/${DOXYGEN_OUTPUT_DIRECTORY})
+doxygen_add_docs(docsWithAll ALL ${CMAKE_CURRENT_BINARY_DIR}/main.cpp)
+
+# Define tests cases that check whether targets were built
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/dirExists.cmake [[
+cmake_minimum_required(VERSION 3.11)
+if(NOT EXISTS ${dirName})
+ message(FATAL_ERROR "Directory does not exist: ${dirName}")
+endif()
+]])
+
+add_test(NAME checkWith COMMAND
+ ${CMAKE_COMMAND}
+ -D dirName=${CMAKE_CURRENT_BINARY_DIR}/outDirWith
+ -P dirExists.cmake
+)
+add_test(NAME checkWithout COMMAND
+ ${CMAKE_COMMAND}
+ -D dirName=${CMAKE_CURRENT_BINARY_DIR}/outDirWithout
+ -P dirExists.cmake
+)
+set_tests_properties(checkWithout PROPERTIES
+ WILL_FAIL TRUE
+)
diff --git a/Tests/FindDoxygen/QuotingTest/CMakeLists.txt b/Tests/FindDoxygen/QuotingTest/CMakeLists.txt
new file mode 100644
index 000000000..26bf090db
--- /dev/null
+++ b/Tests/FindDoxygen/QuotingTest/CMakeLists.txt
@@ -0,0 +1,34 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindDoxygen VERSION 1.0 LANGUAGES NONE)
+
+find_package(Doxygen REQUIRED)
+
+set(DOXYGEN_PROJECT_BRIEF "String with spaces")
+set(DOXYGEN_ALIASES
+ [[somealias="@some_command param"]]
+ "anotherAlias=@foobar"
+)
+
+set(DOXYGEN_VERBATIM_VARS DOXYGEN_ALIASES)
+
+doxygen_add_docs(docsQuoting)
+if(NOT EXISTS "${PROJECT_BINARY_DIR}/Doxyfile.docsQuoting")
+ message(FATAL_ERROR "Missing generated file: Doxyfile.docsQuoting")
+endif()
+
+file(STRINGS "${PROJECT_BINARY_DIR}/Doxyfile.docsQuoting" matches
+ REGEX [[^PROJECT_BRIEF *= *"String with spaces"]]
+)
+if(NOT matches)
+ message(FATAL_ERROR "PROJECT_BRIEF does not match expected contents")
+endif()
+
+file(STRINGS "${PROJECT_BINARY_DIR}/Doxyfile.docsQuoting" matches
+ REGEX [[^ALIASES *= *somealias="@some_command param" anotherAlias=@foobar]]
+)
+if(NOT matches)
+ message(FATAL_ERROR "ALIASES does not match expected contents")
+endif()
+
+add_custom_target(allDocTargets)
+add_dependencies(allDocTargets docsQuoting)
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/FindEnvModules/CMakeLists.txt b/Tests/FindEnvModules/CMakeLists.txt
new file mode 100644
index 000000000..95b7d1ddb
--- /dev/null
+++ b/Tests/FindEnvModules/CMakeLists.txt
@@ -0,0 +1,3 @@
+add_test(FindEnvModules.Test ${CMAKE_CMAKE_COMMAND}
+ -P ${CMAKE_CURRENT_LIST_DIR}/EnvModules.cmake
+)
diff --git a/Tests/FindEnvModules/EnvModules.cmake b/Tests/FindEnvModules/EnvModules.cmake
new file mode 100644
index 000000000..0c81bf21d
--- /dev/null
+++ b/Tests/FindEnvModules/EnvModules.cmake
@@ -0,0 +1,35 @@
+find_package(EnvModules REQUIRED)
+message("module purge")
+env_module(COMMAND purge RESULT_VARIABLE ret_var)
+if(NOT ret_var EQUAL 0)
+ message(FATAL_ERROR "module(purge) returned ${ret_var}")
+endif()
+
+message("module avail")
+env_module_avail(avail_mods)
+foreach(mod IN LISTS avail_mods)
+ message(" ${mod}")
+endforeach()
+
+if(avail_mods)
+ list(GET avail_mods 0 mod0)
+ message("module load ${mod0}")
+ env_module(load ${mod0})
+
+ message("module list")
+ env_module_list(loaded_mods)
+ foreach(mod IN LISTS loaded_mods)
+ message(" ${mod}")
+ endforeach()
+
+ list(LENGTH loaded_mods num_loaded_mods)
+ message("Number of modules loaded: ${num_loaded_mods}")
+ if(NOT num_loaded_mods EQUAL 1)
+ message(FATAL_ERROR "Exactly 1 module should be loaded. Found ${num_loaded_mods}")
+ endif()
+
+ list(GET loaded_mods 0 mod0_actual)
+ if(NOT (mod0_actual MATCHES "^${mod0}"))
+ message(FATAL_ERROR "Loaded module does not match ${mod0}. Actual: ${mod0_actual}")
+ endif()
+endif()
diff --git a/Tests/FindFontconfig/CMakeLists.txt b/Tests/FindFontconfig/CMakeLists.txt
new file mode 100644
index 000000000..d683d8746
--- /dev/null
+++ b/Tests/FindFontconfig/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindFontconfig.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindFontconfig/Test"
+ "${CMake_BINARY_DIR}/Tests/FindFontconfig/Test"
+ ${build_generator_args}
+ --build-project TestFindFontconfig
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindFontconfig/Test/CMakeLists.txt b/Tests/FindFontconfig/Test/CMakeLists.txt
new file mode 100644
index 000000000..36c76b104
--- /dev/null
+++ b/Tests/FindFontconfig/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindFontconfig C)
+include(CTest)
+
+find_package(Fontconfig REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_FONTCONFIG_VERSION="${Fontconfig_VERSION}")
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt Fontconfig::Fontconfig)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${Fontconfig_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${Fontconfig_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindFontconfig/Test/main.c b/Tests/FindFontconfig/Test/main.c
new file mode 100644
index 000000000..c5b596304
--- /dev/null
+++ b/Tests/FindFontconfig/Test/main.c
@@ -0,0 +1,17 @@
+#include <assert.h>
+#include <fontconfig/fontconfig.h>
+#include <stdio.h>
+#include <string.h>
+
+int main()
+{
+ FcInit();
+ printf("Found Fontconfig.\n");
+
+ char fontconfig_version_string[16];
+ snprintf(fontconfig_version_string, 16, "%i.%i.%i", FC_MAJOR, FC_MINOR,
+ FC_REVISION);
+ assert(
+ strcmp(fontconfig_version_string, CMAKE_EXPECTED_FONTCONFIG_VERSION) == 0);
+ return 0;
+}
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/FindGDAL/CMakeLists.txt b/Tests/FindGDAL/CMakeLists.txt
new file mode 100644
index 000000000..12f95e11e
--- /dev/null
+++ b/Tests/FindGDAL/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindGDAL.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindGDAL/Test"
+ "${CMake_BINARY_DIR}/Tests/FindGDAL/Test"
+ ${build_generator_args}
+ --build-project TestFindGDAL
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindGDAL/Test/CMakeLists.txt b/Tests/FindGDAL/Test/CMakeLists.txt
new file mode 100644
index 000000000..8bdc57c91
--- /dev/null
+++ b/Tests/FindGDAL/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindGDAL C)
+include(CTest)
+
+find_package(GDAL REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_GDAL_VERSION="${GDAL_VERSION}")
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt GDAL::GDAL)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${GDAL_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${GDAL_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindGDAL/Test/main.c b/Tests/FindGDAL/Test/main.c
new file mode 100644
index 000000000..7b31a1362
--- /dev/null
+++ b/Tests/FindGDAL/Test/main.c
@@ -0,0 +1,11 @@
+#include <gdal.h>
+#include <stdio.h>
+#include <string.h>
+
+int main()
+{
+ printf("Found GDAL version %s, expected version %s\n", GDAL_RELEASE_NAME,
+ CMAKE_EXPECTED_GDAL_VERSION);
+ GDALAllRegister();
+ return strcmp(GDAL_RELEASE_NAME, CMAKE_EXPECTED_GDAL_VERSION);
+}
diff --git a/Tests/FindGIF/CMakeLists.txt b/Tests/FindGIF/CMakeLists.txt
new file mode 100644
index 000000000..bac64afd0
--- /dev/null
+++ b/Tests/FindGIF/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindGIF.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindGIF/Test"
+ "${CMake_BINARY_DIR}/Tests/FindGIF/Test"
+ ${build_generator_args}
+ --build-project TestFindGIF
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindGIF/Test/CMakeLists.txt b/Tests/FindGIF/Test/CMakeLists.txt
new file mode 100644
index 000000000..961e636fa
--- /dev/null
+++ b/Tests/FindGIF/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.4)
+project(TestFindGIF C)
+include(CTest)
+
+find_package(GIF REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_GIF_VERSION="${GIF_VERSION}")
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt GIF::GIF)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${GIF_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${GIF_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindGIF/Test/main.c b/Tests/FindGIF/Test/main.c
new file mode 100644
index 000000000..4ed72ec1b
--- /dev/null
+++ b/Tests/FindGIF/Test/main.c
@@ -0,0 +1,35 @@
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <gif_lib.h>
+
+// GIFLIB before version 5 didn't know this macro
+#ifndef GIFLIB_MAJOR
+# define GIFLIB_MAJOR 4
+#endif
+
+int main()
+{
+ // because of the API changes we have to test different functions depending
+ // on the version of GIFLIB
+#if GIFLIB_MAJOR >= 5
+ // test the linker
+ GifErrorString(D_GIF_SUCCEEDED);
+
+ // check the version
+ char gif_version_string[16];
+ snprintf(gif_version_string, 16, "%i.%i.%i", GIFLIB_MAJOR, GIFLIB_MINOR,
+ GIFLIB_RELEASE);
+
+ assert(strcmp(gif_version_string, CMAKE_EXPECTED_GIF_VERSION) == 0);
+#else
+ // test the linker
+ GifLastError();
+
+ // unfortunately there is no way to check the version in older version of
+ // GIFLIB
+#endif
+
+ return 0;
+}
diff --git a/Tests/FindGLEW/CMakeLists.txt b/Tests/FindGLEW/CMakeLists.txt
new file mode 100644
index 000000000..ff42bcec1
--- /dev/null
+++ b/Tests/FindGLEW/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindGLEW.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindGLEW/Test"
+ "${CMake_BINARY_DIR}/Tests/FindGLEW/Test"
+ ${build_generator_args}
+ --build-project TestFindGLEW
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindGLEW/Test/CMakeLists.txt b/Tests/FindGLEW/Test/CMakeLists.txt
new file mode 100644
index 000000000..954ee1092
--- /dev/null
+++ b/Tests/FindGLEW/Test/CMakeLists.txt
@@ -0,0 +1,18 @@
+cmake_minimum_required(VERSION 3.1)
+project(TestFindGLEW LANGUAGES CXX)
+include(CTest)
+
+find_package(GLEW REQUIRED)
+
+add_executable(test_glew_shared_tgt main.cpp)
+target_link_libraries(test_glew_shared_tgt GLEW::GLEW)
+add_test(NAME test_glew_shared_tgt COMMAND test_glew_shared_tgt)
+
+add_executable(test_glew_generic_tgt main.cpp)
+target_link_libraries(test_glew_generic_tgt GLEW::glew)
+add_test(NAME test_glew_generic_tgt COMMAND test_glew_generic_tgt)
+
+add_executable(test_glew_var main.cpp)
+target_include_directories(test_glew_var PRIVATE ${GLEW_INCLUDE_DIRS})
+target_link_libraries(test_glew_var PRIVATE ${GLEW_LIBRARIES})
+add_test(NAME test_glew_var COMMAND test_glew_var)
diff --git a/Tests/FindGLEW/Test/main.cpp b/Tests/FindGLEW/Test/main.cpp
new file mode 100644
index 000000000..4a108ad24
--- /dev/null
+++ b/Tests/FindGLEW/Test/main.cpp
@@ -0,0 +1,8 @@
+#include <GL/glew.h>
+
+int main()
+{
+ GLenum init_return = glewInit();
+
+ return (init_return == GLEW_OK);
+}
diff --git a/Tests/FindGit/CMakeLists.txt b/Tests/FindGit/CMakeLists.txt
new file mode 100644
index 000000000..5d061f469
--- /dev/null
+++ b/Tests/FindGit/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindGit.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindGit/Test"
+ "${CMake_BINARY_DIR}/Tests/FindGit/Test"
+ ${build_generator_args}
+ --build-project TestFindGit
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindGit/Test/CMakeLists.txt b/Tests/FindGit/Test/CMakeLists.txt
new file mode 100644
index 000000000..26fb372e6
--- /dev/null
+++ b/Tests/FindGit/Test/CMakeLists.txt
@@ -0,0 +1,13 @@
+cmake_minimum_required(VERSION 3.12)
+project(TestFindGit NONE)
+include(CTest)
+
+find_package(Git REQUIRED)
+
+add_test(NAME test_git
+ COMMAND ${CMAKE_COMMAND}
+ "-DGIT_EXECUTABLE=${GIT_EXECUTABLE}"
+ "-DGIT_EXECUTABLE_TARGET=$<TARGET_FILE:Git::Git>"
+ "-DGIT_VERSION_STRING=${GIT_VERSION_STRING}"
+ -P "${CMAKE_CURRENT_LIST_DIR}/RunGit.cmake"
+ )
diff --git a/Tests/FindGit/Test/RunGit.cmake b/Tests/FindGit/Test/RunGit.cmake
new file mode 100644
index 000000000..f798cd355
--- /dev/null
+++ b/Tests/FindGit/Test/RunGit.cmake
@@ -0,0 +1,20 @@
+cmake_minimum_required(VERSION 3.12)
+
+function(run_git exe exe_display)
+ execute_process(COMMAND ${exe} --version
+ OUTPUT_VARIABLE output
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ RESULT_VARIABLE result
+ )
+
+ if(NOT result EQUAL 0)
+ message(SEND_ERROR "Result of ${exe_display} --version is ${result}, should be 0")
+ endif()
+
+ if(NOT output STREQUAL "git version ${GIT_VERSION_STRING}")
+ message(SEND_ERROR "Output of ${exe_display} --version is \"${output}\", should be \"git version ${GIT_VERSION_STRING}\"")
+ endif()
+endfunction()
+
+run_git("${GIT_EXECUTABLE}" "\${GIT_EXECUTABLE}")
+run_git("${GIT_EXECUTABLE_TARGET}" "Git::Git")
diff --git a/Tests/FindIconv/CMakeLists.txt b/Tests/FindIconv/CMakeLists.txt
new file mode 100644
index 000000000..b205b8056
--- /dev/null
+++ b/Tests/FindIconv/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindIconv.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindIconv/Test"
+ "${CMake_BINARY_DIR}/Tests/FindIconv/Test"
+ ${build_generator_args}
+ --build-project TestFindIconv
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindIconv/Test/CMakeLists.txt b/Tests/FindIconv/Test/CMakeLists.txt
new file mode 100644
index 000000000..a6243f53f
--- /dev/null
+++ b/Tests/FindIconv/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindIconv CXX)
+include(CTest)
+
+find_package(Iconv REQUIRED)
+
+add_executable(test_iconv_tgt main.cxx)
+target_link_libraries(test_iconv_tgt Iconv::Iconv)
+target_compile_features(test_iconv_tgt PRIVATE cxx_std_11)
+add_test(NAME test_iconv_tgt COMMAND test_iconv_tgt)
+
+add_executable(test_iconv_var main.cxx)
+target_include_directories(test_iconv_var PRIVATE ${Iconv_INCLUDE_DIRS})
+target_link_libraries(test_iconv_var PRIVATE ${Iconv_LIBRARIES})
+target_compile_features(test_iconv_var PRIVATE cxx_std_11)
+add_test(NAME test_iconv_var COMMAND test_iconv_var)
diff --git a/Tests/FindIconv/Test/main.cxx b/Tests/FindIconv/Test/main.cxx
new file mode 100644
index 000000000..415ee3768
--- /dev/null
+++ b/Tests/FindIconv/Test/main.cxx
@@ -0,0 +1,52 @@
+extern "C" {
+#include <iconv.h>
+}
+#include <array>
+#include <cstddef>
+#include <cstdlib>
+#include <iostream>
+#include <string>
+#include <system_error>
+
+class iconv_desc
+{
+private:
+ iconv_t iconvd_;
+
+public:
+ iconv_desc(const std::string& tocode, const std::string& fromcode)
+ {
+ iconvd_ = iconv_open(tocode.c_str(), fromcode.c_str());
+ if (iconvd_ == reinterpret_cast<iconv_t>(-1))
+ throw std::system_error(errno, std::system_category());
+ }
+
+ ~iconv_desc() { iconv_close(iconvd_); }
+
+ operator iconv_t() { return this->iconvd_; }
+};
+
+int main()
+{
+ try {
+ auto conv_d = iconv_desc{ "ISO-8859-1", "UTF-8" };
+ auto from_str = std::array<char, 10>{ u8"a\xC3\xA4o\xC3\xB6u\xC3\xBC" };
+ auto to_str = std::array<char, 7>{};
+
+ auto from_str_ptr = from_str.data();
+ auto from_len = from_str.size();
+ auto to_str_ptr = to_str.data();
+ auto to_len = to_str.size();
+ const auto iconv_ret =
+ iconv(conv_d, &from_str_ptr, &from_len, &to_str_ptr, &to_len);
+ if (iconv_ret == static_cast<std::size_t>(-1))
+ throw std::system_error(errno, std::system_category());
+ std::cout << '\'' << from_str.data() << "\' converted to \'"
+ << to_str.data() << '\'' << std::endl;
+ return EXIT_SUCCESS;
+ } catch (const std::system_error& ex) {
+ std::cerr << "ERROR: " << ex.code() << '\n'
+ << ex.code().message() << std::endl;
+ }
+ return EXIT_FAILURE;
+}
diff --git a/Tests/FindJPEG/CMakeLists.txt b/Tests/FindJPEG/CMakeLists.txt
new file mode 100644
index 000000000..c8663c560
--- /dev/null
+++ b/Tests/FindJPEG/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindJPEG.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindJPEG/Test"
+ "${CMake_BINARY_DIR}/Tests/FindJPEG/Test"
+ ${build_generator_args}
+ --build-project TestFindJPEG
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindJPEG/Test/CMakeLists.txt b/Tests/FindJPEG/Test/CMakeLists.txt
new file mode 100644
index 000000000..912c7a19b
--- /dev/null
+++ b/Tests/FindJPEG/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.1)
+project(TestFindJPEG C)
+include(CTest)
+
+find_package(JPEG)
+
+add_definitions(-DCMAKE_EXPECTED_JPEG_VERSION=${JPEG_VERSION})
+
+add_executable(test_jpeg_tgt main.c)
+target_link_libraries(test_jpeg_tgt JPEG::JPEG)
+add_test(NAME test_jpeg_tgt COMMAND test_jpeg_tgt)
+
+add_executable(test_jpeg_var main.c)
+target_include_directories(test_jpeg_var PRIVATE ${JPEG_INCLUDE_DIRS})
+target_link_libraries(test_jpeg_var PRIVATE ${JPEG_LIBRARIES})
+add_test(NAME test_jpeg_var COMMAND test_jpeg_var)
diff --git a/Tests/FindJPEG/Test/main.c b/Tests/FindJPEG/Test/main.c
new file mode 100644
index 000000000..0e23eff5f
--- /dev/null
+++ b/Tests/FindJPEG/Test/main.c
@@ -0,0 +1,16 @@
+#include <assert.h>
+#include <stdio.h>
+
+#include <jpeglib.h>
+
+int main()
+{
+ /* Without any JPEG file to open, test that the call fails as
+ expected. This tests that linking worked. */
+ struct jpeg_decompress_struct cinfo;
+ struct jpeg_error_mgr jerr;
+ cinfo.err = jpeg_std_error(&jerr);
+ jpeg_create_decompress(&cinfo);
+
+ return (JPEG_LIB_VERSION != CMAKE_EXPECTED_JPEG_VERSION);
+}
diff --git a/Tests/FindLibLZMA/CMakeLists.txt b/Tests/FindLibLZMA/CMakeLists.txt
new file mode 100644
index 000000000..6dff0ef22
--- /dev/null
+++ b/Tests/FindLibLZMA/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindLibLZMA.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindLibLZMA/Test"
+ "${CMake_BINARY_DIR}/Tests/FindLibLZMA/Test"
+ ${build_generator_args}
+ --build-project TestFindLibLZMA
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindLibLZMA/Test/CMakeLists.txt b/Tests/FindLibLZMA/Test/CMakeLists.txt
new file mode 100644
index 000000000..c59dcdbdd
--- /dev/null
+++ b/Tests/FindLibLZMA/Test/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.4)
+project(TestFindLZMA C)
+include(CTest)
+
+find_package(LibLZMA REQUIRED)
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt LibLZMA::LibLZMA)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${LIBLZMA_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${LIBLZMA_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindLibLZMA/Test/main.c b/Tests/FindLibLZMA/Test/main.c
new file mode 100644
index 000000000..06e806554
--- /dev/null
+++ b/Tests/FindLibLZMA/Test/main.c
@@ -0,0 +1,15 @@
+#include <assert.h>
+#include <lzma.h>
+#include <string.h>
+
+static const uint8_t test_string[9] = "123456789";
+
+int main()
+{
+ static const uint32_t test_vector = 0xCBF43926;
+
+ uint32_t crc = lzma_crc32(test_string, sizeof(test_string), 0);
+ assert(crc == test_vector);
+
+ return 0;
+}
diff --git a/Tests/FindLibXml2/CMakeLists.txt b/Tests/FindLibXml2/CMakeLists.txt
new file mode 100644
index 000000000..6c2464fd9
--- /dev/null
+++ b/Tests/FindLibXml2/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindLibXml2.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindLibXml2/Test"
+ "${CMake_BINARY_DIR}/Tests/FindLibXml2/Test"
+ ${build_generator_args}
+ --build-project TestFindLibXml2
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindLibXml2/Test/CMakeLists.txt b/Tests/FindLibXml2/Test/CMakeLists.txt
new file mode 100644
index 000000000..df5d8c3d2
--- /dev/null
+++ b/Tests/FindLibXml2/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.4)
+project(TestFindLibXml2 C)
+include(CTest)
+
+find_package(LibXml2 REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_LibXml2_VERSION="${LIBXML2_VERSION_STRING}")
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt LibXml2::LibXml2)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${LIBXML2_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${LIBXML2_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindLibXml2/Test/main.c b/Tests/FindLibXml2/Test/main.c
new file mode 100644
index 000000000..264f07d03
--- /dev/null
+++ b/Tests/FindLibXml2/Test/main.c
@@ -0,0 +1,19 @@
+#include <assert.h>
+#include <libxml/tree.h>
+#include <string.h>
+
+int main()
+{
+ xmlDoc* doc;
+
+ xmlInitParser();
+
+ doc = xmlNewDoc(BAD_CAST "1.0");
+ xmlFreeDoc(doc);
+
+ assert(strstr(CMAKE_EXPECTED_LibXml2_VERSION, LIBXML_DOTTED_VERSION));
+
+ xmlCleanupParser();
+
+ return 0;
+}
diff --git a/Tests/FindLibinput/CMakeLists.txt b/Tests/FindLibinput/CMakeLists.txt
new file mode 100644
index 000000000..8538a55ed
--- /dev/null
+++ b/Tests/FindLibinput/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindLibinput.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindLibinput/Test"
+ "${CMake_BINARY_DIR}/Tests/FindLibinput/Test"
+ ${build_generator_args}
+ --build-project TestFindLibinput
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindLibinput/Test/CMakeLists.txt b/Tests/FindLibinput/Test/CMakeLists.txt
new file mode 100644
index 000000000..1cc68d48e
--- /dev/null
+++ b/Tests/FindLibinput/Test/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindLibinput C)
+include(CTest)
+
+find_package(Libinput REQUIRED)
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt Libinput::Libinput)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${Libinput_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${Libinput_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindLibinput/Test/main.c b/Tests/FindLibinput/Test/main.c
new file mode 100644
index 000000000..391996280
--- /dev/null
+++ b/Tests/FindLibinput/Test/main.c
@@ -0,0 +1,13 @@
+#include <libinput.h>
+#include <stdio.h>
+
+int main()
+{
+ struct libinput_interface interface;
+ interface.open_restricted = 0;
+ interface.close_restricted = 0;
+ struct libinput* li;
+ li = libinput_udev_create_context(&interface, NULL, NULL);
+ printf("Found Libinput.\n");
+ return 0;
+}
diff --git a/Tests/FindMatlab/cmake_matlab_unit_tests4.m b/Tests/FindMatlab/cmake_matlab_unit_tests4.m
new file mode 100644
index 000000000..6a7b04d14
--- /dev/null
+++ b/Tests/FindMatlab/cmake_matlab_unit_tests4.m
@@ -0,0 +1,28 @@
+
+classdef cmake_matlab_unit_tests4 < matlab.unittest.TestCase
+ % Testing R2017b and R2018a APIs
+ properties
+ end
+
+ methods (Test)
+ function testR2017b(testCase)
+ ret = cmake_matlab_mex2a(5+6i);
+ testCase.verifyEqual(ret, 8);
+ end
+
+ function testR2018a(testCase)
+ ret = cmake_matlab_mex2b(5+6i);
+ v = version;
+ n = find(v=='.');
+ v = str2double(v(1:n(2)-1));
+ disp(v)
+ if v>= 9.4 % R2018a
+ testCase.verifyEqual(ret, 16);
+ disp('TESTING version >= 9.4')
+ else
+ testCase.verifyEqual(ret, 8);
+ end
+ end
+
+ end
+end
diff --git a/Tests/FindMatlab/cmake_matlab_unit_tests5.m b/Tests/FindMatlab/cmake_matlab_unit_tests5.m
new file mode 100644
index 000000000..b1936e354
--- /dev/null
+++ b/Tests/FindMatlab/cmake_matlab_unit_tests5.m
@@ -0,0 +1,20 @@
+
+classdef cmake_matlab_unit_tests5 < matlab.unittest.TestCase
+ % C++ API test
+ properties
+ end
+
+ methods (Test)
+ function testDummyCall(testCase)
+ % very simple call test
+ disp('TESTING C++')
+ ret = cmake_matlab_mex3(162);
+ testCase.verifyEqual(ret, 162);
+ end
+
+ function testFailTest(testCase)
+ testCase.verifyError(@() cmake_matlab_mex3, 'MATLAB:mex:CppMexException');
+ end
+
+ end
+end
diff --git a/Tests/FindMatlab/failure_reports/CMakeLists.txt b/Tests/FindMatlab/failure_reports/CMakeLists.txt
new file mode 100644
index 000000000..4b092cd28
--- /dev/null
+++ b/Tests/FindMatlab/failure_reports/CMakeLists.txt
@@ -0,0 +1,55 @@
+
+cmake_minimum_required (VERSION 2.8.12)
+enable_testing()
+project(failure_reports)
+
+# gather tests about proper failure reports
+
+set(MATLAB_FIND_DEBUG TRUE)
+
+if(IS_MCR)
+ set(RUN_UNIT_TESTS FALSE)
+else()
+ set(RUN_UNIT_TESTS TRUE)
+ set(components MAIN_PROGRAM)
+endif()
+
+if(NOT "${MCR_ROOT}" STREQUAL "")
+ set(Matlab_ROOT_DIR "${MCR_ROOT}")
+ if(NOT EXISTS "${MCR_ROOT}")
+ message(FATAL_ERROR "MCR does not exist ${MCR_ROOT}")
+ endif()
+endif()
+
+find_package(Matlab REQUIRED COMPONENTS ${components})
+
+# main extensions for testing, same as other tests
+matlab_add_mex(
+ # target name
+ NAME cmake_matlab_test_wrapper1
+ # output name
+ OUTPUT_NAME cmake_matlab_mex1
+ SRC ${CMAKE_CURRENT_SOURCE_DIR}/../matlab_wrapper1.cpp
+ DOCUMENTATION ${CMAKE_CURRENT_SOURCE_DIR}/../help_text1.m.txt
+ )
+
+if(RUN_UNIT_TESTS)
+ # the unit test file does not exist: the failure should be properly reported
+ matlab_add_unit_test(
+ NAME ${PROJECT_NAME}_matlabtest-1
+ TIMEOUT 300
+ UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../nonexistantfile.m
+ ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1>
+ )
+ set_tests_properties(${PROJECT_NAME}_matlabtest-1 PROPERTIES WILL_FAIL TRUE)
+
+ # without the unit test framework
+ matlab_add_unit_test(
+ NAME ${PROJECT_NAME}_matlabtest-2
+ TIMEOUT 300
+ NO_UNITTEST_FRAMEWORK
+ UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../nonexistantfile2.m
+ ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper1>
+ )
+ set_tests_properties(${PROJECT_NAME}_matlabtest-2 PROPERTIES WILL_FAIL TRUE)
+endif()
diff --git a/Tests/FindMatlab/matlab_wrapper2.cpp b/Tests/FindMatlab/matlab_wrapper2.cpp
new file mode 100644
index 000000000..e768fbfbe
--- /dev/null
+++ b/Tests/FindMatlab/matlab_wrapper2.cpp
@@ -0,0 +1,22 @@
+
+// simple workaround to some compiler specific problems
+// see
+// http://stackoverflow.com/questions/22367516/mex-compile-error-unknown-type-name-char16-t/23281916#23281916
+#include <algorithm>
+
+#include "mex.h"
+
+// This test uses the new complex-interleaved C API (R2018a and newer)
+
+// The input should be a complex array (scalar is OK). It returns the number of
+// bytes in a matrix element. For the old (R2017b) API, this is 8. For the new
+// (R2018a) API, this is 16.
+
+void mexFunction(const int nlhs, mxArray* plhs[], const int nrhs,
+ const mxArray* prhs[])
+{
+ if (nrhs != 1 || !mxIsComplex(prhs[0])) {
+ mexErrMsgTxt("Incorrect arguments");
+ }
+ plhs[0] = mxCreateDoubleScalar(mxGetElementSize(prhs[0]));
+}
diff --git a/Tests/FindMatlab/matlab_wrapper3.cpp b/Tests/FindMatlab/matlab_wrapper3.cpp
new file mode 100644
index 000000000..667081542
--- /dev/null
+++ b/Tests/FindMatlab/matlab_wrapper3.cpp
@@ -0,0 +1,29 @@
+#include "mex.hpp"
+#include "mexAdapter.hpp"
+
+// This test uses the new C++ API (R2018a and newer)
+
+// The input should be a scalar double array. The output is a copy of that
+// array.
+
+using namespace matlab::data;
+using matlab::mex::ArgumentList;
+
+class MexFunction : public matlab::mex::Function
+{
+public:
+ void operator()(ArgumentList outputs, ArgumentList inputs)
+ {
+ std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();
+ ArrayFactory factory;
+ if (inputs[0].getType() != ArrayType::DOUBLE ||
+ inputs[0].getType() == ArrayType::COMPLEX_DOUBLE ||
+ inputs[0].getNumberOfElements() != 1) {
+ matlabPtr->feval(
+ u"error", 0,
+ std::vector<Array>({ factory.createScalar("Incorrect arguments") }));
+ }
+ double a = inputs[0][0];
+ outputs[0] = factory.createScalar(a);
+ }
+};
diff --git a/Tests/FindMatlab/r2018a_check/CMakeLists.txt b/Tests/FindMatlab/r2018a_check/CMakeLists.txt
new file mode 100644
index 000000000..c732be151
--- /dev/null
+++ b/Tests/FindMatlab/r2018a_check/CMakeLists.txt
@@ -0,0 +1,84 @@
+
+cmake_minimum_required (VERSION 2.8.12)
+enable_testing()
+project(r2018a_checks)
+
+set(MATLAB_FIND_DEBUG TRUE)
+
+# this test doesn't do much if MATLAB version < R2018a
+
+if(IS_MCR)
+ set(RUN_UNIT_TESTS FALSE)
+else()
+ set(RUN_UNIT_TESTS TRUE)
+ set(components MAIN_PROGRAM)
+endif()
+
+if(NOT "${MCR_ROOT}" STREQUAL "")
+ set(Matlab_ROOT_DIR "${MCR_ROOT}")
+ if(NOT EXISTS "${MCR_ROOT}")
+ message(FATAL_ERROR "MCR does not exist ${MCR_ROOT}")
+ endif()
+endif()
+
+find_package(Matlab REQUIRED COMPONENTS ${components})
+
+set(IS_R2018a 1)
+if(${Matlab_VERSION_STRING} VERSION_LESS "9.4")
+ # This is an older version of MATLAB, tests will fail
+ set(IS_R2018a 0)
+endif()
+
+matlab_add_mex(
+ # target name
+ NAME cmake_matlab_test_wrapper2a
+ # output name
+ OUTPUT_NAME cmake_matlab_mex2a
+ SRC ${CMAKE_CURRENT_SOURCE_DIR}/../matlab_wrapper2.cpp
+ R2017b
+ )
+
+matlab_add_mex(
+ # target name
+ NAME cmake_matlab_test_wrapper2b
+ # output name
+ OUTPUT_NAME cmake_matlab_mex2b
+ SRC ${CMAKE_CURRENT_SOURCE_DIR}/../matlab_wrapper2.cpp
+ R2018a
+ )
+
+if(IS_R2018a)
+ matlab_add_mex(
+ # target name
+ NAME cmake_matlab_test_wrapper3
+ # output name
+ OUTPUT_NAME cmake_matlab_mex3
+ SRC ${CMAKE_CURRENT_SOURCE_DIR}/../matlab_wrapper3.cpp
+ )
+ set_target_properties(
+ cmake_matlab_test_wrapper3
+ PROPERTIES
+ CXX_STANDARD 11
+ CXX_STANDARD_REQUIRED ON
+ )
+endif()
+
+if(RUN_UNIT_TESTS)
+ # Check that the R2017b and R2018a APIs work.
+ matlab_add_unit_test(
+ NAME ${PROJECT_NAME}_matlabtest-1
+ TIMEOUT 300
+ UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../cmake_matlab_unit_tests4.m
+ ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper2a>
+ )
+
+ # Check that the C++ API works (test run only on R2018a and newer)
+ if(IS_R2018a)
+ matlab_add_unit_test(
+ NAME ${PROJECT_NAME}_matlabtest-3
+ TIMEOUT 300
+ UNITTEST_FILE ${CMAKE_CURRENT_SOURCE_DIR}/../cmake_matlab_unit_tests5.m
+ ADDITIONAL_PATH $<TARGET_FILE_DIR:cmake_matlab_test_wrapper3>
+ )
+ endif()
+endif()
diff --git a/Tests/FindODBC/CMakeLists.txt b/Tests/FindODBC/CMakeLists.txt
new file mode 100644
index 000000000..6a8109062
--- /dev/null
+++ b/Tests/FindODBC/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindODBC.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindODBC/Test"
+ "${CMake_BINARY_DIR}/Tests/FindODBC/Test"
+ ${build_generator_args}
+ --build-project TestFindODBC
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindODBC/Test/CMakeLists.txt b/Tests/FindODBC/Test/CMakeLists.txt
new file mode 100644
index 000000000..a20c0f707
--- /dev/null
+++ b/Tests/FindODBC/Test/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.1)
+project(TestFindODBC C)
+include(CTest)
+
+find_package(ODBC)
+
+add_executable(test_odbc_tgt main.c)
+target_link_libraries(test_odbc_tgt ODBC::ODBC)
+add_test(NAME test_odbc_tgt COMMAND test_odbc_tgt)
+
+add_executable(test_odbc_var main.c)
+target_include_directories(test_odbc_var PRIVATE ${ODBC_INCLUDE_DIRS})
+target_link_libraries(test_odbc_var PRIVATE ${ODBC_LIBRARIES})
+add_test(NAME test_odbc_var COMMAND test_odbc_var)
diff --git a/Tests/FindODBC/Test/main.c b/Tests/FindODBC/Test/main.c
new file mode 100644
index 000000000..34f279ce1
--- /dev/null
+++ b/Tests/FindODBC/Test/main.c
@@ -0,0 +1,12 @@
+#ifdef WIN32
+# include <windows.h>
+#endif
+#include <sql.h>
+
+int main()
+{
+ SQLHENV env;
+ SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
+ SQLFreeHandle(SQL_HANDLE_ENV, env);
+ return 0;
+}
diff --git a/Tests/FindPackageTest/PreferConfig/ABCConfig.cmake b/Tests/FindPackageTest/PreferConfig/ABCConfig.cmake
new file mode 100644
index 000000000..281a5cda9
--- /dev/null
+++ b/Tests/FindPackageTest/PreferConfig/ABCConfig.cmake
@@ -0,0 +1 @@
+set(ABC_FOUND TRUE)
diff --git a/Tests/FindPackageTest/PreferConfig/FindABC.cmake b/Tests/FindPackageTest/PreferConfig/FindABC.cmake
new file mode 100644
index 000000000..281a5cda9
--- /dev/null
+++ b/Tests/FindPackageTest/PreferConfig/FindABC.cmake
@@ -0,0 +1 @@
+set(ABC_FOUND TRUE)
diff --git a/Tests/FindPackageTest/PreferConfigOnlyModule/FindACME.cmake b/Tests/FindPackageTest/PreferConfigOnlyModule/FindACME.cmake
new file mode 100644
index 000000000..7a4e1b3ce
--- /dev/null
+++ b/Tests/FindPackageTest/PreferConfigOnlyModule/FindACME.cmake
@@ -0,0 +1 @@
+set(ACME_FOUND TRUE)
diff --git a/Tests/FindPackageTest/PreferConfigRecurse/ACMEConfig.cmake b/Tests/FindPackageTest/PreferConfigRecurse/ACMEConfig.cmake
new file mode 100644
index 000000000..7a4e1b3ce
--- /dev/null
+++ b/Tests/FindPackageTest/PreferConfigRecurse/ACMEConfig.cmake
@@ -0,0 +1 @@
+set(ACME_FOUND TRUE)
diff --git a/Tests/FindPackageTest/PreferConfigRecurse/FindACME.cmake b/Tests/FindPackageTest/PreferConfigRecurse/FindACME.cmake
new file mode 100644
index 000000000..9bdc7dbc3
--- /dev/null
+++ b/Tests/FindPackageTest/PreferConfigRecurse/FindACME.cmake
@@ -0,0 +1 @@
+find_package(ACME NO_MODULE)
diff --git a/Tests/FindPackageTest/cmake/SetFoundResolvedConfig.cmake b/Tests/FindPackageTest/cmake/SetFoundResolvedConfig.cmake
new file mode 100644
index 000000000..b2cf87ce6
--- /dev/null
+++ b/Tests/FindPackageTest/cmake/SetFoundResolvedConfig.cmake
@@ -0,0 +1 @@
+set(SetFoundResolved_DIR "${CMAKE_CURRENT_LIST_DIR}")
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..66c672c55
--- /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 --binary
+ COMMAND Patch::patch -p1 -i quote-add-date.patch --binary
+ COMMAND ${CMAKE_COMMAND} -E compare_files QUOTE.txt QUOTE.txt.baseline
+ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+ )
diff --git a/Tests/FindPostgreSQL/CMakeLists.txt b/Tests/FindPostgreSQL/CMakeLists.txt
new file mode 100644
index 000000000..50151eec3
--- /dev/null
+++ b/Tests/FindPostgreSQL/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindPostgreSQL.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPostgreSQL/Test"
+ "${CMake_BINARY_DIR}/Tests/FindPostgreSQL/Test"
+ ${build_generator_args}
+ --build-project TestFindPostgreSQL
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindPostgreSQL/Test/CMakeLists.txt b/Tests/FindPostgreSQL/Test/CMakeLists.txt
new file mode 100644
index 000000000..374e1477b
--- /dev/null
+++ b/Tests/FindPostgreSQL/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindPostgreSQL C)
+include(CTest)
+
+find_package(PostgreSQL REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_POSTGRESQL_VERSION="${PostgreSQL_VERSION_STRING}")
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt PostgreSQL::PostgreSQL)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${PostgreSQL_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${PostgreSQL_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindPostgreSQL/Test/main.c b/Tests/FindPostgreSQL/Test/main.c
new file mode 100644
index 000000000..a63377a25
--- /dev/null
+++ b/Tests/FindPostgreSQL/Test/main.c
@@ -0,0 +1,24 @@
+#include <libpq-fe.h>
+#include <stdio.h>
+#include <string.h>
+
+int main()
+{
+ int version = PQlibVersion();
+ char version_string[100];
+ // 9.x and older encoding.
+ if (version < 100000) {
+ int major = version / 10000;
+ int minor = version % 10000 / 100;
+ int patch = version % 100;
+ snprintf(version_string, sizeof(version_string), "%d.%d.%d", major, minor,
+ patch);
+ } else {
+ int major = version / 10000;
+ int minor = version % 10000;
+ snprintf(version_string, sizeof(version_string), "%d.%d", major, minor);
+ }
+ printf("Found PostgreSQL version %s, expected version %s\n", version_string,
+ CMAKE_EXPECTED_POSTGRESQL_VERSION);
+ return strcmp(version_string, CMAKE_EXPECTED_POSTGRESQL_VERSION);
+}
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/FindPython/CMakeLists.txt b/Tests/FindPython/CMakeLists.txt
new file mode 100644
index 000000000..4be2f22b6
--- /dev/null
+++ b/Tests/FindPython/CMakeLists.txt
@@ -0,0 +1,147 @@
+if(CMake_TEST_FindPython)
+ add_test(NAME FindPython.Python2.LOCATION COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/Python2"
+ "${CMake_BINARY_DIR}/Tests/FindPython/Python2.LOCATION"
+ ${build_generator_args}
+ --build-project TestPython2
+ --build-options ${build_options} -DPython2_FIND_STRATEGY=LOCATION
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+ add_test(NAME FindPython.Python2.VERSION COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/Python2"
+ "${CMake_BINARY_DIR}/Tests/FindPython/Python2.VERSION"
+ ${build_generator_args}
+ --build-project TestPython2
+ --build-options ${build_options} -DPython2_FIND_STRATEGY=VERSION
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+ add_test(NAME FindPython.Python2Fail COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/Python2Fail"
+ "${CMake_BINARY_DIR}/Tests/FindPython/Python2Fail"
+ ${build_generator_args}
+ --build-project TestPython2Fail
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+ set_tests_properties(FindPython.Python2Fail PROPERTIES
+ PASS_REGULAR_EXPRESSION "Could NOT find Python2 \\(missing: foobar\\)")
+
+ add_test(NAME FindPython.Python3.LOCATION COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/Python3"
+ "${CMake_BINARY_DIR}/Tests/FindPython/Python3.LOCATION"
+ ${build_generator_args}
+ --build-project TestPython3
+ --build-options ${build_options} -DPython3_FIND_STRATEGY=LOCATION
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+ add_test(NAME FindPython.Python3.VERSION COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/Python3"
+ "${CMake_BINARY_DIR}/Tests/FindPython/Python3.VERSION"
+ ${build_generator_args}
+ --build-project TestPython3
+ --build-options ${build_options} -DPython3_FIND_STRATEGY=VERSION
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+ add_test(NAME FindPython.Python3Fail COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/Python3Fail"
+ "${CMake_BINARY_DIR}/Tests/FindPython/Python3Fail"
+ ${build_generator_args}
+ --build-project TestPython3Fail
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+ set_tests_properties(FindPython.Python3Fail PROPERTIES
+ PASS_REGULAR_EXPRESSION "Could NOT find Python3 \\(missing: foobar\\)")
+
+ add_test(NAME FindPython.Python COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/Python"
+ "${CMake_BINARY_DIR}/Tests/FindPython/Python"
+ ${build_generator_args}
+ --build-project TestPython
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+ add_test(NAME FindPython.MultiplePackages COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/MultiplePackages"
+ "${CMake_BINARY_DIR}/Tests/FindPython/MultiplePackages"
+ ${build_generator_args}
+ --build-project TestMultiplePackages
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+ add_test(NAME FindPython.VirtualEnv COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/VirtualEnv"
+ "${CMake_BINARY_DIR}/Tests/FindPython/VirtualEnv"
+ ${build_generator_args}
+ --build-project TestVirtualEnv
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+ add_test(NAME FindPython.Python2Embedded COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/Python2Embedded"
+ "${CMake_BINARY_DIR}/Tests/FindPython/Python2Embedded"
+ ${build_generator_args}
+ --build-project TestPython2Embedded
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+ add_test(NAME FindPython.Python3Embedded COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/Python3Embedded"
+ "${CMake_BINARY_DIR}/Tests/FindPython/Python3Embedded"
+ ${build_generator_args}
+ --build-project TestPython3Embedded
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+endif()
+
+if(CMake_TEST_FindPython_NumPy)
+ add_test(NAME FindPython.NumPy COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/NumPy"
+ "${CMake_BINARY_DIR}/Tests/FindPython/NumPy"
+ ${build_generator_args}
+ --build-project TestNumPy
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+ add_test(NAME FindPython.NumPyOnly COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPython/NumPyOnly"
+ "${CMake_BINARY_DIR}/Tests/FindPython/NumPyOnly"
+ ${build_generator_args}
+ --build-project TestNumPyOnly
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+ endif()
diff --git a/Tests/FindPython/FindPythonScript.cmake b/Tests/FindPython/FindPythonScript.cmake
new file mode 100644
index 000000000..94500920e
--- /dev/null
+++ b/Tests/FindPython/FindPythonScript.cmake
@@ -0,0 +1 @@
+find_package(${PYTHON_PACKAGE_NAME} REQUIRED QUIET)
diff --git a/Tests/FindPython/MultiplePackages/CMakeLists.txt b/Tests/FindPython/MultiplePackages/CMakeLists.txt
new file mode 100644
index 000000000..5c85155bb
--- /dev/null
+++ b/Tests/FindPython/MultiplePackages/CMakeLists.txt
@@ -0,0 +1,33 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestMultiplePackages C)
+
+find_package (Python2 REQUIRED COMPONENTS Interpreter Development)
+find_package (Python3 REQUIRED COMPONENTS Interpreter Development)
+
+# Must find Python 3
+find_package (Python REQUIRED)
+
+if (NOT Python3_EXECUTABLE STREQUAL Python_EXECUTABLE)
+ message (FATAL_ERROR
+ "Python interpreters do not match:\n"
+ " Python_EXECUTABLE='${Python_EXECUTABLE}'\n"
+ " Python3_EXECUTABLE='${Python3_EXECUTABLE}'\n"
+ )
+endif()
+
+
+Python2_add_library (spam2 MODULE ../spam.c)
+target_compile_definitions (spam2 PRIVATE PYTHON2)
+
+Python3_add_library (spam3 MODULE ../spam.c)
+target_compile_definitions (spam3 PRIVATE PYTHON3)
+
+
+add_test (NAME python2_spam2
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam3>"
+ "${Python2_EXECUTABLE}" -c "import spam2; spam2.system(\"cd\")")
+
+add_test (NAME python3_spam3
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam3>"
+ "${Python3_EXECUTABLE}" -c "import spam3; spam3.system(\"cd\")")
diff --git a/Tests/FindPython/NumPy/CMakeLists.txt b/Tests/FindPython/NumPy/CMakeLists.txt
new file mode 100644
index 000000000..f55702666
--- /dev/null
+++ b/Tests/FindPython/NumPy/CMakeLists.txt
@@ -0,0 +1,22 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestNumPy C)
+
+find_package (Python2 REQUIRED COMPONENTS Interpreter Development NumPy)
+find_package (Python3 REQUIRED COMPONENTS Interpreter Development NumPy)
+
+Python2_add_library (arraytest2 MODULE arraytest.c)
+target_compile_definitions (arraytest2 PRIVATE PYTHON2)
+target_link_libraries (arraytest2 PRIVATE Python2::NumPy)
+
+Python3_add_library (arraytest3 MODULE arraytest.c)
+target_compile_definitions (arraytest3 PRIVATE PYTHON3)
+target_link_libraries (arraytest3 PRIVATE Python3::NumPy)
+
+add_test (NAME python2_arraytest
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:arraytest2>"
+ "${Python2_EXECUTABLE}" -c "import numpy; import arraytest2; arraytest2.vecsq(numpy.array([1, 2, 3]));")
+
+add_test (NAME python3_arraytest
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:arraytest3>"
+ "${Python3_EXECUTABLE}" -c "import numpy; import arraytest3; arraytest3.vecsq(numpy.array([1, 2, 3]));")
diff --git a/Tests/FindPython/NumPy/arraytest.c b/Tests/FindPython/NumPy/arraytest.c
new file mode 100644
index 000000000..db259e55a
--- /dev/null
+++ b/Tests/FindPython/NumPy/arraytest.c
@@ -0,0 +1,58 @@
+#include "Python.h"
+
+#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
+#include "numpy/arrayobject.h"
+
+#include <math.h>
+
+static PyObject* vecsq(PyObject* self, PyObject* args);
+
+static PyMethodDef arraytestMethods[] = { { "vecsq", vecsq, METH_VARARGS },
+ { NULL, NULL } };
+
+static PyObject* vecsq(PyObject* self, PyObject* args)
+{
+ PyArrayObject *vecin, *vecout;
+ npy_intp dims[2];
+ double *cin, *cout;
+ int i, j, n, m;
+
+ if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &vecin))
+ return NULL;
+
+ n = dims[0] = PyArray_NDIM(vecin);
+ vecout = (PyArrayObject*)PyArray_SimpleNew(1, dims, NPY_DOUBLE);
+
+ cin = (double*)PyArray_DATA(vecin);
+ cout = (double*)PyArray_DATA(vecout);
+
+ for (i = 0; i < n; i++) {
+ cout[i] = cin[i] * cin[i];
+ }
+ return PyArray_Return(vecout);
+}
+
+#if defined(PYTHON2)
+PyMODINIT_FUNC init_C_arraytest(void)
+{
+ (void)Py_InitModule("arraytest2", arraytestMethods);
+ import_array();
+}
+#endif
+
+#if defined(PYTHON3)
+static struct PyModuleDef arraytestmodule = {
+ PyModuleDef_HEAD_INIT, "arraytest3", /* name of module */
+ NULL, /* module documentation, may be NULL */
+ -1, /* size of per-interpreter state of the module,
+ or -1 if the module keeps state in global variables. */
+ arraytestMethods
+};
+
+PyMODINIT_FUNC PyInit_C_arraytest(void)
+{
+ PyObject* po = PyModule_Create(&arraytestmodule);
+ import_array();
+ return po;
+}
+#endif
diff --git a/Tests/FindPython/NumPyOnly/CMakeLists.txt b/Tests/FindPython/NumPyOnly/CMakeLists.txt
new file mode 100644
index 000000000..a5db6037c
--- /dev/null
+++ b/Tests/FindPython/NumPyOnly/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestNumPyOnly C)
+
+find_package(Python2 REQUIRED COMPONENTS NumPy)
+find_package(Python3 REQUIRED COMPONENTS NumPy)
+
+Python2_add_library (arraytest2 MODULE ../NumPy/arraytest.c)
+target_compile_definitions (arraytest2 PRIVATE PYTHON2)
+target_link_libraries (arraytest2 PRIVATE Python2::NumPy)
+
+Python3_add_library (arraytest3 MODULE ../NumPy/arraytest.c)
+target_compile_definitions (arraytest3 PRIVATE PYTHON3)
+target_link_libraries (arraytest3 PRIVATE Python3::NumPy)
diff --git a/Tests/FindPython/Python/CMakeLists.txt b/Tests/FindPython/Python/CMakeLists.txt
new file mode 100644
index 000000000..62c805ec7
--- /dev/null
+++ b/Tests/FindPython/Python/CMakeLists.txt
@@ -0,0 +1,32 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestPython C)
+
+include(CTest)
+
+find_package(Python 3 REQUIRED COMPONENTS Interpreter Development)
+if (NOT Python_FOUND)
+ message (FATAL_ERROR "Fail to found Python 3")
+endif()
+
+if(NOT TARGET Python::Interpreter)
+ message(SEND_ERROR "Python::Interpreter not found")
+endif()
+
+if(NOT TARGET Python::Python)
+ message(SEND_ERROR "Python::Python not found")
+endif()
+if(NOT TARGET Python::Module)
+ message(SEND_ERROR "Python::Module not found")
+endif()
+
+Python_add_library (spam3 MODULE ../spam.c)
+target_compile_definitions (spam3 PRIVATE PYTHON3)
+
+add_test (NAME python_spam3
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam3>"
+ "${Python_EXECUTABLE}" -c "import spam3; spam3.system(\"cd\")")
+
+add_test(NAME findpython_script
+ COMMAND "${CMAKE_COMMAND}" -DPYTHON_PACKAGE_NAME=Python
+ -P "${CMAKE_CURRENT_LIST_DIR}/../FindPythonScript.cmake")
diff --git a/Tests/FindPython/Python2/CMakeLists.txt b/Tests/FindPython/Python2/CMakeLists.txt
new file mode 100644
index 000000000..274745a6e
--- /dev/null
+++ b/Tests/FindPython/Python2/CMakeLists.txt
@@ -0,0 +1,37 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestPython2 C)
+
+include(CTest)
+
+find_package(Python2 3 QUIET)
+if (Python2_FOUND)
+ message (FATAL_ERROR "Wrong python version found: ${Python2_VERSION}")
+endif()
+
+find_package(Python2 REQUIRED COMPONENTS Interpreter Development)
+if (NOT Python2_FOUND)
+ message (FATAL_ERROR "Fail to found Python 2")
+endif()
+
+if(NOT TARGET Python2::Interpreter)
+ message(SEND_ERROR "Python2::Interpreter not found")
+endif()
+
+if(NOT TARGET Python2::Python)
+ message(SEND_ERROR "Python2::Python not found")
+endif()
+if(NOT TARGET Python2::Module)
+ message(SEND_ERROR "Python2::Module not found")
+endif()
+
+Python2_add_library (spam2 MODULE ../spam.c)
+target_compile_definitions (spam2 PRIVATE PYTHON2)
+
+add_test (NAME python2_spam2
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam2>"
+ "${Python2_EXECUTABLE}" -c "import spam2; spam2.system(\"cd\")")
+
+add_test(NAME findpython2_script
+ COMMAND "${CMAKE_COMMAND}" -DPYTHON_PACKAGE_NAME=Python2
+ -P "${CMAKE_CURRENT_LIST_DIR}/../FindPythonScript.cmake")
diff --git a/Tests/FindPython/Python2Embedded/CMakeLists.txt b/Tests/FindPython/Python2Embedded/CMakeLists.txt
new file mode 100644
index 000000000..0115deaa3
--- /dev/null
+++ b/Tests/FindPython/Python2Embedded/CMakeLists.txt
@@ -0,0 +1,29 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestPython2Embedded C)
+
+include(CTest)
+
+find_package(Python2 REQUIRED COMPONENTS Development)
+if (NOT Python2_FOUND)
+ message (FATAL_ERROR "Fail to found Python 2")
+endif()
+
+if(NOT TARGET Python2::Python)
+ message(SEND_ERROR "Python2::Python not found")
+endif()
+
+Python2_add_library (display_time2 SHARED ../display_time.c)
+set_property (TARGET display_time2 PROPERTY WINDOWS_EXPORT_ALL_SYMBOLS ON)
+target_compile_definitions (display_time2 PRIVATE PYTHON2)
+
+add_executable (main2 ../main.c)
+target_link_libraries (main2 PRIVATE display_time2)
+
+if (WIN32 OR CYGWIN OR MSYS OR MINGW)
+ list (JOIN Python2_RUNTIME_LIBRARY_DIRS "$<SEMICOLON>" RUNTIME_DIRS)
+ add_test (NAME Python2.Embedded COMMAND "${CMAKE_COMMAND}" -E env "PATH=${RUNTIME_DIRS}" $<TARGET_FILE:main2>)
+else()
+ add_test (NAME Python2.Embedded COMMAND main2)
+endif()
+set_property (TEST Python2.Embedded PROPERTY PASS_REGULAR_EXPRESSION "Today is")
diff --git a/Tests/FindPython/Python2Fail/CMakeLists.txt b/Tests/FindPython/Python2Fail/CMakeLists.txt
new file mode 100644
index 000000000..989688f55
--- /dev/null
+++ b/Tests/FindPython/Python2Fail/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestPython2Fail C)
+
+include(CTest)
+
+find_package(Python2 REQUIRED COMPONENTS Interpreter Development foobar)
+
+Python2_add_library (spam2 MODULE ../spam.c)
+target_compile_definitions (spam2 PRIVATE PYTHON2)
+
+add_test (NAME python2_spam2
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam2>"
+ "${Python2_EXECUTABLE}" -c "import spam2; spam2.system(\"cd\")")
diff --git a/Tests/FindPython/Python3/CMakeLists.txt b/Tests/FindPython/Python3/CMakeLists.txt
new file mode 100644
index 000000000..b21a15bc8
--- /dev/null
+++ b/Tests/FindPython/Python3/CMakeLists.txt
@@ -0,0 +1,37 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestPython3 C)
+
+include(CTest)
+
+find_package(Python3 2 QUIET)
+if (Python3_FOUND)
+ message (FATAL_ERROR "Wrong python version found: ${Python3_VERSION}")
+endif()
+
+find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
+if (NOT Python3_FOUND)
+ message (FATAL_ERROR "Fail to found Python 3")
+endif()
+
+if(NOT TARGET Python3::Interpreter)
+ message(SEND_ERROR "Python2::Interpreter not found")
+endif()
+
+if(NOT TARGET Python3::Python)
+ message(SEND_ERROR "Python2::Python not found")
+endif()
+if(NOT TARGET Python3::Module)
+ message(SEND_ERROR "Python2::Module not found")
+endif()
+
+Python3_add_library (spam3 MODULE ../spam.c)
+target_compile_definitions (spam3 PRIVATE PYTHON3)
+
+add_test (NAME python3_spam3
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam3>"
+ "${Python3_EXECUTABLE}" -c "import spam3; spam3.system(\"cd\")")
+
+add_test(NAME findpython3_script
+ COMMAND "${CMAKE_COMMAND}" -DPYTHON_PACKAGE_NAME=Python3
+ -P "${CMAKE_CURRENT_LIST_DIR}/../FindPythonScript.cmake")
diff --git a/Tests/FindPython/Python3Embedded/CMakeLists.txt b/Tests/FindPython/Python3Embedded/CMakeLists.txt
new file mode 100644
index 000000000..4eb7ebc14
--- /dev/null
+++ b/Tests/FindPython/Python3Embedded/CMakeLists.txt
@@ -0,0 +1,29 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestPython3Embedded C)
+
+include(CTest)
+
+find_package(Python3 REQUIRED COMPONENTS Development)
+if (NOT Python3_FOUND)
+ message (FATAL_ERROR "Fail to found Python 3")
+endif()
+
+if(NOT TARGET Python3::Python)
+ message(SEND_ERROR "Python3::Python not found")
+endif()
+
+Python3_add_library (display_time3 SHARED ../display_time.c)
+set_property (TARGET display_time3 PROPERTY WINDOWS_EXPORT_ALL_SYMBOLS ON)
+target_compile_definitions (display_time3 PRIVATE PYTHON3)
+
+add_executable (main3 ../main.c)
+target_link_libraries (main3 PRIVATE display_time3)
+
+if (WIN32 OR CYGWIN OR MSYS OR MINGW)
+ list (JOIN Python3_RUNTIME_LIBRARY_DIRS "$<SEMICOLON>" RUNTIME_DIRS)
+ add_test (NAME Python3.Embedded COMMAND "${CMAKE_COMMAND}" -E env "PATH=${RUNTIME_DIRS}" $<TARGET_FILE:main3>)
+else()
+ add_test (NAME Python3.Embedded COMMAND main3)
+endif()
+set_property (TEST Python3.Embedded PROPERTY PASS_REGULAR_EXPRESSION "Today is")
diff --git a/Tests/FindPython/Python3Fail/CMakeLists.txt b/Tests/FindPython/Python3Fail/CMakeLists.txt
new file mode 100644
index 000000000..cd46c8864
--- /dev/null
+++ b/Tests/FindPython/Python3Fail/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestPython3Fail C)
+
+include(CTest)
+
+find_package(Python3 REQUIRED COMPONENTS Interpreter Development foobar)
+
+Python3_add_library (spam3 MODULE ../spam.c)
+target_compile_definitions (spam3 PRIVATE PYTHON3)
+
+add_test (NAME python3_spam3
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_FILE_DIR:spam3>"
+ "${Python3_EXECUTABLE}" -c "import spam3; spam3.system(\"cd\")")
diff --git a/Tests/FindPython/VirtualEnv/CMakeLists.txt b/Tests/FindPython/VirtualEnv/CMakeLists.txt
new file mode 100644
index 000000000..64ba20186
--- /dev/null
+++ b/Tests/FindPython/VirtualEnv/CMakeLists.txt
@@ -0,0 +1,42 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestVirtualEnv LANGUAGES NONE)
+
+include(CTest)
+
+find_package(Python3 REQUIRED COMPONENTS Interpreter)
+if (NOT Python3_FOUND)
+ message (FATAL_ERROR "Fail to found Python 3")
+endif()
+
+set (Python3_VIRTUAL_ENV "${CMAKE_CURRENT_BINARY_DIR}/py3venv")
+
+execute_process (COMMAND "${Python3_EXECUTABLE}" -m venv "${Python3_VIRTUAL_ENV}"
+ RESULT_VARIABLE result
+ OUTPUT_VARIABLE outputs
+ ERROR_VARIABLE outputs)
+if (result)
+ message (FATAL_ERROR "Fail to create virtual environment: ${outputs}")
+endif()
+
+add_test(NAME FindPython3.VirtualEnvDefault
+ COMMAND "${CMAKE_COMMAND}" -E env --unset=PYTHONHOME
+ "VIRTUAL_ENV=${Python3_VIRTUAL_ENV}"
+ "${CMAKE_COMMAND}" "-DPYTHON3_VIRTUAL_ENV=${Python3_VIRTUAL_ENV}"
+ -P "${CMAKE_CURRENT_LIST_DIR}/VirtualEnvDefault.cmake")
+
+add_test(NAME FindPython3.VirtualEnvOnly
+ COMMAND "${CMAKE_COMMAND}" -E env --unset=PYTHONHOME
+ "VIRTUAL_ENV=${Python3_VIRTUAL_ENV}"
+ "${CMAKE_COMMAND}" "-DPYTHON3_VIRTUAL_ENV=${Python3_VIRTUAL_ENV}"
+ -P "${CMAKE_CURRENT_LIST_DIR}/VirtualEnvOnly.cmake")
+add_test(NAME FindPython3.UnsetVirtualEnvOnly
+ COMMAND "${CMAKE_COMMAND}" -E env --unset=PYTHONHOME
+ --unset=VIRTUAL_ENV
+ "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_LIST_DIR}/VirtualEnvOnly.cmake")
+
+add_test(NAME FindPython3.VirtualEnvStandard
+ COMMAND "${CMAKE_COMMAND}" -E env --unset=PYTHONHOME
+ "VIRTUAL_ENV=${Python3_VIRTUAL_ENV}"
+ "${CMAKE_COMMAND}" "-DPYTHON3_VIRTUAL_ENV=${Python3_VIRTUAL_ENV}"
+ -P "${CMAKE_CURRENT_LIST_DIR}/VirtualEnvStandard.cmake")
diff --git a/Tests/FindPython/VirtualEnv/VirtualEnvDefault.cmake b/Tests/FindPython/VirtualEnv/VirtualEnvDefault.cmake
new file mode 100644
index 000000000..020ecacd9
--- /dev/null
+++ b/Tests/FindPython/VirtualEnv/VirtualEnvDefault.cmake
@@ -0,0 +1,6 @@
+
+find_package (Python3 REQUIRED)
+
+if (NOT Python3_EXECUTABLE MATCHES "^${PYTHON3_VIRTUAL_ENV}/.+")
+ message (FATAL_ERROR "Fail to use virtual environment")
+endif()
diff --git a/Tests/FindPython/VirtualEnv/VirtualEnvOnly.cmake b/Tests/FindPython/VirtualEnv/VirtualEnvOnly.cmake
new file mode 100644
index 000000000..29a49249c
--- /dev/null
+++ b/Tests/FindPython/VirtualEnv/VirtualEnvOnly.cmake
@@ -0,0 +1,16 @@
+
+#
+# Virtual environment is defined for python3
+# Trying to find a python2 using only virtual environment
+# It is expecting to fail if a virtual environment is active and to success otherwise.
+#
+set (Python2_FIND_VIRTUALENV ONLY)
+find_package (Python2 QUIET)
+
+if (PYTHON3_VIRTUAL_ENV AND Python2_FOUND)
+ message (FATAL_ERROR "Python2 unexpectedly found.")
+endif()
+
+if (NOT PYTHON3_VIRTUAL_ENV AND NOT Python2_FOUND)
+ message (FATAL_ERROR "Fail to find Python2.")
+endif()
diff --git a/Tests/FindPython/VirtualEnv/VirtualEnvStandard.cmake b/Tests/FindPython/VirtualEnv/VirtualEnvStandard.cmake
new file mode 100644
index 000000000..89f27d8da
--- /dev/null
+++ b/Tests/FindPython/VirtualEnv/VirtualEnvStandard.cmake
@@ -0,0 +1,7 @@
+
+set (Python3_FIND_VIRTUALENV STANDARD)
+find_package (Python3 REQUIRED)
+
+if (Python3_EXECUTABLE MATCHES "^${PYTHON3_VIRTUAL_ENV}/.+")
+ message (FATAL_ERROR "Python3 virtual env unexpectedly found.")
+endif()
diff --git a/Tests/FindPython/display_time.c b/Tests/FindPython/display_time.c
new file mode 100644
index 000000000..0e7843422
--- /dev/null
+++ b/Tests/FindPython/display_time.c
@@ -0,0 +1,36 @@
+
+#include <stdio.h>
+
+#define PY_SSIZE_T_CLEAN
+#include <Python.h>
+
+#include "display_time.h"
+
+void display_time()
+{
+#if defined(PYTHON3)
+ wchar_t* program = Py_DecodeLocale("display_time", NULL);
+ if (program == NULL) {
+ fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
+ exit(1);
+ }
+ char* cmd = "from time import time,ctime\n"
+ "print('Today is', ctime(time()))\n";
+#else
+ char* program = "display_time";
+ char* cmd = "from time import time,ctime\n"
+ "print 'Today is', ctime(time())\n";
+#endif
+
+ Py_SetProgramName(program); /* optional but recommended */
+ Py_Initialize();
+ PyRun_SimpleString(cmd);
+#if defined(PYTHON3)
+ if (Py_FinalizeEx() < 0) {
+ exit(120);
+ }
+ PyMem_RawFree(program);
+#else
+ Py_Finalize();
+#endif
+}
diff --git a/Tests/FindPython/display_time.h b/Tests/FindPython/display_time.h
new file mode 100644
index 000000000..d825e0273
--- /dev/null
+++ b/Tests/FindPython/display_time.h
@@ -0,0 +1,2 @@
+
+void display_time();
diff --git a/Tests/FindPython/main.c b/Tests/FindPython/main.c
new file mode 100644
index 000000000..0acba2917
--- /dev/null
+++ b/Tests/FindPython/main.c
@@ -0,0 +1,7 @@
+
+#include "display_time.h"
+
+int main()
+{
+ display_time();
+}
diff --git a/Tests/FindPython/spam.c b/Tests/FindPython/spam.c
new file mode 100644
index 000000000..1c65d5486
--- /dev/null
+++ b/Tests/FindPython/spam.c
@@ -0,0 +1,41 @@
+
+#include <Python.h>
+
+static PyObject* spam_system(PyObject* self, PyObject* args)
+{
+ const char* command;
+ int sts;
+
+ if (!PyArg_ParseTuple(args, "s", &command))
+ return NULL;
+ sts = system(command);
+ /* return PyLong_FromLong(sts); */
+ return Py_BuildValue("i", sts);
+}
+
+static PyMethodDef SpamMethods[] = {
+ { "system", spam_system, METH_VARARGS, "Execute a shell command." },
+ { NULL, NULL, 0, NULL } /* Sentinel */
+};
+
+#if defined(PYTHON2)
+PyMODINIT_FUNC initspam2(void)
+{
+ (void)Py_InitModule("spam2", SpamMethods);
+}
+#endif
+
+#if defined(PYTHON3)
+static struct PyModuleDef spammodule = {
+ PyModuleDef_HEAD_INIT, "spam3", /* name of module */
+ NULL, /* module documentation, may be NULL */
+ -1, /* size of per-interpreter state of the module,
+ or -1 if the module keeps state in global variables. */
+ SpamMethods
+};
+
+PyMODINIT_FUNC PyInit_spam3(void)
+{
+ return PyModule_Create(&spammodule);
+}
+#endif
diff --git a/Tests/FindSQLite3/CMakeLists.txt b/Tests/FindSQLite3/CMakeLists.txt
new file mode 100644
index 000000000..8bf170e35
--- /dev/null
+++ b/Tests/FindSQLite3/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindSQLite3.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindSQLite3/Test"
+ "${CMake_BINARY_DIR}/Tests/FindSQLite3/Test"
+ ${build_generator_args}
+ --build-project TestFindSQLite3
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindSQLite3/Test/CMakeLists.txt b/Tests/FindSQLite3/Test/CMakeLists.txt
new file mode 100644
index 000000000..bcc6ebd20
--- /dev/null
+++ b/Tests/FindSQLite3/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.4)
+project(TestFindSQLite3 C)
+include(CTest)
+
+find_package(SQLite3 REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_SQLite3_VERSION="${SQLite3_VERSION}")
+
+add_executable(test_tgt main.c)
+target_link_libraries(test_tgt SQLite::SQLite3)
+add_test(NAME test_tgt COMMAND test_tgt)
+
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${SQLite3_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${SQLite3_LIBRARIES})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindSQLite3/Test/main.c b/Tests/FindSQLite3/Test/main.c
new file mode 100644
index 000000000..aeb494063
--- /dev/null
+++ b/Tests/FindSQLite3/Test/main.c
@@ -0,0 +1,10 @@
+#include <string.h>
+
+#include <sqlite3.h>
+
+int main()
+{
+ char sqlite3_version[] = SQLITE_VERSION;
+
+ return strcmp(sqlite3_version, CMAKE_EXPECTED_SQLite3_VERSION);
+}
diff --git a/Tests/FindX11/CMakeLists.txt b/Tests/FindX11/CMakeLists.txt
new file mode 100644
index 000000000..cc931a1b8
--- /dev/null
+++ b/Tests/FindX11/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindX11.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindX11/Test"
+ "${CMake_BINARY_DIR}/Tests/FindX11/Test"
+ ${build_generator_args}
+ --build-project TestFindX11
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindX11/Test/CMakeLists.txt b/Tests/FindX11/Test/CMakeLists.txt
new file mode 100644
index 000000000..769271f4b
--- /dev/null
+++ b/Tests/FindX11/Test/CMakeLists.txt
@@ -0,0 +1,89 @@
+cmake_minimum_required(VERSION 3.10)
+project(TestFindX11 C)
+include(CTest)
+
+find_package(X11 REQUIRED)
+
+function (test_x11_component have_var component)
+ if (NOT X11_${component}_FOUND)
+ message("Skipping ${component} because it was not found.")
+ return ()
+ endif ()
+
+ add_executable(test_tgt_${component} main.c)
+ target_link_libraries(test_tgt_${component} PRIVATE X11::${component})
+ target_compile_definitions(test_tgt_${component} PRIVATE HAVE_X11_${component})
+ add_test(NAME test_tgt_${component} COMMAND test_tgt_${component})
+
+ # Add to the list of components to test for the parent.
+ set(${have_var}
+ ${${have_var}}
+ HAVE_X11_${component}
+ PARENT_SCOPE)
+endfunction ()
+
+set(x11_components)
+test_x11_component(x11_components ICE)
+test_x11_component(x11_components SM)
+# Not a component; hack it up.
+set(X11_X11_FOUND ${X11_FOUND})
+test_x11_component(x11_components X11)
+test_x11_component(x11_components Xau)
+test_x11_component(x11_components Xcomposite)
+test_x11_component(x11_components Xdamage)
+test_x11_component(x11_components Xdmcp)
+test_x11_component(x11_components Xext)
+test_x11_component(x11_components Xxf86misc)
+test_x11_component(x11_components Xxf86vm)
+test_x11_component(x11_components Xfixes)
+# We ignore the Xft component because the variables do not provide the required
+# dependency information (Freetype and Fontconfig).
+test_x11_component(x11_components_ignore Xft)
+test_x11_component(x11_components Xi)
+test_x11_component(x11_components Xinerama)
+test_x11_component(x11_components Xkb)
+test_x11_component(x11_components xkbfile)
+test_x11_component(x11_components Xmu)
+test_x11_component(x11_components Xpm)
+test_x11_component(x11_components Xtst)
+test_x11_component(x11_components Xrandr)
+test_x11_component(x11_components Xrender)
+test_x11_component(x11_components XRes)
+test_x11_component(x11_components Xss)
+test_x11_component(x11_components Xt)
+test_x11_component(x11_components Xutil)
+test_x11_component(x11_components Xv)
+
+# The variables do not include dependency information. Just test "everything".
+add_executable(test_var main.c)
+target_include_directories(test_var PRIVATE ${X11_INCLUDE_DIRS})
+target_link_libraries(test_var PRIVATE ${X11_LIBRARIES})
+# Not included in X11_LIBRARIES.
+foreach(lib
+ Xau
+ Xcomposite
+ Xdamage
+ Xdmcp
+ Xxf86misc
+ Xxf86vm
+ Xfixes
+ Xi
+ Xinerama
+ Xkb
+ xkbfile
+ Xmu
+ Xpm
+ Xtst
+ Xrandr
+ Xrender
+ XRes
+ Xss
+ Xt
+ Xv
+ )
+ if (X11_${lib}_FOUND)
+ target_link_libraries(test_var PRIVATE ${X11_${lib}_LIB})
+ endif ()
+endforeach()
+target_compile_definitions(test_var PRIVATE ${x11_components})
+add_test(NAME test_var COMMAND test_var)
diff --git a/Tests/FindX11/Test/main.c b/Tests/FindX11/Test/main.c
new file mode 100644
index 000000000..044bfa278
--- /dev/null
+++ b/Tests/FindX11/Test/main.c
@@ -0,0 +1,405 @@
+#ifdef HAVE_X11_ICE
+# include <X11/ICE/ICElib.h>
+
+static Status test_ICE(void)
+{
+ return IceInitThreads();
+}
+#endif
+
+#ifdef HAVE_X11_SM
+# include <X11/SM/SMlib.h>
+# include <stdlib.h>
+
+static void test_SM(void)
+{
+ SmcProtocolVersion(NULL);
+}
+#endif
+
+#ifdef HAVE_X11_X11
+# include <X11/Xlib.h>
+
+static Status test_X11(void)
+{
+ return XInitThreads();
+}
+#endif
+
+#ifdef HAVE_X11_Xau
+# include <X11/Xauth.h>
+
+static char* test_Xau(void)
+{
+ return XauFileName();
+}
+#endif
+
+#ifdef HAVE_X11_Xcomposite
+# include <X11/extensions/Xcomposite.h>
+
+static int test_Xcomposite(void)
+{
+ return XCompositeVersion();
+}
+#endif
+
+#ifdef HAVE_X11_Xdamage
+# include <X11/extensions/Xdamage.h>
+
+static Bool test_Xdamage(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ int ev_base;
+ int err_base;
+ Bool ret = XDamageQueryExtension(dpy, &ev_base, &err_base);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xdmcp
+# include <X11/Xdmcp.h>
+
+static int test_Xdmcp(void)
+{
+ BYTE data[1024];
+ XdmcpBuffer buf = { data, sizeof(data), 0, 0 };
+ return XdmcpReadRemaining(&buf);
+}
+#endif
+
+#ifdef HAVE_X11_Xext
+# include <X11/Xlib.h>
+# include <X11/extensions/Xext.h>
+
+static int test_Xext(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ int ret = XMissingExtension(dpy, "cmake");
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xxf86misc
+# include <X11/Xlib.h>
+# include <X11/extensions/xf86misc.h>
+
+static Bool test_Xxf86misc(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ Bool ret = XF86MiscSetClientVersion(dpy);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xxf86vm
+# include <X11/Xlib.h>
+# include <X11/extensions/xf86vmode.h>
+
+static Bool test_Xxf86vm(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ Bool ret = XF86VidModeSetClientVersion(dpy);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xfixes
+# include <X11/extensions/Xfixes.h>
+
+static Bool test_Xfixes(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ int ev_base;
+ int err_base;
+ Bool ret = XFixesQueryExtension(dpy, &ev_base, &err_base);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xft
+# include <X11/Xft/Xft.h>
+
+static FcBool test_Xft(void)
+{
+ return XftInitFtLibrary();
+}
+#endif
+
+#ifdef HAVE_X11_Xi
+# include <X11/extensions/XInput.h>
+
+static XExtensionVersion* test_Xi(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ XExtensionVersion* ret = XGetExtensionVersion(dpy, "cmake");
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xinerama
+# include <X11/extensions/Xinerama.h>
+
+static Bool test_Xinerama(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ int ev_base;
+ int err_base;
+ Bool ret = XineramaQueryExtension(dpy, &ev_base, &err_base);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xkb
+# include <X11/XKBlib.h>
+
+static Bool test_Xkb(void)
+{
+ return XkbIgnoreExtension(0);
+}
+#endif
+
+#ifdef HAVE_X11_xkbfile
+# include <stdio.h>
+
+# include <X11/XKBlib.h>
+# include <X11/extensions/XKBfile.h>
+
+# include <stdlib.h>
+
+static void test_xkbfile(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ XkbInitAtoms(dpy);
+ XCloseDisplay(dpy);
+}
+#endif
+
+#ifdef HAVE_X11_Xmu
+# include <X11/Xmu/Xmu.h>
+
+# include <stdlib.h>
+
+static Bool test_Xmu(void)
+{
+ return XmuValidArea(NULL);
+}
+#endif
+
+#ifdef HAVE_X11_Xpm
+# include <X11/xpm.h>
+
+static int test_Xpm(void)
+{
+ return XpmAttributesSize();
+}
+#endif
+
+#ifdef HAVE_X11_Xtst
+# include <X11/extensions/XTest.h>
+
+static Status test_Xtst(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ Status ret = XTestDiscard(dpy);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xrandr
+# include <X11/extensions/Xrandr.h>
+
+static Bool test_Xrandr(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ int ev_base;
+ int err_base;
+ Bool ret = XRRQueryExtension(dpy, &ev_base, &err_base);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xrender
+# include <X11/extensions/Xrender.h>
+
+static Bool test_Xrender(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ int ev_base;
+ int err_base;
+ Bool ret = XRenderQueryExtension(dpy, &ev_base, &err_base);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_XRes
+# include <X11/Xlib.h>
+# include <X11/extensions/XRes.h>
+
+static Bool test_XRes(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ int ev_base;
+ int err_base;
+ Bool ret = XResQueryExtension(dpy, &ev_base, &err_base);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xss
+# include <X11/extensions/scrnsaver.h>
+
+static Bool test_Xss(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ int ev_base;
+ int err_base;
+ Bool ret = XScreenSaverQueryExtension(dpy, &ev_base, &err_base);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#ifdef HAVE_X11_Xt
+# include <X11/Intrinsic.h>
+
+static void test_Xt(void)
+{
+ return XtToolkitInitialize();
+}
+#endif
+
+#ifdef HAVE_X11_Xutil
+# include <X11/Xutil.h>
+
+static int test_Xutil(void)
+{
+ Region r = XCreateRegion();
+ return XDestroyRegion(r);
+}
+#endif
+
+#ifdef HAVE_X11_Xv
+# include <X11/Xlib.h>
+# include <X11/extensions/Xvlib.h>
+
+static int test_Xv(void)
+{
+ Display* dpy = XOpenDisplay(NULL);
+ unsigned int version;
+ unsigned int revision;
+ unsigned int req_base;
+ unsigned int ev_base;
+ unsigned int err_base;
+ int ret =
+ XvQueryExtension(dpy, &version, &revision, &req_base, &ev_base, &err_base);
+ XCloseDisplay(dpy);
+ return ret;
+}
+#endif
+
+#include <stddef.h>
+
+int main(int argc, char* argv[])
+{
+ (void)argv;
+ void* fptrs[] = {
+#ifdef HAVE_X11_ICE
+ test_ICE,
+#endif
+#ifdef HAVE_X11_SM
+ test_SM,
+#endif
+#ifdef HAVE_X11_X11
+ test_X11,
+#endif
+#ifdef HAVE_X11_Xau
+ test_Xau,
+#endif
+#ifdef HAVE_X11_Xcomposite
+ test_Xcomposite,
+#endif
+#ifdef HAVE_X11_Xdamage
+ test_Xdamage,
+#endif
+#ifdef HAVE_X11_Xdmcp
+ test_Xdmcp,
+#endif
+#ifdef HAVE_X11_Xext
+ test_Xext,
+#endif
+#ifdef HAVE_X11_Xxf86misc
+ test_Xxf86misc,
+#endif
+#ifdef HAVE_X11_Xxf86vm
+ test_Xxf86vm,
+#endif
+#ifdef HAVE_X11_Xfixes
+ test_Xfixes,
+#endif
+#ifdef HAVE_X11_Xft
+ test_Xft,
+#endif
+#ifdef HAVE_X11_Xi
+ test_Xi,
+#endif
+#ifdef HAVE_X11_Xinerama
+ test_Xinerama,
+#endif
+#ifdef HAVE_X11_Xkb
+ test_Xkb,
+#endif
+#ifdef HAVE_X11_xkbfile
+ test_xkbfile,
+#endif
+#ifdef HAVE_X11_Xmu
+ test_Xmu,
+#endif
+#ifdef HAVE_X11_Xpm
+ test_Xpm,
+#endif
+#ifdef HAVE_X11_Xtst
+ test_Xtst,
+#endif
+#ifdef HAVE_X11_Xrandr
+ test_Xrandr,
+#endif
+#ifdef HAVE_X11_Xrender
+ test_Xrender,
+#endif
+#ifdef HAVE_X11_XRes
+ test_XRes,
+#endif
+#ifdef HAVE_X11_Xss
+ test_Xss,
+#endif
+#ifdef HAVE_X11_Xt
+ test_Xt,
+#endif
+#ifdef HAVE_X11_Xutil
+ test_Xutil,
+#endif
+#ifdef HAVE_X11_Xv
+ test_Xv,
+#endif
+ NULL,
+ };
+
+ // The code here is to convince the compiler to keep the static functions but
+ // without calling them. This ends up always being "0" because `argc` is
+ // always 1 in the test harness which always returns the sentinel at the end
+ // of the array. The array logic is there to ensure that the contents of
+ // `fptrs` is not optimized out.
+ return (int)fptrs[(sizeof(fptrs) / sizeof(*fptrs)) - argc];
+}
diff --git a/Tests/FortranModules/Submodules/child.f90 b/Tests/FortranModules/Submodules/child.f90
new file mode 100644
index 000000000..c314835ae
--- /dev/null
+++ b/Tests/FortranModules/Submodules/child.f90
@@ -0,0 +1,10 @@
+! Test the notation for a 1st-generation direct
+! descendant of a parent module
+SUBMODULE ( parent ) child
+ implicit none
+CONTAINS
+ module function child_function() result(child_stuff)
+ logical :: child_stuff
+ child_stuff=.true.
+ end function
+END SUBMODULE child
diff --git a/Tests/FortranModules/Submodules/grandchild.f90 b/Tests/FortranModules/Submodules/grandchild.f90
new file mode 100644
index 000000000..1aef63e31
--- /dev/null
+++ b/Tests/FortranModules/Submodules/grandchild.f90
@@ -0,0 +1,8 @@
+! Test the notation for an Nth-generation descendant
+! for N>1, which necessitates the colon.
+submodule ( parent : child ) grandchild
+contains
+ module subroutine grandchild_subroutine()
+ print *,"Test passed."
+ end subroutine
+end submodule grandchild
diff --git a/Tests/FortranModules/Submodules/greatgrandchild.f90 b/Tests/FortranModules/Submodules/greatgrandchild.f90
new file mode 100644
index 000000000..85404eaf5
--- /dev/null
+++ b/Tests/FortranModules/Submodules/greatgrandchild.f90
@@ -0,0 +1,8 @@
+! Test the notation for an Nth-generation descendant
+! for N>1, which necessitates the colon.
+submodule ( parent : grandchild ) GreatGrandChild
+contains
+ module subroutine GreatGrandChild_subroutine()
+ print *,"Test passed."
+ end subroutine
+end submodule GreatGrandChild
diff --git a/Tests/FortranModules/Submodules/parent.f90 b/Tests/FortranModules/Submodules/parent.f90
new file mode 100644
index 000000000..3180b7043
--- /dev/null
+++ b/Tests/FortranModules/Submodules/parent.f90
@@ -0,0 +1,22 @@
+module parent
+ implicit none
+
+ interface
+
+ ! Test Fortran 2008 "module function" syntax
+ module function child_function() result(child_stuff)
+ logical :: child_stuff
+ end function
+ module function sibling_function() result(sibling_stuff)
+ logical :: sibling_stuff
+ end function
+
+ ! Test Fortran 2008 "module subroutine" syntax
+ module subroutine grandchild_subroutine()
+ end subroutine
+ module subroutine GreatGrandChild_subroutine()
+ end subroutine
+
+ end interface
+
+end module parent
diff --git a/Tests/FortranModules/Submodules/sibling.f90 b/Tests/FortranModules/Submodules/sibling.f90
new file mode 100644
index 000000000..8c0943dec
--- /dev/null
+++ b/Tests/FortranModules/Submodules/sibling.f90
@@ -0,0 +1,9 @@
+! Empty submodule for checking disambiguation of
+! nodes at the same vertical level in the tree
+submodule ( parent ) sibling
+contains
+ module function sibling_function() result(sibling_stuff)
+ logical :: sibling_stuff
+ sibling_stuff=.true.
+ end function
+end submodule sibling
diff --git a/Tests/FortranOnly/testRC.rc b/Tests/FortranOnly/testRC.rc
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/FortranOnly/testRC.rc
diff --git a/Tests/GeneratorExpression/srcgenex.c.in b/Tests/GeneratorExpression/srcgenex.c.in
new file mode 100644
index 000000000..4a43bd19b
--- /dev/null
+++ b/Tests/GeneratorExpression/srcgenex.c.in
@@ -0,0 +1,12 @@
+int @TARGET_NAME@(void)
+{
+ return 0;
+}
+
+int main(int argc, char* argv[])
+{
+#ifndef NAME
+#error NAME not defined
+#endif
+ return NAME();
+}
diff --git a/Tests/GeneratorExpression/srcgenex_includes.c.in b/Tests/GeneratorExpression/srcgenex_includes.c.in
new file mode 100644
index 000000000..b48d7dfc3
--- /dev/null
+++ b/Tests/GeneratorExpression/srcgenex_includes.c.in
@@ -0,0 +1,12 @@
+
+#include "@TARGET_NAME@.h"
+
+int @TARGET_NAME@(void)
+{
+ return 0;
+}
+
+int main(int argc, char* argv[])
+{
+ return @TARGET_NAME@();
+}
diff --git a/Tests/GeneratorExpression/srcgenex_includes.h.in b/Tests/GeneratorExpression/srcgenex_includes.h.in
new file mode 100644
index 000000000..2259ca67f
--- /dev/null
+++ b/Tests/GeneratorExpression/srcgenex_includes.h.in
@@ -0,0 +1,7 @@
+
+#if !defined @TARGET_NAME@_H
+#define @TARGET_NAME@_H
+
+int @TARGET_NAME@(void);
+
+#endif
diff --git a/Tests/GhsMulti/GhsMultiCompilerOptions/CMakeLists.txt b/Tests/GhsMulti/GhsMultiCompilerOptions/CMakeLists.txt
new file mode 100644
index 000000000..4a3f5c238
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiCompilerOptions/CMakeLists.txt
@@ -0,0 +1,92 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+message("Copy project")
+configure_file(${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt.in
+ ${CMAKE_CURRENT_BINARY_DIR}/src/CMakeLists.txt COPYONLY)
+
+file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/test.c
+ DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/src
+)
+
+message("Building project")
+set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
+try_compile(RESULT
+ ${CMAKE_CURRENT_BINARY_DIR}/build
+ ${CMAKE_CURRENT_BINARY_DIR}/src
+ test
+ CMAKE_FLAGS
+ -DRUN_TEST=${RUN_TEST}
+ -DCMAKE_BUILD_TYPE=${RUN_TEST_BUILD_TYPE}
+ OUTPUT_VARIABLE OUTPUT)
+
+message("Output from build:\n${OUTPUT}")
+if (RUN_TEST STREQUAL "RELEASE_FLAGS")
+ find_file (fileName test_none.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}/build
+ ${CMAKE_CURRENT_BINARY_DIR}/build/test_none
+ )
+ message("Parsing project file: ${fileName}")
+ file(STRINGS ${fileName} fileText)
+ set(opt "-unexpected_release_option")
+ string(FIND "${fileText}" "${opt}" opt_found)
+ if ( NOT opt_found EQUAL -1 )
+ message(SEND_ERROR "Release option found: ${opt}")
+ endif()
+else()
+ unset(fileName CACHE)
+ find_file (fileName K1.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}/build
+ ${CMAKE_CURRENT_BINARY_DIR}/build/K1
+ )
+ message("Parsing project file: ${fileName}")
+ file(STRINGS ${fileName} fileText)
+ set(opt "-required-debug-option")
+ string(FIND "${fileText}" "${opt}" opt_found)
+ if ( opt_found EQUAL -1 )
+ message(SEND_ERROR "Missing debug option: ${opt}")
+ endif()
+
+ unset(fileName CACHE)
+ find_file (fileName K2.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}/build
+ ${CMAKE_CURRENT_BINARY_DIR}/build/K2
+ )
+ message("Parsing project file: ${fileName}")
+ file(STRINGS ${fileName} fileText)
+ set(opt "-required-debug-option")
+ string(FIND "${fileText}" "${opt}" opt_found)
+ if ( opt_found EQUAL -1 )
+ message(SEND_ERROR "Missing debug option: ${opt}")
+ endif()
+
+ unset(fileName CACHE)
+ find_file (fileName K3.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}/build
+ ${CMAKE_CURRENT_BINARY_DIR}/build/K3
+ )
+ message("Parsing project file: ${fileName}")
+ file(STRINGS ${fileName} fileText)
+ set(opt "-required-debug-option")
+ string(FIND "${fileText}" "${opt}" opt_found)
+ if ( opt_found EQUAL -1 )
+ message(SEND_ERROR "Missing debug option: ${opt}")
+ endif()
+
+ unset(fileName CACHE)
+ find_file (fileName K4.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}/build
+ ${CMAKE_CURRENT_BINARY_DIR}/build/K4
+ )
+ message("Parsing project file: ${fileName}")
+ file(STRINGS ${fileName} fileText)
+ set(opt "-required-debug-option")
+ string(FIND "${fileText}" "${opt}" opt_found)
+ if ( opt_found EQUAL -1 )
+ message(SEND_ERROR "Missing debug option: ${opt}")
+ endif()
+endif()
diff --git a/Tests/GhsMulti/GhsMultiCompilerOptions/CMakeLists.txt.in b/Tests/GhsMulti/GhsMultiCompilerOptions/CMakeLists.txt.in
new file mode 100644
index 000000000..fc24d907b
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiCompilerOptions/CMakeLists.txt.in
@@ -0,0 +1,32 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ add_link_options("-non_shared")
+endif()
+
+if(RUN_TEST STREQUAL "RELEASE_FLAGS")
+ #RELEASE flags used when CMAKE_BUILD_TYPE is undefined
+ string(APPEND CMAKE_C_FLAGS_RELEASE " -unexpected_release_option")
+ add_executable(test_none test.c)
+endif()
+
+if(RUN_TEST STREQUAL "KERNEL_FLAGS")
+ #DEBUG flag missing when -kernel is added as a compile option
+ string(APPEND CMAKE_C_FLAGS_DEBUG " -required-debug-option")
+
+ add_executable(K1 test.c)
+
+ add_executable(K2 test.c)
+ target_compile_options(K2 PRIVATE -kernel)
+
+ add_executable(K3 test.c)
+ target_compile_options(K3 PRIVATE -kernel=fast)
+
+ add_executable(K4 test.c)
+ target_link_options(K4 PRIVATE -kernel)
+endif()
diff --git a/Tests/GhsMulti/GhsMultiCompilerOptions/test.c b/Tests/GhsMulti/GhsMultiCompilerOptions/test.c
new file mode 100644
index 000000000..95f2e8ec1
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiCompilerOptions/test.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+ return -1;
+}
diff --git a/Tests/GhsMulti/GhsMultiCopyFile/CMakeLists.txt b/Tests/GhsMulti/GhsMultiCopyFile/CMakeLists.txt
new file mode 100644
index 000000000..d6d007d9c
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiCopyFile/CMakeLists.txt
@@ -0,0 +1,30 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
+try_compile(RESULT
+ ${CMAKE_CURRENT_BINARY_DIR}/build
+ ${CMAKE_CURRENT_SOURCE_DIR}/test.c
+ OUTPUT_VARIABLE OUTPUT
+ COPY_FILE "${CMAKE_CURRENT_BINARY_DIR}/test_library"
+)
+
+message(STATUS "Output from build:\n${OUTPUT}")
+
+if(NOT RESULT)
+ message(SEND_ERROR "try_compile() failed")
+endif()
+
+if(EXISTS "${CMAKE_CURRENT_BINARY_DIR}/test_library")
+ if (IS_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_library")
+ message(SEND_ERROR "library is folder !")
+ else()
+ message(STATUS "library seems okay")
+ endif()
+else()
+ message(SEND_ERROR "library is not found !")
+endif()
diff --git a/Tests/GhsMulti/GhsMultiCopyFile/test.c b/Tests/GhsMulti/GhsMultiCopyFile/test.c
new file mode 100644
index 000000000..5c657b561
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiCopyFile/test.c
@@ -0,0 +1,4 @@
+int lib(int x)
+{
+ return -x;
+}
diff --git a/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt b/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt
new file mode 100644
index 000000000..93d668bb6
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt
@@ -0,0 +1,110 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+# Tests assume no previous builds in the build directory
+file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/build)
+
+macro (test_output)
+ if (BUILD_OUTPUT STREQUAL EXPECTED_LINES )
+ message("Build OK")
+ else()
+ message("BUILD_OUTPUT")
+ foreach(Line IN LISTS BUILD_OUTPUT)
+ message("${Line}")
+ endforeach()
+ message("EXPECTED_LINES")
+ foreach(Line IN LISTS EXPECTED_LINES)
+ message("${Line}")
+ endforeach()
+ message(SEND_ERROR "Build KO")
+ endif()
+endmacro()
+
+message("Copy project")
+configure_file(${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt.in
+ ${CMAKE_CURRENT_BINARY_DIR}/src/CMakeLists.txt COPYONLY)
+
+file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/exe1.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/lib1.c
+ DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/src
+)
+
+message("Building ALL target")
+try_compile(RESULT
+ ${CMAKE_CURRENT_BINARY_DIR}/build
+ ${CMAKE_CURRENT_BINARY_DIR}/src
+ test
+ CMAKE_FLAGS
+ -DCMAKE_EXE_LINKER_FLAGS=${CMAKE_EXE_LINKER_FLAGS}
+ OUTPUT_VARIABLE BUILD_OUTPUT)
+
+message("Output from build:\n${BUILD_OUTPUT}")
+
+#filter outputs
+string(REPLACE "\r" "" BUILD_OUTPUT "${BUILD_OUTPUT}")
+string(REPLACE "\n" ";" BUILD_OUTPUT "${BUILD_OUTPUT}")
+list(FILTER BUILD_OUTPUT INCLUDE REGEX "^.*CT:")
+
+unset(EXPECTED_LINES)
+list(APPEND EXPECTED_LINES "CT: Processing target_empty_prebuild")
+list(APPEND EXPECTED_LINES "CT: Processing target_empty_postbuild")
+list(APPEND EXPECTED_LINES "CT: Processing target_cmd")
+list(APPEND EXPECTED_LINES "CT: Processing target_cmd_prebuild")
+list(APPEND EXPECTED_LINES "CT: Processing target_cmd_postbuild")
+
+test_output()
+
+message("Building target_update_files target")
+try_compile(RESULT
+ ${CMAKE_CURRENT_BINARY_DIR}/build
+ ${CMAKE_CURRENT_BINARY_DIR}/src
+ test target_update_files
+ CMAKE_FLAGS
+ -DCMAKE_EXE_LINKER_FLAGS=${CMAKE_EXE_LINKER_FLAGS}
+ OUTPUT_VARIABLE BUILD_OUTPUT)
+
+message("Output from build:\n${BUILD_OUTPUT}")
+
+#filter outputs
+string(REPLACE "\r" "" BUILD_OUTPUT "${BUILD_OUTPUT}")
+string(REPLACE "\n" ";" BUILD_OUTPUT "${BUILD_OUTPUT}")
+list(FILTER BUILD_OUTPUT INCLUDE REGEX "^.*CT:")
+
+unset(EXPECTED_LINES)
+list(APPEND EXPECTED_LINES "CT: Processing target_empty_prebuild")
+list(APPEND EXPECTED_LINES "CT: Processing target_empty_postbuild")
+list(APPEND EXPECTED_LINES "CT: generate C file another_file")
+list(APPEND EXPECTED_LINES "CT: generate text file dependsA")
+list(APPEND EXPECTED_LINES "CT: generate text file out_of_order_dep")
+list(APPEND EXPECTED_LINES "CT: generate text files A, B, and C")
+list(APPEND EXPECTED_LINES "CT: Processing target_update_files")
+
+test_output()
+
+message("Rerun target_update_files target")
+try_compile(RESULT
+ ${CMAKE_CURRENT_BINARY_DIR}/build
+ ${CMAKE_CURRENT_BINARY_DIR}/src
+ test target_update_files
+ CMAKE_FLAGS
+ -DCMAKE_EXE_LINKER_FLAGS=${CMAKE_EXE_LINKER_FLAGS}
+ OUTPUT_VARIABLE BUILD_OUTPUT)
+
+message("Output from build:\n${BUILD_OUTPUT}")
+
+#filter outputs
+string(REPLACE "\r" "" BUILD_OUTPUT "${BUILD_OUTPUT}")
+string(REPLACE "\n" ";" BUILD_OUTPUT "${BUILD_OUTPUT}")
+list(FILTER BUILD_OUTPUT INCLUDE REGEX "^.*CT:")
+
+unset(EXPECTED_LINES)
+list(APPEND EXPECTED_LINES "CT: Processing target_empty_prebuild")
+list(APPEND EXPECTED_LINES "CT: Processing target_empty_postbuild")
+list(APPEND EXPECTED_LINES "CT: generate text files A, B, and C")
+list(APPEND EXPECTED_LINES "CT: Processing target_update_files")
+
+test_output()
diff --git a/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt.in b/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt.in
new file mode 100644
index 000000000..fed946cc5
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiCustomTarget/CMakeLists.txt.in
@@ -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.
+
+cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
+
+project(test C)
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ add_link_options("-non_shared")
+endif()
+
+add_library(lib1 lib1.c)
+
+set(TEST_MISSING_TARGET_SRC 0)
+set(TEST_MISSING_TARGET_DEP 0)
+set(TEST_MISSING_DEP 0)
+set(TEST_DEP_CYCLE 0)
+
+add_executable(exe1 exe1.c)
+target_link_libraries(exe1 lib1)
+
+add_custom_target(target_cmd ALL
+ COMMAND ${CMAKE_COMMAND} -E echo "target_cmd" > target_cmd
+ COMMAND ${CMAKE_COMMAND} -E echo "target_cmd_extra" > target_cmd_extra.txt
+ BYPRODUCTS target_cmd target_cmd_extra.txt
+ COMMENT "CT: Processing target_cmd")
+
+add_custom_command(TARGET target_cmd PRE_BUILD
+ COMMAND ${CMAKE_COMMAND} -E echo "target_cmd_prebuild" > target_cmd_prebuild.txt
+ BYPRODUCTS target_cmd_prebuild.txt
+ COMMENT "CT: Processing target_cmd_prebuild")
+#event does not run for custom targets
+add_custom_command(TARGET target_cmd PRE_LINK
+ COMMAND ${CMAKE_COMMAND} -E echo "executing target_cmd_prelink commands"
+ COMMAND ${CMAKE_COMMAND} -E echo "target_cmd_prelink" > target_cmd_prelink.txt
+ BYPRODUCTS target_cmd_prelink.txt
+ COMMENT "CT: Processing target_cmd_prelink")
+add_custom_command(TARGET target_cmd POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E echo "executing target_cmd_postbuild commands"
+ COMMAND ${CMAKE_COMMAND} -E echo "target_cmd_postbuild" > target_cmd_postbuild.txt
+ BYPRODUCTS target_cmd_postbuild.txt
+ COMMENT "CT: Processing target_cmd_postbuild")
+
+add_custom_target(target_empty ALL
+ COMMENT "CT: Processing target_empty")
+
+add_custom_command(TARGET target_empty PRE_BUILD
+ COMMAND ${CMAKE_COMMAND} -E echo "target_empty_prebuild" > target_empty_prebuild.txt
+ BYPRODUCTS target_empty_prebuild.txt
+ COMMENT "CT: Processing target_empty_prebuild")
+add_custom_command(TARGET target_empty POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E echo "target_empty_postbuild" > target_empty_postbuild.txt
+ BYPRODUCTS target_empty_postbuild.txt
+ COMMENT "CT: Processing target_empty_postbuild")
+
+add_dependencies(target_cmd target_empty)
+
+add_custom_command(
+ OUTPUT out_of_order_dep.txt
+ COMMAND ${CMAKE_COMMAND} -E echo "out_of_order_dep" > out_of_order_dep.txt
+ COMMENT "CT: generate text file out_of_order_dep"
+ DEPENDS dependsA.txt
+)
+
+if(TEST_MISSING_TARGET_SRC)
+ set(SRC_FILE does_not_exist)
+endif()
+if(TEST_MISSING_TARGET_DEP)
+ set(DEP_FILE does_not_exist)
+endif()
+
+add_custom_target(target_update_files
+ DEPENDS genc_do_not_list.txt ${DEP_FILE}
+ SOURCES gena.txt genb.txt another_file.c ${SRC_FILE}
+ BYPRODUCTS junkit.txt
+ COMMAND ${CMAKE_COMMAND} -E copy another_file.c junkit.txt
+ COMMENT "CT: Processing target_update_files")
+
+add_custom_command(
+ OUTPUT force_rebuild gena.txt genb.txt genc_do_not_list.txt
+ COMMAND ${CMAKE_COMMAND} -E copy dependsA.txt gena.txt
+ COMMAND ${CMAKE_COMMAND} -E echo "genb" > genb.txt
+ COMMAND ${CMAKE_COMMAND} -E echo "genc" > genc_do_not_list.txt
+ DEPENDS out_of_order_dep.txt dependsA.txt
+ COMMENT "CT: generate text files A, B, and C"
+)
+
+if(TEST_MISSING_DEP)
+ set(MISSING_DEP MISSING_DEP)
+endif()
+if(TEST_DEP_CYCLE)
+ set(DEP_CYCLE out_of_order_dep.txt)
+endif()
+
+add_custom_command(
+ OUTPUT dependsA.txt
+ COMMAND ${CMAKE_COMMAND} -E echo "dependsA" > dependsA.txt
+ DEPENDS ${MISSING_DEP} ${DEP_CYCLE} another_file.c
+ COMMENT "CT: generate text file dependsA"
+)
+
+add_custom_command(
+ OUTPUT another_file.c
+ COMMAND ${CMAKE_COMMAND} -E echo "//auto-gen file" > another_file.c
+ COMMENT "CT: generate C file another_file"
+)
+
+add_dependencies(target_update_files target_empty)
diff --git a/Tests/GhsMulti/GhsMultiCustomTarget/exe1.c b/Tests/GhsMulti/GhsMultiCustomTarget/exe1.c
new file mode 100644
index 000000000..29ad70a3b
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiCustomTarget/exe1.c
@@ -0,0 +1,5 @@
+extern int func(void);
+int main(void)
+{
+ return func();
+}
diff --git a/Tests/GhsMulti/GhsMultiCustomTarget/lib1.c b/Tests/GhsMulti/GhsMultiCustomTarget/lib1.c
new file mode 100644
index 000000000..b35e9cc5e
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiCustomTarget/lib1.c
@@ -0,0 +1,4 @@
+int func(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiDepOrder/CMakeLists.txt b/Tests/GhsMulti/GhsMultiDepOrder/CMakeLists.txt
new file mode 100644
index 000000000..2e2871b11
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDepOrder/CMakeLists.txt
@@ -0,0 +1,12 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+#set_property( GLOBAL PROPERTY GLOBAL_DEPENDS_DEBUG_MODE 1)
+add_subdirectory(exec)
+add_subdirectory(lib)
+add_subdirectory(protolib)
+add_dependencies(lib1 proto)
diff --git a/Tests/GhsMulti/GhsMultiDepOrder/exec/CMakeLists.txt b/Tests/GhsMulti/GhsMultiDepOrder/exec/CMakeLists.txt
new file mode 100644
index 000000000..85ee8056b
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDepOrder/exec/CMakeLists.txt
@@ -0,0 +1,11 @@
+# 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 3.12 FATAL_ERROR)
+
+add_executable(exe1 exe1.c)
+target_link_libraries(exe1 lib1)
+target_include_directories(exe1 PRIVATE "${test_BINARY_DIR}")
+if(CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ target_link_options(exe1 PRIVATE "-non_shared")
+endif()
diff --git a/Tests/GhsMulti/GhsMultiDepOrder/exec/exe1.c b/Tests/GhsMulti/GhsMultiDepOrder/exec/exe1.c
new file mode 100644
index 000000000..fbf4ed43e
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDepOrder/exec/exe1.c
@@ -0,0 +1,8 @@
+#include "lib1.h"
+#include "p.h"
+
+int main(void)
+{
+ return func1() + func2() + func3() + func1p() + func2p() + func3p() +
+ PROTO1 + PROTO2 + PROTO3;
+}
diff --git a/Tests/GhsMulti/GhsMultiDepOrder/lib/CMakeLists.txt b/Tests/GhsMulti/GhsMultiDepOrder/lib/CMakeLists.txt
new file mode 100644
index 000000000..ae30fa2bd
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDepOrder/lib/CMakeLists.txt
@@ -0,0 +1,17 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+add_library(lib1 STATIC
+ func1.c lib1.h
+ "${test_BINARY_DIR}/protolib/proto1.c"
+ "${test_BINARY_DIR}/protolib/proto1.h")
+set_source_files_properties(
+ "${test_BINARY_DIR}/protolib/proto1.c"
+ "${test_BINARY_DIR}/protolib/proto1.h"
+ PROPERTIES GENERATED 1)
+target_include_directories(lib1 PRIVATE "${test_BINARY_DIR}/protolib"
+ PUBLIC .)
+add_custom_command( TARGET lib1 POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy "${test_BINARY_DIR}/protolib/proto1.h" "${test_BINARY_DIR}/p.h"
+ COMMENT "Copy ${test_BINARY_DIR}/protolib/proto1.h ${test_BINARY_DIR}/p.h"
+ BYPRODUCTS "${test_BINARY_DIR}/p.h")
diff --git a/Tests/GhsMulti/GhsMultiDepOrder/lib/func1.c b/Tests/GhsMulti/GhsMultiDepOrder/lib/func1.c
new file mode 100644
index 000000000..53334fe36
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDepOrder/lib/func1.c
@@ -0,0 +1,17 @@
+#include "lib1.h"
+#include "proto1.h"
+
+int func1(void)
+{
+ return 1 + PROTO1;
+}
+
+int func2(void)
+{
+ return 2 + PROTO2;
+}
+
+int func3(void)
+{
+ return 3 + PROTO3;
+}
diff --git a/Tests/GhsMulti/GhsMultiDepOrder/lib/lib1.h b/Tests/GhsMulti/GhsMultiDepOrder/lib/lib1.h
new file mode 100644
index 000000000..5e99f0287
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDepOrder/lib/lib1.h
@@ -0,0 +1,3 @@
+extern int func1(void);
+extern int func2(void);
+extern int func3(void);
diff --git a/Tests/GhsMulti/GhsMultiDepOrder/protolib/CMakeLists.txt b/Tests/GhsMulti/GhsMultiDepOrder/protolib/CMakeLists.txt
new file mode 100644
index 000000000..8cb6869bd
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDepOrder/protolib/CMakeLists.txt
@@ -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.
+
+cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
+
+add_custom_target(proto ALL
+ DEPENDS proto1.c
+ proto1.h
+ SOURCES
+ ${test_SOURCE_DIR}/protolib/proto1.c.in
+ ${test_SOURCE_DIR}/protolib/proto1.h.in
+ COMMENT "Creating proto files")
+
+add_custom_command(
+ OUTPUT proto1.c
+ COMMAND ${CMAKE_COMMAND} -E copy
+ ${test_SOURCE_DIR}/protolib/proto1.c.in proto1.c
+ DEPENDS ${test_SOURCE_DIR}/protolib/proto1.c.in
+ COMMENT "generate proto C files"
+)
+
+add_custom_command(
+ OUTPUT proto1.h
+ COMMAND ${CMAKE_COMMAND} -E copy
+ ${test_SOURCE_DIR}/protolib/proto1.h.in proto1.h
+ DEPENDS ${test_SOURCE_DIR}/protolib/proto1.h.in
+ COMMENT "generate proto H files"
+)
diff --git a/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.c.in b/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.c.in
new file mode 100644
index 000000000..0efb1bd8d
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.c.in
@@ -0,0 +1,16 @@
+#include "proto1.h"
+
+int func1p(void)
+{
+ return 1;
+}
+
+int func2p(void)
+{
+ return 2;
+}
+
+int func3p(void)
+{
+ return 3;
+}
diff --git a/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.h.in b/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.h.in
new file mode 100644
index 000000000..f2f93afdd
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDepOrder/protolib/proto1.h.in
@@ -0,0 +1,7 @@
+extern int func1p(void);
+extern int func2p(void);
+extern int func3p(void);
+
+#define PROTO1 0x1
+#define PROTO2 0x2
+#define PROTO3 0x3
diff --git a/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/CMakeLists.txt b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/CMakeLists.txt
new file mode 100644
index 000000000..a1f152f29
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/CMakeLists.txt
@@ -0,0 +1,17 @@
+cmake_minimum_required(VERSION 3.5)
+project(test C)
+
+add_library(libdemo
+ test.c
+ testCase.c
+ subfolder_test.c
+ subfolder_test_0.c
+ "subfolder/test.c"
+ subfolder/testcase.c
+)
+
+add_executable(demo main.c)
+target_link_libraries(demo libdemo)
+if(CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ target_link_options(demo PRIVATE "-non_shared")
+endif()
diff --git a/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/main.c b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/main.c
new file mode 100644
index 000000000..d4ef7bb0f
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/main.c
@@ -0,0 +1,17 @@
+int test_a(void);
+int test_b(void);
+int test_c(void);
+int test_d(void);
+int test_e(void);
+int test_f(void);
+
+int main(int argc, char* argv[])
+{
+ test_a();
+ test_b();
+ test_c();
+ test_d();
+ test_e();
+ test_f();
+ return 0;
+}
diff --git a/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder/test.c b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder/test.c
new file mode 100644
index 000000000..5d857dde6
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder/test.c
@@ -0,0 +1,4 @@
+int test_b()
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder/testcase.c b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder/testcase.c
new file mode 100644
index 000000000..66ee6f380
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder/testcase.c
@@ -0,0 +1,4 @@
+int test_f()
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder_test.c b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder_test.c
new file mode 100644
index 000000000..83589ba19
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder_test.c
@@ -0,0 +1,4 @@
+int test_c()
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder_test_0.c b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder_test_0.c
new file mode 100644
index 000000000..82f9a52b7
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/subfolder_test_0.c
@@ -0,0 +1,4 @@
+int test_d()
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/test.c b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/test.c
new file mode 100644
index 000000000..feba80efc
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/test.c
@@ -0,0 +1,4 @@
+int test_a()
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/testCase.c b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/testCase.c
new file mode 100644
index 000000000..943c19de6
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiDuplicateSourceFilenames/testCase.c
@@ -0,0 +1,4 @@
+int test_e()
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiExclude/CMakeLists.txt b/Tests/GhsMulti/GhsMultiExclude/CMakeLists.txt
new file mode 100644
index 000000000..0448cf2d6
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiExclude/CMakeLists.txt
@@ -0,0 +1,17 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
+
+project(test C)
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ add_link_options("-non_shared")
+endif()
+
+add_library(lib1 lib1.c)
+set_target_properties( lib1 PROPERTIES EXCLUDE_FROM_ALL yes )
+
+add_library(lib2 EXCLUDE_FROM_ALL lib1.c)
+
+add_executable(exe1 exe1.c)
diff --git a/Tests/GhsMulti/GhsMultiExclude/exe1.c b/Tests/GhsMulti/GhsMultiExclude/exe1.c
new file mode 100644
index 000000000..8488f4e58
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiExclude/exe1.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/GhsMulti/GhsMultiExclude/lib1.c b/Tests/GhsMulti/GhsMultiExclude/lib1.c
new file mode 100644
index 000000000..b35e9cc5e
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiExclude/lib1.c
@@ -0,0 +1,4 @@
+int func(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiExclude/verify.cmake b/Tests/GhsMulti/GhsMultiExclude/verify.cmake
new file mode 100644
index 000000000..0467b5a0d
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiExclude/verify.cmake
@@ -0,0 +1,54 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#test project was generated
+unset(fileName CACHE)
+find_file (fileName lib1.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}/lib1
+ )
+
+if (fileName)
+ message("Found target lib1: ${fileName}")
+else()
+ message(SEND_ERROR "Could not find target lib1: ${fileName}")
+endif()
+
+#test project was built
+unset(fileName CACHE)
+find_file (fileName lib1.a
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}/lib1
+ )
+
+if (fileName)
+ message(SEND_ERROR "Found target lib1: ${fileName}")
+else()
+ message("Could not find target lib1: ${fileName}")
+endif()
+
+#test project was generated
+unset(fileName CACHE)
+find_file (fileName lib2.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}/lib2
+ )
+
+if (fileName)
+ message("Found target lib2 ${fileName}")
+else()
+ message(SEND_ERROR "Could not find target lib2: ${fileName}")
+endif()
+
+#test project was built
+unset(fileName CACHE)
+find_file (fileName lib2.a
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}/lib2
+ )
+
+if (fileName)
+ message(SEND_ERROR "Found target lib2: ${fileName}")
+else()
+ message("Could not find target lib2: ${fileName}")
+endif()
diff --git a/Tests/GhsMulti/GhsMultiExternalProject/CMakeLists.txt b/Tests/GhsMulti/GhsMultiExternalProject/CMakeLists.txt
new file mode 100644
index 000000000..24126c8fa
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiExternalProject/CMakeLists.txt
@@ -0,0 +1,14 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
+
+project(test C)
+include(ExternalProject)
+
+ExternalProject_Add(another_project
+ SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/empty
+ BINARY_DIR empty_build
+ INSTALL_COMMAND ""
+ TEST_COMMAND ""
+ )
diff --git a/Tests/GhsMulti/GhsMultiExternalProject/empty/CMakeLists.txt b/Tests/GhsMulti/GhsMultiExternalProject/empty/CMakeLists.txt
new file mode 100644
index 000000000..6846a9853
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiExternalProject/empty/CMakeLists.txt
@@ -0,0 +1,8 @@
+# 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 3.12 FATAL_ERROR)
+
+project(empty NONE)
+
+message("EMPTY PROJECT")
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/CMakeLists.txt b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/CMakeLists.txt
new file mode 100644
index 000000000..d4cbf0476
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/CMakeLists.txt
@@ -0,0 +1,19 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+add_link_options("-non_shared")
+
+# create virtual AS
+add_executable(vas exe.c)
+target_link_libraries(vas lib)
+add_library(lib func.c)
+
+# create dynamic download INTEGRITY application
+add_executable(dynamic)
+set_target_properties(dynamic PROPERTIES ghs_integrity_app ON)
+target_compile_options(dynamic PRIVATE -dynamic)
+add_dependencies(dynamic vas)
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/exe.c b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/exe.c
new file mode 100644
index 000000000..29ad70a3b
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/exe.c
@@ -0,0 +1,5 @@
+extern int func(void);
+int main(void)
+{
+ return func();
+}
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/func.c b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/func.c
new file mode 100644
index 000000000..b35e9cc5e
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDD/func.c
@@ -0,0 +1,4 @@
+int func(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/CMakeLists.txt b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/CMakeLists.txt
new file mode 100644
index 000000000..3837b5a2e
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/CMakeLists.txt
@@ -0,0 +1,3 @@
+add_executable(App Main.c)
+target_link_libraries(App Lib)
+target_compile_options(App PUBLIC "-non_shared")
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/Main.c b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/Main.c
new file mode 100644
index 000000000..db8d6587d
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/App/Main.c
@@ -0,0 +1,8 @@
+#include "HelperFun.h"
+
+int main(int argc, const char* argv[])
+{
+ int out;
+ out = giveNum();
+ return out;
+}
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/CMakeLists.txt b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/CMakeLists.txt
new file mode 100644
index 000000000..92254e673
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/CMakeLists.txt
@@ -0,0 +1,6 @@
+cmake_minimum_required(VERSION 3.1)
+project(test)
+
+add_subdirectory(App)
+add_subdirectory(Int)
+add_subdirectory(Lib)
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Int/AppDD.int b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Int/AppDD.int
new file mode 100644
index 000000000..5035d581a
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Int/AppDD.int
@@ -0,0 +1,12 @@
+# Input File for the Integrate utility for use with the INTEGRITY real-time
+# operating system by Green Hills Software.
+# Before editing this file, refer to the Integrate Reference Manual.
+
+Kernel
+ Filename DynamicDownload
+EndKernel
+
+AddressSpace App
+ Filename "App/App"
+ Language C
+EndAddressSpace
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Int/CMakeLists.txt b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Int/CMakeLists.txt
new file mode 100644
index 000000000..d173c0151
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Int/CMakeLists.txt
@@ -0,0 +1 @@
+add_executable(AppDD AppDD.int)
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/CMakeLists.txt b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/CMakeLists.txt
new file mode 100644
index 000000000..bb9849abb
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_library(Lib HelperFun.c HelperFun.h)
+target_include_directories(Lib PUBLIC .)
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/HelperFun.c b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/HelperFun.c
new file mode 100644
index 000000000..61922bb75
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/HelperFun.c
@@ -0,0 +1,4 @@
+int giveNum(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/HelperFun.h b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/HelperFun.h
new file mode 100644
index 000000000..00971b04f
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityDDInt/Lib/HelperFun.h
@@ -0,0 +1 @@
+int giveNum(void);
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/CMakeLists.txt b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/CMakeLists.txt
new file mode 100644
index 000000000..3f2f0eba6
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/CMakeLists.txt
@@ -0,0 +1,21 @@
+# 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 3.12 FATAL_ERROR)
+
+add_link_options("-non_shared")
+
+project(test C)
+
+# create virtual AS
+add_executable(vas exe.c)
+target_link_libraries(vas lib)
+add_library(lib func.c)
+
+# create kernel
+add_executable(kernel kernel.c)
+target_link_options(kernel PRIVATE -kernel)
+
+# create monolith INTEGRITY application
+add_executable(monolith test.int)
+add_dependencies(monolith vas)
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/exe.c b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/exe.c
new file mode 100644
index 000000000..29ad70a3b
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/exe.c
@@ -0,0 +1,5 @@
+extern int func(void);
+int main(void)
+{
+ return func();
+}
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/func.c b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/func.c
new file mode 100644
index 000000000..c302418f9
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/func.c
@@ -0,0 +1,5 @@
+
+int func(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/kernel.c b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/kernel.c
new file mode 100644
index 000000000..d1bce33c9
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/kernel.c
@@ -0,0 +1,15 @@
+#include "INTEGRITY.h"
+#include "boottable.h"
+
+void main()
+{
+ Exit(0);
+}
+
+/* This global table will be filled in during the Integrate phase with */
+/* information about the AddressSpaces, Tasks, and Objects that are to be */
+/* created. If you do not plan to use Integrate, you may omit this file from
+ */
+/* the kernel, and the boot table code will then not be included. */
+
+GlobalTable TheGlobalTable = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
diff --git a/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/test.int b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/test.int
new file mode 100644
index 000000000..361793a86
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiIntegrity/GhsMultiIntegrityMonolith/test.int
@@ -0,0 +1,8 @@
+Kernel
+ Filename kernel
+EndKernel
+
+AddressSpace App
+ Filename vas
+ Language C
+EndAddressSpace
diff --git a/Tests/GhsMulti/GhsMultiInterface/CMakeLists.txt b/Tests/GhsMulti/GhsMultiInterface/CMakeLists.txt
new file mode 100644
index 000000000..fa0dce027
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiInterface/CMakeLists.txt
@@ -0,0 +1,8 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+add_library(iface INTERFACE)
diff --git a/Tests/GhsMulti/GhsMultiLinkTest/CMakeLists.txt b/Tests/GhsMulti/GhsMultiLinkTest/CMakeLists.txt
new file mode 100644
index 000000000..da80b510f
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTest/CMakeLists.txt
@@ -0,0 +1,92 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+message("Copy project")
+configure_file(${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt.in
+ ${CMAKE_CURRENT_BINARY_DIR}/link_src/CMakeLists.txt COPYONLY)
+
+file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/exe1.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/exe1.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/func2.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/func3.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/func4.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/func5.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/func6.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/func7.c
+ DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/link_src
+)
+
+message("Building project")
+try_compile(RESULT
+ ${CMAKE_CURRENT_BINARY_DIR}/link_build
+ ${CMAKE_CURRENT_BINARY_DIR}/link_src
+ test
+ CMAKE_FLAGS
+ -DRUN_TEST=${RUN_TEST}
+ -DCMAKE_EXE_LINKER_FLAGS=${CMAKE_EXE_LINKER_FLAGS}
+ OUTPUT_VARIABLE OUTPUT)
+
+message("Output from build:\n${OUTPUT}")
+if (RUN_TEST STREQUAL "NO_FLAGS")
+ if(NOT RESULT)
+ message(SEND_ERROR "Could not build test project (1)!")
+ endif()
+else()
+ unset(fileName CACHE)
+ find_file(fileName exe1.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}/link_build
+ ${CMAKE_CURRENT_BINARY_DIR}/link_build/exe1
+ )
+ message("Parsing project file: ${fileName}")
+ file(STRINGS ${fileName} fileText)
+ set(expected_flags
+ -add-link-options1 -add-link-options2
+ link_directories_used1 link_directories_used2 "c:/absolute"
+ link_libraries_used1 link_libraries_used2
+ -lcsl1 csl2
+ -clinkexe1 -clinkexe2
+ -special-lib2-public-link)
+ foreach(opt IN LISTS expected_flags)
+ string(FIND "${fileText}" "${opt}" opt_found)
+ if ( opt_found EQUAL -1 )
+ message(SEND_ERROR "Could not find: ${opt}")
+ endif()
+ endforeach()
+
+ unset(fileName CACHE)
+ find_file (fileName lib1.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}/link_build
+ ${CMAKE_CURRENT_BINARY_DIR}/link_build/lib1
+ )
+ message("Parsing project file: ${fileName}")
+ file(STRINGS ${fileName} fileText)
+ set(expected_flags
+ -clinkexeA1 -clinkexeA2
+ -static-lib-flags1 -static-lib-flags2)
+ foreach(opt IN LISTS expected_flags)
+ string(FIND "${fileText}" "${opt}" opt_found)
+ if (opt_found EQUAL -1)
+ message(SEND_ERROR "Could not find: ${opt}")
+ endif()
+ endforeach()
+
+ unset(fileName CACHE)
+ find_file (fileName lib2.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}/link_build
+ ${CMAKE_CURRENT_BINARY_DIR}/link_build/lib2
+ )
+ message("Parsing project file: ${fileName}")
+ file(STRINGS ${fileName} fileText)
+ set(expected_flags
+ -clinkexeA1 -clinkexeA2)
+ foreach(opt IN LISTS expected_flags)
+ string(FIND "${fileText}" "${opt}" opt_found)
+ if ( opt_found EQUAL -1 )
+ message(SEND_ERROR "Could not find: ${opt}")
+ endif()
+ endforeach()
+endif()
diff --git a/Tests/GhsMulti/GhsMultiLinkTest/CMakeLists.txt.in b/Tests/GhsMulti/GhsMultiLinkTest/CMakeLists.txt.in
new file mode 100644
index 000000000..58c211524
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTest/CMakeLists.txt.in
@@ -0,0 +1,43 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ add_link_options("-non_shared")
+endif()
+
+if(RUN_TEST STREQUAL "CHECK_FLAGS")
+ add_link_options(-add-link-options1 -add-link-options2)
+ link_directories(link_directories_used1 link_directories_used2 "c:/absolute")
+ link_libraries(link_libraries_used1 link_libraries_used2 )
+ set( CMAKE_C_STANDARD_LIBRARIES "${CMAKE_C_STANDARD_LIBRARIES} -lcsl1 csl2" )
+ set( CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -clinkexe1 -clinkexe2")
+endif()
+
+add_executable(exe1 exe1.c)
+target_link_libraries(exe1 lib1)
+
+if(RUN_TEST STREQUAL "CHECK_FLAGS")
+ set_property(TARGET exe1 APPEND_STRING PROPERTY LINK_FLAGS "--link-flag-prop1 --link-flag-prop2")
+ set_property(TARGET exe1 APPEND PROPERTY LINK_OPTIONS --link-opt-prop1 --link-opt-prop2)
+endif()
+
+if(RUN_TEST STREQUAL "CHECK_FLAGS")
+ set(CMAKE_STATIC_LINKER_FLAGS ${CMAKE_STATIC_LINKER_FLAGS} "-clinkexeA1 -clinkexeA2")
+endif()
+
+add_library(lib1 STATIC func2.c func3.c func4.c)
+target_link_libraries(lib1 lib2)
+
+if(RUN_TEST STREQUAL "CHECK_FLAGS")
+ set_property(TARGET lib1 APPEND_STRING PROPERTY STATIC_LIBRARY_FLAGS "-static-lib-flags1 -static-lib-flags2")
+endif()
+
+add_library(lib2 STATIC func5.c func6.c func7.c)
+
+if(RUN_TEST STREQUAL "CHECK_FLAGS")
+ target_link_options(lib2 PUBLIC -special-lib2-public-link)
+endif()
diff --git a/Tests/GhsMulti/GhsMultiLinkTest/exe1.c b/Tests/GhsMulti/GhsMultiLinkTest/exe1.c
new file mode 100644
index 000000000..f21c12645
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTest/exe1.c
@@ -0,0 +1,6 @@
+#include "exe1.h"
+
+int main(void)
+{
+ return func2a() + func3a() + func4a() + func5a() + func6a() + func7a();
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTest/exe1.h b/Tests/GhsMulti/GhsMultiLinkTest/exe1.h
new file mode 100644
index 000000000..e2b172570
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTest/exe1.h
@@ -0,0 +1,6 @@
+extern int func2a(void);
+extern int func3a(void);
+extern int func4a(void);
+extern int func5a(void);
+extern int func6a(void);
+extern int func7a(void);
diff --git a/Tests/GhsMulti/GhsMultiLinkTest/func2.c b/Tests/GhsMulti/GhsMultiLinkTest/func2.c
new file mode 100644
index 000000000..8f66fba25
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTest/func2.c
@@ -0,0 +1,4 @@
+int func2a(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTest/func3.c b/Tests/GhsMulti/GhsMultiLinkTest/func3.c
new file mode 100644
index 000000000..57c7a6ffb
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTest/func3.c
@@ -0,0 +1,4 @@
+int func3a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTest/func4.c b/Tests/GhsMulti/GhsMultiLinkTest/func4.c
new file mode 100644
index 000000000..109fd7b4a
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTest/func4.c
@@ -0,0 +1,4 @@
+int func4a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTest/func5.c b/Tests/GhsMulti/GhsMultiLinkTest/func5.c
new file mode 100644
index 000000000..f28a705d4
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTest/func5.c
@@ -0,0 +1,4 @@
+int func5a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTest/func6.c b/Tests/GhsMulti/GhsMultiLinkTest/func6.c
new file mode 100644
index 000000000..bf7740658
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTest/func6.c
@@ -0,0 +1,4 @@
+int func6a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTest/func7.c b/Tests/GhsMulti/GhsMultiLinkTest/func7.c
new file mode 100644
index 000000000..6a4a9a1f0
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTest/func7.c
@@ -0,0 +1,4 @@
+int func7a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/CMakeLists.txt b/Tests/GhsMulti/GhsMultiLinkTestSub/CMakeLists.txt
new file mode 100644
index 000000000..145dac0eb
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/CMakeLists.txt
@@ -0,0 +1,9 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+add_subdirectory(sub_exe)
+add_subdirectory(sub_lib)
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/CMakeLists.txt b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/CMakeLists.txt
new file mode 100644
index 000000000..f49e33d6c
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/CMakeLists.txt
@@ -0,0 +1,12 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+add_executable(exe1 exe1.c)
+target_link_libraries(exe1 lib1)
+if(CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ target_link_options(exe1 PRIVATE "-non_shared")
+endif()
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/exe1.c b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/exe1.c
new file mode 100644
index 000000000..f21c12645
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/exe1.c
@@ -0,0 +1,6 @@
+#include "exe1.h"
+
+int main(void)
+{
+ return func2a() + func3a() + func4a() + func5a() + func6a() + func7a();
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/exe1.h b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/exe1.h
new file mode 100644
index 000000000..e2b172570
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_exe/exe1.h
@@ -0,0 +1,6 @@
+extern int func2a(void);
+extern int func3a(void);
+extern int func4a(void);
+extern int func5a(void);
+extern int func6a(void);
+extern int func7a(void);
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/CMakeLists.txt b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/CMakeLists.txt
new file mode 100644
index 000000000..90397304f
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/CMakeLists.txt
@@ -0,0 +1,7 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+add_library(lib1 STATIC func2.c func3.c func4.c)
+target_link_libraries(lib1 lib2)
+
+add_library(lib2 STATIC func5.c func6.c func7.c)
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func2.c b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func2.c
new file mode 100644
index 000000000..8f66fba25
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func2.c
@@ -0,0 +1,4 @@
+int func2a(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func3.c b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func3.c
new file mode 100644
index 000000000..57c7a6ffb
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func3.c
@@ -0,0 +1,4 @@
+int func3a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func4.c b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func4.c
new file mode 100644
index 000000000..109fd7b4a
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func4.c
@@ -0,0 +1,4 @@
+int func4a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func5.c b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func5.c
new file mode 100644
index 000000000..f28a705d4
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func5.c
@@ -0,0 +1,4 @@
+int func5a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func6.c b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func6.c
new file mode 100644
index 000000000..bf7740658
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func6.c
@@ -0,0 +1,4 @@
+int func6a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func7.c b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func7.c
new file mode 100644
index 000000000..6a4a9a1f0
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiLinkTestSub/sub_lib/func7.c
@@ -0,0 +1,4 @@
+int func7a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiMultipleProjects/CMakeLists.txt b/Tests/GhsMulti/GhsMultiMultipleProjects/CMakeLists.txt
new file mode 100644
index 000000000..9e077a9a4
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiMultipleProjects/CMakeLists.txt
@@ -0,0 +1,17 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
+
+project(test C)
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ add_link_options("-non_shared")
+endif()
+
+add_library(lib1 lib1.c)
+add_executable(exe1 exe1.c)
+target_link_libraries(exe1 lib1)
+
+add_subdirectory(sub)
+add_subdirectory(sub2 examples EXCLUDE_FROM_ALL)
diff --git a/Tests/GhsMulti/GhsMultiMultipleProjects/exe1.c b/Tests/GhsMulti/GhsMultiMultipleProjects/exe1.c
new file mode 100644
index 000000000..b9cdd61e7
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiMultipleProjects/exe1.c
@@ -0,0 +1,5 @@
+extern int lib1_func(void);
+int main(void)
+{
+ return lib1_func();
+}
diff --git a/Tests/GhsMulti/GhsMultiMultipleProjects/lib1.c b/Tests/GhsMulti/GhsMultiMultipleProjects/lib1.c
new file mode 100644
index 000000000..510094589
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiMultipleProjects/lib1.c
@@ -0,0 +1,4 @@
+int lib1_func(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiMultipleProjects/sub/CMakeLists.txt b/Tests/GhsMulti/GhsMultiMultipleProjects/sub/CMakeLists.txt
new file mode 100644
index 000000000..0d83bc310
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiMultipleProjects/sub/CMakeLists.txt
@@ -0,0 +1,10 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test2 C)
+
+add_library(lib2 lib2.c)
+add_executable(exe2 exe2.c)
+target_link_libraries(exe2 lib1 lib2)
diff --git a/Tests/GhsMulti/GhsMultiMultipleProjects/sub/exe2.c b/Tests/GhsMulti/GhsMultiMultipleProjects/sub/exe2.c
new file mode 100644
index 000000000..9238cf369
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiMultipleProjects/sub/exe2.c
@@ -0,0 +1,6 @@
+extern int func(void);
+extern int lib1_func(void);
+int main(void)
+{
+ return func() + lib1_func();
+}
diff --git a/Tests/GhsMulti/GhsMultiMultipleProjects/sub/lib2.c b/Tests/GhsMulti/GhsMultiMultipleProjects/sub/lib2.c
new file mode 100644
index 000000000..b35e9cc5e
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiMultipleProjects/sub/lib2.c
@@ -0,0 +1,4 @@
+int func(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiMultipleProjects/sub2/CMakeLists.txt b/Tests/GhsMulti/GhsMultiMultipleProjects/sub2/CMakeLists.txt
new file mode 100644
index 000000000..e42e7fb2c
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiMultipleProjects/sub2/CMakeLists.txt
@@ -0,0 +1,10 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test3 C)
+
+add_library(lib3 lib3.c)
+add_executable(exe3 exe3.c)
+target_link_libraries(exe3 lib1 lib3)
diff --git a/Tests/GhsMulti/GhsMultiMultipleProjects/sub2/exe3.c b/Tests/GhsMulti/GhsMultiMultipleProjects/sub2/exe3.c
new file mode 100644
index 000000000..9238cf369
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiMultipleProjects/sub2/exe3.c
@@ -0,0 +1,6 @@
+extern int func(void);
+extern int lib1_func(void);
+int main(void)
+{
+ return func() + lib1_func();
+}
diff --git a/Tests/GhsMulti/GhsMultiMultipleProjects/sub2/lib3.c b/Tests/GhsMulti/GhsMultiMultipleProjects/sub2/lib3.c
new file mode 100644
index 000000000..b35e9cc5e
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiMultipleProjects/sub2/lib3.c
@@ -0,0 +1,4 @@
+int func(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiMultipleProjects/verify.cmake b/Tests/GhsMulti/GhsMultiMultipleProjects/verify.cmake
new file mode 100644
index 000000000..3855215af
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiMultipleProjects/verify.cmake
@@ -0,0 +1,58 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#test project was generated
+unset(fileName CACHE)
+find_file(fileName lib3.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}/lib3
+ ${CMAKE_CURRENT_BINARY_DIR}/examples
+ )
+
+if (fileName)
+ message("Found target lib3: ${fileName}")
+else()
+ message(SEND_ERROR "Could not find target lib3: ${fileName}")
+endif()
+
+#test project was generated
+unset(fileName CACHE)
+find_file (fileName exe3.gpj
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}/exe3
+ ${CMAKE_CURRENT_BINARY_DIR}/examples
+ )
+
+if (fileName)
+ message("Found target exe3: ${fileName}")
+else()
+ message(SEND_ERROR "Could not find target exe3: ${fileName}")
+endif()
+
+#test project was not built
+unset(fileName CACHE)
+find_file (fileName lib3.a
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}/lib3
+ ${CMAKE_CURRENT_BINARY_DIR}/examples
+ )
+
+if (fileName)
+ message(SEND_ERROR "Found target lib3: ${fileName}")
+else()
+ message("Could not find target lib3: ${fileName}")
+endif()
+
+unset(fileName CACHE)
+find_file (fileName NAMES exe3.as exe3
+ HINTS
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}/exe3
+ ${CMAKE_CURRENT_BINARY_DIR}/examples
+ )
+
+if (fileName)
+ message(SEND_ERROR "Found target exe3: ${fileName}")
+else()
+ message("Could not find target exe3: ${fileName}")
+endif()
diff --git a/Tests/GhsMulti/GhsMultiObjectLibrary/CMakeLists.txt b/Tests/GhsMulti/GhsMultiObjectLibrary/CMakeLists.txt
new file mode 100644
index 000000000..98668e5c9
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiObjectLibrary/CMakeLists.txt
@@ -0,0 +1,13 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+add_library(obj1 OBJECT testOBJ.c testOBJ.h sub/testOBJ.c testOBJ2.c)
+
+add_executable(exe1 exe.c $<TARGET_OBJECTS:obj1>)
+if(CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ target_link_options(exe1 PRIVATE "-non_shared")
+endif()
diff --git a/Tests/GhsMulti/GhsMultiObjectLibrary/exe.c b/Tests/GhsMulti/GhsMultiObjectLibrary/exe.c
new file mode 100644
index 000000000..c2c5a1945
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiObjectLibrary/exe.c
@@ -0,0 +1,8 @@
+extern int funcOBJ(void);
+extern int funcOBJ2(void);
+extern int funcOBJs(void);
+
+int main(void)
+{
+ return funcOBJ() + funcOBJ2() + funcOBJs();
+}
diff --git a/Tests/GhsMulti/GhsMultiObjectLibrary/sub/testOBJ.c b/Tests/GhsMulti/GhsMultiObjectLibrary/sub/testOBJ.c
new file mode 100644
index 000000000..5228ef264
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiObjectLibrary/sub/testOBJ.c
@@ -0,0 +1,4 @@
+int funcOBJs(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ.c b/Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ.c
new file mode 100644
index 000000000..ec6f2c331
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ.c
@@ -0,0 +1,4 @@
+int funcOBJ(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ.h b/Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ.h
new file mode 100644
index 000000000..9aef4315c
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ.h
@@ -0,0 +1 @@
+extern int funcOBJ(void);
diff --git a/Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ2.c b/Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ2.c
new file mode 100644
index 000000000..b6a9b93f2
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiObjectLibrary/testOBJ2.c
@@ -0,0 +1,4 @@
+int funcOBJ2(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiPlatform/CMakeLists.txt b/Tests/GhsMulti/GhsMultiPlatform/CMakeLists.txt
new file mode 100644
index 000000000..b177887c9
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiPlatform/CMakeLists.txt
@@ -0,0 +1,34 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test)
+
+message("PLATFORM_ID = ${PLATFORM_ID}")
+
+message("CMAKE_C_COMPILER = ${CMAKE_C_COMPILER}")
+message("CMAKE_C_COMPILER_ID = ${CMAKE_C_COMPILER_ID}")
+message("CMAKE_C_COMPILER_VERSION = ${CMAKE_C_COMPILER_VERSION}")
+message("CMAKE_C_COMPILER_VERSION_INTERNAL = ${CMAKE_C_COMPILER_VERSION_INTERNAL}")
+message("CMAKE_C_PLATFORM_ID = ${CMAKE_C_PLATFORM_ID}")
+message("CMAKE_C_COMPILER_ARCHITECTURE_ID = ${CMAKE_C_COMPILER_ARCHITECTURE_ID}")
+message("CMAKE_C_COMPILER_ABI = ${CMAKE_C_COMPILER_ABI}")
+message("CMAKE_C_STANDARD_COMPUTED_DEFAULT = ${CMAKE_C_STANDARD_COMPUTED_DEFAULT}")
+
+message("CMAKE_CXX_COMPILER = ${CMAKE_CXX_COMPILER}")
+message("CMAKE_CXX_COMPILER_ID = ${CMAKE_CXX_COMPILER_ID}")
+message("CMAKE_CXX_COMPILER_VERSION = ${CMAKE_CXX_COMPILER_VERSION}")
+message("CMAKE_CXX_COMPILER_VERSION_INTERNAL = ${CMAKE_CXX_COMPILER_VERSION_INTERNAL}")
+message("CMAKE_CXX_PLATFORM_ID = ${CMAKE_CXX_PLATFORM_ID}")
+message("CMAKE_CXX_COMPILER_ARCHITECTURE_ID = ${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}")
+message("CMAKE_CXX_COMPILER_ABI = ${CMAKE_CXX_COMPILER_ABI}")
+message("CMAKE_CXX_STANDARD_COMPUTED_DEFAULT = ${CMAKE_CXX_STANDARD_COMPUTED_DEFAULT}")
+
+if(CMAKE_C_COMPILER AND NOT CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ message(FATAL_ERROR "CMAKE_C_COMPILER_ID != GHS")
+endif()
+
+if(CMAKE_CXX_COMPILER AND NOT CMAKE_CXX_COMPILER_ID STREQUAL "GHS")
+ message(FATAL_ERROR "CMAKE_CXX_COMPILER_ID != GHS")
+endif()
diff --git a/Tests/GhsMulti/GhsMultiRenameInstall/CMakeLists.txt b/Tests/GhsMulti/GhsMultiRenameInstall/CMakeLists.txt
new file mode 100644
index 000000000..b2540d974
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiRenameInstall/CMakeLists.txt
@@ -0,0 +1,42 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+set(targets_to_install "")
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GHS")
+ add_link_options("-non_shared")
+endif()
+
+if(RUN_TEST STREQUAL "SINGLE_EXEC")
+ add_executable(exe1 exe.c)
+ set(targets_to_install exe1)
+endif()
+
+if(RUN_TEST STREQUAL "SINGLE_EXEC_RENAMED")
+ set(name new_name)
+ add_executable(exe1 exe.c)
+ set_property(TARGET exe1 PROPERTY RUNTIME_OUTPUT_DIRECTORY ${name}_bin_$<CONFIG>)
+ set_property(TARGET exe1 PROPERTY OUTPUT_NAME ${name}_$<CONFIG>)
+ set_property(TARGET exe1 PROPERTY SUFFIX .bin)
+ set(targets_to_install exe1)
+endif()
+
+if(RUN_TEST STREQUAL "EXEC_AND_LIB")
+ add_library(lib1 lib1.c)
+ set_property(TARGET lib1 PROPERTY ARCHIVE_OUTPUT_DIRECTORY forced-$<CONFIG>)
+ set_property(TARGET lib1 PROPERTY SUFFIX .LL)
+ set_property(TARGET lib1 PROPERTY OUTPUT_NAME lib1_$<CONFIG>)
+
+ add_executable(exe1 exe1.c)
+ target_link_libraries(exe1 lib1)
+ set(targets_to_install exe1 lib1)
+endif()
+
+install(TARGETS ${targets_to_install}
+ RUNTIME DESTINATION bin
+ LIBRARY DESTINATION lib
+ ARCHIVE DESTINATION lib/static)
diff --git a/Tests/GhsMulti/GhsMultiRenameInstall/exe.c b/Tests/GhsMulti/GhsMultiRenameInstall/exe.c
new file mode 100644
index 000000000..8488f4e58
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiRenameInstall/exe.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/GhsMulti/GhsMultiRenameInstall/exe1.c b/Tests/GhsMulti/GhsMultiRenameInstall/exe1.c
new file mode 100644
index 000000000..29ad70a3b
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiRenameInstall/exe1.c
@@ -0,0 +1,5 @@
+extern int func(void);
+int main(void)
+{
+ return func();
+}
diff --git a/Tests/GhsMulti/GhsMultiRenameInstall/lib1.c b/Tests/GhsMulti/GhsMultiRenameInstall/lib1.c
new file mode 100644
index 000000000..b35e9cc5e
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiRenameInstall/lib1.c
@@ -0,0 +1,4 @@
+int func(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/Atest3.c b/Tests/GhsMulti/GhsMultiSrcGroups/Atest3.c
new file mode 100644
index 000000000..9c9c1d91b
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/Atest3.c
@@ -0,0 +1,4 @@
+int funcA3a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/CMakeLists.txt b/Tests/GhsMulti/GhsMultiSrcGroups/CMakeLists.txt
new file mode 100644
index 000000000..93a1afcb6
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/CMakeLists.txt
@@ -0,0 +1,45 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+#set(CMAKE_FOLDER ON)
+add_executable(groups
+ test1.c
+ test1.h
+ test2a.c
+ test4.c
+ test5.c
+ test6.c
+ test7.c
+ standard.h
+ testOBJ.c
+ testOBJ.h
+ sub/testOBJ.c
+ sub/testOBJ.h
+ textfile.txt
+ textfile2.txt
+ test3.c
+ Atest3.c
+# object.o
+ resource.pdf
+ cmake.rule
+ s5.h
+ s2.h
+ s4.h
+ standard.h
+ )
+
+if(TEST_PROP)
+ set_target_properties(groups PROPERTIES GHS_NO_SOURCE_GROUP_FILE ON)
+endif()
+if(CMAKE_C_COMPILER_ID MATCHES "GHS")
+ target_link_options(groups PRIVATE "-non_shared")
+endif()
+source_group( gC FILES sub/testOBJ.h testOBJ.c testOBJ.h sub/testOBJ.c )
+source_group( gA FILES test1.c test1.h)
+source_group( gB test[65].c )
+source_group( gC\\gD FILES test7.c )
+source_group( docs FILES textfile.txt )
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/cmake.rule b/Tests/GhsMulti/GhsMultiSrcGroups/cmake.rule
new file mode 100644
index 000000000..c6cac6926
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/cmake.rule
@@ -0,0 +1 @@
+empty
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/object.o b/Tests/GhsMulti/GhsMultiSrcGroups/object.o
new file mode 100644
index 000000000..c6cac6926
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/object.o
@@ -0,0 +1 @@
+empty
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/resource.pdf b/Tests/GhsMulti/GhsMultiSrcGroups/resource.pdf
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/resource.pdf
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/s2.h b/Tests/GhsMulti/GhsMultiSrcGroups/s2.h
new file mode 100644
index 000000000..e2b172570
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/s2.h
@@ -0,0 +1,6 @@
+extern int func2a(void);
+extern int func3a(void);
+extern int func4a(void);
+extern int func5a(void);
+extern int func6a(void);
+extern int func7a(void);
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/s4.h b/Tests/GhsMulti/GhsMultiSrcGroups/s4.h
new file mode 100644
index 000000000..e2b172570
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/s4.h
@@ -0,0 +1,6 @@
+extern int func2a(void);
+extern int func3a(void);
+extern int func4a(void);
+extern int func5a(void);
+extern int func6a(void);
+extern int func7a(void);
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/s5.h b/Tests/GhsMulti/GhsMultiSrcGroups/s5.h
new file mode 100644
index 000000000..e2b172570
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/s5.h
@@ -0,0 +1,6 @@
+extern int func2a(void);
+extern int func3a(void);
+extern int func4a(void);
+extern int func5a(void);
+extern int func6a(void);
+extern int func7a(void);
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/standard.h b/Tests/GhsMulti/GhsMultiSrcGroups/standard.h
new file mode 100644
index 000000000..2773a5511
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/standard.h
@@ -0,0 +1 @@
+#define somthing
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/sub/testOBJ.c b/Tests/GhsMulti/GhsMultiSrcGroups/sub/testOBJ.c
new file mode 100644
index 000000000..90ea9b991
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/sub/testOBJ.c
@@ -0,0 +1,6 @@
+#include "testOBJ.h"
+
+int funcOBJsub(void)
+{
+ return func2a() + func3a() + func4a() + func5a() + func6a() + func7a();
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/sub/testOBJ.h b/Tests/GhsMulti/GhsMultiSrcGroups/sub/testOBJ.h
new file mode 100644
index 000000000..e2b172570
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/sub/testOBJ.h
@@ -0,0 +1,6 @@
+extern int func2a(void);
+extern int func3a(void);
+extern int func4a(void);
+extern int func5a(void);
+extern int func6a(void);
+extern int func7a(void);
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/test1.c b/Tests/GhsMulti/GhsMultiSrcGroups/test1.c
new file mode 100644
index 000000000..94f818a0e
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/test1.c
@@ -0,0 +1,6 @@
+#include "test1.h"
+
+int main(void)
+{
+ return func2a() + func3a() + func4a() + func5a() + func6a() + func7a();
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/test1.h b/Tests/GhsMulti/GhsMultiSrcGroups/test1.h
new file mode 100644
index 000000000..e2b172570
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/test1.h
@@ -0,0 +1,6 @@
+extern int func2a(void);
+extern int func3a(void);
+extern int func4a(void);
+extern int func5a(void);
+extern int func6a(void);
+extern int func7a(void);
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/test2a.c b/Tests/GhsMulti/GhsMultiSrcGroups/test2a.c
new file mode 100644
index 000000000..8f66fba25
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/test2a.c
@@ -0,0 +1,4 @@
+int func2a(void)
+{
+ return 2;
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/test3.c b/Tests/GhsMulti/GhsMultiSrcGroups/test3.c
new file mode 100644
index 000000000..57c7a6ffb
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/test3.c
@@ -0,0 +1,4 @@
+int func3a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/test3.h b/Tests/GhsMulti/GhsMultiSrcGroups/test3.h
new file mode 100644
index 000000000..2773a5511
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/test3.h
@@ -0,0 +1 @@
+#define somthing
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/test4.c b/Tests/GhsMulti/GhsMultiSrcGroups/test4.c
new file mode 100644
index 000000000..109fd7b4a
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/test4.c
@@ -0,0 +1,4 @@
+int func4a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/test5.c b/Tests/GhsMulti/GhsMultiSrcGroups/test5.c
new file mode 100644
index 000000000..f28a705d4
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/test5.c
@@ -0,0 +1,4 @@
+int func5a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/test6.c b/Tests/GhsMulti/GhsMultiSrcGroups/test6.c
new file mode 100644
index 000000000..bf7740658
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/test6.c
@@ -0,0 +1,4 @@
+int func6a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/test7.c b/Tests/GhsMulti/GhsMultiSrcGroups/test7.c
new file mode 100644
index 000000000..6a4a9a1f0
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/test7.c
@@ -0,0 +1,4 @@
+int func7a(void)
+{
+ return 1;
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/testOBJ.c b/Tests/GhsMulti/GhsMultiSrcGroups/testOBJ.c
new file mode 100644
index 000000000..e86e2a451
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/testOBJ.c
@@ -0,0 +1,11 @@
+extern int func2a(void);
+extern int func3a(void);
+extern int func4a(void);
+extern int func5a(void);
+extern int func6a(void);
+extern int func7a(void);
+
+int funcOBJ(void)
+{
+ return func2a() + func3a() + func4a() + func5a() + func6a() + func7a();
+}
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/testOBJ.h b/Tests/GhsMulti/GhsMultiSrcGroups/testOBJ.h
new file mode 100644
index 000000000..e2b172570
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/testOBJ.h
@@ -0,0 +1,6 @@
+extern int func2a(void);
+extern int func3a(void);
+extern int func4a(void);
+extern int func5a(void);
+extern int func6a(void);
+extern int func7a(void);
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/textfile.txt b/Tests/GhsMulti/GhsMultiSrcGroups/textfile.txt
new file mode 100644
index 000000000..48cdce852
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/textfile.txt
@@ -0,0 +1 @@
+placeholder
diff --git a/Tests/GhsMulti/GhsMultiSrcGroups/textfile2.txt b/Tests/GhsMulti/GhsMultiSrcGroups/textfile2.txt
new file mode 100644
index 000000000..48cdce852
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiSrcGroups/textfile2.txt
@@ -0,0 +1 @@
+placeholder
diff --git a/Tests/GhsMulti/GhsMultiUnsupportedTargets/CMakeLists.txt b/Tests/GhsMulti/GhsMultiUnsupportedTargets/CMakeLists.txt
new file mode 100644
index 000000000..f5f3c55fd
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiUnsupportedTargets/CMakeLists.txt
@@ -0,0 +1,10 @@
+# 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 3.12 FATAL_ERROR)
+
+project(test C)
+
+add_library(sharedLib SHARED file.c)
+
+add_library(moduleLib MODULE file.c)
diff --git a/Tests/GhsMulti/GhsMultiUnsupportedTargets/file.c b/Tests/GhsMulti/GhsMultiUnsupportedTargets/file.c
new file mode 100644
index 000000000..6a4a9a1f0
--- /dev/null
+++ b/Tests/GhsMulti/GhsMultiUnsupportedTargets/file.c
@@ -0,0 +1,4 @@
+int func7a(void)
+{
+ return 1;
+}
diff --git a/Tests/GoogleTest/Test/empty.cxx b/Tests/GoogleTest/Test/empty.cxx
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/GoogleTest/Test/empty.cxx
diff --git a/Tests/ImportedSameName/A/CMakeLists.txt b/Tests/ImportedSameName/A/CMakeLists.txt
new file mode 100644
index 000000000..0a31b40e2
--- /dev/null
+++ b/Tests/ImportedSameName/A/CMakeLists.txt
@@ -0,0 +1,8 @@
+add_library(a STATIC a.c)
+target_compile_definitions(a INTERFACE DEF_A)
+
+add_library(sameName INTERFACE IMPORTED)
+target_link_libraries(sameName INTERFACE a)
+
+add_library(ifaceA INTERFACE)
+target_link_libraries(ifaceA INTERFACE sameName)
diff --git a/Tests/ImportedSameName/A/a.c b/Tests/ImportedSameName/A/a.c
new file mode 100644
index 000000000..4ef36980e
--- /dev/null
+++ b/Tests/ImportedSameName/A/a.c
@@ -0,0 +1,3 @@
+void a(void)
+{
+}
diff --git a/Tests/ImportedSameName/B/CMakeLists.txt b/Tests/ImportedSameName/B/CMakeLists.txt
new file mode 100644
index 000000000..d93032626
--- /dev/null
+++ b/Tests/ImportedSameName/B/CMakeLists.txt
@@ -0,0 +1,8 @@
+add_library(b STATIC b.c)
+target_compile_definitions(b INTERFACE DEF_B)
+
+add_library(sameName INTERFACE IMPORTED)
+target_link_libraries(sameName INTERFACE b)
+
+add_library(ifaceB INTERFACE)
+target_link_libraries(ifaceB INTERFACE sameName)
diff --git a/Tests/ImportedSameName/B/b.c b/Tests/ImportedSameName/B/b.c
new file mode 100644
index 000000000..c7c7df458
--- /dev/null
+++ b/Tests/ImportedSameName/B/b.c
@@ -0,0 +1,3 @@
+void b(void)
+{
+}
diff --git a/Tests/ImportedSameName/CMakeLists.txt b/Tests/ImportedSameName/CMakeLists.txt
new file mode 100644
index 000000000..4292c123f
--- /dev/null
+++ b/Tests/ImportedSameName/CMakeLists.txt
@@ -0,0 +1,8 @@
+cmake_minimum_required(VERSION 3.12)
+project(ImportedSameName C)
+
+add_subdirectory(A)
+add_subdirectory(B)
+
+add_executable(ImportedSameName main.c)
+target_link_libraries(ImportedSameName PRIVATE ifaceA ifaceB)
diff --git a/Tests/ImportedSameName/main.c b/Tests/ImportedSameName/main.c
new file mode 100644
index 000000000..a0cb27fee
--- /dev/null
+++ b/Tests/ImportedSameName/main.c
@@ -0,0 +1,16 @@
+#ifndef DEF_A
+# error "DEF_A not defined"
+#endif
+#ifndef DEF_B
+# error "DEF_B not defined"
+#endif
+
+extern void a(void);
+extern void b(void);
+
+int main(void)
+{
+ a();
+ b();
+ return 0;
+}
diff --git a/Tests/IncludeDirectories/SystemIncludeDirectories/systemlib/ordertest.h b/Tests/IncludeDirectories/SystemIncludeDirectories/systemlib/ordertest.h
new file mode 100644
index 000000000..28915e6ba
--- /dev/null
+++ b/Tests/IncludeDirectories/SystemIncludeDirectories/systemlib/ordertest.h
@@ -0,0 +1 @@
+#error ordertest.h includes from systemlib
diff --git a/Tests/IncludeDirectories/SystemIncludeDirectories/userlib/ordertest.h b/Tests/IncludeDirectories/SystemIncludeDirectories/userlib/ordertest.h
new file mode 100644
index 000000000..fa882cb5b
--- /dev/null
+++ b/Tests/IncludeDirectories/SystemIncludeDirectories/userlib/ordertest.h
@@ -0,0 +1 @@
+/* empty file */
diff --git a/Tests/IncludeDirectories/ordertest.cpp b/Tests/IncludeDirectories/ordertest.cpp
new file mode 100644
index 000000000..7e24f770f
--- /dev/null
+++ b/Tests/IncludeDirectories/ordertest.cpp
@@ -0,0 +1 @@
+#include "ordertest.h"
diff --git a/Tests/IncludeDirectoriesCPATH/CMakeLists.txt b/Tests/IncludeDirectoriesCPATH/CMakeLists.txt
new file mode 100644
index 000000000..31cbc3680
--- /dev/null
+++ b/Tests/IncludeDirectoriesCPATH/CMakeLists.txt
@@ -0,0 +1,22 @@
+cmake_minimum_required (VERSION 3.14)
+project(IncludeDirectoriesCPATH CXX)
+message(STATUS "ENV{CPATH}: '$ENV{CPATH}'")
+message(STATUS "CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES: '${CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES}'")
+
+include(CheckCXXCompilerFlag)
+check_cxx_compiler_flag(-Wunused-variable run_sys_includes_test)
+if(run_sys_includes_test)
+ # The Bullseye wrapper appears to break the -isystem effect.
+ execute_process(COMMAND ${CMAKE_CXX_COMPILER} --version OUTPUT_VARIABLE out ERROR_VARIABLE out)
+ if("x${out}" MATCHES "Bullseye")
+ set(run_sys_includes_test 0)
+ endif()
+endif()
+if (NOT run_sys_includes_test)
+ return()
+endif()
+
+add_library(consumer consumer.cpp)
+add_library(consumer_system consumer.cpp)
+target_compile_options(consumer_system PRIVATE -Werror=unused-variable)
+target_include_directories(consumer_system SYSTEM PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/viacpath")
diff --git a/Tests/IncludeDirectoriesCPATH/consumer.cpp b/Tests/IncludeDirectoriesCPATH/consumer.cpp
new file mode 100644
index 000000000..59608dada
--- /dev/null
+++ b/Tests/IncludeDirectoriesCPATH/consumer.cpp
@@ -0,0 +1,6 @@
+#include "systemlib.h"
+
+int consumer()
+{
+ return systemlib();
+}
diff --git a/Tests/IncludeDirectoriesCPATH/viacpath/systemlib.h b/Tests/IncludeDirectoriesCPATH/viacpath/systemlib.h
new file mode 100644
index 000000000..1aaafa9f4
--- /dev/null
+++ b/Tests/IncludeDirectoriesCPATH/viacpath/systemlib.h
@@ -0,0 +1,15 @@
+#ifndef SYSTEMLIB_H
+#define SYSTEMLIB_H
+
+int systemlib()
+{
+ return 0;
+}
+
+int unusedFunc()
+{
+ int unused;
+ return systemlib();
+}
+
+#endif
diff --git a/Tests/InterfaceLibrary/excluded/CMakeLists.txt b/Tests/InterfaceLibrary/excluded/CMakeLists.txt
new file mode 100644
index 000000000..69a6807c9
--- /dev/null
+++ b/Tests/InterfaceLibrary/excluded/CMakeLists.txt
@@ -0,0 +1 @@
+add_library(excluded_iface INTERFACE)
diff --git a/Tests/JavaNativeHeaders/CMakeLists.txt b/Tests/JavaNativeHeaders/CMakeLists.txt
new file mode 100644
index 000000000..7dc267942
--- /dev/null
+++ b/Tests/JavaNativeHeaders/CMakeLists.txt
@@ -0,0 +1,18 @@
+project(helloJavaNativeHeaders Java CXX)
+
+cmake_minimum_required (VERSION 2.6)
+set(CMAKE_VERBOSE_MAKEFILE 1)
+
+find_package(Java COMPONENTS Development)
+include (UseJava)
+
+# JNI support
+find_package(JNI)
+
+add_jar(B1 D.java GENERATE_NATIVE_HEADERS D1-native)
+add_jar(E1 E.java GENERATE_NATIVE_HEADERS E1-native)
+
+add_jar(hello4 HelloWorld3.java)
+
+add_library(D SHARED D.cpp E.cpp)
+target_link_libraries (D PRIVATE D1-native E1-native)
diff --git a/Tests/JavaNativeHeaders/D.cpp b/Tests/JavaNativeHeaders/D.cpp
new file mode 100644
index 000000000..2a90a080c
--- /dev/null
+++ b/Tests/JavaNativeHeaders/D.cpp
@@ -0,0 +1,10 @@
+
+#include <jni.h>
+#include <stdio.h>
+
+#include "D.h"
+
+JNIEXPORT void JNICALL Java_D_printName(JNIEnv*, jobject)
+{
+ printf("D\n");
+}
diff --git a/Tests/JavaNativeHeaders/D.java b/Tests/JavaNativeHeaders/D.java
new file mode 100644
index 000000000..449c0df2d
--- /dev/null
+++ b/Tests/JavaNativeHeaders/D.java
@@ -0,0 +1,19 @@
+class D
+{
+ public D()
+ {
+ }
+
+ public native void printName();
+
+ static {
+ try {
+
+ System.loadLibrary("D");
+
+ } catch (UnsatisfiedLinkError e) {
+ System.err.println("Native code library failed to load.\n" + e);
+ System.exit(1);
+ }
+ }
+}
diff --git a/Tests/JavaNativeHeaders/E.cpp b/Tests/JavaNativeHeaders/E.cpp
new file mode 100644
index 000000000..fb98946db
--- /dev/null
+++ b/Tests/JavaNativeHeaders/E.cpp
@@ -0,0 +1,10 @@
+
+#include <jni.h>
+#include <stdio.h>
+
+#include "E.h"
+
+JNIEXPORT void JNICALL Java_E_printName(JNIEnv*, jobject)
+{
+ printf("E\n");
+}
diff --git a/Tests/JavaNativeHeaders/E.java b/Tests/JavaNativeHeaders/E.java
new file mode 100644
index 000000000..30fd95aef
--- /dev/null
+++ b/Tests/JavaNativeHeaders/E.java
@@ -0,0 +1,19 @@
+class E
+{
+ public E()
+ {
+ }
+
+ public native void printName();
+
+ static {
+ try {
+
+ System.loadLibrary("D");
+
+ } catch (UnsatisfiedLinkError e) {
+ System.err.println("Native code library failed to load.\n" + e);
+ System.exit(1);
+ }
+ }
+}
diff --git a/Tests/JavaNativeHeaders/HelloWorld3.java b/Tests/JavaNativeHeaders/HelloWorld3.java
new file mode 100644
index 000000000..77f1fedd9
--- /dev/null
+++ b/Tests/JavaNativeHeaders/HelloWorld3.java
@@ -0,0 +1,15 @@
+class HelloWorld3
+{
+ public static void main(String args[])
+ {
+ D d;
+ d = new D();
+ d.printName();
+
+ E e;
+ e = new E();
+ e.printName();
+
+ System.out.println("Hello World!");
+ }
+}
diff --git a/Tests/MSVCRuntimeLibrary/CMakeLists.txt b/Tests/MSVCRuntimeLibrary/CMakeLists.txt
new file mode 100644
index 000000000..f7d9fec2e
--- /dev/null
+++ b/Tests/MSVCRuntimeLibrary/CMakeLists.txt
@@ -0,0 +1,71 @@
+cmake_minimum_required(VERSION 3.14)
+cmake_policy(SET CMP0091 NEW)
+project(MSVCRuntimeLibrary)
+
+if(CMake_TEST_CUDA)
+ enable_language(CUDA)
+endif()
+
+function(verify_combinations threads lang src)
+ set(verify_tc_config_ Release)
+ set(verify_tc_config_Debug Debug)
+ set(verify_def_MultiThreaded -DVERIFY_MT)
+ set(verify_def_Debug -DVERIFY_DEBUG)
+ set(verify_def_DLL -DVERIFY_DLL)
+ foreach(dbg "" Debug)
+ foreach(dll "" DLL)
+ # Construct the name of this runtime library combination.
+ set(rtl "${threads}${dbg}${dll}")
+
+ # Test that try_compile builds with this RTL.
+ set(CMAKE_MSVC_RUNTIME_LIBRARY "${rtl}")
+ set(CMAKE_TRY_COMPILE_CONFIGURATION "${verify_tc_config_${dbg}}")
+ set(CMAKE_TRY_COMPILE_TARGET_TYPE "STATIC_LIBRARY")
+ try_compile(${rtl}_COMPILES
+ ${CMAKE_CURRENT_BINARY_DIR}/try_compile/${rtl}
+ ${CMAKE_CURRENT_SOURCE_DIR}/${src}
+ COMPILE_DEFINITIONS ${verify_def_${threads}} ${verify_def_${dbg}} ${verify_def_${dll}}
+ OUTPUT_VARIABLE ${rtl}_OUTPUT
+ )
+ if(${rtl}_COMPILES)
+ message(STATUS "try_compile with ${rtl} worked")
+ else()
+ string(REPLACE "\n" "\n " ${rtl}_OUTPUT " ${${rtl}_OUTPUT}")
+ message(SEND_ERROR "try_compile with ${rtl} failed:\n${${rtl}_OUTPUT}")
+ endif()
+
+ # Test that targets build with this RTL.
+ set(CMAKE_MSVC_RUNTIME_LIBRARY "$<$<BOOL:$<TARGET_PROPERTY:BOOL_TRUE>>:${rtl}>$<$<BOOL:$<TARGET_PROPERTY:BOOL_FALSE>>:BadContent>")
+ add_library(${rtl}-${lang} ${src})
+ set_property(TARGET ${rtl}-${lang} PROPERTY BOOL_TRUE TRUE)
+ target_compile_definitions(${rtl}-${lang} PRIVATE ${verify_def_${threads}} ${verify_def_${dbg}} ${verify_def_${dll}})
+ endforeach()
+ endforeach()
+endfunction()
+
+function(verify lang src)
+ add_library(default-${lang} ${src})
+ target_compile_definitions(default-${lang} PRIVATE VERIFY_MT VERIFY_DLL "$<$<CONFIG:Debug>:VERIFY_DEBUG>")
+
+ verify_combinations(MultiThreaded ${lang} ${src})
+
+ # Test known MSVC default behavior when no flag is given.
+ if(CMAKE_${lang}_COMPILER_ID STREQUAL "MSVC")
+ set(CMAKE_MSVC_RUNTIME_LIBRARY "")
+ add_library(empty-${lang} ${src})
+ if(CMAKE_${lang}_COMPILER_VERSION VERSION_GREATER_EQUAL 14)
+ # VS 2005 and above default to multi-threaded.
+ target_compile_definitions(empty-${lang} PRIVATE VERIFY_MT)
+ endif()
+ if(CMAKE_GENERATOR MATCHES "Visual Studio ([^9]|9[0-9])")
+ # VS 2010 and above have a different default runtime library for projects than 'cl'.
+ target_compile_definitions(empty-${lang} PRIVATE VERIFY_DLL)
+ endif()
+ endif()
+endfunction()
+
+verify(C verify.c)
+verify(CXX verify.cxx)
+if(CMake_TEST_CUDA)
+ verify(CUDA verify.cu)
+endif()
diff --git a/Tests/MSVCRuntimeLibrary/Fortran/CMakeLists.txt b/Tests/MSVCRuntimeLibrary/Fortran/CMakeLists.txt
new file mode 100644
index 000000000..27838a40a
--- /dev/null
+++ b/Tests/MSVCRuntimeLibrary/Fortran/CMakeLists.txt
@@ -0,0 +1,58 @@
+cmake_minimum_required(VERSION 3.14)
+cmake_policy(SET CMP0091 NEW)
+project(MSVCRuntimeLibraryFortran Fortran)
+
+foreach(t MultiThreaded SingleThreaded)
+ foreach(dbg "" Debug)
+ foreach(dll "" DLL)
+ set(var "CMAKE_Fortran_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_${t}${dbg}${dll}")
+ if(CMAKE_Fortran_COMPILER_ID STREQUAL "Intel")
+ # ifort does not actually define these, so inject them
+ string(REPLACE "-threads" "-threads;-D_MT" "${var}" "${${var}}")
+ string(REPLACE "-dbglibs" "-dbglibs;-D_DEBUG" "${var}" "${${var}}")
+ elseif(CMAKE_Fortran_COMPILER_ID STREQUAL "Flang")
+ # flang does not actually define these, so inject them
+ string(REPLACE ";--dependent-lib=libcmt;" ";--dependent-lib=libcmt;-D_MT;" "${var}" ";${${var}};")
+ string(REPLACE ";--dependent-lib=msvcrt;" ";--dependent-lib=msvcrt;-D_MT;-D_DLL;" "${var}" ";${${var}};")
+ string(REPLACE ";--dependent-lib=libcmtd;" ";--dependent-lib=libcmtd;-D_MT;-D_DEBUG;" "${var}" ";${${var}};")
+ string(REPLACE ";--dependent-lib=msvcrtd;" ";--dependent-lib=msvcrtd;-D_MT;-D_DEBUG;-D_DLL;" "${var}" ";${${var}};")
+ endif()
+ endforeach()
+ endforeach()
+endforeach()
+string(APPEND CMAKE_Fortran_FLAGS " -w")
+
+function(verify_combinations threads lang src)
+ set(verify_tc_config_ Release)
+ set(verify_tc_config_Debug Debug)
+ set(verify_def_MultiThreaded -DVERIFY_MT)
+ set(verify_def_Debug -DVERIFY_DEBUG)
+ set(verify_def_DLL -DVERIFY_DLL)
+ foreach(dbg "" Debug)
+ foreach(dll "" DLL)
+ # Construct the name of this runtime library combination.
+ set(rtl "${threads}${dbg}${dll}")
+
+ # Test that targets build with this RTL.
+ set(CMAKE_MSVC_RUNTIME_LIBRARY "$<$<BOOL:$<TARGET_PROPERTY:BOOL_TRUE>>:${rtl}>$<$<BOOL:$<TARGET_PROPERTY:BOOL_FALSE>>:BadContent>")
+ add_library(${rtl}-${lang} ${src})
+ set_property(TARGET ${rtl}-${lang} PROPERTY BOOL_TRUE TRUE)
+ target_compile_definitions(${rtl}-${lang} PRIVATE ${verify_def_${threads}} ${verify_def_${dbg}} ${verify_def_${dll}})
+ endforeach()
+ endforeach()
+endfunction()
+
+include_directories(${CMAKE_CURRENT_SOURCE_DIR})
+
+function(verify lang src)
+ add_library(default-${lang} ${src})
+ target_compile_definitions(default-${lang} PRIVATE VERIFY_MT VERIFY_DLL "$<$<CONFIG:Debug>:VERIFY_DEBUG>")
+ verify_combinations(MultiThreaded ${lang} ${src})
+endfunction()
+
+verify(Fortran verify.F90)
+# Intel Fortran for Windows supports single-threaded RTL but it is
+# not implemented by the Visual Studio integration.
+if(CMAKE_Fortran_COMPILER_ID STREQUAL "Intel" AND NOT CMAKE_GENERATOR MATCHES "Visual Studio")
+ verify_combinations(SingleThreaded Fortran verify.F90)
+endif()
diff --git a/Tests/MSVCRuntimeLibrary/Fortran/verify.F90 b/Tests/MSVCRuntimeLibrary/Fortran/verify.F90
new file mode 100644
index 000000000..6fe5e0553
--- /dev/null
+++ b/Tests/MSVCRuntimeLibrary/Fortran/verify.F90
@@ -0,0 +1 @@
+#include "../verify.h"
diff --git a/Tests/MSVCRuntimeLibrary/verify.c b/Tests/MSVCRuntimeLibrary/verify.c
new file mode 100644
index 000000000..741bca6b8
--- /dev/null
+++ b/Tests/MSVCRuntimeLibrary/verify.c
@@ -0,0 +1 @@
+#include "verify.h"
diff --git a/Tests/MSVCRuntimeLibrary/verify.cu b/Tests/MSVCRuntimeLibrary/verify.cu
new file mode 100644
index 000000000..741bca6b8
--- /dev/null
+++ b/Tests/MSVCRuntimeLibrary/verify.cu
@@ -0,0 +1 @@
+#include "verify.h"
diff --git a/Tests/MSVCRuntimeLibrary/verify.cxx b/Tests/MSVCRuntimeLibrary/verify.cxx
new file mode 100644
index 000000000..741bca6b8
--- /dev/null
+++ b/Tests/MSVCRuntimeLibrary/verify.cxx
@@ -0,0 +1 @@
+#include "verify.h"
diff --git a/Tests/MSVCRuntimeLibrary/verify.h b/Tests/MSVCRuntimeLibrary/verify.h
new file mode 100644
index 000000000..58d65fe32
--- /dev/null
+++ b/Tests/MSVCRuntimeLibrary/verify.h
@@ -0,0 +1,29 @@
+#ifdef VERIFY_DEBUG
+# ifndef _DEBUG
+# error "_DEBUG not defined by debug runtime library selection"
+# endif
+#else
+# ifdef _DEBUG
+# error "_DEBUG defined by non-debug runtime library selection"
+# endif
+#endif
+
+#ifdef VERIFY_DLL
+# ifndef _DLL
+# error "_DLL not defined by DLL runtime library selection"
+# endif
+#else
+# ifdef _DLL
+# error "_DLL defined by non-DLL runtime library selection"
+# endif
+#endif
+
+#ifdef VERIFY_MT
+# ifndef _MT
+# error "_MT not defined by multi-threaded runtime library selection"
+# endif
+#else
+# ifdef _MT
+# error "_MT defined by single-threaded runtime library selection"
+# endif
+#endif
diff --git a/Tests/MakeClean/ToClean/EmptySubDir/CMakeLists.txt b/Tests/MakeClean/ToClean/EmptySubDir/CMakeLists.txt
new file mode 100644
index 000000000..55893ae06
--- /dev/null
+++ b/Tests/MakeClean/ToClean/EmptySubDir/CMakeLists.txt
@@ -0,0 +1,17 @@
+cmake_minimum_required(VERSION 3.14)
+
+# Subdirectory CMakeLists.txt without targets
+set(CSD ${CMAKE_CURRENT_SOURCE_DIR})
+set(CBD ${CMAKE_CURRENT_BINARY_DIR})
+
+# Register a file path relative to the build directory
+set(DirPropFileRel "DirPropFileRel.txt")
+writeCleanFile("${CBD}/${DirPropFileRel}")
+set_directory_properties(PROPERTIES ADDITIONAL_CLEAN_FILES ${DirPropFileRel})
+addCleanFile("${CBD}/${DirPropFileRel}")
+
+# Register an absolute file path
+set(DirPropFileAbs "${CBD}/DirPropFileAbs.txt")
+writeCleanFile("${DirPropFileAbs}")
+set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_CLEAN_FILES ${DirPropFileAbs})
+addCleanFile("${DirPropFileAbs}")
diff --git a/Tests/Module/ExternalData/Data5/Data5.dat.md5 b/Tests/Module/ExternalData/Data5/Data5.dat.md5
new file mode 100644
index 000000000..70e39bd5d
--- /dev/null
+++ b/Tests/Module/ExternalData/Data5/Data5.dat.md5
@@ -0,0 +1 @@
+8c018830e3efa5caf3c7415028335a57
diff --git a/Tests/Module/FindDependency/packages/Pack7/Pack7Config.cmake b/Tests/Module/FindDependency/packages/Pack7/Pack7Config.cmake
new file mode 100644
index 000000000..9df13457f
--- /dev/null
+++ b/Tests/Module/FindDependency/packages/Pack7/Pack7Config.cmake
@@ -0,0 +1,14 @@
+if(NOT Pack7_FOUND)
+ set(Pack7_FOUND 1)
+ add_library(Pack7::Pack7 INTERFACE IMPORTED)
+ set_property(TARGET Pack7::Pack7 PROPERTY INTERFACE_COMPILE_DEFINITIONS HAVE_PACK7)
+endif()
+
+foreach(module ${Pack7_FIND_COMPONENTS})
+ if(module STREQUAL "Comp1")
+ add_library(Pack7::Comp1 INTERFACE IMPORTED)
+ set_property(TARGET Pack7::Comp1 PROPERTY INTERFACE_COMPILE_DEFINITIONS HAVE_PACK7_COMP1)
+ set_property(TARGET Pack7::Comp1 PROPERTY INTERFACE_LINK_LIBRARIES Pack7::Pack7)
+ set(Pack7_Comp1_FOUND 1)
+ endif()
+endforeach()
diff --git a/Tests/Module/FindDependency/packages/Pack8/Pack8Config.cmake b/Tests/Module/FindDependency/packages/Pack8/Pack8Config.cmake
new file mode 100644
index 000000000..d7ca054e7
--- /dev/null
+++ b/Tests/Module/FindDependency/packages/Pack8/Pack8Config.cmake
@@ -0,0 +1,7 @@
+include(CMakeFindDependencyMacro)
+
+find_dependency(Pack7 REQUIRED COMPONENTS Comp1)
+
+add_library(Pack8::Lib INTERFACE IMPORTED)
+set_property(TARGET Pack8::Lib PROPERTY INTERFACE_COMPILE_DEFINITIONS HAVE_PACK8)
+set_property(TARGET Pack8::Lib PROPERTY INTERFACE_LINK_LIBRARIES Pack7::Comp1)
diff --git a/Tests/Module/WriteCompilerDetectionHeader/main_bare.cpp b/Tests/Module/WriteCompilerDetectionHeader/main_bare.cpp
new file mode 100644
index 000000000..6954318a2
--- /dev/null
+++ b/Tests/Module/WriteCompilerDetectionHeader/main_bare.cpp
@@ -0,0 +1,23 @@
+#include "test_compiler_detection_bare_features.h"
+
+class base
+{
+public:
+ virtual ~base() {}
+ virtual void baz() = 0;
+};
+
+class foo final
+{
+public:
+ virtual ~foo() {}
+ char* bar;
+ void baz() noexcept override { bar = nullptr; }
+};
+
+int main()
+{
+ foo f;
+
+ return 0;
+}
diff --git a/Tests/OutName/CMakeLists.txt b/Tests/OutName/CMakeLists.txt
new file mode 100644
index 000000000..f024defc2
--- /dev/null
+++ b/Tests/OutName/CMakeLists.txt
@@ -0,0 +1,6 @@
+cmake_minimum_required(VERSION 3.12)
+project(OutName C)
+
+add_executable(OutName main.c)
+set_property(TARGET OutName PROPERTY PREFIX exe.)
+set_property(TARGET OutName PROPERTY SUFFIX .exe)
diff --git a/Tests/OutName/main.c b/Tests/OutName/main.c
new file mode 100644
index 000000000..8488f4e58
--- /dev/null
+++ b/Tests/OutName/main.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/Qt4Autogen/CMakeLists.txt b/Tests/Qt4Autogen/CMakeLists.txt
new file mode 100644
index 000000000..68b885bab
--- /dev/null
+++ b/Tests/Qt4Autogen/CMakeLists.txt
@@ -0,0 +1,9 @@
+# Set Qt test version and include the Autogen test macros
+set(QT_TEST_VERSION 4)
+include("../QtAutogen/TestMacros.cmake")
+
+# Qt4 only tests
+ADD_AUTOGEN_TEST(DefinesTest)
+
+# Common tests
+include("../QtAutogen/Tests.cmake")
diff --git a/Tests/Qt5Autogen/CMakeLists.txt b/Tests/Qt5Autogen/CMakeLists.txt
new file mode 100644
index 000000000..49d33cc8e
--- /dev/null
+++ b/Tests/Qt5Autogen/CMakeLists.txt
@@ -0,0 +1,6 @@
+# Set Qt test version and include the Autogen test macros
+set(QT_TEST_VERSION 5)
+include("../QtAutogen/TestMacros.cmake")
+
+# Common tests
+include("../QtAutogen/Tests.cmake")
diff --git a/Tests/QtAutogen/AutogenCoreTest.cmake b/Tests/QtAutogen/AutogenCoreTest.cmake
new file mode 100644
index 000000000..580385928
--- /dev/null
+++ b/Tests/QtAutogen/AutogenCoreTest.cmake
@@ -0,0 +1,55 @@
+
+# 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)
+ list(APPEND CMAKE_PREFIX_PATH ${Qt_PREFIX_DIR})
+endif()
+
+if (QT_TEST_VERSION EQUAL 4)
+
+ find_package(Qt4 REQUIRED QtCore)
+ include(UseQt4)
+
+ set(QT_QTCORE_TARGET Qt4::QtCore)
+
+ # Qt macros
+ macro(qtx_wrap_cpp)
+ qt4_wrap_cpp(${ARGN})
+ endmacro()
+ macro(qtx_generate_moc)
+ qt4_generate_moc(${ARGN})
+ endmacro()
+
+elseif(QT_TEST_VERSION EQUAL 5)
+
+ find_package(Qt5Core REQUIRED)
+
+ set(QT_QTCORE_TARGET Qt5::Core)
+ set(QT_LIBRARIES Qt5::Core)
+
+ # Include directories
+ include_directories(${Qt5Core_INCLUDE_DIRS})
+
+ # Definitions
+ if(Qt5_POSITION_INDEPENDENT_CODE AND CMAKE_CXX_COMPILE_OPTIONS_PIC)
+ add_definitions(${CMAKE_CXX_COMPILE_OPTIONS_PIC})
+ endif()
+
+ # Qt macros
+ macro(qtx_wrap_cpp)
+ qt5_wrap_cpp(${ARGN})
+ endmacro()
+ macro(qtx_generate_moc)
+ qt5_generate_moc(${ARGN})
+ endmacro()
+
+else()
+ message(SEND_ERROR "Invalid Qt version specified: ${QT_TEST_VERSION}")
+endif()
+
+# Get Qt compile features
+get_property(QT_COMPILE_FEATURES
+ TARGET ${QT_QTCORE_TARGET}
+ PROPERTY INTERFACE_COMPILE_FEATURES
+)
diff --git a/Tests/QtAutogen/AutogenGuiTest.cmake b/Tests/QtAutogen/AutogenGuiTest.cmake
new file mode 100644
index 000000000..b76d341a4
--- /dev/null
+++ b/Tests/QtAutogen/AutogenGuiTest.cmake
@@ -0,0 +1,55 @@
+
+# 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)
+ list(APPEND CMAKE_PREFIX_PATH ${Qt_PREFIX_DIR})
+endif()
+
+if (QT_TEST_VERSION EQUAL 4)
+
+ find_package(Qt4 REQUIRED)
+ include(UseQt4)
+
+ set(QT_QTCORE_TARGET Qt4::QtCore)
+
+ # Qt macros
+ macro(qtx_wrap_cpp)
+ qt4_wrap_cpp(${ARGN})
+ endmacro()
+ macro(qtx_generate_moc)
+ qt4_generate_moc(${ARGN})
+ endmacro()
+
+elseif(QT_TEST_VERSION EQUAL 5)
+
+ find_package(Qt5Widgets REQUIRED)
+
+ set(QT_QTCORE_TARGET Qt5::Core)
+ set(QT_LIBRARIES Qt5::Widgets)
+
+ # Include directories
+ include_directories(${Qt5Widgets_INCLUDE_DIRS})
+
+ # Definitions
+ if(Qt5_POSITION_INDEPENDENT_CODE AND CMAKE_CXX_COMPILE_OPTIONS_PIC)
+ add_definitions(${CMAKE_CXX_COMPILE_OPTIONS_PIC})
+ endif()
+
+ # Qt macros
+ macro(qtx_wrap_cpp)
+ qt5_wrap_cpp(${ARGN})
+ endmacro()
+ macro(qtx_generate_moc)
+ qt5_generate_moc(${ARGN})
+ endmacro()
+
+else()
+ message(SEND_ERROR "Invalid Qt version specified: ${QT_TEST_VERSION}")
+endif()
+
+# Get Qt compile features
+get_property(QT_COMPILE_FEATURES
+ TARGET ${QT_QTCORE_TARGET}
+ PROPERTY INTERFACE_COMPILE_FEATURES
+)
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/CMakeLists.txt b/Tests/QtAutogen/AutogenOriginDependsOff/CMakeLists.txt
new file mode 100644
index 000000000..9e6fe8b34
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/CMakeLists.txt
@@ -0,0 +1,71 @@
+cmake_minimum_required(VERSION 3.11)
+project(AutogenOriginDependsOff)
+include("../AutogenCoreTest.cmake")
+
+set(CSD ${CMAKE_CURRENT_SOURCE_DIR})
+set(CBD ${CMAKE_CURRENT_BINARY_DIR})
+include_directories(${CSD})
+include_directories(${CBD})
+
+# A GENERATED file ensures there will be an _autogen target in VS
+add_custom_command (
+ OUTPUT "${CBD}/config.hpp"
+ COMMAND ${CMAKE_COMMAND} -E copy "${CSD}/config.hpp.in" "${CBD}/config.hpp"
+ )
+
+
+# Library "a_mc" provides a header that holds a string with the content of
+# mocs_compilation.cpp from a_qt. It therefore must depend on a_qt_autogen.
+add_custom_target ( a_mc
+ COMMAND ${CMAKE_COMMAND} -E sleep 2
+ COMMAND ${CMAKE_COMMAND}
+ "-DMCF=${CBD}/a_qt_autogen/mocs_compilation.cpp"
+ "-DCF_IN=${CSD}/a_mc.hpp.in"
+ "-DCF_OUT=${CBD}/a_mc.hpp"
+ -P ${CSD}/configure_content.cmake
+ )
+add_dependencies ( a_mc a_qt_autogen )
+
+# Library "a_qt"
+# - depends on a GENERATED file
+# - AUTOMOC enabled
+# - depends on a target (a_mc) that depends on a_qt_qutogen
+add_library ( a_qt a_qt.cpp "${CBD}/config.hpp" )
+add_dependencies ( a_qt a_mc )
+target_link_libraries ( a_qt ${QT_QTCORE_TARGET})
+set_target_properties ( a_qt PROPERTIES AUTOMOC TRUE)
+# Disable AUTOGEN_ORIGIN_DEPENDS to avoid loop dependencies
+set_target_properties ( a_qt PROPERTIES AUTOGEN_ORIGIN_DEPENDS OFF)
+
+
+# Library "b_mc" provides a header that holds a string function that returns
+# the content of mocs_compilation.cpp from b_qt.
+# It therefore must depend on b_qt_autogen.
+add_custom_command (
+ OUTPUT ${CBD}/b_mc.cpp
+ DEPENDS b_qt_autogen
+ COMMAND ${CMAKE_COMMAND} -E sleep 2
+ COMMAND ${CMAKE_COMMAND}
+ "-DMCF=${CBD}/b_qt_autogen/mocs_compilation.cpp"
+ "-DCF_IN=${CSD}/b_mc.cpp.in"
+ "-DCF_OUT=${CBD}/b_mc.cpp"
+ -P ${CSD}/configure_content.cmake
+ )
+add_library ( b_mc ${CSD}/b_mc.hpp ${CBD}/b_mc.cpp )
+
+# Library "b_qt"
+# - depends on a GENERATED file
+# - AUTOMOC enabled
+# - depends on a library (b_mc) that depends on b_qt_qutogen
+add_library ( b_qt b_qt.cpp "${CBD}/config.hpp" )
+target_link_libraries ( b_qt b_mc )
+target_link_libraries ( b_qt ${QT_QTCORE_TARGET})
+set_target_properties ( b_qt PROPERTIES AUTOMOC TRUE)
+# Disable AUTOGEN_ORIGIN_DEPENDS to avoid loop dependencies
+set_target_properties ( b_qt PROPERTIES AUTOGEN_ORIGIN_DEPENDS OFF)
+
+
+# The main target depends on both libraries which depend on the _autogen
+# target of the main target.
+add_executable ( autogenOriginDependsOff main.cpp )
+target_link_libraries ( autogenOriginDependsOff a_qt b_qt )
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/a_mc.hpp.in b/Tests/QtAutogen/AutogenOriginDependsOff/a_mc.hpp.in
new file mode 100644
index 000000000..fe71f673d
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/a_mc.hpp.in
@@ -0,0 +1,9 @@
+#ifndef A_MC_HPP
+#define A_MC_HPP
+
+namespace a_mc {
+
+char const* mocs_compilation = "@MOCS_COMPILATION@";
+}
+
+#endif
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/a_qt.cpp b/Tests/QtAutogen/AutogenOriginDependsOff/a_qt.cpp
new file mode 100644
index 000000000..e498969e9
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/a_qt.cpp
@@ -0,0 +1,28 @@
+
+#include "a_qt.hpp"
+#include <a_mc.hpp>
+
+namespace a_qt {
+
+/// @brief A source local QObject based class
+class Source_QObject : public QObject
+{
+ Q_OBJECT
+public:
+ Source_QObject() {}
+ ~Source_QObject() {}
+
+ std::string str;
+};
+
+std::string mocs_compilation()
+{
+ // Create and destroy QObject based classes
+ Header_QObject header_obj;
+ Source_QObject source_obj;
+
+ return std::string(a_mc::mocs_compilation);
+}
+}
+
+#include "a_qt.moc"
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/a_qt.hpp b/Tests/QtAutogen/AutogenOriginDependsOff/a_qt.hpp
new file mode 100644
index 000000000..e2387ee11
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/a_qt.hpp
@@ -0,0 +1,25 @@
+#ifndef A_QT_HPP
+#define A_QT_HPP
+
+#include <QObject>
+#include <config.hpp>
+#include <string>
+
+namespace a_qt {
+
+/// @brief A header local QObject based class
+class Header_QObject : public QObject
+{
+ Q_OBJECT
+public:
+ Header_QObject() {}
+ ~Header_QObject() {}
+
+ std::string str;
+};
+
+/// @brief Function that returns the content of mocs_compilation.cpp
+extern std::string mocs_compilation();
+}
+
+#endif
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/b_mc.cpp.in b/Tests/QtAutogen/AutogenOriginDependsOff/b_mc.cpp.in
new file mode 100644
index 000000000..0f5ec308c
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/b_mc.cpp.in
@@ -0,0 +1,9 @@
+#include <b_mc.hpp>
+
+namespace b_mc {
+
+char const* mocs_compilation()
+{
+ return "@MOCS_COMPILATION@";
+}
+}
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/b_mc.hpp b/Tests/QtAutogen/AutogenOriginDependsOff/b_mc.hpp
new file mode 100644
index 000000000..043727359
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/b_mc.hpp
@@ -0,0 +1,9 @@
+#ifndef B_MC_HPP
+#define B_MC_HPP
+
+namespace b_mc {
+
+extern char const* mocs_compilation();
+}
+
+#endif
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/b_qt.cpp b/Tests/QtAutogen/AutogenOriginDependsOff/b_qt.cpp
new file mode 100644
index 000000000..f72f6ca9f
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/b_qt.cpp
@@ -0,0 +1,28 @@
+
+#include "b_qt.hpp"
+#include <b_mc.hpp>
+
+namespace b_qt {
+
+/// @brief A source local QObject based class
+class Source_QObject : public QObject
+{
+ Q_OBJECT
+public:
+ Source_QObject() {}
+ ~Source_QObject() {}
+
+ std::string str;
+};
+
+std::string mocs_compilation()
+{
+ // Create and destroy QObject based classes
+ Header_QObject header_obj;
+ Source_QObject source_obj;
+
+ return std::string(b_mc::mocs_compilation());
+}
+}
+
+#include "b_qt.moc"
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/b_qt.hpp b/Tests/QtAutogen/AutogenOriginDependsOff/b_qt.hpp
new file mode 100644
index 000000000..d7f0311a6
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/b_qt.hpp
@@ -0,0 +1,25 @@
+#ifndef B_QT_HPP
+#define B_QT_HPP
+
+#include <QObject>
+#include <config.hpp>
+#include <string>
+
+namespace b_qt {
+
+/// @brief A header local QObject based class
+class Header_QObject : public QObject
+{
+ Q_OBJECT
+public:
+ Header_QObject() {}
+ ~Header_QObject() {}
+
+ std::string str;
+};
+
+/// @brief Function that returns the content of mocs_compilation.cpp
+extern std::string mocs_compilation();
+}
+
+#endif
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/config.hpp.in b/Tests/QtAutogen/AutogenOriginDependsOff/config.hpp.in
new file mode 100644
index 000000000..e415d0855
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/config.hpp.in
@@ -0,0 +1,8 @@
+#ifndef CONFIG_HPP
+#define CONFIG_HPP
+
+// Application configuration
+
+enum dummy { NO_OP };
+
+#endif
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/configure_content.cmake b/Tests/QtAutogen/AutogenOriginDependsOff/configure_content.cmake
new file mode 100644
index 000000000..0fc6e638d
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/configure_content.cmake
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.10)
+
+# Read mocs_compilation.cpp file into variable
+file(READ "${MCF}" MOCS_COMPILATION)
+string(REPLACE "\\" "\\\\" MOCS_COMPILATION "${MOCS_COMPILATION}" )
+string(REPLACE "\"" "\\\"" MOCS_COMPILATION "${MOCS_COMPILATION}" )
+string(REPLACE "\n" "\"\n\"" MOCS_COMPILATION "${MOCS_COMPILATION}" )
+
+# Configure file
+configure_file ( "${CF_IN}" "${CF_OUT}" @ONLY )
diff --git a/Tests/QtAutogen/AutogenOriginDependsOff/main.cpp b/Tests/QtAutogen/AutogenOriginDependsOff/main.cpp
new file mode 100644
index 000000000..a3425f14c
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOff/main.cpp
@@ -0,0 +1,15 @@
+
+#include <a_qt.hpp>
+#include <b_qt.hpp>
+#include <string>
+
+int main()
+{
+ if (a_qt::mocs_compilation().empty()) {
+ return -1;
+ }
+ if (b_qt::mocs_compilation().empty()) {
+ return -1;
+ }
+ return 0;
+}
diff --git a/Tests/QtAutogen/AutogenOriginDependsOn/CMakeLists.txt b/Tests/QtAutogen/AutogenOriginDependsOn/CMakeLists.txt
new file mode 100644
index 000000000..5aabe0e68
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOn/CMakeLists.txt
@@ -0,0 +1,91 @@
+cmake_minimum_required(VERSION 3.10)
+project(AutogenOriginDependsOn)
+include("../AutogenCoreTest.cmake")
+
+include_directories(${CMAKE_CURRENT_BINARY_DIR})
+set(CSD ${CMAKE_CURRENT_SOURCE_DIR})
+set(CBD ${CMAKE_CURRENT_BINARY_DIR})
+
+# -- Test dependency on header generated by a custom command
+#
+# The ORIGIN_autogen target must depend on the same *GENERATED* source files as
+# the ORIGIN target. This is a requirement to ensure that all files for the
+# ORIGIN target are generated before the ORIGIN_autogen target is built.
+#
+# This tests the dependency of the mocDepGenFile_autogen target of
+# mocDepGenFile to the source file GenFile.hpp, which is *GENERATED*
+# by a custom command.
+# If mocDepGenFile_autogen gets built *before* or in *parallel* to the
+# custom command, the build will fail. That's because GenFile.hpp,
+# which is required by mocDepGenFile_autogen, is only valid after the
+# custom command has been completed.
+#
+# The sleep seconds artificially increase the build time of the custom command
+# to simulate a slow file generation process that takes longer to run than
+# the build of the mocDepGenFile_autogen target.
+add_custom_command(
+ OUTPUT ${CBD}/GenFile.hpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_invalid.hpp.in ${CBD}/GenFile.hpp
+ COMMAND ${CMAKE_COMMAND} -E sleep 3
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_valid.hpp.in ${CBD}/GenFile.hpp)
+
+add_executable(mocDepGenFile testGenFile.cpp ${CBD}/GenFile.hpp)
+target_link_libraries(mocDepGenFile ${QT_QTCORE_TARGET})
+set_target_properties(mocDepGenFile PROPERTIES AUTOMOC TRUE)
+
+
+# -- Test dependency on header generating custom target
+#
+# The ORIGIN_autogen target must depend on the same user defined targets
+# as the ORIGIN target. This is a requirement to ensure that all files for the
+# ORIGIN target are generated before the ORIGIN_autogen target is built.
+#
+# This tests the dependency of the mocDepTarget_autogen target of
+# mocDepTarget to the utility target mocDepTargetUtil.
+# If mocDepTarget_autogen gets built *before* or in *parallel* to
+# mocDepTargetUtil, the build will fail. That's
+# because GenTarget.hpp, which is required by mocDepTarget_autogen,
+# is only valid after the mocDepTargetUtil build has been completed.
+#
+# The sleep seconds artificially increase the build time of mocDepTargetUtil
+# to simulate a slow utility target build that takes longer to run than
+# the build of the mocDepTarget_autogen target.
+add_custom_target(mocDepTargetUtil
+ BYPRODUCTS ${CBD}/GenTarget.hpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_invalid.hpp.in ${CBD}/GenTarget.hpp
+ COMMAND ${CMAKE_COMMAND} -E sleep 3
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_valid.hpp.in ${CBD}/GenTarget.hpp)
+
+add_executable(mocDepTarget testGenTarget.cpp)
+target_link_libraries(mocDepTarget ${QT_QTCORE_TARGET})
+set_target_properties(mocDepTarget PROPERTIES AUTOMOC TRUE)
+add_dependencies(mocDepTarget mocDepTargetUtil)
+
+
+# -- Test 3: Depend on generated linked library
+# The ORIGIN_autogen target must depend on the same linked libraries
+# as the ORIGIN target. This is a requirement to ensure that all files for the
+# ORIGIN target are generated before the ORIGIN_autogen target is built.
+#
+# This tests the dependency of the mocDepGenLib_autogen target of mocDepGenLib
+# to the user generated library SimpleLib, which mocDepGenLib links to.
+# If mocDepGenLib_autogen gets built *before* or in *parallel* to SimpleLib,
+# the build will fail. That's because simpleLib.hpp, which is required by
+# mocDepGenLib_autogen, is only valid after the SimpleLib build has been
+# completed.
+#
+# The sleep seconds artificially increase the build time of SimpleLib
+# to simulate a slow utility library build that takes longer to run than
+# the build of the mocDepGenLib_autogen target.
+add_custom_command(
+ OUTPUT ${CBD}/simpleLib.hpp ${CBD}/simpleLib.cpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_invalid.hpp.in ${CBD}/simpleLib.hpp
+ COMMAND ${CMAKE_COMMAND} -E sleep 3
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/simpleLib.hpp.in ${CBD}/simpleLib.hpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/simpleLib.cpp.in ${CBD}/simpleLib.cpp)
+add_library(SimpleLib STATIC ${CBD}/simpleLib.hpp ${CBD}/simpleLib.cpp)
+target_link_libraries(SimpleLib ${QT_QTCORE_TARGET})
+
+add_executable(mocDepGenLib testGenLib.cpp)
+target_link_libraries(mocDepGenLib SimpleLib ${QT_QTCORE_TARGET})
+set_target_properties(mocDepGenLib PROPERTIES AUTOMOC TRUE)
diff --git a/Tests/QtAutogen/AutogenOriginDependsOn/object_invalid.hpp.in b/Tests/QtAutogen/AutogenOriginDependsOn/object_invalid.hpp.in
new file mode 100644
index 000000000..854d9a143
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOn/object_invalid.hpp.in
@@ -0,0 +1 @@
+#ifndef
diff --git a/Tests/QtAutogen/AutogenOriginDependsOn/object_valid.hpp.in b/Tests/QtAutogen/AutogenOriginDependsOn/object_valid.hpp.in
new file mode 100644
index 000000000..f364f7c97
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOn/object_valid.hpp.in
@@ -0,0 +1,14 @@
+#ifndef OBJECT_HPP
+#define OBJECT_HPP
+
+#include <QObject>
+
+class Object : public QObject
+{
+ Q_OBJECT
+public:
+ Q_SLOT
+ void aSlot(){};
+};
+
+#endif
diff --git a/Tests/QtAutogen/AutogenOriginDependsOn/simpleLib.cpp.in b/Tests/QtAutogen/AutogenOriginDependsOn/simpleLib.cpp.in
new file mode 100644
index 000000000..fa33bd375
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOn/simpleLib.cpp.in
@@ -0,0 +1,9 @@
+#include "simpleLib.hpp"
+
+SimpleLib::SimpleLib()
+{
+}
+
+SimpleLib::~SimpleLib()
+{
+}
diff --git a/Tests/QtAutogen/AutogenOriginDependsOn/simpleLib.hpp.in b/Tests/QtAutogen/AutogenOriginDependsOn/simpleLib.hpp.in
new file mode 100644
index 000000000..b65b0cb4a
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOn/simpleLib.hpp.in
@@ -0,0 +1,14 @@
+#ifndef SIMPLE_LIB_H
+#define SIMPLE_LIB_H
+
+#include <QObject>
+
+class SimpleLib : public QObject
+{
+ Q_OBJECT
+public:
+ SimpleLib();
+ ~SimpleLib();
+};
+
+#endif
diff --git a/Tests/QtAutogen/AutogenOriginDependsOn/testGenFile.cpp b/Tests/QtAutogen/AutogenOriginDependsOn/testGenFile.cpp
new file mode 100644
index 000000000..7df6e137c
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOn/testGenFile.cpp
@@ -0,0 +1,8 @@
+
+#include "GenFile.hpp"
+
+int main()
+{
+ Object obj;
+ return 0;
+}
diff --git a/Tests/QtAutogen/AutogenOriginDependsOn/testGenLib.cpp b/Tests/QtAutogen/AutogenOriginDependsOn/testGenLib.cpp
new file mode 100644
index 000000000..c14e15958
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOn/testGenLib.cpp
@@ -0,0 +1,12 @@
+
+#include "testGenLib.hpp"
+
+int main()
+{
+ SimpleLib libObject;
+ LObject lobject;
+ return 0;
+}
+
+// Depend on and AUTOMOC the SimpleLib header simpleLib.hpp
+#include "moc_simpleLib.cpp"
diff --git a/Tests/QtAutogen/AutogenOriginDependsOn/testGenLib.hpp b/Tests/QtAutogen/AutogenOriginDependsOn/testGenLib.hpp
new file mode 100644
index 000000000..408335bd2
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOn/testGenLib.hpp
@@ -0,0 +1,16 @@
+#ifndef TEST3_HPP
+#define TEST3_HPP
+
+#include "simpleLib.hpp"
+#include <QObject>
+
+// This object triggers the AUTOMOC on this file
+class LObject : public QObject
+{
+ Q_OBJECT
+public:
+ Q_SLOT
+ void aSlot(){};
+};
+
+#endif
diff --git a/Tests/QtAutogen/AutogenOriginDependsOn/testGenTarget.cpp b/Tests/QtAutogen/AutogenOriginDependsOn/testGenTarget.cpp
new file mode 100644
index 000000000..911076efd
--- /dev/null
+++ b/Tests/QtAutogen/AutogenOriginDependsOn/testGenTarget.cpp
@@ -0,0 +1,9 @@
+
+#include "GenTarget.hpp"
+#include "moc_GenTarget.cpp"
+
+int main()
+{
+ Object obj;
+ return 0;
+}
diff --git a/Tests/QtAutogen/AutogenTargetDepends/CMakeLists.txt b/Tests/QtAutogen/AutogenTargetDepends/CMakeLists.txt
new file mode 100644
index 000000000..492b5dbd3
--- /dev/null
+++ b/Tests/QtAutogen/AutogenTargetDepends/CMakeLists.txt
@@ -0,0 +1,54 @@
+cmake_minimum_required(VERSION 3.10)
+project(AutogenTargetDepends)
+include("../AutogenCoreTest.cmake")
+
+include_directories(${CMAKE_CURRENT_BINARY_DIR})
+set(CSD ${CMAKE_CURRENT_SOURCE_DIR})
+set(CBD ${CMAKE_CURRENT_BINARY_DIR})
+
+# -- Test AUTOGEN_TARGET_DEPENDS with GENERATED file dependency
+#
+# This tests the dependency of the mocDepATDFile_autogen target of
+# mocDepATDTarget to the utility target mocDepATDFileUtil.
+# If mocDepATDFile_autogen gets built *before* or in *parallel* to
+# mocDepATDFileUtil, the build will fail. That's
+# because ATDFile.hpp, which is required by mocDepATDFile_autogen,
+# is only valid after the mocDepATDFileUtil build has been completed.
+#
+# The sleep seconds artificially increase the build time of
+# mocDepATDFileUtil to simulate a slow utility target build that takes
+# longer to run than the build of the mocDepATDFile_autogen target.
+add_custom_command(
+ OUTPUT ${CBD}/ATDFile.hpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_invalid.hpp.in ${CBD}/ATDFile.hpp
+ COMMAND ${CMAKE_COMMAND} -E sleep 3
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_valid.hpp.in ${CBD}/ATDFile.hpp)
+
+add_executable(mocDepATDFile testATDFile.cpp)
+target_link_libraries(mocDepATDFile ${QT_QTCORE_TARGET})
+set_target_properties(mocDepATDFile PROPERTIES AUTOMOC TRUE)
+set_target_properties(mocDepATDFile PROPERTIES AUTOGEN_TARGET_DEPENDS ${CBD}/ATDFile.hpp)
+
+
+# -- Test AUTOGEN_TARGET_DEPENDS with target dependency
+#
+# This tests the dependency of the mocDepATDTarget_autogen target of
+# mocDepATDTarget to the utility target mocDepATDTargetUtil.
+# If mocDepATDTarget_autogen gets built *before* or in *parallel* to
+# mocDepATDTargetUtil, the build will fail. That's
+# because ATDTarget.hpp, which is required by mocDepATDTarget_autogen,
+# is only valid after the mocDepATDTargetUtil build has been completed.
+#
+# The sleep seconds artificially increase the build time of
+# mocDepATDTargetUtil to simulate a slow utility target build that takes
+# longer to run than the build of the mocDepATDTarget_autogen target.
+add_custom_target(mocDepATDTargetUtil
+ BYPRODUCTS ${CBD}/ATDTarget.hpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_invalid.hpp.in ${CBD}/ATDTarget.hpp
+ COMMAND ${CMAKE_COMMAND} -E sleep 3
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/object_valid.hpp.in ${CBD}/ATDTarget.hpp)
+
+add_executable(mocDepATDTarget testATDTarget.cpp)
+target_link_libraries(mocDepATDTarget ${QT_QTCORE_TARGET})
+set_target_properties(mocDepATDTarget PROPERTIES AUTOMOC TRUE)
+set_target_properties(mocDepATDTarget PROPERTIES AUTOGEN_TARGET_DEPENDS mocDepATDTargetUtil)
diff --git a/Tests/QtAutogen/AutogenTargetDepends/object_invalid.hpp.in b/Tests/QtAutogen/AutogenTargetDepends/object_invalid.hpp.in
new file mode 100644
index 000000000..854d9a143
--- /dev/null
+++ b/Tests/QtAutogen/AutogenTargetDepends/object_invalid.hpp.in
@@ -0,0 +1 @@
+#ifndef
diff --git a/Tests/QtAutogen/AutogenTargetDepends/object_valid.hpp.in b/Tests/QtAutogen/AutogenTargetDepends/object_valid.hpp.in
new file mode 100644
index 000000000..f364f7c97
--- /dev/null
+++ b/Tests/QtAutogen/AutogenTargetDepends/object_valid.hpp.in
@@ -0,0 +1,14 @@
+#ifndef OBJECT_HPP
+#define OBJECT_HPP
+
+#include <QObject>
+
+class Object : public QObject
+{
+ Q_OBJECT
+public:
+ Q_SLOT
+ void aSlot(){};
+};
+
+#endif
diff --git a/Tests/QtAutogen/AutogenTargetDepends/testATDFile.cpp b/Tests/QtAutogen/AutogenTargetDepends/testATDFile.cpp
new file mode 100644
index 000000000..6bddfcd39
--- /dev/null
+++ b/Tests/QtAutogen/AutogenTargetDepends/testATDFile.cpp
@@ -0,0 +1,9 @@
+
+#include "ATDFile.hpp"
+#include "moc_ATDFile.cpp"
+
+int main()
+{
+ Object obj;
+ return 0;
+}
diff --git a/Tests/QtAutogen/AutogenTargetDepends/testATDTarget.cpp b/Tests/QtAutogen/AutogenTargetDepends/testATDTarget.cpp
new file mode 100644
index 000000000..831fc2691
--- /dev/null
+++ b/Tests/QtAutogen/AutogenTargetDepends/testATDTarget.cpp
@@ -0,0 +1,9 @@
+
+#include "ATDTarget.hpp"
+#include "moc_ATDTarget.cpp"
+
+int main()
+{
+ Object obj;
+ return 0;
+}
diff --git a/Tests/QtAutogen/Complex/Adir/CMakeLists.txt b/Tests/QtAutogen/Complex/Adir/CMakeLists.txt
new file mode 100644
index 000000000..a1c36ffce
--- /dev/null
+++ b/Tests/QtAutogen/Complex/Adir/CMakeLists.txt
@@ -0,0 +1,8 @@
+
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+set(CMAKE_AUTOMOC ON)
+set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
+
+add_library(libA SHARED libA.cpp)
+target_link_libraries(libA LINK_PUBLIC ${QT_QTCORE_TARGET})
+generate_export_header(libA)
diff --git a/Tests/QtAutogen/Complex/Adir/libA.cpp b/Tests/QtAutogen/Complex/Adir/libA.cpp
new file mode 100644
index 000000000..f79f24af4
--- /dev/null
+++ b/Tests/QtAutogen/Complex/Adir/libA.cpp
@@ -0,0 +1,12 @@
+
+#include "libA.h"
+
+LibA::LibA(QObject* parent)
+ : QObject(parent)
+{
+}
+
+int LibA::foo()
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/Complex/Adir/libA.h b/Tests/QtAutogen/Complex/Adir/libA.h
new file mode 100644
index 000000000..c4eb9f7dc
--- /dev/null
+++ b/Tests/QtAutogen/Complex/Adir/libA.h
@@ -0,0 +1,18 @@
+
+#ifndef LIBA_H
+#define LIBA_H
+
+#include "liba_export.h"
+
+#include <QObject>
+
+class LIBA_EXPORT LibA : public QObject
+{
+ Q_OBJECT
+public:
+ explicit LibA(QObject* parent = 0);
+
+ int foo();
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/Bdir/CMakeLists.txt b/Tests/QtAutogen/Complex/Bdir/CMakeLists.txt
new file mode 100644
index 000000000..d33876308
--- /dev/null
+++ b/Tests/QtAutogen/Complex/Bdir/CMakeLists.txt
@@ -0,0 +1,9 @@
+
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+set(CMAKE_AUTOMOC ON)
+set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
+
+add_library(libB SHARED libB.cpp)
+generate_export_header(libB)
+
+target_link_libraries(libB LINK_PUBLIC libA)
diff --git a/Tests/QtAutogen/Complex/Bdir/libB.cpp b/Tests/QtAutogen/Complex/Bdir/libB.cpp
new file mode 100644
index 000000000..d3b675333
--- /dev/null
+++ b/Tests/QtAutogen/Complex/Bdir/libB.cpp
@@ -0,0 +1,12 @@
+
+#include "libB.h"
+
+LibB::LibB(QObject* parent)
+ : QObject(parent)
+{
+}
+
+int LibB::foo()
+{
+ return a.foo();
+}
diff --git a/Tests/QtAutogen/Complex/Bdir/libB.h b/Tests/QtAutogen/Complex/Bdir/libB.h
new file mode 100644
index 000000000..e4ab788c0
--- /dev/null
+++ b/Tests/QtAutogen/Complex/Bdir/libB.h
@@ -0,0 +1,22 @@
+
+#ifndef LIBB_H
+#define LIBB_H
+
+#include "libb_export.h"
+
+#include "libA.h"
+#include <QObject>
+
+class LIBB_EXPORT LibB : public QObject
+{
+ Q_OBJECT
+public:
+ explicit LibB(QObject* parent = 0);
+
+ int foo();
+
+private:
+ LibA a;
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/CMakeLists.txt b/Tests/QtAutogen/Complex/CMakeLists.txt
new file mode 100644
index 000000000..d9fdf5cf4
--- /dev/null
+++ b/Tests/QtAutogen/Complex/CMakeLists.txt
@@ -0,0 +1,85 @@
+cmake_minimum_required(VERSION 3.10)
+project(Complex)
+include("../AutogenGuiTest.cmake")
+
+# -- Test: AUTOMOC AUTORCC AUTOUIC
+add_definitions(-DFOO -DSomeDefine="Barx")
+
+# enable relaxed mode so automoc can handle all the special cases:
+set(CMAKE_AUTOMOC_RELAXED_MODE TRUE)
+set(CMAKE_AUTOUIC ON)
+set(CMAKE_AUTORCC ON)
+
+# create an executable and two library targets, each requiring automoc:
+add_library(codeeditorLib STATIC codeeditor.cpp)
+add_library(privateSlot OBJECT private_slot.cpp)
+# Pass Qt compiler features to targets that don't link against Qt
+target_compile_features(codeeditorLib PRIVATE ${QT_COMPILE_FEATURES})
+target_compile_features(privateSlot PRIVATE ${QT_COMPILE_FEATURES})
+
+configure_file(generated_resource.qrc.in generated_resource.qrc @ONLY)
+add_custom_command(
+ OUTPUT generated.txt
+ COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/generated.txt.in" "${CMAKE_CURRENT_BINARY_DIR}/generated.txt"
+ DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/generated.txt.in"
+)
+
+add_custom_target(generate_moc_input
+ DEPENDS generated.txt
+ COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/myinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}"
+ COMMAND ${CMAKE_COMMAND} -E rename "${CMAKE_CURRENT_BINARY_DIR}/myinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}/myinterface.h"
+)
+
+add_custom_command(
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h"
+ COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/myotherinterface.h.in" "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h"
+ DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/myotherinterface.h.in"
+)
+
+get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
+if(NOT _isMultiConfig AND NOT CMAKE_GENERATOR STREQUAL Ninja)
+ set(debug_srcs "$<$<CONFIG:Debug>:debug_class.cpp>" $<$<CONFIG:Debug>:debug_resource.qrc>)
+ set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS $<$<CONFIG:Debug>:TEST_DEBUG_CLASS>)
+endif()
+
+# The -no-protection option disables the generation of include guards. Verify
+# that setting the source file property has an effect by using this and
+# issue an error in the preprocessor in calwidget.cpp if the include guard
+# is defined.
+set_source_files_properties(calwidget.ui PROPERTIES AUTOUIC_OPTIONS "-no-protection")
+
+add_executable(QtAutogen main.cpp calwidget.cpp second_widget.cpp foo.cpp blub.cpp bar.cpp abc.cpp
+ multiplewidgets.cpp
+ xyz.cpp yaf.cpp gadget.cpp $<TARGET_OBJECTS:privateSlot>
+ test.qrc second_resource.qrc resourcetester.cpp generated.cpp ${debug_srcs}
+ ${CMAKE_CURRENT_BINARY_DIR}/generated_resource.qrc
+)
+set_property(TARGET QtAutogen APPEND PROPERTY AUTOGEN_TARGET_DEPENDS generate_moc_input "${CMAKE_CURRENT_BINARY_DIR}/myotherinterface.h")
+
+add_executable(targetObjectsTest targetObjectsTest.cpp $<TARGET_OBJECTS:privateSlot>)
+target_link_libraries(targetObjectsTest ${QT_LIBRARIES})
+
+set_target_properties(
+ QtAutogen codeeditorLib privateSlot targetObjectsTest
+ PROPERTIES
+ AUTOMOC TRUE
+)
+
+
+include(GenerateExportHeader)
+# The order is relevant here. B depends on A, and B headers depend on A
+# headers both subdirectories use CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE and we
+# test that CMAKE_AUTOMOC successfully reads the include directories
+# for the build interface from those targets. There has previously been
+# a bug where caching of the include directories happened before
+# extracting the includes to pass to moc.
+add_subdirectory(Bdir)
+add_subdirectory(Adir)
+add_library(libC SHARED libC.cpp)
+set_target_properties(libC PROPERTIES AUTOMOC TRUE)
+generate_export_header(libC)
+target_link_libraries(libC LINK_PUBLIC libB)
+target_include_directories(libC PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
+set_property(TARGET libC APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_BINARY_DIR} )
+
+target_link_libraries(QtAutogen codeeditorLib ${QT_LIBRARIES} libC)
diff --git a/Tests/QtAutogen/Complex/abc.cpp b/Tests/QtAutogen/Complex/abc.cpp
new file mode 100644
index 000000000..2929b92ee
--- /dev/null
+++ b/Tests/QtAutogen/Complex/abc.cpp
@@ -0,0 +1,39 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "abc.h"
+#include "abc_p.h"
+
+#include <stdio.h>
+
+class PrintAbc : public QObject
+{
+ Q_OBJECT
+public:
+ PrintAbc()
+ : QObject()
+ {
+ }
+public slots:
+ void print() const { printf("abc\n"); }
+};
+
+Abc::Abc()
+ : QObject()
+{
+}
+
+void Abc::doAbc()
+{
+ PrintAbc pa;
+ pa.print();
+ AbcP abcP;
+ abcP.doAbcP();
+}
+
+// check that including the moc file for the cpp file and the header works:
+#include "abc.moc"
+#include "moc_abc.cpp"
+#include "moc_abc_p.cpp"
+
+// check that including a moc file from another header works:
+#include "moc_xyz.cpp"
diff --git a/Tests/QtAutogen/Complex/abc.h b/Tests/QtAutogen/Complex/abc.h
new file mode 100644
index 000000000..ec5f4115a
--- /dev/null
+++ b/Tests/QtAutogen/Complex/abc.h
@@ -0,0 +1,17 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef ABC_H
+#define ABC_H
+
+#include <QObject>
+
+class Abc : public QObject
+{
+ Q_OBJECT
+public:
+ Abc();
+public slots:
+ void doAbc();
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/abc_p.h b/Tests/QtAutogen/Complex/abc_p.h
new file mode 100644
index 000000000..be984876c
--- /dev/null
+++ b/Tests/QtAutogen/Complex/abc_p.h
@@ -0,0 +1,19 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef ABC_P_H
+#define ABC_P_H
+
+#include <QObject>
+
+#include <stdio.h>
+
+class AbcP : public QObject
+{
+ Q_OBJECT
+public:
+ AbcP() {}
+public slots:
+ void doAbcP() { printf("I am private abc !\n"); }
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/bar.cpp b/Tests/QtAutogen/Complex/bar.cpp
new file mode 100644
index 000000000..734bd7a8e
--- /dev/null
+++ b/Tests/QtAutogen/Complex/bar.cpp
@@ -0,0 +1,17 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "sub/bar.h"
+
+#include <stdio.h>
+
+Bar::Bar()
+ : QObject()
+{
+}
+
+void Bar::doBar()
+{
+ printf("Hello bar !\n");
+}
+
+#include "sub/moc_bar.cpp"
diff --git a/Tests/QtAutogen/Complex/blub.cpp b/Tests/QtAutogen/Complex/blub.cpp
new file mode 100644
index 000000000..1c497e00f
--- /dev/null
+++ b/Tests/QtAutogen/Complex/blub.cpp
@@ -0,0 +1,31 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "blub.h"
+
+#include <stdio.h>
+
+class BlubBlub : public QObject
+{
+ Q_OBJECT
+public:
+ BlubBlub()
+ : QObject()
+ {
+ }
+public slots:
+ int getValue() const { return 13; }
+};
+
+Blub::Blub()
+{
+}
+
+void Blub::blubber()
+{
+ BlubBlub bb;
+ printf("Blub blub %d ! \n", bb.getValue());
+}
+
+// test the case that the wrong moc-file is included, it should
+// actually be "blub.moc"
+#include "moc_blub.cpp"
diff --git a/Tests/QtAutogen/Complex/blub.h b/Tests/QtAutogen/Complex/blub.h
new file mode 100644
index 000000000..ff798782b
--- /dev/null
+++ b/Tests/QtAutogen/Complex/blub.h
@@ -0,0 +1,15 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef BLUB_H
+#define BLUB_H
+
+#include <QObject>
+
+class Blub
+{
+public:
+ Blub();
+ void blubber();
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/calwidget.cpp b/Tests/QtAutogen/Complex/calwidget.cpp
new file mode 100644
index 000000000..8ce53f14a
--- /dev/null
+++ b/Tests/QtAutogen/Complex/calwidget.cpp
@@ -0,0 +1,436 @@
+/****************************************************************************
+ **
+ ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+ ** All rights reserved.
+ ** Contact: Nokia Corporation (qt-info@nokia.com)
+ **
+ ** This file is part of the examples of the Qt Toolkit.
+ **
+ ** $QT_BEGIN_LICENSE:BSD$
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** "Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ ** * Redistributions of source code must retain the above copyright
+ ** notice, this list of conditions and the following disclaimer.
+ ** * 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.
+ ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ ** OWNER 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."
+ ** $QT_END_LICENSE$
+ **
+ ****************************************************************************/
+
+#include <QCalendarWidget>
+#include <QCheckBox>
+#include <QComboBox>
+#include <QDateEdit>
+#include <QGridLayout>
+#include <QGroupBox>
+#include <QLabel>
+#include <QTextCharFormat>
+
+#include "calwidget.h"
+
+#include "ui_calwidget.h"
+#ifdef UI_CALWIDGET_H
+# error Definition of UI_CALWIDGET_H should be disabled by file option.
+#endif
+
+Window::Window()
+ : ui(new Ui::Window)
+{
+ createPreviewGroupBox();
+ createGeneralOptionsGroupBox();
+ createDatesGroupBox();
+ createTextFormatsGroupBox();
+
+ QGridLayout* layout = new QGridLayout;
+ layout->addWidget(previewGroupBox, 0, 0);
+ layout->addWidget(generalOptionsGroupBox, 0, 1);
+ layout->addWidget(datesGroupBox, 1, 0);
+ layout->addWidget(textFormatsGroupBox, 1, 1);
+ layout->setSizeConstraint(QLayout::SetFixedSize);
+ setLayout(layout);
+
+ previewLayout->setRowMinimumHeight(0, calendar->sizeHint().height());
+ previewLayout->setColumnMinimumWidth(0, calendar->sizeHint().width());
+
+ setWindowTitle(tr("Calendar Widget"));
+}
+
+void Window::localeChanged(int index)
+{
+ calendar->setLocale(localeCombo->itemData(index).toLocale());
+}
+
+void Window::firstDayChanged(int index)
+{
+ calendar->setFirstDayOfWeek(
+ Qt::DayOfWeek(firstDayCombo->itemData(index).toInt()));
+}
+
+void Window::selectionModeChanged(int index)
+{
+ calendar->setSelectionMode(QCalendarWidget::SelectionMode(
+ selectionModeCombo->itemData(index).toInt()));
+}
+
+void Window::horizontalHeaderChanged(int index)
+{
+ calendar->setHorizontalHeaderFormat(QCalendarWidget::HorizontalHeaderFormat(
+ horizontalHeaderCombo->itemData(index).toInt()));
+}
+
+void Window::verticalHeaderChanged(int index)
+{
+ calendar->setVerticalHeaderFormat(QCalendarWidget::VerticalHeaderFormat(
+ verticalHeaderCombo->itemData(index).toInt()));
+}
+
+void Window::selectedDateChanged()
+{
+ currentDateEdit->setDate(calendar->selectedDate());
+}
+
+void Window::minimumDateChanged(const QDate& date)
+{
+ calendar->setMinimumDate(date);
+ maximumDateEdit->setDate(calendar->maximumDate());
+}
+
+void Window::maximumDateChanged(const QDate& date)
+{
+ calendar->setMaximumDate(date);
+ minimumDateEdit->setDate(calendar->minimumDate());
+}
+
+void Window::weekdayFormatChanged()
+{
+ QTextCharFormat format;
+
+ format.setForeground(qvariant_cast<QColor>(
+ weekdayColorCombo->itemData(weekdayColorCombo->currentIndex())));
+ calendar->setWeekdayTextFormat(Qt::Monday, format);
+ calendar->setWeekdayTextFormat(Qt::Tuesday, format);
+ calendar->setWeekdayTextFormat(Qt::Wednesday, format);
+ calendar->setWeekdayTextFormat(Qt::Thursday, format);
+ calendar->setWeekdayTextFormat(Qt::Friday, format);
+}
+
+void Window::weekendFormatChanged()
+{
+ QTextCharFormat format;
+
+ format.setForeground(qvariant_cast<QColor>(
+ weekendColorCombo->itemData(weekendColorCombo->currentIndex())));
+ calendar->setWeekdayTextFormat(Qt::Saturday, format);
+ calendar->setWeekdayTextFormat(Qt::Sunday, format);
+}
+
+void Window::reformatHeaders()
+{
+ QString text = headerTextFormatCombo->currentText();
+ QTextCharFormat format;
+
+ if (text == tr("Bold")) {
+ format.setFontWeight(QFont::Bold);
+ } else if (text == tr("Italic")) {
+ format.setFontItalic(true);
+ } else if (text == tr("Green")) {
+ format.setForeground(Qt::green);
+ }
+ calendar->setHeaderTextFormat(format);
+}
+
+void Window::reformatCalendarPage()
+{
+ if (firstFridayCheckBox->isChecked()) {
+ QDate firstFriday(calendar->yearShown(), calendar->monthShown(), 1);
+ while (firstFriday.dayOfWeek() != Qt::Friday)
+ firstFriday = firstFriday.addDays(1);
+ QTextCharFormat firstFridayFormat;
+ firstFridayFormat.setForeground(Qt::blue);
+ calendar->setDateTextFormat(firstFriday, firstFridayFormat);
+ }
+
+ // May First in Red takes precedence
+ if (mayFirstCheckBox->isChecked()) {
+ const QDate mayFirst(calendar->yearShown(), 5, 1);
+ QTextCharFormat mayFirstFormat;
+ mayFirstFormat.setForeground(Qt::red);
+ calendar->setDateTextFormat(mayFirst, mayFirstFormat);
+ }
+}
+
+void Window::createPreviewGroupBox()
+{
+ previewGroupBox = new QGroupBox(tr("Preview"));
+
+ calendar = new QCalendarWidget;
+ calendar->setMinimumDate(QDate(1900, 1, 1));
+ calendar->setMaximumDate(QDate(3000, 1, 1));
+ calendar->setGridVisible(true);
+
+ connect(calendar, SIGNAL(currentPageChanged(int, int)), this,
+ SLOT(reformatCalendarPage()));
+
+ previewLayout = new QGridLayout;
+ previewLayout->addWidget(calendar, 0, 0, Qt::AlignCenter);
+ previewGroupBox->setLayout(previewLayout);
+}
+
+void Window::createGeneralOptionsGroupBox()
+{
+ generalOptionsGroupBox = new QGroupBox(tr("General Options"));
+
+ localeCombo = new QComboBox;
+ int curLocaleIndex = -1;
+ int index = 0;
+ for (int _lang = QLocale::C; _lang <= QLocale::LastLanguage; ++_lang) {
+ QLocale::Language lang = static_cast<QLocale::Language>(_lang);
+ QList<QLocale::Country> countries = QLocale::countriesForLanguage(lang);
+ for (int i = 0; i < countries.count(); ++i) {
+ QLocale::Country country = countries.at(i);
+ QString label = QLocale::languageToString(lang);
+ label += QLatin1Char('/');
+ label += QLocale::countryToString(country);
+ QLocale locale(lang, country);
+ if (this->locale().language() == lang &&
+ this->locale().country() == country)
+ curLocaleIndex = index;
+ localeCombo->addItem(label, locale);
+ ++index;
+ }
+ }
+ if (curLocaleIndex != -1)
+ localeCombo->setCurrentIndex(curLocaleIndex);
+ localeLabel = new QLabel(tr("&Locale"));
+ localeLabel->setBuddy(localeCombo);
+
+ firstDayCombo = new QComboBox;
+ firstDayCombo->addItem(tr("Sunday"), Qt::Sunday);
+ firstDayCombo->addItem(tr("Monday"), Qt::Monday);
+ firstDayCombo->addItem(tr("Tuesday"), Qt::Tuesday);
+ firstDayCombo->addItem(tr("Wednesday"), Qt::Wednesday);
+ firstDayCombo->addItem(tr("Thursday"), Qt::Thursday);
+ firstDayCombo->addItem(tr("Friday"), Qt::Friday);
+ firstDayCombo->addItem(tr("Saturday"), Qt::Saturday);
+
+ firstDayLabel = new QLabel(tr("Wee&k starts on:"));
+ firstDayLabel->setBuddy(firstDayCombo);
+
+ selectionModeCombo = new QComboBox;
+ selectionModeCombo->addItem(tr("Single selection"),
+ QCalendarWidget::SingleSelection);
+ selectionModeCombo->addItem(tr("None"), QCalendarWidget::NoSelection);
+
+ selectionModeLabel = new QLabel(tr("&Selection mode:"));
+ selectionModeLabel->setBuddy(selectionModeCombo);
+
+ gridCheckBox = new QCheckBox(tr("&Grid"));
+ gridCheckBox->setChecked(calendar->isGridVisible());
+
+ navigationCheckBox = new QCheckBox(tr("&Navigation bar"));
+ navigationCheckBox->setChecked(true);
+
+ horizontalHeaderCombo = new QComboBox;
+ horizontalHeaderCombo->addItem(tr("Single letter day names"),
+ QCalendarWidget::SingleLetterDayNames);
+ horizontalHeaderCombo->addItem(tr("Short day names"),
+ QCalendarWidget::ShortDayNames);
+ horizontalHeaderCombo->addItem(tr("None"),
+ QCalendarWidget::NoHorizontalHeader);
+ horizontalHeaderCombo->setCurrentIndex(1);
+
+ horizontalHeaderLabel = new QLabel(tr("&Horizontal header:"));
+ horizontalHeaderLabel->setBuddy(horizontalHeaderCombo);
+
+ verticalHeaderCombo = new QComboBox;
+ verticalHeaderCombo->addItem(tr("ISO week numbers"),
+ QCalendarWidget::ISOWeekNumbers);
+ verticalHeaderCombo->addItem(tr("None"), QCalendarWidget::NoVerticalHeader);
+
+ verticalHeaderLabel = new QLabel(tr("&Vertical header:"));
+ verticalHeaderLabel->setBuddy(verticalHeaderCombo);
+
+ connect(localeCombo, SIGNAL(currentIndexChanged(int)), this,
+ SLOT(localeChanged(int)));
+ connect(firstDayCombo, SIGNAL(currentIndexChanged(int)), this,
+ SLOT(firstDayChanged(int)));
+ connect(selectionModeCombo, SIGNAL(currentIndexChanged(int)), this,
+ SLOT(selectionModeChanged(int)));
+ connect(gridCheckBox, SIGNAL(toggled(bool)), calendar,
+ SLOT(setGridVisible(bool)));
+ connect(navigationCheckBox, SIGNAL(toggled(bool)), calendar,
+ SLOT(setNavigationBarVisible(bool)));
+ connect(horizontalHeaderCombo, SIGNAL(currentIndexChanged(int)), this,
+ SLOT(horizontalHeaderChanged(int)));
+ connect(verticalHeaderCombo, SIGNAL(currentIndexChanged(int)), this,
+ SLOT(verticalHeaderChanged(int)));
+
+ QHBoxLayout* checkBoxLayout = new QHBoxLayout;
+ checkBoxLayout->addWidget(gridCheckBox);
+ checkBoxLayout->addStretch();
+ checkBoxLayout->addWidget(navigationCheckBox);
+
+ QGridLayout* outerLayout = new QGridLayout;
+ outerLayout->addWidget(localeLabel, 0, 0);
+ outerLayout->addWidget(localeCombo, 0, 1);
+ outerLayout->addWidget(firstDayLabel, 1, 0);
+ outerLayout->addWidget(firstDayCombo, 1, 1);
+ outerLayout->addWidget(selectionModeLabel, 2, 0);
+ outerLayout->addWidget(selectionModeCombo, 2, 1);
+ outerLayout->addLayout(checkBoxLayout, 3, 0, 1, 2);
+ outerLayout->addWidget(horizontalHeaderLabel, 4, 0);
+ outerLayout->addWidget(horizontalHeaderCombo, 4, 1);
+ outerLayout->addWidget(verticalHeaderLabel, 5, 0);
+ outerLayout->addWidget(verticalHeaderCombo, 5, 1);
+ generalOptionsGroupBox->setLayout(outerLayout);
+
+ firstDayChanged(firstDayCombo->currentIndex());
+ selectionModeChanged(selectionModeCombo->currentIndex());
+ horizontalHeaderChanged(horizontalHeaderCombo->currentIndex());
+ verticalHeaderChanged(verticalHeaderCombo->currentIndex());
+}
+
+void Window::createDatesGroupBox()
+{
+ datesGroupBox = new QGroupBox(tr("Dates"));
+
+ minimumDateEdit = new QDateEdit;
+ minimumDateEdit->setDisplayFormat("MMM d yyyy");
+ minimumDateEdit->setDateRange(calendar->minimumDate(),
+ calendar->maximumDate());
+ minimumDateEdit->setDate(calendar->minimumDate());
+
+ minimumDateLabel = new QLabel(tr("&Minimum Date:"));
+ minimumDateLabel->setBuddy(minimumDateEdit);
+
+ currentDateEdit = new QDateEdit;
+ currentDateEdit->setDisplayFormat("MMM d yyyy");
+ currentDateEdit->setDate(calendar->selectedDate());
+ currentDateEdit->setDateRange(calendar->minimumDate(),
+ calendar->maximumDate());
+
+ currentDateLabel = new QLabel(tr("&Current Date:"));
+ currentDateLabel->setBuddy(currentDateEdit);
+
+ maximumDateEdit = new QDateEdit;
+ maximumDateEdit->setDisplayFormat("MMM d yyyy");
+ maximumDateEdit->setDateRange(calendar->minimumDate(),
+ calendar->maximumDate());
+ maximumDateEdit->setDate(calendar->maximumDate());
+
+ maximumDateLabel = new QLabel(tr("Ma&ximum Date:"));
+ maximumDateLabel->setBuddy(maximumDateEdit);
+
+ connect(currentDateEdit, SIGNAL(dateChanged(QDate)), calendar,
+ SLOT(setSelectedDate(QDate)));
+ connect(calendar, SIGNAL(selectionChanged()), this,
+ SLOT(selectedDateChanged()));
+ connect(minimumDateEdit, SIGNAL(dateChanged(QDate)), this,
+ SLOT(minimumDateChanged(QDate)));
+ connect(maximumDateEdit, SIGNAL(dateChanged(QDate)), this,
+ SLOT(maximumDateChanged(QDate)));
+
+ QGridLayout* dateBoxLayout = new QGridLayout;
+ dateBoxLayout->addWidget(currentDateLabel, 1, 0);
+ dateBoxLayout->addWidget(currentDateEdit, 1, 1);
+ dateBoxLayout->addWidget(minimumDateLabel, 0, 0);
+ dateBoxLayout->addWidget(minimumDateEdit, 0, 1);
+ dateBoxLayout->addWidget(maximumDateLabel, 2, 0);
+ dateBoxLayout->addWidget(maximumDateEdit, 2, 1);
+ dateBoxLayout->setRowStretch(3, 1);
+
+ datesGroupBox->setLayout(dateBoxLayout);
+}
+
+void Window::createTextFormatsGroupBox()
+{
+ textFormatsGroupBox = new QGroupBox(tr("Text Formats"));
+
+ weekdayColorCombo = createColorComboBox();
+ weekdayColorCombo->setCurrentIndex(weekdayColorCombo->findText(tr("Black")));
+
+ weekdayColorLabel = new QLabel(tr("&Weekday color:"));
+ weekdayColorLabel->setBuddy(weekdayColorCombo);
+
+ weekendColorCombo = createColorComboBox();
+ weekendColorCombo->setCurrentIndex(weekendColorCombo->findText(tr("Red")));
+
+ weekendColorLabel = new QLabel(tr("Week&end color:"));
+ weekendColorLabel->setBuddy(weekendColorCombo);
+
+ headerTextFormatCombo = new QComboBox;
+ headerTextFormatCombo->addItem(tr("Bold"));
+ headerTextFormatCombo->addItem(tr("Italic"));
+ headerTextFormatCombo->addItem(tr("Plain"));
+
+ headerTextFormatLabel = new QLabel(tr("&Header text:"));
+ headerTextFormatLabel->setBuddy(headerTextFormatCombo);
+
+ firstFridayCheckBox = new QCheckBox(tr("&First Friday in blue"));
+
+ mayFirstCheckBox = new QCheckBox(tr("May &1 in red"));
+
+ connect(weekdayColorCombo, SIGNAL(currentIndexChanged(int)), this,
+ SLOT(weekdayFormatChanged()));
+ connect(weekendColorCombo, SIGNAL(currentIndexChanged(int)), this,
+ SLOT(weekendFormatChanged()));
+ connect(headerTextFormatCombo, SIGNAL(currentIndexChanged(QString)), this,
+ SLOT(reformatHeaders()));
+ connect(firstFridayCheckBox, SIGNAL(toggled(bool)), this,
+ SLOT(reformatCalendarPage()));
+ connect(mayFirstCheckBox, SIGNAL(toggled(bool)), this,
+ SLOT(reformatCalendarPage()));
+
+ QHBoxLayout* checkBoxLayout = new QHBoxLayout;
+ checkBoxLayout->addWidget(firstFridayCheckBox);
+ checkBoxLayout->addStretch();
+ checkBoxLayout->addWidget(mayFirstCheckBox);
+
+ QGridLayout* outerLayout = new QGridLayout;
+ outerLayout->addWidget(weekdayColorLabel, 0, 0);
+ outerLayout->addWidget(weekdayColorCombo, 0, 1);
+ outerLayout->addWidget(weekendColorLabel, 1, 0);
+ outerLayout->addWidget(weekendColorCombo, 1, 1);
+ outerLayout->addWidget(headerTextFormatLabel, 2, 0);
+ outerLayout->addWidget(headerTextFormatCombo, 2, 1);
+ outerLayout->addLayout(checkBoxLayout, 3, 0, 1, 2);
+ textFormatsGroupBox->setLayout(outerLayout);
+
+ weekdayFormatChanged();
+ weekendFormatChanged();
+ reformatHeaders();
+ reformatCalendarPage();
+}
+
+QComboBox* Window::createColorComboBox()
+{
+ QComboBox* comboBox = new QComboBox;
+ comboBox->addItem(tr("Red"), QColor(Qt::red));
+ comboBox->addItem(tr("Blue"), QColor(Qt::blue));
+ comboBox->addItem(tr("Black"), QColor(Qt::black));
+ comboBox->addItem(tr("Magenta"), QColor(Qt::magenta));
+ return comboBox;
+}
+
+//#include "moc_calwidget.cpp"
diff --git a/Tests/QtAutogen/Complex/calwidget.h b/Tests/QtAutogen/Complex/calwidget.h
new file mode 100644
index 000000000..084d959bd
--- /dev/null
+++ b/Tests/QtAutogen/Complex/calwidget.h
@@ -0,0 +1,127 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the examples of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:BSD$
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+** * Redistributions of source code must retain the above copyright
+** notice, this list of conditions and the following disclaimer.
+** * 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.
+** * Neither the name of Nokia Corporation and its Subsidiary(-ies) 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+** OWNER 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."
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef WINDOW_H
+#define WINDOW_H
+
+#include <QWidget>
+
+class QCalendarWidget;
+class QCheckBox;
+class QComboBox;
+class QDate;
+class QDateEdit;
+class QGridLayout;
+class QGroupBox;
+class QLabel;
+
+namespace Ui {
+class Window;
+}
+
+class Window : public QWidget
+{
+ Q_OBJECT
+
+public:
+ Window();
+
+private slots:
+ void localeChanged(int index);
+ void firstDayChanged(int index);
+ void selectionModeChanged(int index);
+ void horizontalHeaderChanged(int index);
+ void verticalHeaderChanged(int index);
+ void selectedDateChanged();
+ void minimumDateChanged(const QDate& date);
+ void maximumDateChanged(const QDate& date);
+ void weekdayFormatChanged();
+ void weekendFormatChanged();
+ void reformatHeaders();
+ void reformatCalendarPage();
+
+private:
+ void createPreviewGroupBox();
+ void createGeneralOptionsGroupBox();
+ void createDatesGroupBox();
+ void createTextFormatsGroupBox();
+ QComboBox* createColorComboBox();
+
+ QGroupBox* previewGroupBox;
+ QGridLayout* previewLayout;
+ QCalendarWidget* calendar;
+
+ QGroupBox* generalOptionsGroupBox;
+ QLabel* localeLabel;
+ QLabel* firstDayLabel;
+ QLabel* selectionModeLabel;
+ QLabel* horizontalHeaderLabel;
+ QLabel* verticalHeaderLabel;
+ QComboBox* localeCombo;
+ QComboBox* firstDayCombo;
+ QComboBox* selectionModeCombo;
+ QCheckBox* gridCheckBox;
+ QCheckBox* navigationCheckBox;
+ QComboBox* horizontalHeaderCombo;
+ QComboBox* verticalHeaderCombo;
+
+ QGroupBox* datesGroupBox;
+ QLabel* currentDateLabel;
+ QLabel* minimumDateLabel;
+ QLabel* maximumDateLabel;
+ QDateEdit* currentDateEdit;
+ QDateEdit* minimumDateEdit;
+ QDateEdit* maximumDateEdit;
+
+ QGroupBox* textFormatsGroupBox;
+ QLabel* weekdayColorLabel;
+ QLabel* weekendColorLabel;
+ QLabel* headerTextFormatLabel;
+ QComboBox* weekdayColorCombo;
+ QComboBox* weekendColorCombo;
+ QComboBox* headerTextFormatCombo;
+
+ QCheckBox* firstFridayCheckBox;
+ QCheckBox* mayFirstCheckBox;
+
+ Ui::Window* ui;
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/calwidget.ui b/Tests/QtAutogen/Complex/calwidget.ui
new file mode 100644
index 000000000..1c245cac9
--- /dev/null
+++ b/Tests/QtAutogen/Complex/calwidget.ui
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Window</class>
+ <widget class="QWidget" name="Window">
+ <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>
+ <widget class="QPushButton" name="pushButton">
+ <property name="geometry">
+ <rect>
+ <x>90</x>
+ <y>180</y>
+ <width>94</width>
+ <height>24</height>
+ </rect>
+ </property>
+ <property name="text">
+ <string>PushButton</string>
+ </property>
+ </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/Complex/codeeditor.cpp b/Tests/QtAutogen/Complex/codeeditor.cpp
new file mode 100644
index 000000000..0caf8a7df
--- /dev/null
+++ b/Tests/QtAutogen/Complex/codeeditor.cpp
@@ -0,0 +1,146 @@
+/****************************************************************************
+ **
+ ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+ ** All rights reserved.
+ ** Contact: Nokia Corporation (qt-info@nokia.com)
+ **
+ ** This file is part of the examples of the Qt Toolkit.
+ **
+ ** $QT_BEGIN_LICENSE:BSD$
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** "Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ ** * Redistributions of source code must retain the above copyright
+ ** notice, this list of conditions and the following disclaimer.
+ ** * 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.
+ ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ ** OWNER 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."
+ ** $QT_END_LICENSE$
+ **
+ ****************************************************************************/
+
+#include <QtGui>
+
+#include "codeeditor.h"
+
+CodeEditor::CodeEditor(QWidget* parent)
+ : QPlainTextEdit(parent)
+{
+ lineNumberArea = new LineNumberArea(this);
+
+ connect(this, SIGNAL(blockCountChanged(int)), this,
+ SLOT(updateLineNumberAreaWidth(int)));
+ connect(this, SIGNAL(updateRequest(QRect, int)), this,
+ SLOT(updateLineNumberArea(QRect, int)));
+ connect(this, SIGNAL(cursorPositionChanged()), this,
+ SLOT(highlightCurrentLine()));
+
+ updateLineNumberAreaWidth(0);
+ highlightCurrentLine();
+}
+
+int CodeEditor::lineNumberAreaWidth()
+{
+ int digits = 1;
+ int max = qMax(1, blockCount());
+ while (max >= 10) {
+ max /= 10;
+ ++digits;
+ }
+
+ int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
+
+ return space;
+}
+
+void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
+{
+ setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
+}
+
+void CodeEditor::updateLineNumberArea(const QRect& rect, int dy)
+{
+ if (dy)
+ lineNumberArea->scroll(0, dy);
+ else
+ lineNumberArea->update(0, rect.y(), lineNumberArea->width(),
+ rect.height());
+
+ if (rect.contains(viewport()->rect()))
+ updateLineNumberAreaWidth(0);
+}
+
+void CodeEditor::resizeEvent(QResizeEvent* e)
+{
+ QPlainTextEdit::resizeEvent(e);
+
+ QRect cr = contentsRect();
+ lineNumberArea->setGeometry(
+ QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
+}
+
+void CodeEditor::highlightCurrentLine()
+{
+ QList<QTextEdit::ExtraSelection> extraSelections;
+
+ if (!isReadOnly()) {
+ QTextEdit::ExtraSelection selection;
+
+ QColor lineColor = QColor(Qt::yellow).lighter(160);
+
+ selection.format.setBackground(lineColor);
+ selection.format.setProperty(QTextFormat::FullWidthSelection, true);
+ selection.cursor = textCursor();
+ selection.cursor.clearSelection();
+ extraSelections.append(selection);
+ }
+
+ setExtraSelections(extraSelections);
+}
+
+void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent* event)
+{
+ QPainter painter(lineNumberArea);
+ painter.fillRect(event->rect(), Qt::lightGray);
+
+ QTextBlock block = firstVisibleBlock();
+ int blockNumber = block.blockNumber();
+ int top =
+ (int)blockBoundingGeometry(block).translated(contentOffset()).top();
+ int bottom = top + (int)blockBoundingRect(block).height();
+
+ while (block.isValid() && top <= event->rect().bottom()) {
+ if (block.isVisible() && bottom >= event->rect().top()) {
+ QString number = QString::number(blockNumber + 1);
+ painter.setPen(Qt::black);
+ painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
+ Qt::AlignRight, number);
+ }
+
+ block = block.next();
+ top = bottom;
+ bottom = top + (int)blockBoundingRect(block).height();
+ ++blockNumber;
+ }
+}
+
+#include "codeeditor.moc"
diff --git a/Tests/QtAutogen/Complex/codeeditor.h b/Tests/QtAutogen/Complex/codeeditor.h
new file mode 100644
index 000000000..b410bd4e6
--- /dev/null
+++ b/Tests/QtAutogen/Complex/codeeditor.h
@@ -0,0 +1,100 @@
+/****************************************************************************
+**
+** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the examples of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:BSD$
+** You may use this file under the terms of the BSD license as follows:
+**
+** "Redistribution and use in source and binary forms, with or without
+** modification, are permitted provided that the following conditions are
+** met:
+** * Redistributions of source code must retain the above copyright
+** notice, this list of conditions and the following disclaimer.
+** * 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.
+** * Neither the name of Nokia Corporation and its Subsidiary(-ies) 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+** OWNER 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."
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef CODEEDITOR_H
+#define CODEEDITOR_H
+
+#include <QObject>
+#include <QPlainTextEdit>
+
+class QPaintEvent;
+class QResizeEvent;
+class QSize;
+class QWidget;
+
+class LineNumberArea;
+
+class CodeEditor : public QPlainTextEdit
+{
+ Q_OBJECT
+
+public:
+ CodeEditor(QWidget* parent = 0);
+
+ void lineNumberAreaPaintEvent(QPaintEvent* event);
+ int lineNumberAreaWidth();
+
+protected:
+ void resizeEvent(QResizeEvent* event);
+
+private slots:
+ void updateLineNumberAreaWidth(int newBlockCount);
+ void highlightCurrentLine();
+ void updateLineNumberArea(const QRect&, int);
+
+private:
+ QWidget* lineNumberArea;
+};
+
+class LineNumberArea : public QWidget
+{
+public:
+ LineNumberArea(CodeEditor* editor)
+ : QWidget(editor)
+ {
+ codeEditor = editor;
+ }
+
+ QSize sizeHint() const
+ {
+ return QSize(codeEditor->lineNumberAreaWidth(), 0);
+ }
+
+protected:
+ void paintEvent(QPaintEvent* event)
+ {
+ codeEditor->lineNumberAreaPaintEvent(event);
+ }
+
+private:
+ CodeEditor* codeEditor;
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/debug_class.cpp b/Tests/QtAutogen/Complex/debug_class.cpp
new file mode 100644
index 000000000..46b09e705
--- /dev/null
+++ b/Tests/QtAutogen/Complex/debug_class.cpp
@@ -0,0 +1,10 @@
+
+#include "debug_class.h"
+#include "ui_debug_class.h"
+
+DebugClass::DebugClass(QWidget* parent)
+ : QWidget(parent)
+ , ui(new Ui::DebugClass)
+{
+ ui->setupUi(this);
+}
diff --git a/Tests/QtAutogen/Complex/debug_class.h b/Tests/QtAutogen/Complex/debug_class.h
new file mode 100644
index 000000000..c02f0ede6
--- /dev/null
+++ b/Tests/QtAutogen/Complex/debug_class.h
@@ -0,0 +1,19 @@
+
+#include <QWidget>
+
+namespace Ui {
+class DebugClass;
+}
+
+class DebugClass : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit DebugClass(QWidget* parent = 0);
+
+signals:
+ void someSignal();
+
+private:
+ Ui::DebugClass* ui;
+};
diff --git a/Tests/QtAutogen/Complex/debug_class.ui b/Tests/QtAutogen/Complex/debug_class.ui
new file mode 100644
index 000000000..dc2e1ac18
--- /dev/null
+++ b/Tests/QtAutogen/Complex/debug_class.ui
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>DebugClass</class>
+ <widget class="QWidget" name="DebugClass">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>300</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>DebugClass</string>
+ </property>
+ <widget class="QCheckBox" name="checkBox">
+ <property name="geometry">
+ <rect>
+ <x>50</x>
+ <y>20</y>
+ <width>82</width>
+ <height>21</height>
+ </rect>
+ </property>
+ <property name="text">
+ <string>CheckBox</string>
+ </property>
+ </widget>
+ <widget class="QPushButton" name="pushButton">
+ <property name="geometry">
+ <rect>
+ <x>40</x>
+ <y>70</y>
+ <width>94</width>
+ <height>24</height>
+ </rect>
+ </property>
+ <property name="text">
+ <string>PushButton</string>
+ </property>
+ </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/Complex/debug_resource.qrc b/Tests/QtAutogen/Complex/debug_resource.qrc
new file mode 100644
index 000000000..db98b9bc1
--- /dev/null
+++ b/Tests/QtAutogen/Complex/debug_resource.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>debug_class.ui</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/Complex/foo.cpp b/Tests/QtAutogen/Complex/foo.cpp
new file mode 100644
index 000000000..f665eee01
--- /dev/null
+++ b/Tests/QtAutogen/Complex/foo.cpp
@@ -0,0 +1,30 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "foo.h"
+
+#include <stdio.h>
+
+class FooFoo : public QObject
+{
+ Q_OBJECT
+public:
+ FooFoo()
+ : QObject()
+ {
+ }
+public slots:
+ int getValue() const { return 12; }
+};
+
+Foo::Foo()
+ : QObject()
+{
+}
+
+void Foo::doFoo()
+{
+ FooFoo ff;
+ printf("Hello automoc: %d\n", ff.getValue());
+}
+
+#include "foo.moc"
diff --git a/Tests/QtAutogen/Complex/foo.h b/Tests/QtAutogen/Complex/foo.h
new file mode 100644
index 000000000..3e03fe6bd
--- /dev/null
+++ b/Tests/QtAutogen/Complex/foo.h
@@ -0,0 +1,20 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef FOO_H
+#define FOO_H
+
+#include <QObject>
+
+class Foo
+#ifdef FOO
+ : public QObject
+#endif
+{
+ Q_OBJECT
+public:
+ Foo();
+public slots:
+ void doFoo();
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/gadget.cpp b/Tests/QtAutogen/Complex/gadget.cpp
new file mode 100644
index 000000000..23d95fa4a
--- /dev/null
+++ b/Tests/QtAutogen/Complex/gadget.cpp
@@ -0,0 +1,4 @@
+
+#include "gadget.h"
+
+#include "moc_gadget.cpp"
diff --git a/Tests/QtAutogen/Complex/gadget.h b/Tests/QtAutogen/Complex/gadget.h
new file mode 100644
index 000000000..3253e31d9
--- /dev/null
+++ b/Tests/QtAutogen/Complex/gadget.h
@@ -0,0 +1,19 @@
+
+#ifndef GADGET_H
+#define GADGET_H
+
+#include <QObject>
+
+class Gadget
+{
+ Q_GADGET
+ Q_ENUMS(Type)
+public:
+ enum Type
+ {
+ Type0,
+ Type1
+ };
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/generated.cpp b/Tests/QtAutogen/Complex/generated.cpp
new file mode 100644
index 000000000..d514c619c
--- /dev/null
+++ b/Tests/QtAutogen/Complex/generated.cpp
@@ -0,0 +1,9 @@
+
+#include "generated.h"
+
+Generated::Generated(QObject* parent)
+ : QObject(parent)
+{
+}
+
+#include "moc_generated.cpp"
diff --git a/Tests/QtAutogen/Complex/generated.h b/Tests/QtAutogen/Complex/generated.h
new file mode 100644
index 000000000..cac14dedb
--- /dev/null
+++ b/Tests/QtAutogen/Complex/generated.h
@@ -0,0 +1,21 @@
+
+#ifndef GENERATED_H
+#define GENERATED_H
+
+#include <QObject>
+
+#include "myinterface.h"
+#include "myotherinterface.h"
+
+class Generated
+ : public QObject
+ , MyInterface
+ , MyOtherInterface
+{
+ Q_OBJECT
+ Q_INTERFACES(MyInterface MyOtherInterface)
+public:
+ explicit Generated(QObject* parent = 0);
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/generated.txt.in b/Tests/QtAutogen/Complex/generated.txt.in
new file mode 100644
index 000000000..77507bb8e
--- /dev/null
+++ b/Tests/QtAutogen/Complex/generated.txt.in
@@ -0,0 +1 @@
+Some generated text file.
diff --git a/Tests/QtAutogen/Complex/generated_resource.qrc.in b/Tests/QtAutogen/Complex/generated_resource.qrc.in
new file mode 100644
index 000000000..da5fa6289
--- /dev/null
+++ b/Tests/QtAutogen/Complex/generated_resource.qrc.in
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>generated.txt</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/Complex/libC.cpp b/Tests/QtAutogen/Complex/libC.cpp
new file mode 100644
index 000000000..a3acff161
--- /dev/null
+++ b/Tests/QtAutogen/Complex/libC.cpp
@@ -0,0 +1,12 @@
+
+#include "libC.h"
+
+LibC::LibC(QObject* parent)
+ : QObject(parent)
+{
+}
+
+int LibC::foo()
+{
+ return b.foo();
+}
diff --git a/Tests/QtAutogen/Complex/libC.h b/Tests/QtAutogen/Complex/libC.h
new file mode 100644
index 000000000..3bc2bad54
--- /dev/null
+++ b/Tests/QtAutogen/Complex/libC.h
@@ -0,0 +1,22 @@
+
+#ifndef LIBC_H
+#define LIBC_H
+
+#include "libc_export.h"
+
+#include "libB.h"
+#include <QObject>
+
+class LIBC_EXPORT LibC : public QObject
+{
+ Q_OBJECT
+public:
+ explicit LibC(QObject* parent = 0);
+
+ int foo();
+
+private:
+ LibB b;
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/main.cpp b/Tests/QtAutogen/Complex/main.cpp
new file mode 100644
index 000000000..b5b6ed173
--- /dev/null
+++ b/Tests/QtAutogen/Complex/main.cpp
@@ -0,0 +1,93 @@
+/****************************************************************************
+ **
+ ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
+ ** All rights reserved.
+ ** Contact: Nokia Corporation (qt-info@nokia.com)
+ **
+ ** This file is part of the examples of the Qt Toolkit.
+ **
+ ** $QT_BEGIN_LICENSE:BSD$
+ ** You may use this file under the terms of the BSD license as follows:
+ **
+ ** "Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are
+ ** met:
+ ** * Redistributions of source code must retain the above copyright
+ ** notice, this list of conditions and the following disclaimer.
+ ** * 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.
+ ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ ** OWNER 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."
+ ** $QT_END_LICENSE$
+ **
+ ****************************************************************************/
+
+#include <QCoreApplication>
+#include <QTimer>
+
+#include "abc.h"
+#include "blub.h"
+#include "calwidget.h"
+#include "codeeditor.h"
+#include "foo.h"
+#include "libC.h"
+#include "resourcetester.h"
+#include "sub/bar.h"
+#include "xyz.h"
+#include "yaf.h"
+#ifdef TEST_DEBUG_CLASS
+# include "debug_class.h"
+# include <iostream>
+#endif
+
+int main(int argv, char** args)
+{
+ QCoreApplication app(argv, args);
+
+ Foo foo;
+ foo.doFoo();
+
+ Blub b;
+ b.blubber();
+
+ Bar bar;
+ bar.doBar();
+
+ Abc abc;
+ abc.doAbc();
+
+ Xyz xyz;
+ xyz.doXyz();
+
+ Yaf yaf;
+ yaf.doYaf();
+
+ LibC lc;
+ lc.foo();
+
+ ResourceTester rt;
+
+ QTimer::singleShot(0, &rt, SLOT(doTest()));
+
+#ifdef TEST_DEBUG_CLASS
+ std::cout << DebugClass::staticMetaObject.className() << std::endl;
+#endif
+
+ return app.exec();
+}
diff --git a/Tests/QtAutogen/Complex/multiplewidgets.cpp b/Tests/QtAutogen/Complex/multiplewidgets.cpp
new file mode 100644
index 000000000..fda36ea92
--- /dev/null
+++ b/Tests/QtAutogen/Complex/multiplewidgets.cpp
@@ -0,0 +1,19 @@
+
+#include "multiplewidgets.h"
+
+#include "ui_widget1.h"
+#include "ui_widget2.h"
+
+Widget1::Widget1(QWidget* parent)
+ : QWidget(parent)
+ , ui(new Ui::Widget1)
+{
+ ui->setupUi(this);
+}
+
+Widget2::Widget2(QWidget* parent)
+ : QWidget(parent)
+ , ui(new Ui::Widget2)
+{
+ ui->setupUi(this);
+}
diff --git a/Tests/QtAutogen/Complex/multiplewidgets.h b/Tests/QtAutogen/Complex/multiplewidgets.h
new file mode 100644
index 000000000..a4d0a5021
--- /dev/null
+++ b/Tests/QtAutogen/Complex/multiplewidgets.h
@@ -0,0 +1,35 @@
+
+#ifndef MULTIPLEWIDGETS_H
+#define MULTIPLEWIDGETS_H
+
+#include <QWidget>
+
+namespace Ui {
+class Widget1;
+}
+
+class Widget1 : public QWidget
+{
+ Q_OBJECT
+public:
+ Widget1(QWidget* parent = 0);
+
+private:
+ Ui::Widget1* ui;
+};
+
+namespace Ui {
+class Widget2;
+}
+
+class Widget2 : public QWidget
+{
+ Q_OBJECT
+public:
+ Widget2(QWidget* parent = 0);
+
+private:
+ Ui::Widget2* ui;
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/myinterface.h.in b/Tests/QtAutogen/Complex/myinterface.h.in
new file mode 100644
index 000000000..c6c0ba1b6
--- /dev/null
+++ b/Tests/QtAutogen/Complex/myinterface.h.in
@@ -0,0 +1,14 @@
+
+#ifndef MYINTERFACE_H
+#define MYINTERFACE_H
+
+#include <QObject>
+
+class MyInterface
+{
+
+};
+
+Q_DECLARE_INTERFACE(MyInterface, "org.cmake.example.MyInterface")
+
+#endif
diff --git a/Tests/QtAutogen/Complex/myotherinterface.h.in b/Tests/QtAutogen/Complex/myotherinterface.h.in
new file mode 100644
index 000000000..d21e7af7c
--- /dev/null
+++ b/Tests/QtAutogen/Complex/myotherinterface.h.in
@@ -0,0 +1,14 @@
+
+#ifndef MYOTHERINTERFACE_H
+#define MYOTHERINTERFACE_H
+
+#include <QObject>
+
+class MyOtherInterface
+{
+
+};
+
+Q_DECLARE_INTERFACE(MyOtherInterface, "org.cmake.example.MyOtherInterface")
+
+#endif
diff --git a/Tests/QtAutogen/Complex/private_slot.cpp b/Tests/QtAutogen/Complex/private_slot.cpp
new file mode 100644
index 000000000..ab1682a25
--- /dev/null
+++ b/Tests/QtAutogen/Complex/private_slot.cpp
@@ -0,0 +1,16 @@
+
+#include "private_slot.h"
+
+class PrivateSlotPrivate
+{
+public:
+ void privateSlot() {}
+};
+
+PrivateSlot::PrivateSlot(QObject* parent)
+ : QObject(parent)
+ , d(new PrivateSlotPrivate)
+{
+}
+
+#include "private_slot.moc"
diff --git a/Tests/QtAutogen/Complex/private_slot.h b/Tests/QtAutogen/Complex/private_slot.h
new file mode 100644
index 000000000..8041eb2ae
--- /dev/null
+++ b/Tests/QtAutogen/Complex/private_slot.h
@@ -0,0 +1,20 @@
+
+#ifndef PRIVATE_SLOT_H
+#define PRIVATE_SLOT_H
+
+#include <QObject>
+
+class PrivateSlotPrivate;
+
+class PrivateSlot : public QObject
+{
+ Q_OBJECT
+public:
+ PrivateSlot(QObject* parent = 0);
+
+private:
+ PrivateSlotPrivate* const d;
+ Q_PRIVATE_SLOT(d, void privateSlot())
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/resourcetester.cpp b/Tests/QtAutogen/Complex/resourcetester.cpp
new file mode 100644
index 000000000..4ecb6b482
--- /dev/null
+++ b/Tests/QtAutogen/Complex/resourcetester.cpp
@@ -0,0 +1,26 @@
+
+#include "resourcetester.h"
+
+#include <QApplication>
+#include <QDebug>
+#include <QFile>
+#include <QTimer>
+
+ResourceTester::ResourceTester(QObject* parent)
+ : QObject(parent)
+{
+}
+
+void ResourceTester::doTest()
+{
+ if (!QFile::exists(":/CMakeLists.txt"))
+ qApp->exit(EXIT_FAILURE);
+ if (!QFile::exists(":/main.cpp"))
+ qApp->exit(EXIT_FAILURE);
+#ifdef TEST_DEBUG_CLASS
+ if (!QFile::exists(":/debug_class.ui"))
+ qApp->exit(EXIT_FAILURE);
+#endif
+
+ QTimer::singleShot(0, qApp, SLOT(quit()));
+}
diff --git a/Tests/QtAutogen/Complex/resourcetester.h b/Tests/QtAutogen/Complex/resourcetester.h
new file mode 100644
index 000000000..dbdb3ad72
--- /dev/null
+++ b/Tests/QtAutogen/Complex/resourcetester.h
@@ -0,0 +1,17 @@
+
+#ifndef RESOURCE_TESTER_H
+#define RESOURCE_TESTER_H
+
+#include <QObject>
+
+class ResourceTester : public QObject
+{
+ Q_OBJECT
+public:
+ explicit ResourceTester(QObject* parent = 0);
+
+private slots:
+ void doTest();
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/second_resource.qrc b/Tests/QtAutogen/Complex/second_resource.qrc
new file mode 100644
index 000000000..27bfb143b
--- /dev/null
+++ b/Tests/QtAutogen/Complex/second_resource.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>main.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/Complex/second_widget.cpp b/Tests/QtAutogen/Complex/second_widget.cpp
new file mode 100644
index 000000000..c575f1013
--- /dev/null
+++ b/Tests/QtAutogen/Complex/second_widget.cpp
@@ -0,0 +1,15 @@
+
+#include "second_widget.h"
+#include "ui_second_widget.h"
+
+SecondWidget::SecondWidget(QWidget* parent)
+ : QWidget(parent)
+ , ui(new Ui::SecondWidget)
+{
+ ui->setupUi(this);
+}
+
+SecondWidget::~SecondWidget()
+{
+ delete ui;
+}
diff --git a/Tests/QtAutogen/Complex/second_widget.h b/Tests/QtAutogen/Complex/second_widget.h
new file mode 100644
index 000000000..c7929c4b1
--- /dev/null
+++ b/Tests/QtAutogen/Complex/second_widget.h
@@ -0,0 +1,18 @@
+
+#include <QWidget>
+
+namespace Ui {
+class SecondWidget;
+}
+
+class SecondWidget : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit SecondWidget(QWidget* parent = 0);
+
+ ~SecondWidget();
+
+private:
+ Ui::SecondWidget* ui;
+};
diff --git a/Tests/QtAutogen/Complex/second_widget.ui b/Tests/QtAutogen/Complex/second_widget.ui
new file mode 100644
index 000000000..4effa589c
--- /dev/null
+++ b/Tests/QtAutogen/Complex/second_widget.ui
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>SecondWidget</class>
+ <widget class="QWidget" name="SecondWidget">
+ <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>
+ <widget class="QPushButton" name="pushButton">
+ <property name="geometry">
+ <rect>
+ <x>80</x>
+ <y>20</y>
+ <width>94</width>
+ <height>24</height>
+ </rect>
+ </property>
+ <property name="text">
+ <string>PushButton</string>
+ </property>
+ </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/Complex/sub/bar.h b/Tests/QtAutogen/Complex/sub/bar.h
new file mode 100644
index 000000000..e4093f61c
--- /dev/null
+++ b/Tests/QtAutogen/Complex/sub/bar.h
@@ -0,0 +1,17 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef BAR_H
+#define BAR_H
+
+#include <QObject>
+
+class Bar : public QObject
+{
+ Q_OBJECT
+public:
+ Bar();
+public slots:
+ void doBar();
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/targetObjectsTest.cpp b/Tests/QtAutogen/Complex/targetObjectsTest.cpp
new file mode 100644
index 000000000..766b7751b
--- /dev/null
+++ b/Tests/QtAutogen/Complex/targetObjectsTest.cpp
@@ -0,0 +1,5 @@
+
+int main()
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/Complex/test.qrc b/Tests/QtAutogen/Complex/test.qrc
new file mode 100644
index 000000000..c3d4e3cdb
--- /dev/null
+++ b/Tests/QtAutogen/Complex/test.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>CMakeLists.txt</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/Complex/widget1.ui b/Tests/QtAutogen/Complex/widget1.ui
new file mode 100644
index 000000000..8fce81a9a
--- /dev/null
+++ b/Tests/QtAutogen/Complex/widget1.ui
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Widget1</class>
+ <widget class="QWidget" name="Widget1">
+ <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>
+ <widget class="QPushButton" name="pushButton">
+ <property name="geometry">
+ <rect>
+ <x>140</x>
+ <y>80</y>
+ <width>80</width>
+ <height>23</height>
+ </rect>
+ </property>
+ <property name="text">
+ <string>PushButton</string>
+ </property>
+ </widget>
+ <widget class="QPushButton" name="pushButton_2">
+ <property name="geometry">
+ <rect>
+ <x>190</x>
+ <y>170</y>
+ <width>80</width>
+ <height>23</height>
+ </rect>
+ </property>
+ <property name="text">
+ <string>PushButton</string>
+ </property>
+ </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/Complex/widget2.ui b/Tests/QtAutogen/Complex/widget2.ui
new file mode 100644
index 000000000..1f411b9fb
--- /dev/null
+++ b/Tests/QtAutogen/Complex/widget2.ui
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Widget2</class>
+ <widget class="QWidget" name="Widget1">
+ <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>
+ <widget class="QListWidget" name="listWidget">
+ <property name="geometry">
+ <rect>
+ <x>20</x>
+ <y>20</y>
+ <width>256</width>
+ <height>192</height>
+ </rect>
+ </property>
+ </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/Complex/xyz.cpp b/Tests/QtAutogen/Complex/xyz.cpp
new file mode 100644
index 000000000..e46c9d3ed
--- /dev/null
+++ b/Tests/QtAutogen/Complex/xyz.cpp
@@ -0,0 +1,15 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "xyz.h"
+
+#include <stdio.h>
+
+Xyz::Xyz()
+ : QObject()
+{
+}
+
+void Xyz::doXyz()
+{
+ printf("This is xyz !\n");
+}
diff --git a/Tests/QtAutogen/Complex/xyz.h b/Tests/QtAutogen/Complex/xyz.h
new file mode 100644
index 000000000..8b813fd3a
--- /dev/null
+++ b/Tests/QtAutogen/Complex/xyz.h
@@ -0,0 +1,17 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef XYZ_H
+#define XYZ_H
+
+#include <QObject>
+
+class Xyz : public QObject
+{
+ Q_OBJECT
+public:
+ Xyz();
+public slots:
+ void doXyz();
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/yaf.cpp b/Tests/QtAutogen/Complex/yaf.cpp
new file mode 100644
index 000000000..70e26aa95
--- /dev/null
+++ b/Tests/QtAutogen/Complex/yaf.cpp
@@ -0,0 +1,19 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "yaf.h"
+#include "yaf_p.h"
+
+#include <stdio.h>
+
+Yaf::Yaf()
+{
+}
+
+void Yaf::doYaf()
+{
+ YafP yafP;
+ yafP.doYafP();
+}
+
+// check that including a moc file from a private header the wrong way works:
+#include "yaf_p.moc"
diff --git a/Tests/QtAutogen/Complex/yaf.h b/Tests/QtAutogen/Complex/yaf.h
new file mode 100644
index 000000000..f27106199
--- /dev/null
+++ b/Tests/QtAutogen/Complex/yaf.h
@@ -0,0 +1,15 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef YAF_H
+#define YAF_H
+
+class Yaf
+{
+public:
+ Yaf();
+
+public:
+ void doYaf();
+};
+
+#endif
diff --git a/Tests/QtAutogen/Complex/yaf_p.h b/Tests/QtAutogen/Complex/yaf_p.h
new file mode 100644
index 000000000..ea5eed69c
--- /dev/null
+++ b/Tests/QtAutogen/Complex/yaf_p.h
@@ -0,0 +1,19 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef YAF_P_H
+#define YAF_P_H
+
+#include <QObject>
+
+#include <stdio.h>
+
+class YafP : public QObject
+{
+ Q_OBJECT
+public:
+ YafP() {}
+public slots:
+ void doYafP() { printf("I am yet another file !\n"); }
+};
+
+#endif
diff --git a/Tests/QtAutogen/DefinesTest/CMakeLists.txt b/Tests/QtAutogen/DefinesTest/CMakeLists.txt
new file mode 100644
index 000000000..3761dd842
--- /dev/null
+++ b/Tests/QtAutogen/DefinesTest/CMakeLists.txt
@@ -0,0 +1,13 @@
+cmake_minimum_required(VERSION 3.10)
+project(DefinesTest)
+
+# Qt4 only definitions test
+if(NOT QT_TEST_VERSION EQUAL 4)
+ message(ERROR "Invalid Qt test version. This test is for Qt4 only.")
+endif()
+
+find_package(Qt4 REQUIRED)
+
+add_executable(DefinesTest defines_test.cpp)
+set_target_properties(DefinesTest PROPERTIES AUTOMOC TRUE)
+target_link_libraries(DefinesTest Qt4::QtGui)
diff --git a/Tests/QtAutogen/DefinesTest/defines_test.cpp b/Tests/QtAutogen/DefinesTest/defines_test.cpp
new file mode 100644
index 000000000..a5336221d
--- /dev/null
+++ b/Tests/QtAutogen/DefinesTest/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/QtAutogen/GlobalAutogenTarget/CMakeLists.txt b/Tests/QtAutogen/GlobalAutogenTarget/CMakeLists.txt
new file mode 100644
index 000000000..81fd8db27
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/CMakeLists.txt
@@ -0,0 +1,126 @@
+cmake_minimum_required(VERSION 3.12)
+project(GlobalAutogenTarget)
+include("../AutogenCoreTest.cmake")
+
+# This tests
+# CMAKE_GLOBAL_AUTOGEN_TARGET,
+# CMAKE_GLOBAL_AUTORCC_TARGET,
+# CMAKE_GLOBAL_AUTOGEN_TARGET_NAME and
+# CMAKE_GLOBAL_AUTORCC_TARGET_NAME
+# for the latter two with different values in different subdirectories.
+
+# Directories
+set(GAT_SDIR "${CMAKE_CURRENT_SOURCE_DIR}/GAT")
+set(GAT_BDIR "${CMAKE_CURRENT_BINARY_DIR}/GAT")
+# Files
+set(MCA "sda/sda_autogen/mocs_compilation.cpp")
+set(MCB "sdb/sdb_autogen/mocs_compilation.cpp")
+set(MCC "sdc/sdc_autogen/mocs_compilation.cpp")
+set(MCG "gat_autogen/mocs_compilation.cpp")
+
+set(DRA "sda/sda_autogen/*qrc_data.cpp")
+set(DRB "sdb/sdb_autogen/*qrc_data.cpp")
+set(DRC "sdc/sdc_autogen/*qrc_data.cpp")
+set(DRG "gat_autogen/*qrc_data.cpp")
+
+# -- Utility macros
+macro(GAT_FIND_FILES VAR NAME)
+ file(GLOB_RECURSE ${VAR} ${GAT_BDIR}/*${NAME})
+endmacro()
+
+macro(GAT_FIND_FILE NAME)
+ GAT_FIND_FILES(LST ${NAME})
+ if(LST)
+ message("Good find ${LST}")
+ else()
+ message(SEND_ERROR "Expected to find ${GAT_BDIR}/${NAME}")
+ endif()
+ unset(LST)
+endmacro()
+
+macro(GAT_FIND_FILE_NOT NAME)
+ GAT_FIND_FILES(LST ${NAME})
+ if(LST)
+ message(SEND_ERROR "Not expected to find ${GAT_BDIR}/${NAME}")
+ else()
+ message("Good not find ${GAT_BDIR}/${NAME}")
+ endif()
+ unset(LST)
+endmacro()
+
+macro(GAT_BUILD_TARGET NAME)
+ message("___ Building GAT ${NAME} target ___")
+ execute_process(
+ COMMAND "${CMAKE_COMMAND}" --build "${GAT_BDIR}" --target ${NAME}
+ WORKING_DIRECTORY "${GAT_BDIR}"
+ RESULT_VARIABLE result)
+ if (result)
+ message(SEND_ERROR "Building of GAT ${NAME} target failed")
+ endif()
+endmacro()
+
+
+# -- Remove and recreate build directory
+file(REMOVE_RECURSE ${GAT_BDIR})
+file(MAKE_DIRECTORY ${GAT_BDIR})
+
+
+# -- Configure project
+message("___ Configuring GAT project ___")
+execute_process(
+ COMMAND "${CMAKE_COMMAND}" "${GAT_SDIR}"
+ -G "${CMAKE_GENERATOR}"
+ -A "${CMAKE_GENERATOR_PLATFORM}"
+ -T "${CMAKE_GENERATOR_TOOLSET}"
+ "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
+ "-DCMAKE_AUTOGEN_VERBOSE=${CMAKE_AUTOGEN_VERBOSE}"
+ "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}"
+ WORKING_DIRECTORY "${GAT_BDIR}"
+ OUTPUT_VARIABLE output
+ RESULT_VARIABLE result)
+if (result)
+ message(SEND_ERROR "Configuring of GAT project failed")
+else()
+ message("Configuring of GAT project succeeded")
+ message("${output}")
+endif()
+
+
+# -- Build autogen subtargets
+GAT_BUILD_TARGET("autogen")
+GAT_FIND_FILE("${MCA}")
+GAT_FIND_FILE_NOT("${MCB}")
+GAT_FIND_FILE_NOT("${MCC}")
+GAT_FIND_FILE("${MCG}")
+
+GAT_BUILD_TARGET("global_autogen_sdb")
+GAT_FIND_FILE("${MCA}")
+GAT_FIND_FILE("${MCB}")
+GAT_FIND_FILE_NOT("${MCC}")
+GAT_FIND_FILE("${MCG}")
+
+GAT_BUILD_TARGET("all_autogen")
+GAT_FIND_FILE("${MCA}")
+GAT_FIND_FILE("${MCB}")
+GAT_FIND_FILE("${MCC}")
+GAT_FIND_FILE("${MCG}")
+
+
+# -- Build autorcc subtargets
+GAT_BUILD_TARGET("autorcc")
+GAT_FIND_FILE("${DRA}")
+GAT_FIND_FILE_NOT("${DRB}")
+GAT_FIND_FILE_NOT("${DRC}")
+GAT_FIND_FILE("${DRG}")
+
+GAT_BUILD_TARGET("global_autorcc_sdb")
+GAT_FIND_FILE("${DRA}")
+GAT_FIND_FILE("${DRB}")
+GAT_FIND_FILE_NOT("${DRC}")
+GAT_FIND_FILE("${DRG}")
+
+GAT_BUILD_TARGET("all_autorcc")
+GAT_FIND_FILE("${DRA}")
+GAT_FIND_FILE("${DRB}")
+GAT_FIND_FILE("${DRC}")
+GAT_FIND_FILE("${DRG}")
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/CMakeLists.txt b/Tests/QtAutogen/GlobalAutogenTarget/GAT/CMakeLists.txt
new file mode 100644
index 000000000..3925197fe
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/CMakeLists.txt
@@ -0,0 +1,28 @@
+cmake_minimum_required(VERSION 3.12)
+project(GAT)
+include("../../AutogenCoreTest.cmake")
+
+# Include directories
+include_directories(${CMAKE_CURRENT_SOURCE_DIR})
+
+# Enable AUTOMOC/UIC/RCC
+set(CMAKE_AUTOMOC ON)
+set(CMAKE_AUTOUIC ON)
+set(CMAKE_AUTORCC ON)
+# Disable ORIGN_DEPENDS and enable AUTOGEN global targets
+set(CMAKE_AUTOGEN_ORIGIN_DEPENDS OFF)
+set(CMAKE_GLOBAL_AUTOGEN_TARGET ON)
+set(CMAKE_GLOBAL_AUTORCC_TARGET ON)
+
+add_subdirectory(sda)
+add_subdirectory(sdb)
+add_subdirectory(sdc)
+
+# Add custom target that depends on all autogen/autorcc targets
+add_custom_target(all_autogen DEPENDS autogen global_autogen_sdb global_autogen_sdc)
+add_custom_target(all_autorcc DEPENDS autorcc global_autorcc_sdb global_autorcc_sdc)
+
+# Main target
+add_executable(gat data.qrc item.cpp main.cpp)
+target_link_libraries(gat ${QT_LIBRARIES})
+target_link_libraries(gat sda sdb sdc)
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/data.qrc b/Tests/QtAutogen/GlobalAutogenTarget/GAT/data.qrc
new file mode 100644
index 000000000..68d02c9eb
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/data.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/item.cpp b/Tests/QtAutogen/GlobalAutogenTarget/GAT/item.cpp
new file mode 100644
index 000000000..3d1fbe7cf
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/item.cpp
@@ -0,0 +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/GlobalAutogenTarget/GAT/item.hpp b/Tests/QtAutogen/GlobalAutogenTarget/GAT/item.hpp
new file mode 100644
index 000000000..75e83f483
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/item.hpp
@@ -0,0 +1,15 @@
+#ifndef ITEM_HPP
+#define ITEM_HPP
+
+#include <QObject>
+// Include ui_view.h in source and header
+#include <ui_view.h>
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/main.cpp b/Tests/QtAutogen/GlobalAutogenTarget/GAT/main.cpp
new file mode 100644
index 000000000..79c00b407
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/main.cpp
@@ -0,0 +1,15 @@
+#include "item.hpp"
+#include "sda/sda.hpp"
+#include "sdb/sdb.hpp"
+#include "sdc/sdc.hpp"
+
+int main(int argv, char** args)
+{
+ // Object instances
+ Item item;
+ // Library calls
+ sda();
+ sdb();
+ sdc();
+ return 0;
+}
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/CMakeLists.txt b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/CMakeLists.txt
new file mode 100644
index 000000000..795e91e97
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_library(sda ../item.cpp ../data.qrc sda.cpp)
+target_link_libraries(sda ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/sda.cpp b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/sda.cpp
new file mode 100644
index 000000000..ec4dec88a
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/sda.cpp
@@ -0,0 +1,6 @@
+#include <item.hpp>
+
+void sda()
+{
+ Item item;
+}
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/sda.hpp b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/sda.hpp
new file mode 100644
index 000000000..89ac744b3
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sda/sda.hpp
@@ -0,0 +1,6 @@
+#ifndef SDA_HPP
+#define SDA_HPP
+
+void sda();
+
+#endif
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/CMakeLists.txt b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/CMakeLists.txt
new file mode 100644
index 000000000..5c686fec4
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(CMAKE_GLOBAL_AUTOGEN_TARGET_NAME "global_autogen_sdb")
+set(CMAKE_GLOBAL_AUTORCC_TARGET_NAME "global_autorcc_sdb")
+
+add_library(sdb ../item.cpp ../data.qrc sdb.cpp)
+target_link_libraries(sdb ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/sdb.cpp b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/sdb.cpp
new file mode 100644
index 000000000..e32c46709
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/sdb.cpp
@@ -0,0 +1,6 @@
+#include <item.hpp>
+
+void sdb()
+{
+ Item item;
+}
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/sdb.hpp b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/sdb.hpp
new file mode 100644
index 000000000..a5b0f62f9
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdb/sdb.hpp
@@ -0,0 +1,6 @@
+#ifndef SDB_HPP
+#define SDB_HPP
+
+void sdb();
+
+#endif
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/CMakeLists.txt b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/CMakeLists.txt
new file mode 100644
index 000000000..2698bda6b
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/CMakeLists.txt
@@ -0,0 +1,5 @@
+set(CMAKE_GLOBAL_AUTOGEN_TARGET_NAME "global_autogen_sdc")
+set(CMAKE_GLOBAL_AUTORCC_TARGET_NAME "global_autorcc_sdc")
+
+add_library(sdc ../item.cpp ../data.qrc sdc.cpp)
+target_link_libraries(sdc ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/sdc.cpp b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/sdc.cpp
new file mode 100644
index 000000000..a97cd4276
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/sdc.cpp
@@ -0,0 +1,6 @@
+#include <item.hpp>
+
+void sdc()
+{
+ Item item;
+}
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/sdc.hpp b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/sdc.hpp
new file mode 100644
index 000000000..7e9217902
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/sdc/sdc.hpp
@@ -0,0 +1,6 @@
+#ifndef SDC_HPP
+#define SDC_HPP
+
+void sdc();
+
+#endif
diff --git a/Tests/QtAutogen/GlobalAutogenTarget/GAT/view.ui b/Tests/QtAutogen/GlobalAutogenTarget/GAT/view.ui
new file mode 100644
index 000000000..2ffe7344c
--- /dev/null
+++ b/Tests/QtAutogen/GlobalAutogenTarget/GAT/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/LowMinimumVersion/CMakeLists.txt b/Tests/QtAutogen/LowMinimumVersion/CMakeLists.txt
new file mode 100644
index 000000000..e1af3d863
--- /dev/null
+++ b/Tests/QtAutogen/LowMinimumVersion/CMakeLists.txt
@@ -0,0 +1,16 @@
+# Use a low minimum version
+cmake_minimum_required(VERSION 3.0)
+project(LowMinimumVersion)
+include("../AutogenGuiTest.cmake")
+
+set(CMAKE_AUTOMOC ON)
+set(CMAKE_AUTOUIC ON)
+set(CMAKE_AUTORCC ON)
+add_executable(lowMinimumVersion
+ main.cpp
+ item.hpp
+ item.cpp
+ view.ui
+ someText.txt
+ example.qrc)
+target_link_libraries(lowMinimumVersion ${QT_QTCORE_TARGET})
diff --git a/Tests/QtAutogen/LowMinimumVersion/example.qrc b/Tests/QtAutogen/LowMinimumVersion/example.qrc
new file mode 100644
index 000000000..551ecc815
--- /dev/null
+++ b/Tests/QtAutogen/LowMinimumVersion/example.qrc
@@ -0,0 +1,5 @@
+<RCC>
+ <qresource prefix="Example">
+ <file>someText.txt</file>
+ </qresource>
+</RCC>
diff --git a/Tests/QtAutogen/LowMinimumVersion/item.cpp b/Tests/QtAutogen/LowMinimumVersion/item.cpp
new file mode 100644
index 000000000..e2f19b204
--- /dev/null
+++ b/Tests/QtAutogen/LowMinimumVersion/item.cpp
@@ -0,0 +1,19 @@
+#include "item.hpp"
+#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/LowMinimumVersion/item.hpp b/Tests/QtAutogen/LowMinimumVersion/item.hpp
new file mode 100644
index 000000000..01255d480
--- /dev/null
+++ b/Tests/QtAutogen/LowMinimumVersion/item.hpp
@@ -0,0 +1,15 @@
+#ifndef ITEM_HPP
+#define ITEM_HPP
+
+#include <QObject>
+
+class Item : public QObject
+{
+ Q_OBJECT
+
+public:
+ Q_SLOT
+ void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/LowMinimumVersion/main.cpp b/Tests/QtAutogen/LowMinimumVersion/main.cpp
new file mode 100644
index 000000000..9f225a4aa
--- /dev/null
+++ b/Tests/QtAutogen/LowMinimumVersion/main.cpp
@@ -0,0 +1,10 @@
+#include "item.hpp"
+
+int main(int argc, char* argv[])
+{
+ Q_INIT_RESOURCE(example);
+ Item item;
+ item.go();
+
+ return 0;
+}
diff --git a/Tests/QtAutogen/LowMinimumVersion/someText.txt b/Tests/QtAutogen/LowMinimumVersion/someText.txt
new file mode 100644
index 000000000..750dae3a1
--- /dev/null
+++ b/Tests/QtAutogen/LowMinimumVersion/someText.txt
@@ -0,0 +1 @@
+Hello world, you're an interesting place.
diff --git a/Tests/QtAutogen/LowMinimumVersion/view.ui b/Tests/QtAutogen/LowMinimumVersion/view.ui
new file mode 100644
index 000000000..2ffe7344c
--- /dev/null
+++ b/Tests/QtAutogen/LowMinimumVersion/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/MacOsFW/CMakeLists.txt b/Tests/QtAutogen/MacOsFW/CMakeLists.txt
new file mode 100644
index 000000000..c08efc47a
--- /dev/null
+++ b/Tests/QtAutogen/MacOsFW/CMakeLists.txt
@@ -0,0 +1,21 @@
+cmake_minimum_required(VERSION 3.10)
+project(MacOsFW)
+include("../AutogenGuiTest.cmake")
+
+find_package(Qt5Test REQUIRED)
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/output/bin)
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/output/lib)
+set(CMAKE_INSTALL_NAME_DIR ${CMAKE_BINARY_DIR}/output/lib)
+
+if(POLICY CMP0042) # in CMake 3.0.0+
+ set (CMAKE_MACOSX_RPATH OFF) # otherwise ON by default
+endif(POLICY CMP0042)
+
+if(POLICY CMP0068) # in CMake 3.9+
+ cmake_policy(SET CMP0068 NEW)
+endif(POLICY CMP0068)
+
+add_subdirectory(src)
+add_subdirectory(test)
diff --git a/Tests/QtAutogen/MacOsFW/src/CMakeLists.txt b/Tests/QtAutogen/MacOsFW/src/CMakeLists.txt
new file mode 100644
index 000000000..a02be00c5
--- /dev/null
+++ b/Tests/QtAutogen/MacOsFW/src/CMakeLists.txt
@@ -0,0 +1,33 @@
+set(MACOS_FW_LIB_VERSION "0.1")
+set(MACOS_FW_LIB_SRCS
+ macos_fw_lib.cpp
+)
+set(MACOS_FW_LIB_HDRS
+ macos_fw_lib.h
+)
+
+include_directories(
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${Qt5Core_INCLUDE_DIRS}
+)
+
+add_library(macos_fw_lib SHARED
+ ${MACOS_FW_LIB_SRCS}
+ ${MACOS_FW_LIB_HDRS}
+)
+set_target_properties(macos_fw_lib PROPERTIES AUTOMOC TRUE)
+set_target_properties(macos_fw_lib PROPERTIES
+ CLEAN_DIRECT_OUTPUT 1
+ FRAMEWORK 1
+ FRAMEWORK_VERSION ${MACOS_FW_LIB_VERSION}
+ VERSION ${MACOS_FW_LIB_VERSION}
+ SOVERSION ${MACOS_FW_LIB_VERSION}
+ MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${MACOS_FW_LIB_VERSION}
+ MACOSX_FRAMEWORK_IDENTIFIER org.macos.fw_lib
+ POSITION_INDEPENDENT_CODE ON
+ PUBLIC_HEADER "${MACOS_FW_LIB_HDRS}"
+)
+target_link_libraries(macos_fw_lib
+ Qt5::Core
+)
diff --git a/Tests/QtAutogen/MacOsFW/src/macos_fw_lib.cpp b/Tests/QtAutogen/MacOsFW/src/macos_fw_lib.cpp
new file mode 100644
index 000000000..881a8c9b6
--- /dev/null
+++ b/Tests/QtAutogen/MacOsFW/src/macos_fw_lib.cpp
@@ -0,0 +1,17 @@
+#include "macos_fw_lib.h"
+
+#include <QString>
+#include <QtGlobal>
+
+MacosFWLib::MacosFWLib()
+{
+}
+
+MacosFWLib::~MacosFWLib()
+{
+}
+
+QString MacosFWLib::qtVersionString() const
+{
+ return QString(qVersion());
+}
diff --git a/Tests/QtAutogen/MacOsFW/src/macos_fw_lib.h b/Tests/QtAutogen/MacOsFW/src/macos_fw_lib.h
new file mode 100644
index 000000000..e66e0ea6c
--- /dev/null
+++ b/Tests/QtAutogen/MacOsFW/src/macos_fw_lib.h
@@ -0,0 +1,18 @@
+#ifndef MACOSFWLIB_H
+#define MACOSFWLIB_H
+
+#include <QObject>
+#include <QString>
+
+class __attribute__((visibility("default"))) MacosFWLib : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit MacosFWLib();
+ ~MacosFWLib();
+
+ QString qtVersionString() const;
+};
+
+#endif // MACOSFWLIB_H
diff --git a/Tests/QtAutogen/MacOsFW/test/CMakeLists.txt b/Tests/QtAutogen/MacOsFW/test/CMakeLists.txt
new file mode 100644
index 000000000..521c18450
--- /dev/null
+++ b/Tests/QtAutogen/MacOsFW/test/CMakeLists.txt
@@ -0,0 +1,19 @@
+include_directories(
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_CURRENT_SOURCE_DIR}/../src
+)
+include_directories(SYSTEM
+ ${Qt5Core_INCLUDE_DIRS}
+ ${Qt5Widgets_INCLUDE_DIRS}
+)
+
+set(testname AutomocMacosFWLib)
+add_executable(${testname} testMacosFWLib.cpp)
+set_target_properties(${testname} PROPERTIES AUTOMOC TRUE)
+target_link_libraries(${testname}
+ Qt5::Core
+ Qt5::Widgets
+ Qt5::Test
+ macos_fw_lib
+)
diff --git a/Tests/QtAutogen/MacOsFW/test/testMacosFWLib.cpp b/Tests/QtAutogen/MacOsFW/test/testMacosFWLib.cpp
new file mode 100644
index 000000000..3476d6176
--- /dev/null
+++ b/Tests/QtAutogen/MacOsFW/test/testMacosFWLib.cpp
@@ -0,0 +1,42 @@
+#include <QObject>
+#include <QString>
+
+#include "macos_fw_lib.h"
+#include "testMacosFWLib.h"
+
+class TestMacosFWLib : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void initTestCase();
+ void cleanupTestCase();
+ void init() {}
+ void cleanup() {}
+
+ void testQtVersion();
+};
+
+void TestMacosFWLib::initTestCase()
+{
+}
+
+void TestMacosFWLib::cleanupTestCase()
+{
+}
+
+void TestMacosFWLib::testQtVersion()
+{
+ MacosFWLib* testLib = new MacosFWLib();
+ QVERIFY(testLib->qtVersionString().contains("5."));
+ testLib->deleteLater();
+}
+
+int main(int argc, char* argv[])
+{
+ QApplication app(argc, argv, false);
+ MacosFWLib testObject;
+ return QTest::qExec(&testObject, argc, argv);
+}
+
+#include "testMacosFWLib.moc"
diff --git a/Tests/QtAutogen/MacOsFW/test/testMacosFWLib.h b/Tests/QtAutogen/MacOsFW/test/testMacosFWLib.h
new file mode 100644
index 000000000..1fe8dae65
--- /dev/null
+++ b/Tests/QtAutogen/MacOsFW/test/testMacosFWLib.h
@@ -0,0 +1,7 @@
+#ifndef TESTMACOSFWLIB_H
+#define TESTMACOSFWLIB_H
+
+#include "qapplication.h"
+#include <QtTest/QtTest>
+
+#endif // TESTMACOSFWLIB_H
diff --git a/Tests/QtAutogen/ManySources/CMakeLists.txt b/Tests/QtAutogen/ManySources/CMakeLists.txt
new file mode 100644
index 000000000..df8a2a662
--- /dev/null
+++ b/Tests/QtAutogen/ManySources/CMakeLists.txt
@@ -0,0 +1,35 @@
+cmake_minimum_required(VERSION 3.10)
+project(ManySources)
+include("../AutogenGuiTest.cmake")
+
+# Test AUTOMOC and AUTOUIC on many source files to stress the concurrent
+# parsing and processing framework.
+
+set(CSD ${CMAKE_CURRENT_SOURCE_DIR})
+set(CBD ${CMAKE_CURRENT_BINARY_DIR})
+
+set(SRCS main.cpp)
+set(MAIN_INCLUDES "\n// Item includes\n")
+set(MAIN_ITEMS "\n// Items\n")
+
+set(NUM 24)
+foreach(III RANGE 1 ${NUM})
+ configure_file(${CSD}/object.h.in ${CBD}/object_${III}.h)
+ configure_file(${CSD}/item.h.in ${CBD}/item_${III}.h)
+ configure_file(${CSD}/item.cpp.in ${CBD}/item_${III}.cpp)
+ configure_file(${CSD}/view.ui.in ${CBD}/view_${III}.ui)
+ configure_file(${CSD}/data.qrc.in ${CBD}/data_${III}.qrc)
+
+ list(APPEND SRCS ${CBD}/item_${III}.cpp)
+ list(APPEND SRCS ${CBD}/data_${III}.qrc)
+
+ string(APPEND MAIN_INCLUDES "#include \"item_${III}.h\"\n")
+ string(APPEND MAIN_ITEMS "Item_${III} item_${III};\n")
+ string(APPEND MAIN_ITEMS "item_${III}.TheSlot();\n")
+endforeach()
+
+configure_file(${CSD}/main.cpp.in ${CBD}/main.cpp)
+
+add_executable(manySources ${SRCS} ${CBD}/main.cpp)
+target_link_libraries(manySources ${QT_LIBRARIES})
+set_target_properties(manySources PROPERTIES AUTOMOC 1 AUTOUIC 1 AUTORCC 1)
diff --git a/Tests/QtAutogen/ManySources/data.qrc.in b/Tests/QtAutogen/ManySources/data.qrc.in
new file mode 100644
index 000000000..870d48631
--- /dev/null
+++ b/Tests/QtAutogen/ManySources/data.qrc.in
@@ -0,0 +1,7 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>object_@III@.h</file>
+ <file>item_@III@.h</file>
+ <file>item_@III@.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/ManySources/item.cpp.in b/Tests/QtAutogen/ManySources/item.cpp.in
new file mode 100644
index 000000000..c34ad16d0
--- /dev/null
+++ b/Tests/QtAutogen/ManySources/item.cpp.in
@@ -0,0 +1,27 @@
+#include "item_@III@.h"
+#include "object_@III@.h"
+// AUTOUIC include
+#include <ui_view_@III@.h>
+
+class LocalObject_@III@ : public QObject
+{
+ Q_OBJECT;
+
+public:
+ LocalObject_@III@() = default;
+ ~LocalObject_@III@() = default;
+};
+
+void Item_@III@ ::TheSlot()
+{
+ LocalObject_@III@ localObject;
+ Object_@III@ obj;
+ obj.ObjectSlot();
+
+ Ui_View_@III@ ui_view;
+}
+
+// AUTOMOC includes
+#include "item_@III@.moc"
+#include "moc_item_@III@.cpp"
+#include "moc_object_@III@.cpp"
diff --git a/Tests/QtAutogen/ManySources/item.h.in b/Tests/QtAutogen/ManySources/item.h.in
new file mode 100644
index 000000000..67ad79435
--- /dev/null
+++ b/Tests/QtAutogen/ManySources/item.h.in
@@ -0,0 +1,15 @@
+#ifndef ITEM_@III@HPP
+#define ITEM_@III@HPP
+
+#include <QObject>
+
+class Item_@III@ : public QObject
+{
+ Q_OBJECT
+
+public:
+ Q_SLOT
+ void TheSlot();
+};
+
+#endif
diff --git a/Tests/QtAutogen/ManySources/main.cpp.in b/Tests/QtAutogen/ManySources/main.cpp.in
new file mode 100644
index 000000000..e1dda40b7
--- /dev/null
+++ b/Tests/QtAutogen/ManySources/main.cpp.in
@@ -0,0 +1,7 @@
+@MAIN_INCLUDES@
+
+int main(int argv, char** args)
+{
+ @MAIN_ITEMS@
+ return 0;
+}
diff --git a/Tests/QtAutogen/ManySources/object.h.in b/Tests/QtAutogen/ManySources/object.h.in
new file mode 100644
index 000000000..a747cbcfa
--- /dev/null
+++ b/Tests/QtAutogen/ManySources/object.h.in
@@ -0,0 +1,15 @@
+#ifndef OBJECT_@III@H
+#define OBJECT_@III@H
+
+#include <QObject>
+
+class Object_@III@ : public QObject
+{
+ Q_OBJECT
+
+public:
+ Q_SLOT
+ void ObjectSlot(){};
+};
+
+#endif
diff --git a/Tests/QtAutogen/ManySources/view.ui.in b/Tests/QtAutogen/ManySources/view.ui.in
new file mode 100644
index 000000000..6901fe3de
--- /dev/null
+++ b/Tests/QtAutogen/ManySources/view.ui.in
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>View_@III@</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/MocCMP0071/CMakeLists.txt b/Tests/QtAutogen/MocCMP0071/CMakeLists.txt
new file mode 100644
index 000000000..5c58a8278
--- /dev/null
+++ b/Tests/QtAutogen/MocCMP0071/CMakeLists.txt
@@ -0,0 +1,6 @@
+cmake_minimum_required(VERSION 3.10)
+project(MocCMP0071)
+include("../AutogenCoreTest.cmake")
+
+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..954fe3dc1
--- /dev/null
+++ b/Tests/QtAutogen/MocCMP0071/NEW/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.10)
+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..68fa06708
--- /dev/null
+++ b/Tests/QtAutogen/MocCMP0071/OLD/CMakeLists.txt
@@ -0,0 +1,18 @@
+cmake_minimum_required(VERSION 3.10)
+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/MocInclude/EObjA.cpp b/Tests/QtAutogen/MocInclude/EObjA.cpp
new file mode 100644
index 000000000..7681c29b9
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/EObjA.cpp
@@ -0,0 +1,44 @@
+#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()
+{
+ delete d;
+}
+
+// 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..d8bf2844c
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/EObjAExtra_p.hpp
@@ -0,0 +1,14 @@
+#ifndef EOBJAEXTRA_P_HPP
+#define EOBJAEXTRA_P_HPP
+
+#include <QObject>
+
+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..9ef5624ab
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/EObjA_p.hpp
@@ -0,0 +1,14 @@
+#ifndef EOBJA_P_HPP
+#define EOBJA_P_HPP
+
+#include <QObject>
+
+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..3068c682d
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/EObjB.cpp
@@ -0,0 +1,45 @@
+#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()
+{
+ delete d;
+}
+
+// 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..84b1ea270
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/EObjB_p.hpp
@@ -0,0 +1,14 @@
+#ifndef EOBJB_P_HPP
+#define EOBJB_P_HPP
+
+#include <QObject>
+
+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..97113d6d1
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/LObjA_p.h
@@ -0,0 +1,14 @@
+#ifndef LOBJA_P_HPP
+#define LOBJA_P_HPP
+
+#include <QObject>
+
+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..b88f40e5c
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/LObjB_p.h
@@ -0,0 +1,14 @@
+#ifndef LOBJB_P_HPP
+#define LOBJB_P_HPP
+
+#include <QObject>
+
+class LObjBPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ LObjBPrivate();
+ ~LObjBPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/MocInclude/ObjA.cpp b/Tests/QtAutogen/MocInclude/ObjA.cpp
new file mode 100644
index 000000000..6f6b90ef1
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/ObjA.cpp
@@ -0,0 +1,20 @@
+#include "ObjA.hpp"
+#include "ObjA_p.h"
+
+ObjAPrivate::ObjAPrivate()
+{
+}
+
+ObjAPrivate::~ObjAPrivate()
+{
+}
+
+ObjA::ObjA()
+ : d(new ObjAPrivate)
+{
+}
+
+ObjA::~ObjA()
+{
+ delete d;
+}
diff --git a/Tests/QtAutogen/MocInclude/ObjA.hpp b/Tests/QtAutogen/MocInclude/ObjA.hpp
new file mode 100644
index 000000000..f16c924aa
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/ObjA.hpp
@@ -0,0 +1,19 @@
+#ifndef OBJA_HPP
+#define OBJA_HPP
+
+#include <QObject>
+
+// Object source comes without any _moc/.moc includes
+class ObjAPrivate;
+class ObjA : public QObject
+{
+ Q_OBJECT
+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..d944bc637
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/ObjA_p.h
@@ -0,0 +1,14 @@
+#ifndef OBJA_P_HPP
+#define OBJA_P_HPP
+
+#include <QObject>
+
+class ObjAPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ ObjAPrivate();
+ ~ObjAPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/MocInclude/ObjB.cpp b/Tests/QtAutogen/MocInclude/ObjB.cpp
new file mode 100644
index 000000000..a6f2509af
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/ObjB.cpp
@@ -0,0 +1,22 @@
+#include "ObjB.hpp"
+#include "ObjB_p.h"
+
+ObjBPrivate::ObjBPrivate()
+{
+}
+
+ObjBPrivate::~ObjBPrivate()
+{
+}
+
+ObjB::ObjB()
+ : d(new ObjBPrivate)
+{
+}
+
+ObjB::~ObjB()
+{
+ delete d;
+}
+
+#include "moc_ObjB.cpp"
diff --git a/Tests/QtAutogen/MocInclude/ObjB.hpp b/Tests/QtAutogen/MocInclude/ObjB.hpp
new file mode 100644
index 000000000..2ac8d1700
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/ObjB.hpp
@@ -0,0 +1,19 @@
+#ifndef ObjB_HPP
+#define ObjB_HPP
+
+#include <QObject>
+
+// Object source comes with a _moc include
+class ObjBPrivate;
+class ObjB : public QObject
+{
+ Q_OBJECT
+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..61ba6042e
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/ObjB_p.h
@@ -0,0 +1,14 @@
+#ifndef OBJB_P_HPP
+#define OBJB_P_HPP
+
+#include <QObject>
+
+class ObjBPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ ObjBPrivate();
+ ~ObjBPrivate();
+};
+
+#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..2ca28414d
--- /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/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..3231fac96
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/subExtra/EObjBExtra_p.hpp
@@ -0,0 +1,14 @@
+#ifndef EOBJBEXTRA_P_HPP
+#define EOBJBEXTRA_P_HPP
+
+#include <QObject>
+
+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..4a4375543
--- /dev/null
+++ b/Tests/QtAutogen/MocInclude/subGlobal/GObj_p.hpp
@@ -0,0 +1,17 @@
+#ifndef GOBJ_P_HPP
+#define GOBJ_P_HPP
+
+#include <QObject>
+
+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
new file mode 100644
index 000000000..8b4da3453
--- /dev/null
+++ b/Tests/QtAutogen/MocIncludeRelaxed/CMakeLists.txt
@@ -0,0 +1,20 @@
+cmake_minimum_required(VERSION 3.10)
+project(MocIncludeRelaxed)
+include("../AutogenCoreTest.cmake")
+
+# Test moc include patterns
+set(CMAKE_AUTOMOC_RELAXED_MODE TRUE)
+
+# Shared executable
+set(MOC_INCLUDE_NAME "mocIncludeRelaxed")
+include(${CMAKE_CURRENT_SOURCE_DIR}/../MocInclude/shared.cmake)
+
+# Relaxed only executable
+add_executable(mocIncludeRelaxedOnly
+ RObjA.cpp
+ RObjB.cpp
+ RObjC.cpp
+ RMain.cpp
+)
+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
new file mode 100644
index 000000000..5a3148dda
--- /dev/null
+++ b/Tests/QtAutogen/MocIncludeRelaxed/main.cpp
@@ -0,0 +1,26 @@
+#include "EObjA.hpp"
+#include "EObjB.hpp"
+#include "LObjA.hpp"
+#include "LObjB.hpp"
+#include "ObjA.hpp"
+#include "ObjB.hpp"
+#include "SObjA.hpp"
+#include "SObjB.hpp"
+#include "subGlobal/GObj.hpp"
+
+int main(int argv, char** args)
+{
+ subGlobal::GObj gObj;
+ ObjA objA;
+ ObjB objB;
+ LObjA lObjA;
+ LObjB lObjB;
+ EObjA eObjA;
+ EObjB eObjB;
+ SObjA sObjA;
+ SObjB sObjB;
+ return 0;
+}
+
+// Header in global subdirectory
+#include "subGlobal/moc_GObj.cpp"
diff --git a/Tests/QtAutogen/MocIncludeStrict/CMakeLists.txt b/Tests/QtAutogen/MocIncludeStrict/CMakeLists.txt
new file mode 100644
index 000000000..d0aaebf37
--- /dev/null
+++ b/Tests/QtAutogen/MocIncludeStrict/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.10)
+project(MocIncludeStrict)
+include("../AutogenCoreTest.cmake")
+
+# Test moc include patterns
+set(CMAKE_AUTOMOC_RELAXED_MODE FALSE)
+
+# Shared executable
+set(MOC_INCLUDE_NAME "mocIncludeStrict")
+include(${CMAKE_CURRENT_SOURCE_DIR}/../MocInclude/shared.cmake)
diff --git a/Tests/QtAutogen/MocIncludeStrict/main.cpp b/Tests/QtAutogen/MocIncludeStrict/main.cpp
new file mode 100644
index 000000000..5a3148dda
--- /dev/null
+++ b/Tests/QtAutogen/MocIncludeStrict/main.cpp
@@ -0,0 +1,26 @@
+#include "EObjA.hpp"
+#include "EObjB.hpp"
+#include "LObjA.hpp"
+#include "LObjB.hpp"
+#include "ObjA.hpp"
+#include "ObjB.hpp"
+#include "SObjA.hpp"
+#include "SObjB.hpp"
+#include "subGlobal/GObj.hpp"
+
+int main(int argv, char** args)
+{
+ subGlobal::GObj gObj;
+ ObjA objA;
+ ObjB objB;
+ LObjA lObjA;
+ LObjB lObjB;
+ EObjA eObjA;
+ EObjB eObjB;
+ SObjA sObjA;
+ SObjB sObjB;
+ return 0;
+}
+
+// Header in global subdirectory
+#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..bf13d187d
--- /dev/null
+++ b/Tests/QtAutogen/MocMacroName/CMakeLists.txt
@@ -0,0 +1,17 @@
+cmake_minimum_required(VERSION 3.10)
+project(MocMacroName)
+include("../AutogenCoreTest.cmake")
+
+# Test CMAKE_AUTOMOC_MACRO_NAMES and AUTOMOC_MACRO_NAMES
+list(APPEND CMAKE_AUTOMOC_MACRO_NAMES "QO1_ALIAS")
+
+add_executable(mocMacroName
+ main.cpp
+ Gadget.cpp
+ Object.cpp
+ Object1Aliased.cpp
+ Object2Aliased.cpp
+)
+set_property(TARGET mocMacroName PROPERTY AUTOMOC ON)
+set_property(TARGET mocMacroName APPEND PROPERTY AUTOMOC_MACRO_NAMES "QO2_ALIAS")
+target_link_libraries(mocMacroName ${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..d7cb51590
--- /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..cab792edc
--- /dev/null
+++ b/Tests/QtAutogen/MocMacroName/Gadget.hpp
@@ -0,0 +1,19 @@
+#ifndef GADGET_HPP
+#define GADGET_HPP
+
+#include <QMetaType>
+
+class Gadget
+{
+ Q_GADGET
+ Q_PROPERTY(int test READ getTest)
+public:
+ Gadget();
+
+ int getTest() { return _test; }
+
+private:
+ int _test;
+};
+
+#endif
diff --git a/Tests/QtAutogen/MocMacroName/Object.cpp b/Tests/QtAutogen/MocMacroName/Object.cpp
new file mode 100644
index 000000000..800ebf3da
--- /dev/null
+++ b/Tests/QtAutogen/MocMacroName/Object.cpp
@@ -0,0 +1,10 @@
+#include "Object.hpp"
+
+Object::Object()
+ : _test(0)
+{
+}
+
+void Object::aSlot()
+{
+}
diff --git a/Tests/QtAutogen/MocMacroName/Object.hpp b/Tests/QtAutogen/MocMacroName/Object.hpp
new file mode 100644
index 000000000..aadae1f6d
--- /dev/null
+++ b/Tests/QtAutogen/MocMacroName/Object.hpp
@@ -0,0 +1,22 @@
+#ifndef OBJECT_HPP
+#define OBJECT_HPP
+
+#include <QObject>
+
+class Object : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int test READ getTest)
+public:
+ Object();
+
+ int getTest() { return _test; }
+
+ Q_SLOT
+ void aSlot();
+
+private:
+ 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/MocOnly/CMakeLists.txt b/Tests/QtAutogen/MocOnly/CMakeLists.txt
new file mode 100644
index 000000000..e109154aa
--- /dev/null
+++ b/Tests/QtAutogen/MocOnly/CMakeLists.txt
@@ -0,0 +1,17 @@
+cmake_minimum_required(VERSION 3.10)
+project(MocOnly)
+include("../AutogenCoreTest.cmake")
+
+add_executable(mocOnly
+ main.cpp
+ # Test different Q_OBJECT position styles
+ StyleA.cpp
+ StyleB.cpp
+ # Test different moc_/.moc include positions
+ IncA.cpp
+ IncB.cpp
+)
+set_property(TARGET mocOnly PROPERTY AUTOMOC ON)
+target_link_libraries(mocOnly ${QT_LIBRARIES})
+# Add compile definitions with unusual characters
+target_compile_definitions(mocOnly PUBLIC "TOKEN=\"hello\;\"" )
diff --git a/Tests/QtAutogen/MocOnly/IncA.cpp b/Tests/QtAutogen/MocOnly/IncA.cpp
new file mode 100644
index 000000000..94610cd48
--- /dev/null
+++ b/Tests/QtAutogen/MocOnly/IncA.cpp
@@ -0,0 +1,19 @@
+#include "moc_IncA.cpp"
+/// AUTOMOC moc_ include on the first line of the file!
+#include "IncA.hpp"
+
+/// @brief Source local QObject
+///
+class IncAPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ IncAPrivate(){};
+};
+
+IncA::IncA()
+{
+ IncAPrivate priv;
+}
+
+#include "IncA.moc"
diff --git a/Tests/QtAutogen/MocOnly/IncA.hpp b/Tests/QtAutogen/MocOnly/IncA.hpp
new file mode 100644
index 000000000..ecc889f9d
--- /dev/null
+++ b/Tests/QtAutogen/MocOnly/IncA.hpp
@@ -0,0 +1,15 @@
+#ifndef INCA_HPP
+#define INCA_HPP
+
+#include <QObject>
+
+/// @brief Test moc include pattern in the source file
+///
+class IncA : public QObject
+{
+ Q_OBJECT
+public:
+ IncA();
+};
+
+#endif
diff --git a/Tests/QtAutogen/MocOnly/IncB.cpp b/Tests/QtAutogen/MocOnly/IncB.cpp
new file mode 100644
index 000000000..bd441a978
--- /dev/null
+++ b/Tests/QtAutogen/MocOnly/IncB.cpp
@@ -0,0 +1,19 @@
+#include "IncB.hpp"
+
+/// @brief Source local QObject
+///
+class IncBPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ IncBPrivate(){};
+};
+
+IncB::IncB()
+{
+ IncBPrivate priv;
+}
+
+/// AUTOMOC moc_ include on the last line of the file!
+#include "IncB.moc"
+#include "moc_IncB.cpp"
diff --git a/Tests/QtAutogen/MocOnly/IncB.hpp b/Tests/QtAutogen/MocOnly/IncB.hpp
new file mode 100644
index 000000000..8331ea2b7
--- /dev/null
+++ b/Tests/QtAutogen/MocOnly/IncB.hpp
@@ -0,0 +1,15 @@
+#ifndef INCB_HPP
+#define INCB_HPP
+
+#include <QObject>
+
+/// @brief Test moc include pattern in the source file
+///
+class IncB : public QObject
+{
+ Q_OBJECT
+public:
+ IncB();
+};
+
+#endif
diff --git a/Tests/QtAutogen/MocOnly/StyleA.cpp b/Tests/QtAutogen/MocOnly/StyleA.cpp
new file mode 100644
index 000000000..ced1dd151
--- /dev/null
+++ b/Tests/QtAutogen/MocOnly/StyleA.cpp
@@ -0,0 +1,5 @@
+#include "StyleA.hpp"
+
+StyleA::StyleA()
+{
+}
diff --git a/Tests/QtAutogen/MocOnly/StyleA.hpp b/Tests/QtAutogen/MocOnly/StyleA.hpp
new file mode 100644
index 000000000..5ba0a8768
--- /dev/null
+++ b/Tests/QtAutogen/MocOnly/StyleA.hpp
@@ -0,0 +1,17 @@
+#ifndef STYLEA_HPP
+#define STYLEA_HPP
+
+#include <QObject>
+
+/* clang-format off */
+/// Q_OBJECT on a single new line
+///
+class StyleA : public QObject
+{
+ Q_OBJECT
+public:
+ StyleA();
+};
+/* clang-format on */
+
+#endif
diff --git a/Tests/QtAutogen/MocOnly/StyleB.cpp b/Tests/QtAutogen/MocOnly/StyleB.cpp
new file mode 100644
index 000000000..bec6c1c36
--- /dev/null
+++ b/Tests/QtAutogen/MocOnly/StyleB.cpp
@@ -0,0 +1,5 @@
+#include "StyleB.hpp"
+
+StyleB::StyleB()
+{
+}
diff --git a/Tests/QtAutogen/MocOnly/StyleB.hpp b/Tests/QtAutogen/MocOnly/StyleB.hpp
new file mode 100644
index 000000000..86abaa8c9
--- /dev/null
+++ b/Tests/QtAutogen/MocOnly/StyleB.hpp
@@ -0,0 +1,16 @@
+#ifndef STYLEB_HPP
+#define STYLEB_HPP
+
+#include <QObject>
+
+/* clang-format off */
+/// Q_OBJECT behind a brace on a new line
+///
+class StyleB : public QObject
+{ Q_OBJECT
+public:
+ StyleB();
+};
+/* clang-format on */
+
+#endif
diff --git a/Tests/QtAutogen/MocOnly/main.cpp b/Tests/QtAutogen/MocOnly/main.cpp
new file mode 100644
index 000000000..b83b8063b
--- /dev/null
+++ b/Tests/QtAutogen/MocOnly/main.cpp
@@ -0,0 +1,18 @@
+#include "IncA.hpp"
+#include "IncB.hpp"
+#include "StyleA.hpp"
+#include "StyleB.hpp"
+#include <iostream>
+
+int main(int argv, char** args)
+{
+ StyleA styleA;
+ StyleB styleB;
+ IncA incA;
+ IncB incB;
+
+ // Test the TOKEN definition passed on the command line
+ std::string token(TOKEN);
+ std::cout << "std::string(TOKEN): \"" << token << "\"\n";
+ return (token == "hello;") ? 0 : -1;
+}
diff --git a/Tests/QtAutogen/MocOptions/CMakeLists.txt b/Tests/QtAutogen/MocOptions/CMakeLists.txt
new file mode 100644
index 000000000..19ee6587e
--- /dev/null
+++ b/Tests/QtAutogen/MocOptions/CMakeLists.txt
@@ -0,0 +1,9 @@
+cmake_minimum_required(VERSION 3.10)
+project(MocOptions)
+include("../AutogenCoreTest.cmake")
+
+# Test extra options passed to moc via AUTOMOC_MOC_OPTIONS
+add_executable(mocOptions Object.cpp main.cpp)
+set_property(TARGET mocOptions PROPERTY AUTOMOC ON)
+set_property(TARGET mocOptions PROPERTY AUTOMOC_MOC_OPTIONS "-nw")
+target_link_libraries(mocOptions ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/MocOptions/Object.cpp b/Tests/QtAutogen/MocOptions/Object.cpp
new file mode 100644
index 000000000..ad109f14c
--- /dev/null
+++ b/Tests/QtAutogen/MocOptions/Object.cpp
@@ -0,0 +1,5 @@
+#include "Object.hpp"
+
+Object::Object()
+{
+}
diff --git a/Tests/QtAutogen/MocOptions/Object.hpp b/Tests/QtAutogen/MocOptions/Object.hpp
new file mode 100644
index 000000000..e7a614200
--- /dev/null
+++ b/Tests/QtAutogen/MocOptions/Object.hpp
@@ -0,0 +1,13 @@
+#ifndef Object_HPP
+#define Object_HPP
+
+#include <QObject>
+
+class Object : public QObject
+{
+ Q_OBJECT
+public:
+ Object();
+};
+
+#endif
diff --git a/Tests/QtAutogen/MocOptions/main.cpp b/Tests/QtAutogen/MocOptions/main.cpp
new file mode 100644
index 000000000..7aeab1a89
--- /dev/null
+++ b/Tests/QtAutogen/MocOptions/main.cpp
@@ -0,0 +1,7 @@
+#include "Object.hpp"
+
+int main(int argv, char** args)
+{
+ Object object;
+ return 0;
+}
diff --git a/Tests/QtAutogen/MocOsMacros/CMakeLists.txt b/Tests/QtAutogen/MocOsMacros/CMakeLists.txt
new file mode 100644
index 000000000..b0125f6c3
--- /dev/null
+++ b/Tests/QtAutogen/MocOsMacros/CMakeLists.txt
@@ -0,0 +1,32 @@
+cmake_minimum_required(VERSION 3.11)
+project(MocOsMacros)
+include("../AutogenCoreTest.cmake")
+
+# Tests if moc processes Q_OS_XXX macros
+
+message( "Qt5Core_VERSION: ${Qt5Core_VERSION}" )
+message(
+ "CMAKE_CXX_COMPILER_PREDEFINES_COMMAND: "
+ ${CMAKE_CXX_COMPILER_PREDEFINES_COMMAND} )
+
+# On some platforms (e.g. MAC) Q_OS_XXX requires moc to include moc_predefs.h
+# which is supported since Qt 5.8 and requires
+# CMAKE_CXX_COMPILER_PREDEFINES_COMMAND to be defined.
+if( ( ${Qt5Core_VERSION} VERSION_GREATER_EQUAL "5.8" ) AND
+ DEFINED CMAKE_CXX_COMPILER_PREDEFINES_COMMAND
+)
+ message( "Test enabled!" )
+ message(
+ "CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES: "
+ ${CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES} )
+
+ set(CMAKE_AUTOMOC True)
+ add_executable(mocOsMacros
+ main.cpp
+ TestClass.cpp
+ TestClass.hpp
+ )
+ target_link_libraries(mocOsMacros PRIVATE ${QT_QTCORE_TARGET})
+else()
+ message( "Test disabled!" )
+endif()
diff --git a/Tests/QtAutogen/MocOsMacros/TestClass.cpp b/Tests/QtAutogen/MocOsMacros/TestClass.cpp
new file mode 100644
index 000000000..13f8fd93a
--- /dev/null
+++ b/Tests/QtAutogen/MocOsMacros/TestClass.cpp
@@ -0,0 +1,82 @@
+#include "TestClass.hpp"
+#include <iostream>
+
+void TestClass::open()
+{
+ std::cout << "open\n";
+}
+
+// -- Mac
+#ifndef Q_OS_MAC
+void TestClass::MacNotDef()
+{
+ std::cout << "MacNotDef\n";
+}
+#else
+void TestClass::MacNotDefElse()
+{
+ std::cout << "MacNotDefElse\n";
+}
+#endif
+
+#ifdef Q_OS_MAC
+void TestClass::MacDef()
+{
+ std::cout << "MacDef\n";
+}
+#else
+void TestClass::MacDefElse()
+{
+ std::cout << "MacDefElse\n";
+}
+#endif
+
+// -- Unix
+#ifndef Q_OS_UNIX
+void TestClass::UnixNotDef()
+{
+ std::cout << "UnixNotDef\n";
+}
+#else
+void TestClass::UnixNotDefElse()
+{
+ std::cout << "UnixNotDefElse\n";
+}
+#endif
+
+#ifdef Q_OS_UNIX
+void TestClass::UnixDef()
+{
+ std::cout << "UnixDef\n";
+}
+#else
+void TestClass::UnixDefElse()
+{
+ std::cout << "UnixDefElse\n";
+}
+#endif
+
+// -- Windows
+#ifndef Q_OS_WIN
+void TestClass::WindowsNotDef()
+{
+ std::cout << "WindowsNotDef\n";
+}
+#else
+void TestClass::WindowsNotDefElse()
+{
+ std::cout << "WindowsNotDefElse\n";
+}
+#endif
+
+#ifdef Q_OS_WIN
+void TestClass::WindowsDef()
+{
+ std::cout << "WindowsDef\n";
+}
+#else
+void TestClass::WindowsDefElse()
+{
+ std::cout << "WindowsDefElse\n";
+}
+#endif
diff --git a/Tests/QtAutogen/MocOsMacros/TestClass.hpp b/Tests/QtAutogen/MocOsMacros/TestClass.hpp
new file mode 100644
index 000000000..87fd49478
--- /dev/null
+++ b/Tests/QtAutogen/MocOsMacros/TestClass.hpp
@@ -0,0 +1,57 @@
+#ifndef TestClass_hpp
+#define TestClass_hpp
+
+#include <QObject>
+#include <QtGlobal>
+// include qplatformdefs.h for #18669
+#include <qplatformdefs.h>
+
+class TestClass : public QObject
+{
+ Q_OBJECT
+public Q_SLOTS:
+
+ // Method named "open" to test if #18669 is fixed
+ void open();
+
+// -- Mac
+#ifndef Q_OS_MAC
+ void MacNotDef();
+#else
+ void MacNotDefElse();
+#endif
+
+#ifdef Q_OS_MAC
+ void MacDef();
+#else
+ void MacDefElse();
+#endif
+
+// -- Unix
+#ifndef Q_OS_UNIX
+ void UnixNotDef();
+#else
+ void UnixNotDefElse();
+#endif
+
+#ifdef Q_OS_UNIX
+ void UnixDef();
+#else
+ void UnixDefElse();
+#endif
+
+// -- Windows
+#ifndef Q_OS_WIN
+ void WindowsNotDef();
+#else
+ void WindowsNotDefElse();
+#endif
+
+#ifdef Q_OS_WIN
+ void WindowsDef();
+#else
+ void WindowsDefElse();
+#endif
+};
+
+#endif /* TestClass_hpp */
diff --git a/Tests/QtAutogen/MocOsMacros/main.cpp b/Tests/QtAutogen/MocOsMacros/main.cpp
new file mode 100644
index 000000000..f8eec3cbc
--- /dev/null
+++ b/Tests/QtAutogen/MocOsMacros/main.cpp
@@ -0,0 +1,32 @@
+#include "TestClass.hpp"
+#include <QtGlobal>
+
+int main()
+{
+ TestClass a;
+#ifdef Q_OS_MAC
+ a.MacNotDefElse();
+ a.MacDef();
+#else
+ a.MacNotDef();
+ a.MacDefElse();
+#endif
+
+#ifdef Q_OS_UNIX
+ a.UnixNotDefElse();
+ a.UnixDef();
+#else
+ a.UnixNotDef();
+ a.UnixDefElse();
+#endif
+
+#ifdef Q_OS_WIN
+ a.WindowsNotDefElse();
+ a.WindowsDef();
+#else
+ a.WindowsNotDef();
+ a.WindowsDefElse();
+#endif
+
+ return 0;
+}
diff --git a/Tests/QtAutogen/MocSkipSource/CMakeLists.txt b/Tests/QtAutogen/MocSkipSource/CMakeLists.txt
new file mode 100644
index 000000000..454e896e8
--- /dev/null
+++ b/Tests/QtAutogen/MocSkipSource/CMakeLists.txt
@@ -0,0 +1,36 @@
+cmake_minimum_required(VERSION 3.10)
+project(MocSkipSource)
+include("../AutogenCoreTest.cmake")
+
+# Test for SKIP_AUTOMOC and SKIP_AUTOGEN on an AUTOMOC enabled target
+
+# Generate header mocs manually
+qtx_wrap_cpp(skipMocWrapMoc
+ qItemA.hpp
+ qItemB.hpp
+ qItemC.hpp
+ qItemD.hpp
+)
+set(skipMocSources
+ skipMoc.cpp
+ qItemA.cpp
+ qItemB.cpp
+ qItemC.cpp
+ 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 qItemA.cpp PROPERTY SKIP_AUTOMOC ON)
+set_property(SOURCE qItemB.cpp PROPERTY SKIP_AUTOGEN ON)
+# When hpp files are skipped, the cpp still get processed.
+set_property(SOURCE qItemC.hpp PROPERTY SKIP_AUTOMOC ON)
+set_property(SOURCE 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})
diff --git a/Tests/QtAutogen/MocSkipSource/qItemA.cpp b/Tests/QtAutogen/MocSkipSource/qItemA.cpp
new file mode 100644
index 000000000..522c2c758
--- /dev/null
+++ b/Tests/QtAutogen/MocSkipSource/qItemA.cpp
@@ -0,0 +1,5 @@
+#include "qItemA.hpp"
+
+void QItemA::go()
+{
+}
diff --git a/Tests/QtAutogen/MocSkipSource/qItemA.hpp b/Tests/QtAutogen/MocSkipSource/qItemA.hpp
new file mode 100644
index 000000000..d295faf3a
--- /dev/null
+++ b/Tests/QtAutogen/MocSkipSource/qItemA.hpp
@@ -0,0 +1,13 @@
+#ifndef QITEMA_HPP
+#define QITEMA_HPP
+
+#include <QObject>
+
+class QItemA : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/MocSkipSource/qItemB.cpp b/Tests/QtAutogen/MocSkipSource/qItemB.cpp
new file mode 100644
index 000000000..636e15dfe
--- /dev/null
+++ b/Tests/QtAutogen/MocSkipSource/qItemB.cpp
@@ -0,0 +1,5 @@
+#include "qItemB.hpp"
+
+void QItemB::go()
+{
+}
diff --git a/Tests/QtAutogen/MocSkipSource/qItemB.hpp b/Tests/QtAutogen/MocSkipSource/qItemB.hpp
new file mode 100644
index 000000000..177591525
--- /dev/null
+++ b/Tests/QtAutogen/MocSkipSource/qItemB.hpp
@@ -0,0 +1,13 @@
+#ifndef QITEMB_HPP
+#define QITEMB_HPP
+
+#include <QObject>
+
+class QItemB : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/MocSkipSource/qItemC.cpp b/Tests/QtAutogen/MocSkipSource/qItemC.cpp
new file mode 100644
index 000000000..622f2829e
--- /dev/null
+++ b/Tests/QtAutogen/MocSkipSource/qItemC.cpp
@@ -0,0 +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/MocSkipSource/qItemC.hpp b/Tests/QtAutogen/MocSkipSource/qItemC.hpp
new file mode 100644
index 000000000..f06bda269
--- /dev/null
+++ b/Tests/QtAutogen/MocSkipSource/qItemC.hpp
@@ -0,0 +1,13 @@
+#ifndef QITEMC_HPP
+#define QITEMC_HPP
+
+#include <QObject>
+
+class QItemC : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/MocSkipSource/qItemD.cpp b/Tests/QtAutogen/MocSkipSource/qItemD.cpp
new file mode 100644
index 000000000..fe0f4e4da
--- /dev/null
+++ b/Tests/QtAutogen/MocSkipSource/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/MocSkipSource/qItemD.hpp b/Tests/QtAutogen/MocSkipSource/qItemD.hpp
new file mode 100644
index 000000000..99e0acbed
--- /dev/null
+++ b/Tests/QtAutogen/MocSkipSource/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/MocSkipSource/skipMoc.cpp b/Tests/QtAutogen/MocSkipSource/skipMoc.cpp
new file mode 100644
index 000000000..c91533410
--- /dev/null
+++ b/Tests/QtAutogen/MocSkipSource/skipMoc.cpp
@@ -0,0 +1,16 @@
+
+#include "qItemA.hpp"
+#include "qItemB.hpp"
+#include "qItemC.hpp"
+#include "qItemD.hpp"
+
+int main(int, char**)
+{
+ QItemA itemA;
+ QItemB itemB;
+ QItemC itemC;
+ QItemD itemD;
+
+ // Fails to link if the symbol is not present.
+ return 0;
+}
diff --git a/Tests/QtAutogen/ObjectLibrary/CMakeLists.txt b/Tests/QtAutogen/ObjectLibrary/CMakeLists.txt
new file mode 100644
index 000000000..ec204e775
--- /dev/null
+++ b/Tests/QtAutogen/ObjectLibrary/CMakeLists.txt
@@ -0,0 +1,18 @@
+cmake_minimum_required(VERSION 3.10)
+project(ObjectLibrary)
+include("../AutogenCoreTest.cmake")
+
+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/Parallel/CMakeLists.txt b/Tests/QtAutogen/Parallel/CMakeLists.txt
new file mode 100644
index 000000000..299bcbfd7
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.10)
+project(Parallel)
+include("../AutogenGuiTest.cmake")
+
+# Test different values for AUTOGEN_PARALLEL
+include("../Parallel/parallel.cmake")
+
+add_executable(parallel ${PARALLEL_SRC})
+set_target_properties(parallel PROPERTIES AUTOGEN_PARALLEL "")
+target_link_libraries(parallel ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/Parallel/aaa/bbb/data.qrc b/Tests/QtAutogen/Parallel/aaa/bbb/data.qrc
new file mode 100644
index 000000000..0ea353756
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/aaa/bbb/data.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="aaa/bbb">
+ <file>item.hpp</file>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/Parallel/aaa/bbb/item.cpp b/Tests/QtAutogen/Parallel/aaa/bbb/item.cpp
new file mode 100644
index 000000000..850206f6b
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/aaa/bbb/item.cpp
@@ -0,0 +1,22 @@
+#include "item.hpp"
+
+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/Parallel/aaa/bbb/item.hpp b/Tests/QtAutogen/Parallel/aaa/bbb/item.hpp
new file mode 100644
index 000000000..085504385
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/aaa/bbb/item.hpp
@@ -0,0 +1,18 @@
+#ifndef AAA_BBB_ITEM_HPP
+#define AAA_BBB_ITEM_HPP
+
+#include <QObject>
+
+namespace aaa {
+namespace bbb {
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+}
+}
+
+#endif
diff --git a/Tests/QtAutogen/Parallel/aaa/data.qrc b/Tests/QtAutogen/Parallel/aaa/data.qrc
new file mode 100644
index 000000000..379af60c8
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/aaa/data.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="aaa/">
+ <file>item.hpp</file>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/Parallel/aaa/item.cpp b/Tests/QtAutogen/Parallel/aaa/item.cpp
new file mode 100644
index 000000000..e35d3d128
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/aaa/item.cpp
@@ -0,0 +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/Parallel/aaa/item.hpp b/Tests/QtAutogen/Parallel/aaa/item.hpp
new file mode 100644
index 000000000..875f72fdb
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/aaa/item.hpp
@@ -0,0 +1,18 @@
+#ifndef AAA_ITEM_HPP
+#define AAA_ITEM_HPP
+
+#include <QObject>
+// Include ui_view.h only in header
+#include <aaa/ui_view.h>
+
+namespace aaa {
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+}
+
+#endif
diff --git a/Tests/QtAutogen/Parallel/aaa/view.ui b/Tests/QtAutogen/Parallel/aaa/view.ui
new file mode 100644
index 000000000..0f0998006
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/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/Parallel/bbb/aaa/data.qrc b/Tests/QtAutogen/Parallel/bbb/aaa/data.qrc
new file mode 100644
index 000000000..da980091a
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/bbb/aaa/data.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="bbb/aaa/">
+ <file>item.hpp</file>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/Parallel/bbb/aaa/item.cpp b/Tests/QtAutogen/Parallel/bbb/aaa/item.cpp
new file mode 100644
index 000000000..7ad01c3ef
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/bbb/aaa/item.cpp
@@ -0,0 +1,22 @@
+#include "item.hpp"
+
+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/Parallel/bbb/aaa/item.hpp b/Tests/QtAutogen/Parallel/bbb/aaa/item.hpp
new file mode 100644
index 000000000..be07ca84c
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/bbb/aaa/item.hpp
@@ -0,0 +1,18 @@
+#ifndef BBB_AAA_ITEM_HPP
+#define BBB_AAA_ITEM_HPP
+
+#include <QObject>
+
+namespace bbb {
+namespace aaa {
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+}
+}
+
+#endif
diff --git a/Tests/QtAutogen/Parallel/bbb/data.qrc b/Tests/QtAutogen/Parallel/bbb/data.qrc
new file mode 100644
index 000000000..5b080f5fa
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/bbb/data.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="bbb/">
+ <file>item.hpp</file>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/Parallel/bbb/item.cpp b/Tests/QtAutogen/Parallel/bbb/item.cpp
new file mode 100644
index 000000000..9ef128ed0
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/bbb/item.cpp
@@ -0,0 +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/Parallel/bbb/item.hpp b/Tests/QtAutogen/Parallel/bbb/item.hpp
new file mode 100644
index 000000000..d39a9d711
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/bbb/item.hpp
@@ -0,0 +1,17 @@
+#ifndef BBB_ITEM_HPP
+#define BBB_ITEM_HPP
+
+#include <QObject>
+// Include ui_view.h only in source
+
+namespace bbb {
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+}
+
+#endif
diff --git a/Tests/QtAutogen/Parallel/bbb/view.ui b/Tests/QtAutogen/Parallel/bbb/view.ui
new file mode 100644
index 000000000..a8f506e88
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/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/Parallel/ccc/data.qrc b/Tests/QtAutogen/Parallel/ccc/data.qrc
new file mode 100644
index 000000000..f934c39b9
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/ccc/data.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="ccc/">
+ <file>item.hpp</file>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/Parallel/ccc/item.cpp b/Tests/QtAutogen/Parallel/ccc/item.cpp
new file mode 100644
index 000000000..ab8a2817b
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/ccc/item.cpp
@@ -0,0 +1,25 @@
+#include "item.hpp"
+// Include ui_view.h in source and header
+#include <ccc/ui_view.h>
+
+namespace ccc {
+
+class MocLocal : public QObject
+{
+ Q_OBJECT;
+
+public:
+ MocLocal() = default;
+ ~MocLocal() = default;
+};
+
+void Item::go()
+{
+ Ui_ViewCCC ui;
+ MocLocal obj;
+}
+}
+
+// Include own moc files
+#include "ccc/item.moc"
+#include "moc_item.cpp"
diff --git a/Tests/QtAutogen/Parallel/ccc/item.hpp b/Tests/QtAutogen/Parallel/ccc/item.hpp
new file mode 100644
index 000000000..20d9dd978
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/ccc/item.hpp
@@ -0,0 +1,18 @@
+#ifndef CCC_ITEM_HPP
+#define CCC_ITEM_HPP
+
+#include <QObject>
+// Include ui_view.h in source and header
+#include <ccc/ui_view.h>
+
+namespace ccc {
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+}
+
+#endif
diff --git a/Tests/QtAutogen/Parallel/ccc/view.ui b/Tests/QtAutogen/Parallel/ccc/view.ui
new file mode 100644
index 000000000..7989c6973
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/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/Parallel/data.qrc b/Tests/QtAutogen/Parallel/data.qrc
new file mode 100644
index 000000000..4ce0b4ec1
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/data.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>main.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/Parallel/item.cpp b/Tests/QtAutogen/Parallel/item.cpp
new file mode 100644
index 000000000..3d1fbe7cf
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/item.cpp
@@ -0,0 +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/Parallel/item.hpp b/Tests/QtAutogen/Parallel/item.hpp
new file mode 100644
index 000000000..75e83f483
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/item.hpp
@@ -0,0 +1,15 @@
+#ifndef ITEM_HPP
+#define ITEM_HPP
+
+#include <QObject>
+// Include ui_view.h in source and header
+#include <ui_view.h>
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/Parallel/main.cpp b/Tests/QtAutogen/Parallel/main.cpp
new file mode 100644
index 000000000..a4ffcb350
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/main.cpp
@@ -0,0 +1,16 @@
+#include "aaa/bbb/item.hpp"
+#include "aaa/item.hpp"
+#include "bbb/aaa/item.hpp"
+#include "bbb/item.hpp"
+#include "ccc/item.hpp"
+
+int main(int argv, char** args)
+{
+ // Object instances
+ ::aaa::Item aaa_item;
+ ::aaa::bbb::Item aaa_bbb_item;
+ ::bbb::Item bbb_item;
+ ::bbb::aaa::Item bbb_aaa_item;
+ ::ccc::Item ccc_item;
+ return 0;
+}
diff --git a/Tests/QtAutogen/Parallel/parallel.cmake b/Tests/QtAutogen/Parallel/parallel.cmake
new file mode 100644
index 000000000..551bcd82b
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/parallel.cmake
@@ -0,0 +1,24 @@
+set(CMAKE_AUTOMOC ON)
+set(CMAKE_AUTOUIC ON)
+set(CMAKE_AUTORCC ON)
+
+
+set(PBASE ${CMAKE_CURRENT_LIST_DIR})
+set(PARALLEL_SRC
+ ${PBASE}/aaa/bbb/item.cpp
+ ${PBASE}/aaa/bbb/data.qrc
+ ${PBASE}/aaa/item.cpp
+ ${PBASE}/aaa/data.qrc
+
+ ${PBASE}/bbb/aaa/item.cpp
+ ${PBASE}/bbb/aaa/data.qrc
+ ${PBASE}/bbb/item.cpp
+ ${PBASE}/bbb/data.qrc
+
+ ${PBASE}/ccc/item.cpp
+ ${PBASE}/ccc/data.qrc
+
+ ${PBASE}/item.cpp
+ ${PBASE}/data.qrc
+ ${PBASE}/main.cpp
+)
diff --git a/Tests/QtAutogen/Parallel/view.ui b/Tests/QtAutogen/Parallel/view.ui
new file mode 100644
index 000000000..2ffe7344c
--- /dev/null
+++ b/Tests/QtAutogen/Parallel/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/Parallel1/CMakeLists.txt b/Tests/QtAutogen/Parallel1/CMakeLists.txt
new file mode 100644
index 000000000..5c7d547df
--- /dev/null
+++ b/Tests/QtAutogen/Parallel1/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.10)
+project(Parallel1)
+include("../AutogenGuiTest.cmake")
+
+# Test different values for AUTOGEN_PARALLEL
+include("../Parallel/parallel.cmake")
+
+add_executable(parallel1 ${PARALLEL_SRC})
+set_target_properties(parallel1 PROPERTIES AUTOGEN_PARALLEL 1)
+target_link_libraries(parallel1 ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/Parallel2/CMakeLists.txt b/Tests/QtAutogen/Parallel2/CMakeLists.txt
new file mode 100644
index 000000000..668aea4bd
--- /dev/null
+++ b/Tests/QtAutogen/Parallel2/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.10)
+project(Parallel2)
+include("../AutogenGuiTest.cmake")
+
+# Test different values for AUTOGEN_PARALLEL
+include("../Parallel/parallel.cmake")
+
+add_executable(parallel2 ${PARALLEL_SRC})
+set_target_properties(parallel2 PROPERTIES AUTOGEN_PARALLEL 2)
+target_link_libraries(parallel2 ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/Parallel3/CMakeLists.txt b/Tests/QtAutogen/Parallel3/CMakeLists.txt
new file mode 100644
index 000000000..5c50f5ee5
--- /dev/null
+++ b/Tests/QtAutogen/Parallel3/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.10)
+project(Parallel3)
+include("../AutogenGuiTest.cmake")
+
+# Test different values for AUTOGEN_PARALLEL
+include("../Parallel/parallel.cmake")
+
+add_executable(parallel3 ${PARALLEL_SRC})
+set_target_properties(parallel3 PROPERTIES AUTOGEN_PARALLEL 3)
+target_link_libraries(parallel3 ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/Parallel4/CMakeLists.txt b/Tests/QtAutogen/Parallel4/CMakeLists.txt
new file mode 100644
index 000000000..2c40c6a67
--- /dev/null
+++ b/Tests/QtAutogen/Parallel4/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.10)
+project(Parallel4)
+include("../AutogenGuiTest.cmake")
+
+# Test different values for AUTOGEN_PARALLEL
+include("../Parallel/parallel.cmake")
+
+add_executable(parallel4 ${PARALLEL_SRC})
+set_target_properties(parallel4 PROPERTIES AUTOGEN_PARALLEL 4)
+target_link_libraries(parallel4 ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/ParallelAUTO/CMakeLists.txt b/Tests/QtAutogen/ParallelAUTO/CMakeLists.txt
new file mode 100644
index 000000000..cddece37a
--- /dev/null
+++ b/Tests/QtAutogen/ParallelAUTO/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.10)
+project(ParallelAUTO)
+include("../AutogenGuiTest.cmake")
+
+# Test different values for AUTOGEN_PARALLEL
+include("../Parallel/parallel.cmake")
+
+add_executable(parallelAUTO ${PARALLEL_SRC})
+set_target_properties(parallelAUTO PROPERTIES AUTOGEN_PARALLEL "AUTO")
+target_link_libraries(parallelAUTO ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/RccEmpty/CMakeLists.txt b/Tests/QtAutogen/RccEmpty/CMakeLists.txt
new file mode 100644
index 000000000..a8e2af1b6
--- /dev/null
+++ b/Tests/QtAutogen/RccEmpty/CMakeLists.txt
@@ -0,0 +1,8 @@
+cmake_minimum_required(VERSION 3.10)
+project(RccEmpty)
+include("../AutogenCoreTest.cmake")
+
+# Test AUTORCC on a .qrc file with no resource files
+add_executable(rccEmpty rccEmpty.cpp rccEmptyRes.qrc)
+set_property(TARGET rccEmpty PROPERTY AUTORCC ON)
+target_link_libraries(rccEmpty ${QT_QTCORE_TARGET})
diff --git a/Tests/QtAutogen/RccEmpty/rccEmpty.cpp b/Tests/QtAutogen/RccEmpty/rccEmpty.cpp
new file mode 100644
index 000000000..7f2c52786
--- /dev/null
+++ b/Tests/QtAutogen/RccEmpty/rccEmpty.cpp
@@ -0,0 +1,9 @@
+
+extern int qInitResources_rccEmptyRes();
+
+int main(int, char**)
+{
+ // Fails to link if the symbol is not present.
+ qInitResources_rccEmptyRes();
+ return 0;
+}
diff --git a/Tests/QtAutogen/RccEmpty/rccEmptyRes.qrc b/Tests/QtAutogen/RccEmpty/rccEmptyRes.qrc
new file mode 100644
index 000000000..4ca9cd583
--- /dev/null
+++ b/Tests/QtAutogen/RccEmpty/rccEmptyRes.qrc
@@ -0,0 +1,4 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RccOffMocLibrary/CMakeLists.txt b/Tests/QtAutogen/RccOffMocLibrary/CMakeLists.txt
new file mode 100644
index 000000000..61b9601a2
--- /dev/null
+++ b/Tests/QtAutogen/RccOffMocLibrary/CMakeLists.txt
@@ -0,0 +1,17 @@
+cmake_minimum_required(VERSION 3.10)
+project(RccOffMocLibrary)
+include("../AutogenCoreTest.cmake")
+
+# Add not_generated_file.qrc to the source list to get the file-level
+# dependency, but don't generate a c++ file from it. Disable the AUTORCC
+# feature for this target. This tests that qrc files in the sources don't
+# have an effect on generation if AUTORCC is off.
+add_library(empty STATIC empty.cpp not_generated_file.qrc)
+set_target_properties(empty PROPERTIES AUTORCC OFF)
+set_target_properties(empty PROPERTIES AUTOMOC TRUE)
+target_link_libraries(empty no_link_language)
+add_library(no_link_language STATIC empty.h)
+set_target_properties(no_link_language PROPERTIES AUTOMOC TRUE)
+# Pass Qt compiler features to targets that don't link against Qt
+target_compile_features(no_link_language PRIVATE ${QT_COMPILE_FEATURES})
+target_compile_features(empty PRIVATE ${QT_COMPILE_FEATURES})
diff --git a/Tests/QtAutogen/RccOffMocLibrary/empty.cpp b/Tests/QtAutogen/RccOffMocLibrary/empty.cpp
new file mode 100644
index 000000000..ab32cf6c8
--- /dev/null
+++ b/Tests/QtAutogen/RccOffMocLibrary/empty.cpp
@@ -0,0 +1 @@
+// No content
diff --git a/Tests/QtAutogen/RccOffMocLibrary/empty.h b/Tests/QtAutogen/RccOffMocLibrary/empty.h
new file mode 100644
index 000000000..6bdd2ac89
--- /dev/null
+++ b/Tests/QtAutogen/RccOffMocLibrary/empty.h
@@ -0,0 +1,9 @@
+
+#include <QObject>
+
+class Empty : public QObject
+{
+ Q_OBJECT
+public:
+ explicit Empty(QObject* parent = 0) {}
+};
diff --git a/Tests/QtAutogen/RccOffMocLibrary/not_generated_file.qrc b/Tests/QtAutogen/RccOffMocLibrary/not_generated_file.qrc
new file mode 100644
index 000000000..c7698343a
--- /dev/null
+++ b/Tests/QtAutogen/RccOffMocLibrary/not_generated_file.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>abc.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RccOnly/CMakeLists.txt b/Tests/QtAutogen/RccOnly/CMakeLists.txt
new file mode 100644
index 000000000..f3776f575
--- /dev/null
+++ b/Tests/QtAutogen/RccOnly/CMakeLists.txt
@@ -0,0 +1,8 @@
+cmake_minimum_required(VERSION 3.10)
+project(RccOnly)
+include("../AutogenCoreTest.cmake")
+
+# Test AUTORCC being enabled only
+add_executable(rccOnly rccOnly.cpp rccOnlyRes.qrc)
+set_property(TARGET rccOnly PROPERTY AUTORCC ON)
+target_link_libraries(rccOnly ${QT_QTCORE_TARGET})
diff --git a/Tests/QtAutogen/RccOnly/rccOnly.cpp b/Tests/QtAutogen/RccOnly/rccOnly.cpp
new file mode 100644
index 000000000..61c7bf4ed
--- /dev/null
+++ b/Tests/QtAutogen/RccOnly/rccOnly.cpp
@@ -0,0 +1,9 @@
+
+extern int qInitResources_rccOnlyRes();
+
+int main(int, char**)
+{
+ // Fails to link if the symbol is not present.
+ qInitResources_rccOnlyRes();
+ return 0;
+}
diff --git a/Tests/QtAutogen/RccOnly/rccOnlyRes.qrc b/Tests/QtAutogen/RccOnly/rccOnlyRes.qrc
new file mode 100644
index 000000000..555134877
--- /dev/null
+++ b/Tests/QtAutogen/RccOnly/rccOnlyRes.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>rccOnly.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RccSkipSource/CMakeLists.txt b/Tests/QtAutogen/RccSkipSource/CMakeLists.txt
new file mode 100644
index 000000000..42232744f
--- /dev/null
+++ b/Tests/QtAutogen/RccSkipSource/CMakeLists.txt
@@ -0,0 +1,23 @@
+cmake_minimum_required(VERSION 3.10)
+project(RccSkipSource)
+include("../AutogenCoreTest.cmake")
+
+# Test for SKIP_AUTORCC and SKIP_AUTOGEN on an AUTORCC enabled target
+set(skipRccSources
+ skipRcc.cpp
+ skipRccBad1.qrc
+ skipRccBad2.qrc
+ skipRccGood.qrc
+)
+set_property(SOURCE skipRccBad1.qrc PROPERTY SKIP_AUTORCC ON)
+set_property(SOURCE skipRccBad2.qrc PROPERTY SKIP_AUTOGEN ON)
+# AUTORCC enabled
+add_executable(skipRccA ${skipRccSources})
+set_property(TARGET skipRccA PROPERTY AUTORCC ON)
+target_link_libraries(skipRccA ${QT_LIBRARIES})
+# AUTORCC, AUTOUIC and AUTOMOC enabled
+add_executable(skipRccB ${skipRccSources})
+set_property(TARGET skipRccB PROPERTY AUTORCC ON)
+set_property(TARGET skipRccB PROPERTY AUTOUIC ON)
+set_property(TARGET skipRccB PROPERTY AUTOMOC ON)
+target_link_libraries(skipRccB ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/RccSkipSource/skipRcc.cpp b/Tests/QtAutogen/RccSkipSource/skipRcc.cpp
new file mode 100644
index 000000000..ec5711088
--- /dev/null
+++ b/Tests/QtAutogen/RccSkipSource/skipRcc.cpp
@@ -0,0 +1,9 @@
+
+extern int qInitResources_skipRccGood();
+
+int main(int, char**)
+{
+ // Fails to link if the symbol is not present.
+ qInitResources_skipRccGood();
+ return 0;
+}
diff --git a/Tests/QtAutogen/RccSkipSource/skipRccBad1.qrc b/Tests/QtAutogen/RccSkipSource/skipRccBad1.qrc
new file mode 100644
index 000000000..6cbd9ed18
--- /dev/null
+++ b/Tests/QtAutogen/RccSkipSource/skipRccBad1.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>skipRccGood.cpp</file>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RccSkipSource/skipRccBad2.qrc b/Tests/QtAutogen/RccSkipSource/skipRccBad2.qrc
new file mode 100644
index 000000000..b32c5896c
--- /dev/null
+++ b/Tests/QtAutogen/RccSkipSource/skipRccBad2.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><
+<qresource>
+ <file>skipRccGood.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RccSkipSource/skipRccGood.qrc b/Tests/QtAutogen/RccSkipSource/skipRccGood.qrc
new file mode 100644
index 000000000..21a94b0c5
--- /dev/null
+++ b/Tests/QtAutogen/RccSkipSource/skipRccGood.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>skipRccBad1.qrc</file>
+ <file>skipRccBad2.qrc</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RerunMocBasic/CMakeLists.txt b/Tests/QtAutogen/RerunMocBasic/CMakeLists.txt
new file mode 100644
index 000000000..9b32e5951
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocBasic/CMakeLists.txt
@@ -0,0 +1,102 @@
+cmake_minimum_required(VERSION 3.10)
+project(RerunMocBasic)
+include("../AutogenCoreTest.cmake")
+
+# Dummy executable to generate a clean target
+add_executable(dummy dummy.cpp)
+
+# Utility variables
+set(timeformat "%Y.%j.%H.%M%S")
+set(mocBasicSrcDir "${CMAKE_CURRENT_SOURCE_DIR}/MocBasic")
+set(mocBasicBinDir "${CMAKE_CURRENT_BINARY_DIR}/MocBasic")
+
+# Utility macros
+macro(sleep)
+ message(STATUS "Sleeping for a few seconds.")
+ execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+endmacro()
+
+macro(acquire_timestamp When)
+ file(TIMESTAMP "${mocBasicBin}" time${When} "${timeformat}")
+endmacro()
+
+macro(rebuild buildName)
+ message(STATUS "Starting build ${buildName}.")
+ execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocBasicBinDir}" RESULT_VARIABLE result)
+ if (result)
+ message(FATAL_ERROR "Build ${buildName} failed.")
+ else()
+ message(STATUS "Build ${buildName} finished.")
+ endif()
+endmacro()
+
+macro(require_change)
+ if (timeAfter VERSION_GREATER timeBefore)
+ message(STATUS "As expected the file ${mocBasicBin} changed.")
+ else()
+ message(SEND_ERROR "Unexpectedly the file ${mocBasicBin} did not change!\nTimestamp pre: ${timeBefore}\nTimestamp aft: ${timeAfter}\n")
+ endif()
+endmacro()
+
+macro(require_change_not)
+ if (timeAfter VERSION_GREATER timeBefore)
+ message(SEND_ERROR "Unexpectedly the file ${mocBasicBin} changed!\nTimestamp pre: ${timeBefore}\nTimestamp aft: ${timeAfter}\n")
+ else()
+ message(STATUS "As expected the file ${mocBasicBin} did not change.")
+ endif()
+endmacro()
+
+
+# Initial build
+configure_file("${mocBasicSrcDir}/test1a.h.in" "${mocBasicBinDir}/test1.h" COPYONLY)
+try_compile(MOC_RERUN
+ "${mocBasicBinDir}"
+ "${mocBasicSrcDir}"
+ MocBasic
+ CMAKE_FLAGS "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
+ "-DCMAKE_AUTOGEN_VERBOSE=${CMAKE_AUTOGEN_VERBOSE}"
+ "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}"
+ OUTPUT_VARIABLE output
+)
+if (NOT MOC_RERUN)
+ message(FATAL_ERROR "Initial build of mocBasic failed. Output: ${output}")
+endif()
+
+# Get name of the output binary
+file(STRINGS "${mocBasicBinDir}/mocBasic.txt" mocBasicList ENCODING UTF-8)
+list(GET mocBasicList 0 mocBasicBin)
+
+# To avoid a race condition where the binary has the same timestamp
+# as a source file and therefore gets rebuild
+# - sleep to ensure a timestamp change
+# - touch binary to ensure it has a new timestamp
+acquire_timestamp(Before)
+sleep()
+message(STATUS "Touching binary file to ensure a new timestamps")
+file(TOUCH_NOCREATE "${mocBasicBin}")
+acquire_timestamp(After)
+require_change()
+
+
+# - Ensure that the timestamp will change
+# - Change header file content
+# - Rebuild
+acquire_timestamp(Before)
+sleep()
+message(STATUS "Changing the header content for a MOC re-run")
+configure_file("${mocBasicSrcDir}/test1b.h.in" "${mocBasicBinDir}/test1.h" COPYONLY)
+sleep()
+rebuild(2)
+acquire_timestamp(After)
+require_change()
+
+
+# - Ensure that the timestamp would change
+# - Change nothing
+# - Rebuild
+acquire_timestamp(Before)
+sleep()
+message(STATUS "Changing nothing for no MOC re-run")
+rebuild(3)
+acquire_timestamp(After)
+require_change_not()
diff --git a/Tests/QtAutogen/RerunMocBasic/MocBasic/CMakeLists.txt b/Tests/QtAutogen/RerunMocBasic/MocBasic/CMakeLists.txt
new file mode 100644
index 000000000..6a9f5507c
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocBasic/MocBasic/CMakeLists.txt
@@ -0,0 +1,24 @@
+cmake_minimum_required(VERSION 3.10)
+project(MocBasic)
+include("../../AutogenCoreTest.cmake")
+
+set(CMAKE_AUTOMOC ON)
+set(CMAKE_AUTORCC ON)
+
+# Generated source file
+add_custom_command(OUTPUT ${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(mocBasic
+ ${CMAKE_CURRENT_BINARY_DIR}/test1.h
+ ${CMAKE_CURRENT_BINARY_DIR}/main.cpp
+ res1.qrc
+)
+target_include_directories(mocBasic PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
+target_link_libraries(mocBasic ${QT_QTCORE_TARGET})
+# Write target name to text file
+add_custom_command(TARGET mocBasic POST_BUILD COMMAND
+ ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:mocBasic>" > mocBasic.txt
+)
diff --git a/Tests/QtAutogen/RerunMocBasic/MocBasic/input.txt b/Tests/QtAutogen/RerunMocBasic/MocBasic/input.txt
new file mode 100644
index 000000000..da627624b
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocBasic/MocBasic/input.txt
@@ -0,0 +1 @@
+Res1 input.
diff --git a/Tests/QtAutogen/RerunMocBasic/MocBasic/main.cpp.in b/Tests/QtAutogen/RerunMocBasic/MocBasic/main.cpp.in
new file mode 100644
index 000000000..9d7ea37ae
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocBasic/MocBasic/main.cpp.in
@@ -0,0 +1,23 @@
+#include "test1.h"
+
+extern int qInitResources_res1();
+
+class Test2 : public QObject
+{
+ Q_OBJECT
+public slots:
+ void onTst1() {}
+};
+
+int main()
+{
+ // Fails to link if the rcc generated symbol is not present.
+ qInitResources_res1();
+
+ Test1 test1;
+ Test2 test2;
+
+ return 0;
+}
+
+#include "main.moc"
diff --git a/Tests/QtAutogen/RerunMocBasic/MocBasic/res1.qrc b/Tests/QtAutogen/RerunMocBasic/MocBasic/res1.qrc
new file mode 100644
index 000000000..fb804b5ec
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocBasic/MocBasic/res1.qrc
@@ -0,0 +1,5 @@
+<RCC>
+ <qresource prefix="/">
+ <file>input.txt</file>
+ </qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RerunMocBasic/MocBasic/test1a.h.in b/Tests/QtAutogen/RerunMocBasic/MocBasic/test1a.h.in
new file mode 100644
index 000000000..a335046ba
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocBasic/MocBasic/test1a.h.in
@@ -0,0 +1,8 @@
+#include <QObject>
+class Test1 : public QObject
+{
+ Q_OBJECT
+public slots:
+ void onTst1() {}
+ void onTst2() {}
+};
diff --git a/Tests/QtAutogen/RerunMocBasic/MocBasic/test1b.h.in b/Tests/QtAutogen/RerunMocBasic/MocBasic/test1b.h.in
new file mode 100644
index 000000000..6128eeba1
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocBasic/MocBasic/test1b.h.in
@@ -0,0 +1,7 @@
+#include <QObject>
+class Test1 : public QObject
+{
+ Q_OBJECT
+public slots:
+ void onTst1() {}
+};
diff --git a/Tests/QtAutogen/RerunMocBasic/dummy.cpp b/Tests/QtAutogen/RerunMocBasic/dummy.cpp
new file mode 100644
index 000000000..4837a76b8
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocBasic/dummy.cpp
@@ -0,0 +1,5 @@
+
+int main(int argv, char** args)
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/RerunMocPlugin/CMakeLists.txt b/Tests/QtAutogen/RerunMocPlugin/CMakeLists.txt
new file mode 100644
index 000000000..e1951f1d0
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/CMakeLists.txt
@@ -0,0 +1,134 @@
+cmake_minimum_required(VERSION 3.10)
+project(RerunMocPlugin)
+include("../AutogenCoreTest.cmake")
+
+# Tests Q_PLUGIN_METADATA and CMAKE_AUTOMOC_DEPEND_FILTERS
+# json file change detection
+
+# Dummy executable to generate a clean target
+add_executable(dummy dummy.cpp)
+
+# Utility variables
+set(timeformat "%Y.%j.%H.%M%S")
+set(mocPlugSrcDir "${CMAKE_CURRENT_SOURCE_DIR}/MocPlugin")
+set(mocPlugBinDir "${CMAKE_CURRENT_BINARY_DIR}/MocPlugin")
+
+# Utility macros
+macro(sleep)
+ message(STATUS "Sleeping for a few seconds.")
+ execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+endmacro()
+
+macro(rebuild buildName)
+ message(STATUS "Starting build ${buildName}.")
+ execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocPlugBinDir}" RESULT_VARIABLE result)
+ if (result)
+ message(FATAL_ERROR "Build ${buildName} failed.")
+ else()
+ message(STATUS "Build ${buildName} finished.")
+ endif()
+endmacro()
+
+macro(require_change PLG)
+ if (pl${PLG}After VERSION_GREATER pl${PLG}Before)
+ message(STATUS "As expected the file ${pl${PLG}File} changed.")
+ else()
+ message(SEND_ERROR
+ "Unexpectedly the file ${pl${PLG}File} did not change!\nTimestamp pre: ${pl${PLG}Before}\nTimestamp aft: ${pl${PLG}After}\n")
+ endif()
+endmacro()
+
+macro(require_change_not PLG)
+ if (pl${PLG}After VERSION_GREATER pl${PLG}Before)
+ message(SEND_ERROR
+ "Unexpectedly the file ${pl${PLG}File} changed!\nTimestamp pre: ${pl${PLG}Before}\nTimestamp aft: ${pl${PLG}After}\n")
+ else()
+ message(STATUS "As expected the file ${pl${PLG}File} did not change.")
+ endif()
+endmacro()
+
+macro(acquire_timestamps When)
+ file(TIMESTAMP "${plAFile}" plA${When} "${timeformat}")
+ file(TIMESTAMP "${plBFile}" plB${When} "${timeformat}")
+ file(TIMESTAMP "${plCFile}" plC${When} "${timeformat}")
+ file(TIMESTAMP "${plDFile}" plD${When} "${timeformat}")
+ file(TIMESTAMP "${plEFile}" plE${When} "${timeformat}")
+endmacro()
+
+
+# Initial build
+try_compile(MOC_PLUGIN
+ "${mocPlugBinDir}"
+ "${mocPlugSrcDir}"
+ MocPlugin
+ CMAKE_FLAGS "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
+ "-DCMAKE_AUTOGEN_VERBOSE=${CMAKE_AUTOGEN_VERBOSE}"
+ "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}"
+ OUTPUT_VARIABLE output
+)
+if (NOT MOC_PLUGIN)
+ message(FATAL_ERROR "Initial build of mocPlugin failed. Output: ${output}")
+endif()
+
+# Get names of the output binaries
+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)
+
+# To avoid a race condition where the library has the same timestamp
+# as a source file and therefore gets rebuild
+# - sleep to ensure a timestamp change
+# - rebuild library to ensure it has a new timestamp
+sleep()
+message(STATUS "Rebuilding library files to ensure new timestamps")
+rebuild(1)
+
+
+# - Ensure that the timestamp will change.
+# - Change the json files referenced by Q_PLUGIN_METADATA
+# - Rebuild
+acquire_timestamps(Before)
+sleep()
+message(STATUS "Changing json files.")
+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")
+sleep()
+rebuild(2)
+acquire_timestamps(After)
+# Test changes
+require_change_not(A)
+require_change_not(B)
+require_change(C)
+require_change(D)
+# There's a bug in Ninja on Windows:
+# https://gitlab.kitware.com/cmake/cmake/issues/16776
+if(NOT ("${CMAKE_GENERATOR}" MATCHES "Ninja"))
+ require_change(E)
+endif()
+
+
+# - Ensure that the timestamp will change.
+# - Change the json files referenced by A_CUSTOM_MACRO
+# - Rebuild
+acquire_timestamps(Before)
+sleep()
+message(STATUS "Changing json files")
+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")
+sleep()
+rebuild(3)
+acquire_timestamps(After)
+# Test changes
+require_change_not(A)
+require_change_not(B)
+require_change(C)
+require_change(D)
+# There's a bug in Ninja on Windows
+# https://gitlab.kitware.com/cmake/cmake/issues/16776
+if(NOT ("${CMAKE_GENERATOR}" MATCHES "Ninja"))
+ require_change(E)
+endif()
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/CMakeLists.txt b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/CMakeLists.txt
new file mode 100644
index 000000000..506828976
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/CMakeLists.txt
@@ -0,0 +1,31 @@
+cmake_minimum_required(VERSION 3.10)
+project(MocPlugin)
+include("../../AutogenGuiTest.cmake")
+
+if (QT_TEST_VERSION LESS 5)
+ message(SEND_ERROR "Qt 5 or higher required.")
+endif()
+
+set(CMAKE_AUTOMOC_DEPEND_FILTERS
+ "A_CUSTOM_MACRO"
+ "[\n][ \t]*A_CUSTOM_MACRO[ \t\r\n]*\\([^,]+,[ \t\r\n]*\"([^\"]+)\""
+)
+
+configure_file(jsonIn/StyleC.json jsonFiles/StyleC.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)
+
+include_directories("${CMAKE_CURRENT_BINARY_DIR}/jsonFiles")
+link_libraries(Qt5::Widgets)
+
+add_library(PlugA STATIC StyleA.cpp)
+add_library(PlugB STATIC StyleB.cpp)
+add_library(PlugC STATIC StyleC.cpp)
+add_library(PlugD STATIC StyleD.cpp)
+add_library(PlugE STATIC StyleE.cpp)
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.cpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.cpp
new file mode 100644
index 000000000..b5e87533c
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.cpp
@@ -0,0 +1,6 @@
+#include "StyleA.hpp"
+
+QStyle* StyleA::create(const QString& key)
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.hpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.hpp
new file mode 100644
index 000000000..35158a4b0
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.hpp
@@ -0,0 +1,17 @@
+#ifndef STYLEA_HPP
+#define STYLEA_HPP
+
+#include "UtilityMacros.hpp"
+#include <QStylePlugin>
+
+class StyleA : public QStylePlugin
+{
+ Q_OBJECT
+ // 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:
+ QStyle* create(const QString& key);
+};
+
+#endif
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.json b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.json
new file mode 100644
index 000000000..cc3395369
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA.json
@@ -0,0 +1 @@
+{ "Keys": [ "Rocket", "Starbuster" ] }
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA_Custom.json b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA_Custom.json
new file mode 100644
index 000000000..cc3395369
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleA_Custom.json
@@ -0,0 +1 @@
+{ "Keys": [ "Rocket", "Starbuster" ] }
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleB.cpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleB.cpp
new file mode 100644
index 000000000..17d440035
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleB.cpp
@@ -0,0 +1,6 @@
+#include "StyleB.hpp"
+
+QStyle* StyleB::create(const QString& key)
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleB.hpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleB.hpp
new file mode 100644
index 000000000..15b79c598
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleB.hpp
@@ -0,0 +1,17 @@
+#ifndef STYLEB_HPP
+#define STYLEB_HPP
+
+#include "UtilityMacros.hpp"
+#include <QStylePlugin>
+
+class StyleB : public QStylePlugin
+{
+ Q_OBJECT
+ // 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:
+ QStyle* create(const QString& key);
+};
+
+#endif
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleC.cpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleC.cpp
new file mode 100644
index 000000000..37e756487
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleC.cpp
@@ -0,0 +1,6 @@
+#include "StyleC.hpp"
+
+QStyle* StyleC::create(const QString& key)
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleC.hpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleC.hpp
new file mode 100644
index 000000000..b0a41150b
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleC.hpp
@@ -0,0 +1,17 @@
+#ifndef STYLEC_HPP
+#define STYLEC_HPP
+
+#include "UtilityMacros.hpp"
+#include <QStylePlugin>
+
+class StyleC : public QStylePlugin
+{
+ Q_OBJECT
+ // Json file in global root directory
+ Q_PLUGIN_METADATA(IID "org.styles.C" FILE "StyleC.json")
+ A_CUSTOM_MACRO(SomeArg, "StyleC_Custom.json", AnotherArg)
+public:
+ QStyle* create(const QString& key);
+};
+
+#endif
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleD.cpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleD.cpp
new file mode 100644
index 000000000..7e4b121fc
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleD.cpp
@@ -0,0 +1,6 @@
+#include "StyleD.hpp"
+
+QStyle* StyleD::create(const QString& key)
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleD.hpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleD.hpp
new file mode 100644
index 000000000..9696aaa26
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleD.hpp
@@ -0,0 +1,17 @@
+#ifndef STYLED_HPP
+#define STYLED_HPP
+
+#include "UtilityMacros.hpp"
+#include <QStylePlugin>
+
+class StyleD : public QStylePlugin
+{
+ Q_OBJECT
+ // Json file in global sub director
+ Q_PLUGIN_METADATA(IID "org.styles.D" FILE "sub/StyleD.json")
+ A_CUSTOM_MACRO(SomeArg, "sub/StyleD_Custom.json", AnotherArg)
+public:
+ QStyle* create(const QString& key);
+};
+
+#endif
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleE.cpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleE.cpp
new file mode 100644
index 000000000..344831969
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleE.cpp
@@ -0,0 +1,9 @@
+#include "StyleE.hpp"
+
+QStyle* StyleE::create(const QString& key)
+{
+ return 0;
+}
+
+// AUTOMOC the StyleEInclude.hpp header
+#include "moc_StyleEInclude.cpp"
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleE.hpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleE.hpp
new file mode 100644
index 000000000..a0690343d
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/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/QtAutogen/RerunMocPlugin/MocPlugin/StyleEInclude.hpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/StyleEInclude.hpp
new file mode 100644
index 000000000..f9734db4d
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/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/RerunMocPlugin/MocPlugin/UtilityMacros.hpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/UtilityMacros.hpp
new file mode 100644
index 000000000..53a4284ee
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/UtilityMacros.hpp
@@ -0,0 +1,7 @@
+#ifndef UTILITYMACROS_HPP
+#define UTILITYMACROS_HPP
+
+// Empty test macro definition
+#define A_CUSTOM_MACRO(name, jsonFile, pluginRegistrations)
+
+#endif
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleB.json b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleB.json
new file mode 100644
index 000000000..cd155dc0e
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleB.json
@@ -0,0 +1 @@
+{ "Keys": [ "Red", "Green" ] }
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleB_Custom.json b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleB_Custom.json
new file mode 100644
index 000000000..129cac41f
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleB_Custom.json
@@ -0,0 +1 @@
+{ "Keys": [ "Rocket", "StarbusterB" ] }
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleC.json b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleC.json
new file mode 100644
index 000000000..119aaa4b7
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleC.json
@@ -0,0 +1 @@
+{ "Keys": [ "Boat", "Ship" ] }
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleD.json b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleD.json
new file mode 100644
index 000000000..732c547ab
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleD.json
@@ -0,0 +1 @@
+{ "Keys": [ "Bike", "Car" ] }
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleE.json b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleE.json
new file mode 100644
index 000000000..5412c94f6
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/jsonIn/StyleE.json
@@ -0,0 +1 @@
+{ "Keys": [ "Floor", "Ceiling" ] }
diff --git a/Tests/QtAutogen/RerunMocPlugin/MocPlugin/main.cpp b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/main.cpp
new file mode 100644
index 000000000..3ba2ddc6d
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/MocPlugin/main.cpp
@@ -0,0 +1,6 @@
+#include "StyleA.hpp"
+
+int main(int argv, char** args)
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/RerunMocPlugin/dummy.cpp b/Tests/QtAutogen/RerunMocPlugin/dummy.cpp
new file mode 100644
index 000000000..4837a76b8
--- /dev/null
+++ b/Tests/QtAutogen/RerunMocPlugin/dummy.cpp
@@ -0,0 +1,5 @@
+
+int main(int argv, char** args)
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/RerunRccConfigChange/CMakeLists.txt b/Tests/QtAutogen/RerunRccConfigChange/CMakeLists.txt
new file mode 100644
index 000000000..33c01acbe
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccConfigChange/CMakeLists.txt
@@ -0,0 +1,47 @@
+cmake_minimum_required(VERSION 3.11.2)
+project(RerunRccConfigChange)
+include("../AutogenCoreTest.cmake")
+
+# Tests rcc rebuilding after a configuration change
+
+# Dummy executable to generate a clean target
+add_executable(dummy dummy.cpp)
+
+# When a .qrc or a file listed in a .qrc file changes,
+# the target must be rebuilt
+set(rccDepSD "${CMAKE_CURRENT_SOURCE_DIR}/RccConfigChange")
+set(rccDepBD "${CMAKE_CURRENT_BINARY_DIR}/RccConfigChange")
+
+# Rebuild macro
+macro(rebuild CFG)
+ message(STATUS "Rebuilding rccConfigChange in ${CFG} configuration.")
+ execute_process(
+ COMMAND "${CMAKE_COMMAND}" --build . --config "${CFG}"
+ WORKING_DIRECTORY "${rccDepBD}"
+ RESULT_VARIABLE result)
+ if (result)
+ message(FATAL_ERROR "${CFG} build of rccConfigChange failed.")
+ else()
+ message(STATUS "${CFG} build of rccConfigChange finished.")
+ endif()
+endmacro()
+
+# Initial build
+try_compile(RCC_DEPENDS
+ "${rccDepBD}"
+ "${rccDepSD}"
+ RccConfigChange
+ CMAKE_FLAGS "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
+ "-DCMAKE_AUTOGEN_VERBOSE=${CMAKE_AUTOGEN_VERBOSE}"
+ "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}"
+ OUTPUT_VARIABLE output
+)
+if (NOT RCC_DEPENDS)
+ message(FATAL_ERROR "Initial build of rccConfigChange failed. Output: ${output}")
+endif()
+
+# Rebuild: Release
+rebuild(Release)
+
+# Rebuild: Debug
+rebuild(Debug)
diff --git a/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/CMakeLists.txt b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/CMakeLists.txt
new file mode 100644
index 000000000..e2dd0ac38
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/CMakeLists.txt
@@ -0,0 +1,26 @@
+cmake_minimum_required(VERSION 3.11.2)
+project(RccConfigChange)
+include("../../AutogenCoreTest.cmake")
+
+# Enable AUTORCC for all targets
+set(CMAKE_AUTORCC ON)
+
+# Initial resource files setup
+configure_file(resGen/input1.txt.in resGen/input1.txt COPYONLY)
+configure_file(resGen/input2.txt.in resGen/input2.txt COPYONLY)
+configure_file(resGen.qrc.in resGen.qrc COPYONLY)
+
+# Generated qrc file with dependency
+add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc
+ DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/resGen.qrc.in
+ COMMAND ${CMAKE_COMMAND} -E sleep 2
+ COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/resGen.qrc.in ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc
+)
+
+# Target that uses a plain .qrc file
+add_executable(rccConfigChangePlain main.cpp resPlain.qrc)
+target_link_libraries(rccConfigChangePlain ${QT_QTCORE_TARGET})
+
+# Target that uses a GENERATED .qrc file
+add_executable(rccConfigChangeGen main.cpp ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc )
+target_link_libraries(rccConfigChangeGen ${QT_QTCORE_TARGET})
diff --git a/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/main.cpp b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/main.cpp
new file mode 100644
index 000000000..766b7751b
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/main.cpp
@@ -0,0 +1,5 @@
+
+int main()
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen.qrc.in b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen.qrc.in
new file mode 100644
index 000000000..967477252
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen.qrc.in
@@ -0,0 +1,6 @@
+<RCC>
+ <qresource prefix="/TextsGenerated">
+ <file>resGen/input1.txt</file>
+ <file>resGen/input2.txt</file>
+ </qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen/input1.txt.in b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen/input1.txt.in
new file mode 100644
index 000000000..4f24589b0
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen/input1.txt.in
@@ -0,0 +1 @@
+Generated resource input.
diff --git a/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen/input2.txt.in b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen/input2.txt.in
new file mode 100644
index 000000000..4f24589b0
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resGen/input2.txt.in
@@ -0,0 +1 @@
+Generated resource input.
diff --git a/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain.qrc b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain.qrc
new file mode 100644
index 000000000..e448726a0
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain.qrc
@@ -0,0 +1,6 @@
+<RCC>
+ <qresource prefix="/TextsPlain">
+ <file>resPlain/input1.txt</file>
+ <file>resPlain/input2.txt</file>
+ </qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain/input1.txt b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain/input1.txt
new file mode 100644
index 000000000..03969c6a5
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain/input1.txt
@@ -0,0 +1 @@
+Plain resource input.
diff --git a/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain/input2.txt b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain/input2.txt
new file mode 100644
index 000000000..03969c6a5
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccConfigChange/RccConfigChange/resPlain/input2.txt
@@ -0,0 +1 @@
+Plain resource input.
diff --git a/Tests/QtAutogen/RerunRccConfigChange/dummy.cpp b/Tests/QtAutogen/RerunRccConfigChange/dummy.cpp
new file mode 100644
index 000000000..4837a76b8
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccConfigChange/dummy.cpp
@@ -0,0 +1,5 @@
+
+int main(int argv, char** args)
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/RerunRccDepends/CMakeLists.txt b/Tests/QtAutogen/RerunRccDepends/CMakeLists.txt
new file mode 100644
index 000000000..1301550f2
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/CMakeLists.txt
@@ -0,0 +1,153 @@
+cmake_minimum_required(VERSION 3.10)
+project(RerunRccDepends)
+include("../AutogenCoreTest.cmake")
+
+# Tests rcc rebuilding when a resource file changes
+# When a .qrc or a file listed in a .qrc file changes,
+# the target must be rebuilt
+
+# Dummy executable to generate a clean target
+add_executable(dummy dummy.cpp)
+
+# Utility variables
+set(timeformat "%Y.%j.%H.%M%S")
+set(rccDepSD "${CMAKE_CURRENT_SOURCE_DIR}/RccDepends")
+set(rccDepBD "${CMAKE_CURRENT_BINARY_DIR}/RccDepends")
+
+# Utility macros
+macro(sleep)
+ message(STATUS "Sleeping for a few seconds.")
+ execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+endmacro()
+
+macro(acquire_timestamps When)
+ file(TIMESTAMP "${rccDepBinPlain}" rdPlain${When} "${timeformat}")
+ file(TIMESTAMP "${rccDepBinGenerated}" rdGenerated${When} "${timeformat}")
+endmacro()
+
+macro(rebuild buildName)
+ message(STATUS "Starting build ${buildName} of rccDepends.")
+ execute_process(
+ COMMAND "${CMAKE_COMMAND}" --build .
+ WORKING_DIRECTORY "${rccDepBD}"
+ RESULT_VARIABLE result)
+ if (result)
+ message(FATAL_ERROR "Build ${buildName} of rccDepends failed.")
+ else()
+ message(STATUS "Build ${buildName} of rccDepends finished.")
+ endif()
+endmacro()
+
+macro(require_change type)
+ if (rd${type}After VERSION_GREATER rd${type}Before)
+ message(STATUS "As expected the ${type} .qrc file ${rccDepBin${type}} changed.")
+ else()
+ message(SEND_ERROR "Unexpectedly the ${type} .qrc file ${rccDepBin${type}} did not change!\nTimestamp pre: ${rd${type}Before}\nTimestamp aft: ${rd${type}After}\n")
+ endif()
+endmacro()
+
+macro(require_change_not type)
+ if (rd${type}After VERSION_GREATER rd${type}Before)
+ message(SEND_ERROR "Unexpectedly the ${type} .qrc file ${rccDepBin${type}} changed!\nTimestamp pre: ${rd${type}Before}\nTimestamp aft: ${rd${type}After}\n")
+ else()
+ message(STATUS "As expected the ${type} .qrc file ${rccDepBin${type}} did not change.")
+ endif()
+endmacro()
+
+
+# Initial configuration
+configure_file(${rccDepSD}/resPlainA.qrc.in ${rccDepBD}/resPlain.qrc COPYONLY)
+configure_file(${rccDepSD}/resGenA.qrc.in ${rccDepBD}/resGen.qrc.in COPYONLY)
+
+# Initial build
+try_compile(RCC_DEPENDS
+ "${rccDepBD}"
+ "${rccDepSD}"
+ RccDepends
+ CMAKE_FLAGS "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
+ "-DCMAKE_AUTOGEN_VERBOSE=${CMAKE_AUTOGEN_VERBOSE}"
+ "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}"
+ OUTPUT_VARIABLE output
+)
+if (NOT RCC_DEPENDS)
+ message(FATAL_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 rccDepBinGenerated)
+message(STATUS "Target that uses a plain .qrc file is:\n ${rccDepBinPlain}")
+message(STATUS "Target that uses a GENERATED .qrc file is:\n ${rccDepBinGenerated}")
+
+# To avoid a race condition where the binary has the same timestamp
+# as a source file and therefore gets rebuild
+# - sleep to ensure a timestamp change
+# - touch binary to ensure it has a new timestamp
+acquire_timestamps(Before)
+sleep()
+message(STATUS "Touching binary files to ensure new timestamps")
+file(TOUCH_NOCREATE "${rccDepBinPlain}" "${rccDepBinGenerated}")
+acquire_timestamps(After)
+require_change(Plain)
+require_change(Generated)
+
+
+# - Ensure that the timestamp will change
+# - Change a resource files listed in the .qrc file
+# - Rebuild
+acquire_timestamps(Before)
+sleep()
+message(STATUS "Changing a resource file listed in the .qrc file")
+file(TOUCH "${rccDepBD}/resPlain/input.txt" "${rccDepBD}/resGen/input.txt")
+sleep()
+rebuild(2)
+acquire_timestamps(After)
+# - Test if timestamps changed
+require_change(Plain)
+require_change(Generated)
+
+
+# - Ensure that the timestamp will change
+# - Change the .qrc file
+# - Rebuild
+acquire_timestamps(Before)
+sleep()
+message(STATUS "Changing the .qrc file")
+configure_file(${rccDepSD}/resPlainB.qrc.in ${rccDepBD}/resPlain.qrc COPYONLY)
+configure_file(${rccDepSD}/resGenB.qrc.in ${rccDepBD}/resGen.qrc.in COPYONLY)
+sleep()
+rebuild(3)
+acquire_timestamps(After)
+# - Test if timestamps changed
+require_change(Plain)
+require_change(Generated)
+
+
+# - Ensure that the timestamp will change
+# - Change a newly added resource files listed in the .qrc file
+# - Rebuild
+acquire_timestamps(Before)
+sleep()
+message(STATUS "Changing a newly added resource file listed in the .qrc file")
+file(TOUCH "${rccDepBD}/resPlain/inputAdded.txt" "${rccDepBD}/resGen/inputAdded.txt")
+sleep()
+rebuild(4)
+acquire_timestamps(After)
+# - Test if timestamps changed
+require_change(Plain)
+require_change(Generated)
+
+
+# - Ensure that the timestamp will change
+# - Change nothing
+# - Rebuild
+acquire_timestamps(Before)
+sleep()
+message(STATUS "Changing nothing in the .qrc file")
+rebuild(5)
+acquire_timestamps(After)
+# - Test if timestamps changed
+require_change_not(Plain)
+require_change_not(Generated)
diff --git a/Tests/QtAutogen/RerunRccDepends/RccDepends/CMakeLists.txt b/Tests/QtAutogen/RerunRccDepends/RccDepends/CMakeLists.txt
new file mode 100644
index 000000000..150f849b3
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/RccDepends/CMakeLists.txt
@@ -0,0 +1,33 @@
+cmake_minimum_required(VERSION 3.10)
+project(RccDepends)
+include("../../AutogenCoreTest.cmake")
+
+# 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 ${CMAKE_CURRENT_BINARY_DIR}/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_QTCORE_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_QTCORE_TARGET})
+add_custom_command(TARGET rccDependsGen POST_BUILD COMMAND
+ ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:rccDependsGen>" > targetGen.txt
+)
diff --git a/Tests/QtAutogen/RerunRccDepends/RccDepends/main.cpp b/Tests/QtAutogen/RerunRccDepends/RccDepends/main.cpp
new file mode 100644
index 000000000..766b7751b
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/RccDepends/main.cpp
@@ -0,0 +1,5 @@
+
+int main()
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/RerunRccDepends/RccDepends/resGen/input.txt.in b/Tests/QtAutogen/RerunRccDepends/RccDepends/resGen/input.txt.in
new file mode 100644
index 000000000..4f24589b0
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/RccDepends/resGen/input.txt.in
@@ -0,0 +1 @@
+Generated resource input.
diff --git a/Tests/QtAutogen/RerunRccDepends/RccDepends/resGen/inputAdded.txt.in b/Tests/QtAutogen/RerunRccDepends/RccDepends/resGen/inputAdded.txt.in
new file mode 100644
index 000000000..4f24589b0
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/RccDepends/resGen/inputAdded.txt.in
@@ -0,0 +1 @@
+Generated resource input.
diff --git a/Tests/QtAutogen/RerunRccDepends/RccDepends/resGenA.qrc.in b/Tests/QtAutogen/RerunRccDepends/RccDepends/resGenA.qrc.in
new file mode 100644
index 000000000..c131a3460
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/RccDepends/resGenA.qrc.in
@@ -0,0 +1,5 @@
+<RCC>
+ <qresource prefix="/TextsGenerated">
+ <file>resGen/input.txt</file>
+ </qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RerunRccDepends/RccDepends/resGenB.qrc.in b/Tests/QtAutogen/RerunRccDepends/RccDepends/resGenB.qrc.in
new file mode 100644
index 000000000..8c7e64311
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/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/QtAutogen/RerunRccDepends/RccDepends/resPlain/input.txt.in b/Tests/QtAutogen/RerunRccDepends/RccDepends/resPlain/input.txt.in
new file mode 100644
index 000000000..a5e407a17
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/RccDepends/resPlain/input.txt.in
@@ -0,0 +1 @@
+Plaint resource input.
diff --git a/Tests/QtAutogen/RerunRccDepends/RccDepends/resPlain/inputAdded.txt.in b/Tests/QtAutogen/RerunRccDepends/RccDepends/resPlain/inputAdded.txt.in
new file mode 100644
index 000000000..a5e407a17
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/RccDepends/resPlain/inputAdded.txt.in
@@ -0,0 +1 @@
+Plaint resource input.
diff --git a/Tests/QtAutogen/RerunRccDepends/RccDepends/resPlainA.qrc.in b/Tests/QtAutogen/RerunRccDepends/RccDepends/resPlainA.qrc.in
new file mode 100644
index 000000000..c135d85b5
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/RccDepends/resPlainA.qrc.in
@@ -0,0 +1,5 @@
+<RCC>
+ <qresource prefix="/TextsPlain">
+ <file>resPlain/input.txt</file>
+ </qresource>
+</RCC>
diff --git a/Tests/QtAutogen/RerunRccDepends/RccDepends/resPlainB.qrc.in b/Tests/QtAutogen/RerunRccDepends/RccDepends/resPlainB.qrc.in
new file mode 100644
index 000000000..186b6535a
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/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/QtAutogen/RerunRccDepends/dummy.cpp b/Tests/QtAutogen/RerunRccDepends/dummy.cpp
new file mode 100644
index 000000000..4837a76b8
--- /dev/null
+++ b/Tests/QtAutogen/RerunRccDepends/dummy.cpp
@@ -0,0 +1,5 @@
+
+int main(int argv, char** args)
+{
+ return 0;
+}
diff --git a/Tests/QtAutogen/SameName/CMakeLists.txt b/Tests/QtAutogen/SameName/CMakeLists.txt
new file mode 100644
index 000000000..0a80d5eee
--- /dev/null
+++ b/Tests/QtAutogen/SameName/CMakeLists.txt
@@ -0,0 +1,43 @@
+cmake_minimum_required(VERSION 3.10)
+project(SameName)
+include("../AutogenGuiTest.cmake")
+
+# Test AUTOMOC and AUTORCC on source files with the same name
+# but in different subdirectories
+
+add_executable(sameName
+ aaa/bbb/item.cpp
+ aaa/bbb/data.qrc
+ aaa/item.cpp
+ aaa/data.qrc
+ bbb/aaa/item.cpp
+ bbb/aaa/data.qrc
+ bbb/item.cpp
+ bbb/data.qrc
+ ccc/item.cpp
+ ccc/data.qrc
+ item.cpp
+ object.h
+ object.h++
+ object.hpp
+ object.hxx
+ data.qrc
+ main.cpp
+)
+target_link_libraries(sameName ${QT_LIBRARIES})
+set_target_properties(sameName PROPERTIES
+ AUTOMOC TRUE
+ AUTOUIC TRUE
+ AUTORCC TRUE
+)
+
+# Set different compression levels
+if (QT_TEST_VERSION EQUAL 4)
+ set(rccCompress "-compress")
+else()
+ set(rccCompress "--compress")
+endif()
+set_target_properties(sameName PROPERTIES AUTORCC_OPTIONS "${rccCompress};1" )
+set_source_files_properties(aaa/data.qrc PROPERTIES AUTORCC_OPTIONS "${rccCompress};2" )
+set_source_files_properties(bbb/data.qrc PROPERTIES AUTORCC_OPTIONS "${rccCompress};3" )
+set_source_files_properties(ccc/data.qrc PROPERTIES AUTORCC_OPTIONS "${rccCompress};4" )
diff --git a/Tests/QtAutogen/SameName/aaa/bbb/data.qrc b/Tests/QtAutogen/SameName/aaa/bbb/data.qrc
new file mode 100644
index 000000000..0ea353756
--- /dev/null
+++ b/Tests/QtAutogen/SameName/aaa/bbb/data.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="aaa/bbb">
+ <file>item.hpp</file>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/SameName/aaa/bbb/item.cpp b/Tests/QtAutogen/SameName/aaa/bbb/item.cpp
new file mode 100644
index 000000000..850206f6b
--- /dev/null
+++ b/Tests/QtAutogen/SameName/aaa/bbb/item.cpp
@@ -0,0 +1,22 @@
+#include "item.hpp"
+
+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/bbb/item.hpp b/Tests/QtAutogen/SameName/aaa/bbb/item.hpp
new file mode 100644
index 000000000..085504385
--- /dev/null
+++ b/Tests/QtAutogen/SameName/aaa/bbb/item.hpp
@@ -0,0 +1,18 @@
+#ifndef AAA_BBB_ITEM_HPP
+#define AAA_BBB_ITEM_HPP
+
+#include <QObject>
+
+namespace aaa {
+namespace bbb {
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+}
+}
+
+#endif
diff --git a/Tests/QtAutogen/SameName/aaa/data.qrc b/Tests/QtAutogen/SameName/aaa/data.qrc
new file mode 100644
index 000000000..379af60c8
--- /dev/null
+++ b/Tests/QtAutogen/SameName/aaa/data.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="aaa/">
+ <file>item.hpp</file>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/SameName/aaa/item.cpp b/Tests/QtAutogen/SameName/aaa/item.cpp
new file mode 100644
index 000000000..e35d3d128
--- /dev/null
+++ b/Tests/QtAutogen/SameName/aaa/item.cpp
@@ -0,0 +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
new file mode 100644
index 000000000..875f72fdb
--- /dev/null
+++ b/Tests/QtAutogen/SameName/aaa/item.hpp
@@ -0,0 +1,18 @@
+#ifndef AAA_ITEM_HPP
+#define AAA_ITEM_HPP
+
+#include <QObject>
+// Include ui_view.h only in header
+#include <aaa/ui_view.h>
+
+namespace aaa {
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+}
+
+#endif
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/data.qrc b/Tests/QtAutogen/SameName/bbb/aaa/data.qrc
new file mode 100644
index 000000000..da980091a
--- /dev/null
+++ b/Tests/QtAutogen/SameName/bbb/aaa/data.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="bbb/aaa/">
+ <file>item.hpp</file>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/SameName/bbb/aaa/item.cpp b/Tests/QtAutogen/SameName/bbb/aaa/item.cpp
new file mode 100644
index 000000000..7ad01c3ef
--- /dev/null
+++ b/Tests/QtAutogen/SameName/bbb/aaa/item.cpp
@@ -0,0 +1,22 @@
+#include "item.hpp"
+
+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/aaa/item.hpp b/Tests/QtAutogen/SameName/bbb/aaa/item.hpp
new file mode 100644
index 000000000..be07ca84c
--- /dev/null
+++ b/Tests/QtAutogen/SameName/bbb/aaa/item.hpp
@@ -0,0 +1,18 @@
+#ifndef BBB_AAA_ITEM_HPP
+#define BBB_AAA_ITEM_HPP
+
+#include <QObject>
+
+namespace bbb {
+namespace aaa {
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+}
+}
+
+#endif
diff --git a/Tests/QtAutogen/SameName/bbb/data.qrc b/Tests/QtAutogen/SameName/bbb/data.qrc
new file mode 100644
index 000000000..5b080f5fa
--- /dev/null
+++ b/Tests/QtAutogen/SameName/bbb/data.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="bbb/">
+ <file>item.hpp</file>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/SameName/bbb/item.cpp b/Tests/QtAutogen/SameName/bbb/item.cpp
new file mode 100644
index 000000000..9ef128ed0
--- /dev/null
+++ b/Tests/QtAutogen/SameName/bbb/item.cpp
@@ -0,0 +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
new file mode 100644
index 000000000..d39a9d711
--- /dev/null
+++ b/Tests/QtAutogen/SameName/bbb/item.hpp
@@ -0,0 +1,17 @@
+#ifndef BBB_ITEM_HPP
+#define BBB_ITEM_HPP
+
+#include <QObject>
+// Include ui_view.h only in source
+
+namespace bbb {
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+}
+
+#endif
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/data.qrc b/Tests/QtAutogen/SameName/ccc/data.qrc
new file mode 100644
index 000000000..f934c39b9
--- /dev/null
+++ b/Tests/QtAutogen/SameName/ccc/data.qrc
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource prefix="ccc/">
+ <file>item.hpp</file>
+ <file>item.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/SameName/ccc/item.cpp b/Tests/QtAutogen/SameName/ccc/item.cpp
new file mode 100644
index 000000000..ab8a2817b
--- /dev/null
+++ b/Tests/QtAutogen/SameName/ccc/item.cpp
@@ -0,0 +1,25 @@
+#include "item.hpp"
+// Include ui_view.h in source and header
+#include <ccc/ui_view.h>
+
+namespace ccc {
+
+class MocLocal : public QObject
+{
+ Q_OBJECT;
+
+public:
+ MocLocal() = default;
+ ~MocLocal() = default;
+};
+
+void Item::go()
+{
+ Ui_ViewCCC ui;
+ MocLocal obj;
+}
+}
+
+// Include own moc files
+#include "ccc/item.moc"
+#include "moc_item.cpp"
diff --git a/Tests/QtAutogen/SameName/ccc/item.hpp b/Tests/QtAutogen/SameName/ccc/item.hpp
new file mode 100644
index 000000000..20d9dd978
--- /dev/null
+++ b/Tests/QtAutogen/SameName/ccc/item.hpp
@@ -0,0 +1,18 @@
+#ifndef CCC_ITEM_HPP
+#define CCC_ITEM_HPP
+
+#include <QObject>
+// Include ui_view.h in source and header
+#include <ccc/ui_view.h>
+
+namespace ccc {
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+}
+
+#endif
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/data.qrc b/Tests/QtAutogen/SameName/data.qrc
new file mode 100644
index 000000000..4ce0b4ec1
--- /dev/null
+++ b/Tests/QtAutogen/SameName/data.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>main.cpp</file>
+</qresource>
+</RCC>
diff --git a/Tests/QtAutogen/SameName/item.cpp b/Tests/QtAutogen/SameName/item.cpp
new file mode 100644
index 000000000..3d1fbe7cf
--- /dev/null
+++ b/Tests/QtAutogen/SameName/item.cpp
@@ -0,0 +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
new file mode 100644
index 000000000..75e83f483
--- /dev/null
+++ b/Tests/QtAutogen/SameName/item.hpp
@@ -0,0 +1,15 @@
+#ifndef ITEM_HPP
+#define ITEM_HPP
+
+#include <QObject>
+// Include ui_view.h in source and header
+#include <ui_view.h>
+
+class Item : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/SameName/main.cpp b/Tests/QtAutogen/SameName/main.cpp
new file mode 100644
index 000000000..92f15cd5f
--- /dev/null
+++ b/Tests/QtAutogen/SameName/main.cpp
@@ -0,0 +1,27 @@
+#include "aaa/bbb/item.hpp"
+#include "aaa/item.hpp"
+#include "bbb/aaa/item.hpp"
+#include "bbb/item.hpp"
+#include "ccc/item.hpp"
+#include "item.hpp"
+#include "object.h"
+#include "object.h++"
+#include "object.hpp"
+#include "object.hxx"
+
+int main(int argv, char** args)
+{
+ // Item instances
+ ::Item item;
+ ::aaa::Item aaa_item;
+ ::aaa::bbb::Item aaa_bbb_item;
+ ::bbb::Item bbb_item;
+ ::bbb::aaa::Item bbb_aaa_item;
+ ::ccc::Item ccc_item;
+ // Object instances
+ ::Object_h obj_h;
+ ::Object_hplpl obj_hplpl;
+ ::Object_hpp obj_hpp;
+ ::Object_hxx obj_hxx;
+ return 0;
+}
diff --git a/Tests/QtAutogen/SameName/object.h b/Tests/QtAutogen/SameName/object.h
new file mode 100644
index 000000000..86620941a
--- /dev/null
+++ b/Tests/QtAutogen/SameName/object.h
@@ -0,0 +1,13 @@
+#ifndef OBJECT_H
+#define OBJECT_H
+
+#include <QObject>
+
+class Object_h : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go(){};
+};
+
+#endif
diff --git a/Tests/QtAutogen/SameName/object.h++ b/Tests/QtAutogen/SameName/object.h++
new file mode 100644
index 000000000..64222b7ec
--- /dev/null
+++ b/Tests/QtAutogen/SameName/object.h++
@@ -0,0 +1,13 @@
+#ifndef OBJECT_HPLPL
+#define OBJECT_HPLPL
+
+#include <QObject>
+
+class Object_hplpl : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go(){};
+};
+
+#endif
diff --git a/Tests/QtAutogen/SameName/object.hpp b/Tests/QtAutogen/SameName/object.hpp
new file mode 100644
index 000000000..035050ec7
--- /dev/null
+++ b/Tests/QtAutogen/SameName/object.hpp
@@ -0,0 +1,13 @@
+#ifndef OBJECT_HPP
+#define OBJECT_HPP
+
+#include <QObject>
+
+class Object_hpp : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go(){};
+};
+
+#endif
diff --git a/Tests/QtAutogen/SameName/object.hxx b/Tests/QtAutogen/SameName/object.hxx
new file mode 100644
index 000000000..c3c050f13
--- /dev/null
+++ b/Tests/QtAutogen/SameName/object.hxx
@@ -0,0 +1,13 @@
+#ifndef OBJECT_HXX
+#define OBJECT_HXX
+
+#include <QObject>
+
+class Object_hxx : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go(){};
+};
+
+#endif
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/StaticLibraryCycle/CMakeLists.txt b/Tests/QtAutogen/StaticLibraryCycle/CMakeLists.txt
new file mode 100644
index 000000000..f3536ba2c
--- /dev/null
+++ b/Tests/QtAutogen/StaticLibraryCycle/CMakeLists.txt
@@ -0,0 +1,20 @@
+cmake_minimum_required(VERSION 3.10)
+project(StaticLibraryCycle)
+include("../AutogenCoreTest.cmake")
+
+# Test AUTOMOC on cyclic static libraries
+
+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..faa52e610
--- /dev/null
+++ b/Tests/QtAutogen/StaticLibraryCycle/a.cpp
@@ -0,0 +1,12 @@
+#include "a.h"
+#include "b.h"
+
+bool A::recursed = false;
+
+A::A()
+{
+ if (!A::recursed) {
+ A::recursed = true;
+ B b;
+ }
+}
diff --git a/Tests/QtAutogen/StaticLibraryCycle/a.h b/Tests/QtAutogen/StaticLibraryCycle/a.h
new file mode 100644
index 000000000..f24398e5e
--- /dev/null
+++ b/Tests/QtAutogen/StaticLibraryCycle/a.h
@@ -0,0 +1,15 @@
+#ifndef CLASSA_HPP
+#define CLASSA_HPP
+
+#include <QObject>
+
+class A : public QObject
+{
+ Q_OBJECT
+ static bool recursed;
+
+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/QtAutogen/TestMacros.cmake b/Tests/QtAutogen/TestMacros.cmake
new file mode 100644
index 000000000..0e2718807
--- /dev/null
+++ b/Tests/QtAutogen/TestMacros.cmake
@@ -0,0 +1,61 @@
+# Autogen build options
+set(Autogen_BUILD_OPTIONS "-DQT_TEST_VERSION=${QT_TEST_VERSION}")
+if(NOT _isMultiConfig) # Set in Tests/CMakeLists.txt
+ list(APPEND Autogen_BUILD_OPTIONS "-DCMAKE_BUILD_TYPE=$<CONFIGURATION>")
+endif()
+list(APPEND Autogen_BUILD_OPTIONS
+ "-DCMAKE_AUTOGEN_VERBOSE=1"
+ "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}"
+)
+
+# A macro to add a QtAutogen test
+macro(ADD_AUTOGEN_TEST NAME)
+ if(${ARGC} GREATER 1)
+ # On Windows there is no RPATH, so while Qt might be available for building,
+ # the required dlls may not be in the PATH, so we can't run the executables
+ # on that platform.
+ if(WIN32)
+ set(_TestCommand --test-command ${CMAKE_CTEST_COMMAND} -V)
+ else()
+ set(_TestCommand --test-command ${ARGN})
+ endif()
+ endif()
+
+ set(_QtXAutogen "Qt${QT_TEST_VERSION}Autogen")
+ set(_SourceDir "${CMake_SOURCE_DIR}/Tests/QtAutogen/${NAME}")
+ set(_BuildDir "${CMake_BINARY_DIR}/Tests/${_QtXAutogen}/${NAME}")
+ add_test(NAME "${_QtXAutogen}.${NAME}" COMMAND "${CMAKE_CTEST_COMMAND}"
+ --build-and-test
+ "${_SourceDir}"
+ "${_BuildDir}"
+ ${build_generator_args}
+ --build-project ${NAME}
+ --build-exe-dir "${_BuildDir}"
+ --force-new-ctest-process
+ --build-options ${build_options} ${Autogen_BUILD_OPTIONS}
+ ${_TestCommand}
+ )
+ list(APPEND TEST_BUILD_DIRS "${_BuildDir}")
+ unset(_TestCommand)
+ unset(_QtXAutogen)
+ unset(_SourceDir)
+ unset(_BuildDir)
+endmacro()
+
+# Allow using qtx_wrap_cpp and qtx_generate_moc or not
+set(QT_TEST_ALLOW_QT_MACROS TRUE)
+# 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)
+ # Qt4 moc does not support utf8 paths in _parameter files generated by
+ # qtx_wrap_cpp
+ # https://bugreports.qt.io/browse/QTBUG-35480
+ if(QT_TEST_VERSION EQUAL 4)
+ set(QT_TEST_ALLOW_QT_MACROS FALSE)
+ endif()
+ # On windows qtx_wrap_cpp also fails in Qt5 when used on a path that
+ # contains non ASCII characters
+ if(WIN32)
+ set(QT_TEST_ALLOW_QT_MACROS FALSE)
+ endif()
+endif()
diff --git a/Tests/QtAutogen/Tests.cmake b/Tests/QtAutogen/Tests.cmake
new file mode 100644
index 000000000..6771828e6
--- /dev/null
+++ b/Tests/QtAutogen/Tests.cmake
@@ -0,0 +1,48 @@
+# Qt4 and Qt5 tests
+ADD_AUTOGEN_TEST(AutogenOriginDependsOff autogenOriginDependsOff)
+ADD_AUTOGEN_TEST(AutogenOriginDependsOn)
+ADD_AUTOGEN_TEST(AutogenTargetDepends)
+ADD_AUTOGEN_TEST(Complex QtAutogen)
+ADD_AUTOGEN_TEST(GlobalAutogenTarget)
+ADD_AUTOGEN_TEST(LowMinimumVersion lowMinimumVersion)
+ADD_AUTOGEN_TEST(ManySources manySources)
+ADD_AUTOGEN_TEST(MocOnly mocOnly)
+ADD_AUTOGEN_TEST(MocOptions mocOptions)
+ADD_AUTOGEN_TEST(ObjectLibrary someProgram)
+ADD_AUTOGEN_TEST(Parallel parallel)
+ADD_AUTOGEN_TEST(Parallel1 parallel1)
+ADD_AUTOGEN_TEST(Parallel2 parallel2)
+ADD_AUTOGEN_TEST(Parallel3 parallel3)
+ADD_AUTOGEN_TEST(Parallel4 parallel4)
+ADD_AUTOGEN_TEST(ParallelAUTO parallelAUTO)
+ADD_AUTOGEN_TEST(RccEmpty rccEmpty)
+ADD_AUTOGEN_TEST(RccOffMocLibrary)
+ADD_AUTOGEN_TEST(RccOnly rccOnly)
+ADD_AUTOGEN_TEST(RccSkipSource)
+ADD_AUTOGEN_TEST(RerunMocBasic)
+ADD_AUTOGEN_TEST(RerunRccConfigChange)
+ADD_AUTOGEN_TEST(RerunRccDepends)
+ADD_AUTOGEN_TEST(SameName sameName)
+ADD_AUTOGEN_TEST(StaticLibraryCycle slc)
+ADD_AUTOGEN_TEST(UicInclude uicInclude)
+ADD_AUTOGEN_TEST(UicInterface QtAutoUicInterface)
+ADD_AUTOGEN_TEST(UicNoGui uicNoGui)
+ADD_AUTOGEN_TEST(UicOnly uicOnly)
+ADD_AUTOGEN_TEST(UicSkipSource)
+
+if(QT_TEST_ALLOW_QT_MACROS)
+ ADD_AUTOGEN_TEST(MocCMP0071)
+ ADD_AUTOGEN_TEST(MocIncludeRelaxed mocIncludeRelaxed)
+ ADD_AUTOGEN_TEST(MocIncludeStrict mocIncludeStrict)
+ ADD_AUTOGEN_TEST(MocSkipSource)
+endif()
+
+# Qt5 only tests
+if(QT_TEST_VERSION GREATER 4)
+ ADD_AUTOGEN_TEST(MocMacroName mocMacroName)
+ ADD_AUTOGEN_TEST(MocOsMacros)
+ ADD_AUTOGEN_TEST(RerunMocPlugin)
+ if(APPLE)
+ ADD_AUTOGEN_TEST(MacOsFW)
+ endif()
+endif()
diff --git a/Tests/QtAutogen/UicInclude/CMakeLists.txt b/Tests/QtAutogen/UicInclude/CMakeLists.txt
new file mode 100644
index 000000000..929868b52
--- /dev/null
+++ b/Tests/QtAutogen/UicInclude/CMakeLists.txt
@@ -0,0 +1,11 @@
+cmake_minimum_required(VERSION 3.10)
+project(UicInclude)
+include("../AutogenGuiTest.cmake")
+
+# Test uic include patterns
+set(CMAKE_AUTOUIC_SEARCH_PATHS "dirA")
+
+add_executable(uicInclude main.cpp)
+target_link_libraries(uicInclude ${QT_LIBRARIES})
+set_target_properties(uicInclude PROPERTIES AUTOUIC ON)
+set_property(TARGET uicInclude APPEND PROPERTY AUTOUIC_SEARCH_PATHS "dirB")
diff --git a/Tests/QtAutogen/UicInclude/PageC.ui b/Tests/QtAutogen/UicInclude/PageC.ui
new file mode 100644
index 000000000..bb2fb5e6a
--- /dev/null
+++ b/Tests/QtAutogen/UicInclude/PageC.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>PageC</class>
+ <widget class="QWidget" name="PageC">
+ <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/UicInclude/PageC2.ui b/Tests/QtAutogen/UicInclude/PageC2.ui
new file mode 100644
index 000000000..daab86839
--- /dev/null
+++ b/Tests/QtAutogen/UicInclude/PageC2.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>PageC2</class>
+ <widget class="QWidget" name="PageC2">
+ <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/UicInclude/dirA/PageA.ui b/Tests/QtAutogen/UicInclude/dirA/PageA.ui
new file mode 100644
index 000000000..dd8180292
--- /dev/null
+++ b/Tests/QtAutogen/UicInclude/dirA/PageA.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>PageA</class>
+ <widget class="QWidget" name="PageA">
+ <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/UicInclude/dirB/PageB.ui b/Tests/QtAutogen/UicInclude/dirB/PageB.ui
new file mode 100644
index 000000000..fa6dfa615
--- /dev/null
+++ b/Tests/QtAutogen/UicInclude/dirB/PageB.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>PageB</class>
+ <widget class="QWidget" name="PageB">
+ <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/UicInclude/dirB/PageB2.ui b/Tests/QtAutogen/UicInclude/dirB/PageB2.ui
new file mode 100644
index 000000000..2225150b5
--- /dev/null
+++ b/Tests/QtAutogen/UicInclude/dirB/PageB2.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>PageB2</class>
+ <widget class="QWidget" name="PageB2">
+ <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/UicInclude/dirB/subB/PageBsub.ui b/Tests/QtAutogen/UicInclude/dirB/subB/PageBsub.ui
new file mode 100644
index 000000000..873016ec8
--- /dev/null
+++ b/Tests/QtAutogen/UicInclude/dirB/subB/PageBsub.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>PageBsub</class>
+ <widget class="QWidget" name="PageBsub">
+ <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/UicInclude/main.cpp b/Tests/QtAutogen/UicInclude/main.cpp
new file mode 100644
index 000000000..c8e760962
--- /dev/null
+++ b/Tests/QtAutogen/UicInclude/main.cpp
@@ -0,0 +1,18 @@
+
+#include "main.hpp"
+
+int main(int argv, char** args)
+{
+ return 0;
+}
+
+// .ui files in CMAKE_AUTOUIC_SEARCH_PATHS
+#include "ui_PageA.h"
+// .ui files in AUTOUIC_SEARCH_PATHS
+#include "sub/gen/deep/ui_PageB2.h"
+#include "subB/ui_PageBsub.h"
+#include "ui_PageB.h"
+// .ui files in source's vicinity
+#include "sub/gen/deep/ui_PageC2.h"
+#include "subC/ui_PageCsub.h"
+#include "ui_PageC.h"
diff --git a/Tests/QtAutogen/UicInclude/main.hpp b/Tests/QtAutogen/UicInclude/main.hpp
new file mode 100644
index 000000000..58ddc261f
--- /dev/null
+++ b/Tests/QtAutogen/UicInclude/main.hpp
@@ -0,0 +1,6 @@
+#ifndef MAIN_HPP
+#define MAIN_HPP
+
+#include "ui_PageA.h"
+
+#endif
diff --git a/Tests/QtAutogen/UicInclude/subC/PageCsub.ui b/Tests/QtAutogen/UicInclude/subC/PageCsub.ui
new file mode 100644
index 000000000..0268326b9
--- /dev/null
+++ b/Tests/QtAutogen/UicInclude/subC/PageCsub.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>PageCsub</class>
+ <widget class="QWidget" name="PageCsub">
+ <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/UicInterface/CMakeLists.txt b/Tests/QtAutogen/UicInterface/CMakeLists.txt
new file mode 100644
index 000000000..e0227645b
--- /dev/null
+++ b/Tests/QtAutogen/UicInterface/CMakeLists.txt
@@ -0,0 +1,58 @@
+cmake_minimum_required(VERSION 3.10)
+project(UicInterface)
+include("../AutogenGuiTest.cmake")
+
+set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON)
+set(CMAKE_AUTOMOC ON)
+set(CMAKE_AUTOUIC ON)
+
+# BEGIN Upstream
+
+set(CMAKE_VERBOSE_MAKEFILE ON)
+
+add_library(KI18n klocalizedstring.cpp)
+target_link_libraries(KI18n ${QT_QTCORE_TARGET})
+
+set(autouic_options
+ -tr tr2$<$<NOT:$<BOOL:$<TARGET_PROPERTY:NO_KUIT_SEMANTIC>>>:x>i18n
+)
+if (NOT Qt5Widgets_VERSION VERSION_LESS 5.3.0)
+ list(APPEND autouic_options -include klocalizedstring.h)
+endif()
+
+set_property(TARGET KI18n APPEND PROPERTY
+ INTERFACE_AUTOUIC_OPTIONS ${autouic_options}
+)
+
+set(domainProp $<TARGET_PROPERTY:TRANSLATION_DOMAIN>)
+set(nameLower $<LOWER_CASE:$<MAKE_C_IDENTIFIER:$<TARGET_PROPERTY:NAME>>>)
+set(domain_logic
+ $<$<BOOL:${domainProp}>:${domainProp}>$<$<NOT:$<BOOL:${domainProp}>>:${nameLower}>
+)
+set_property(TARGET KI18n APPEND PROPERTY
+ INTERFACE_COMPILE_DEFINITIONS "TRANSLATION_DOMAIN=${domain_logic}"
+)
+
+# END upstream
+
+get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
+if(_isMultiConfig)
+set(INC_DIR "include_$<CONFIG>" )
+else()
+set(INC_DIR "include" )
+endif()
+
+add_library(LibWidget libwidget.cpp)
+target_link_libraries(LibWidget KI18n ${QT_LIBRARIES})
+set_property(TARGET LibWidget PROPERTY NO_KUIT_SEMANTIC ON)
+set_property(TARGET LibWidget PROPERTY TRANSLATION_DOMAIN customdomain)
+
+add_library(MyWidget mywidget.cpp)
+target_link_libraries(MyWidget KI18n ${QT_LIBRARIES})
+
+add_executable(QtAutoUicInterface main.cpp)
+target_compile_definitions(QtAutoUicInterface
+ PRIVATE
+ UI_LIBWIDGET_H="${CMAKE_CURRENT_BINARY_DIR}/LibWidget_autogen/${INC_DIR}/ui_libwidget.h"
+ UI_MYWIDGET_H="${CMAKE_CURRENT_BINARY_DIR}/MyWidget_autogen/${INC_DIR}/ui_mywidget.h"
+)
diff --git a/Tests/QtAutogen/UicInterface/klocalizedstring.cpp b/Tests/QtAutogen/UicInterface/klocalizedstring.cpp
new file mode 100644
index 000000000..b629cd176
--- /dev/null
+++ b/Tests/QtAutogen/UicInterface/klocalizedstring.cpp
@@ -0,0 +1,12 @@
+
+#include "klocalizedstring.h"
+
+QString tr2xi18n(const char* text, const char*)
+{
+ return QLatin1String("TranslatedX") + QString::fromLatin1(text);
+}
+
+QString tr2i18n(const char* text, const char*)
+{
+ return QLatin1String("Translated") + QString::fromLatin1(text);
+}
diff --git a/Tests/QtAutogen/UicInterface/klocalizedstring.h b/Tests/QtAutogen/UicInterface/klocalizedstring.h
new file mode 100644
index 000000000..6129599dc
--- /dev/null
+++ b/Tests/QtAutogen/UicInterface/klocalizedstring.h
@@ -0,0 +1,17 @@
+
+#ifndef KLOCALIZEDSTRING_H
+#define KLOCALIZEDSTRING_H
+
+#include <QString>
+
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ QString tr2xi18n(const char* text, const char* comment = 0);
+
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ QString tr2i18n(const char* text, const char* comment = 0);
+
+#endif
diff --git a/Tests/QtAutogen/UicInterface/libwidget.cpp b/Tests/QtAutogen/UicInterface/libwidget.cpp
new file mode 100644
index 000000000..008c22a96
--- /dev/null
+++ b/Tests/QtAutogen/UicInterface/libwidget.cpp
@@ -0,0 +1,14 @@
+
+#include "libwidget.h"
+
+LibWidget::LibWidget(QWidget* parent)
+ : QWidget(parent)
+ , ui(new Ui::LibWidget)
+{
+ ui->setupUi(this);
+}
+
+LibWidget::~LibWidget()
+{
+ delete ui;
+}
diff --git a/Tests/QtAutogen/UicInterface/libwidget.h b/Tests/QtAutogen/UicInterface/libwidget.h
new file mode 100644
index 000000000..a7ad14f62
--- /dev/null
+++ b/Tests/QtAutogen/UicInterface/libwidget.h
@@ -0,0 +1,25 @@
+
+#ifndef LIBWIDGET_H
+#define LIBWIDGET_H
+
+#include <QWidget>
+#include <memory>
+
+#if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
+# include <klocalizedstring.h>
+#endif
+
+#include "ui_libwidget.h"
+
+class LibWidget : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit LibWidget(QWidget* parent = 0);
+ ~LibWidget();
+
+private:
+ Ui::LibWidget* ui;
+};
+
+#endif
diff --git a/Tests/QtAutogen/UicInterface/libwidget.ui b/Tests/QtAutogen/UicInterface/libwidget.ui
new file mode 100644
index 000000000..897371e4a
--- /dev/null
+++ b/Tests/QtAutogen/UicInterface/libwidget.ui
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>LibWidget</class>
+ <widget class="QWidget" name="LibWidget">
+ <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>
+ <widget class="QLabel" name="label">
+ <property name="geometry">
+ <rect>
+ <x>180</x>
+ <y>60</y>
+ <width>57</width>
+ <height>15</height>
+ </rect>
+ </property>
+ <property name="text">
+ <string>LibLabel</string>
+ </property>
+ </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/UicInterface/main.cpp b/Tests/QtAutogen/UicInterface/main.cpp
new file mode 100644
index 000000000..68bd84363
--- /dev/null
+++ b/Tests/QtAutogen/UicInterface/main.cpp
@@ -0,0 +1,67 @@
+
+#include <fstream>
+#include <iostream>
+#include <string>
+
+int main(int argc, char** argv)
+{
+ std::ifstream f;
+ f.open(UI_LIBWIDGET_H);
+ if (!f.is_open()) {
+ std::cout << "Could not open \"" UI_LIBWIDGET_H "\"." << std::endl;
+ return -1;
+ }
+
+ {
+ bool gotTr2i18n = false;
+
+ while (!f.eof()) {
+ std::string output;
+ getline(f, output);
+ if (!gotTr2i18n) {
+ gotTr2i18n = output.find("tr2i18n") != std::string::npos;
+ }
+ if (output.find("tr2xi18n") != std::string::npos) {
+ std::cout << "ui_libwidget,h uses tr2xi18n, though it should not."
+ << std::endl;
+ return -1;
+ }
+ }
+
+ if (!gotTr2i18n) {
+ std::cout << "Did not find tr2i18n in ui_libwidget.h" << std::endl;
+ return -1;
+ }
+ }
+
+ f.close();
+ f.open(UI_MYWIDGET_H);
+ if (!f.is_open()) {
+ std::cout << "Could not open \"" UI_MYWIDGET_H "\"." << std::endl;
+ return -1;
+ }
+
+ {
+ bool gotTr2xi18n = false;
+
+ while (!f.eof()) {
+ std::string output;
+ getline(f, output);
+ if (!gotTr2xi18n) {
+ gotTr2xi18n = output.find("tr2xi18n") != std::string::npos;
+ }
+ if (output.find("tr2i18n") != std::string::npos) {
+ std::cout << "ui_mywidget,h uses tr2i18n, though it should not."
+ << std::endl;
+ return -1;
+ }
+ }
+ if (!gotTr2xi18n) {
+ std::cout << "Did not find tr2xi18n in ui_mywidget.h" << std::endl;
+ return -1;
+ }
+ }
+ f.close();
+
+ return 0;
+}
diff --git a/Tests/QtAutogen/UicInterface/mywidget.cpp b/Tests/QtAutogen/UicInterface/mywidget.cpp
new file mode 100644
index 000000000..7cf1a1318
--- /dev/null
+++ b/Tests/QtAutogen/UicInterface/mywidget.cpp
@@ -0,0 +1,14 @@
+
+#include "mywidget.h"
+
+MyWidget::MyWidget(QWidget* parent)
+ : QWidget(parent)
+ , ui(new Ui::MyWidget)
+{
+ ui->setupUi(this);
+}
+
+MyWidget::~MyWidget()
+{
+ delete ui;
+}
diff --git a/Tests/QtAutogen/UicInterface/mywidget.h b/Tests/QtAutogen/UicInterface/mywidget.h
new file mode 100644
index 000000000..1d31ce7a7
--- /dev/null
+++ b/Tests/QtAutogen/UicInterface/mywidget.h
@@ -0,0 +1,25 @@
+
+#ifndef MYWIDGET_H
+#define MYWIDGET_H
+
+#include <QWidget>
+#include <memory>
+
+#if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
+# include <klocalizedstring.h>
+#endif
+
+#include "ui_mywidget.h"
+
+class MyWidget : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit MyWidget(QWidget* parent = 0);
+ ~MyWidget();
+
+private:
+ Ui::MyWidget* ui;
+};
+
+#endif
diff --git a/Tests/QtAutogen/UicInterface/mywidget.ui b/Tests/QtAutogen/UicInterface/mywidget.ui
new file mode 100644
index 000000000..b2b9cc592
--- /dev/null
+++ b/Tests/QtAutogen/UicInterface/mywidget.ui
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>MyWidget</class>
+ <widget class="QWidget" name="MyWidget">
+ <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>
+ <widget class="QPushButton" name="pushButton">
+ <property name="geometry">
+ <rect>
+ <x>110</x>
+ <y>40</y>
+ <width>81</width>
+ <height>23</height>
+ </rect>
+ </property>
+ <property name="text">
+ <string>Special button</string>
+ </property>
+ </widget>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/UicNoGui/CMakeLists.txt b/Tests/QtAutogen/UicNoGui/CMakeLists.txt
new file mode 100644
index 000000000..076299db1
--- /dev/null
+++ b/Tests/QtAutogen/UicNoGui/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.13)
+project(UicNoGui)
+include("../AutogenCoreTest.cmake")
+
+# This tests creates a target that has AUTOUIC enabled but does not
+# link against QtXWidgets.
+
+set(CMAKE_AUTOMOC ON)
+set(CMAKE_AUTOUIC ON)
+set(CMAKE_AUTORCC ON)
+
+add_subdirectory(MocOnly)
+add_subdirectory(NoQt)
+
+add_executable(uicNoGui main.cpp)
+target_link_libraries(uicNoGui mocOnly noQt)
diff --git a/Tests/QtAutogen/UicNoGui/MocOnly/CMakeLists.txt b/Tests/QtAutogen/UicNoGui/MocOnly/CMakeLists.txt
new file mode 100644
index 000000000..4fcd75fa0
--- /dev/null
+++ b/Tests/QtAutogen/UicNoGui/MocOnly/CMakeLists.txt
@@ -0,0 +1,3 @@
+# Library uses QtCore only (no Widgets)
+add_library(mocOnly main.cpp)
+target_link_libraries(mocOnly ${QT_QTCORE_TARGET})
diff --git a/Tests/QtAutogen/UicNoGui/MocOnly/main.cpp b/Tests/QtAutogen/UicNoGui/MocOnly/main.cpp
new file mode 100644
index 000000000..3091845ef
--- /dev/null
+++ b/Tests/QtAutogen/UicNoGui/MocOnly/main.cpp
@@ -0,0 +1,15 @@
+#include <QObject>
+
+class LocalObject : public QObject
+{
+ Q_OBJECT
+public:
+ LocalObject(){};
+};
+
+void mocOnly()
+{
+ LocalObject obj;
+}
+
+#include "main.moc"
diff --git a/Tests/QtAutogen/UicNoGui/NoQt/CMakeLists.txt b/Tests/QtAutogen/UicNoGui/NoQt/CMakeLists.txt
new file mode 100644
index 000000000..f2bf3eec1
--- /dev/null
+++ b/Tests/QtAutogen/UicNoGui/NoQt/CMakeLists.txt
@@ -0,0 +1,2 @@
+# Library doesn't use or link against Qt at all
+add_library(noQt main.cpp)
diff --git a/Tests/QtAutogen/UicNoGui/NoQt/main.cpp b/Tests/QtAutogen/UicNoGui/NoQt/main.cpp
new file mode 100644
index 000000000..0052cc864
--- /dev/null
+++ b/Tests/QtAutogen/UicNoGui/NoQt/main.cpp
@@ -0,0 +1,4 @@
+
+void noQt()
+{
+}
diff --git a/Tests/QtAutogen/UicNoGui/main.cpp b/Tests/QtAutogen/UicNoGui/main.cpp
new file mode 100644
index 000000000..e90c60aa5
--- /dev/null
+++ b/Tests/QtAutogen/UicNoGui/main.cpp
@@ -0,0 +1,9 @@
+extern void mocOnly();
+extern void noQt();
+
+int main(int argc, char* argv[])
+{
+ mocOnly();
+ noQt();
+ return 0;
+}
diff --git a/Tests/QtAutogen/UicOnly/CMakeLists.txt b/Tests/QtAutogen/UicOnly/CMakeLists.txt
new file mode 100644
index 000000000..b16325438
--- /dev/null
+++ b/Tests/QtAutogen/UicOnly/CMakeLists.txt
@@ -0,0 +1,8 @@
+cmake_minimum_required(VERSION 3.10)
+project(UicOnly)
+include("../AutogenGuiTest.cmake")
+
+# Test AUTOUIC being enabled only
+add_executable(uicOnly main.cpp UicOnly.cpp)
+set_property(TARGET uicOnly PROPERTY AUTOUIC ON)
+target_link_libraries(uicOnly ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/UicOnly/UicOnly.cpp b/Tests/QtAutogen/UicOnly/UicOnly.cpp
new file mode 100644
index 000000000..8eee6d213
--- /dev/null
+++ b/Tests/QtAutogen/UicOnly/UicOnly.cpp
@@ -0,0 +1,18 @@
+#include "ui_uiC.h"
+#include "ui_uiD.h"
+// AUTOUIC includes on the first two lines of a source file
+#include "UicOnly.hpp"
+
+UicOnly::UicOnly()
+ : uiA(new Ui::UiA)
+ , uiB(new Ui::UiB)
+{
+ Ui::UiC uiC;
+ Ui::UiD uiD;
+}
+
+UicOnly::~UicOnly()
+{
+ delete uiB;
+ delete uiA;
+}
diff --git a/Tests/QtAutogen/UicOnly/UicOnly.hpp b/Tests/QtAutogen/UicOnly/UicOnly.hpp
new file mode 100644
index 000000000..24e1e0b94
--- /dev/null
+++ b/Tests/QtAutogen/UicOnly/UicOnly.hpp
@@ -0,0 +1,15 @@
+#include "ui_uiA.h"
+#include "ui_uiB.h"
+// AUTOUIC includes on the first two lines of a header file
+#include <QObject>
+
+class UicOnly : public QObject
+{
+public:
+ UicOnly();
+ ~UicOnly();
+
+private:
+ Ui::UiA* uiA;
+ Ui::UiB* uiB;
+};
diff --git a/Tests/QtAutogen/UicOnly/main.cpp b/Tests/QtAutogen/UicOnly/main.cpp
new file mode 100644
index 000000000..bdd242ec2
--- /dev/null
+++ b/Tests/QtAutogen/UicOnly/main.cpp
@@ -0,0 +1,7 @@
+#include "UicOnly.hpp"
+
+int main(int argc, char* argv[])
+{
+ UicOnly uicOnly;
+ return 0;
+}
diff --git a/Tests/QtAutogen/UicOnly/uiA.ui b/Tests/QtAutogen/UicOnly/uiA.ui
new file mode 100644
index 000000000..4c5762e82
--- /dev/null
+++ b/Tests/QtAutogen/UicOnly/uiA.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>UiA</class>
+ <widget class="QWidget" name="UiA">
+ <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/UicOnly/uiB.ui b/Tests/QtAutogen/UicOnly/uiB.ui
new file mode 100644
index 000000000..6ca77dec3
--- /dev/null
+++ b/Tests/QtAutogen/UicOnly/uiB.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>UiB</class>
+ <widget class="QWidget" name="UiB">
+ <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/UicOnly/uiC.ui b/Tests/QtAutogen/UicOnly/uiC.ui
new file mode 100644
index 000000000..6802550cb
--- /dev/null
+++ b/Tests/QtAutogen/UicOnly/uiC.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>UiC</class>
+ <widget class="QWidget" name="UiC">
+ <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/UicOnly/uiD.ui b/Tests/QtAutogen/UicOnly/uiD.ui
new file mode 100644
index 000000000..aad79cf7f
--- /dev/null
+++ b/Tests/QtAutogen/UicOnly/uiD.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>UiD</class>
+ <widget class="QWidget" name="UiD">
+ <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/UicSkipSource/CMakeLists.txt b/Tests/QtAutogen/UicSkipSource/CMakeLists.txt
new file mode 100644
index 000000000..dc3b7d4eb
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/CMakeLists.txt
@@ -0,0 +1,22 @@
+cmake_minimum_required(VERSION 3.10)
+project(UicSkipSource)
+include("../AutogenGuiTest.cmake")
+
+# Test for SKIP_AUTOUIC and SKIP_AUTOGEN on an AUTOUIC enabled target
+set(skipUicSources
+ skipUic.cpp
+ skipUicGen.cpp
+ skipUicNoGen1.cpp
+ skipUicNoGen2.cpp
+)
+set_property(SOURCE skipUicNoGen1.cpp PROPERTY SKIP_AUTOUIC ON)
+set_property(SOURCE skipUicNoGen2.cpp PROPERTY SKIP_AUTOGEN ON)
+# AUTOUIC enabled
+add_executable(skipUicA ${skipUicSources})
+set_property(TARGET skipUicA PROPERTY AUTOUIC ON)
+target_link_libraries(skipUicA ${QT_LIBRARIES})
+# AUTOUIC and AUTOMOC enabled
+add_executable(skipUicB ${skipUicSources})
+set_property(TARGET skipUicB PROPERTY AUTOUIC ON)
+set_property(TARGET skipUicB PROPERTY AUTOMOC ON)
+target_link_libraries(skipUicB ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/UicSkipSource/skipUic.cpp b/Tests/QtAutogen/UicSkipSource/skipUic.cpp
new file mode 100644
index 000000000..c4a7ce95b
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/skipUic.cpp
@@ -0,0 +1,22 @@
+
+#include "skipUicGen.hpp"
+#include "skipUicNoGen1.hpp"
+#include "skipUicNoGen2.hpp"
+
+int main(int, char**)
+{
+ skipGen();
+ skipNoGen1();
+ skipNoGen2();
+
+ return 0;
+}
+
+// -- Function definitions
+void ui_nogen1()
+{
+}
+
+void ui_nogen2()
+{
+}
diff --git a/Tests/QtAutogen/UicSkipSource/skipUicGen.cpp b/Tests/QtAutogen/UicSkipSource/skipUicGen.cpp
new file mode 100644
index 000000000..d2a55a6f1
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/skipUicGen.cpp
@@ -0,0 +1,7 @@
+
+#include "skipUicGen.hpp"
+#include "ui_uigen2.h"
+
+void skipGen()
+{
+}
diff --git a/Tests/QtAutogen/UicSkipSource/skipUicGen.hpp b/Tests/QtAutogen/UicSkipSource/skipUicGen.hpp
new file mode 100644
index 000000000..3669f0e5b
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/skipUicGen.hpp
@@ -0,0 +1,8 @@
+#ifndef SKIPUICGEN_HPP
+#define SKIPUICGEN_HPP
+
+#include "ui_uigen1.h"
+
+void skipGen();
+
+#endif
diff --git a/Tests/QtAutogen/UicSkipSource/skipUicNoGen1.cpp b/Tests/QtAutogen/UicSkipSource/skipUicNoGen1.cpp
new file mode 100644
index 000000000..f591a42ba
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/skipUicNoGen1.cpp
@@ -0,0 +1,7 @@
+
+#include "skipUicNoGen1.hpp"
+#include "ui_nogen2.h"
+
+void skipNoGen1()
+{
+}
diff --git a/Tests/QtAutogen/UicSkipSource/skipUicNoGen1.hpp b/Tests/QtAutogen/UicSkipSource/skipUicNoGen1.hpp
new file mode 100644
index 000000000..286469598
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/skipUicNoGen1.hpp
@@ -0,0 +1,8 @@
+#ifndef SKIPUICNOGEN1_H
+#define SKIPUICNOGEN1_H
+
+#include "ui_nogen1.h"
+
+void skipNoGen1();
+
+#endif
diff --git a/Tests/QtAutogen/UicSkipSource/skipUicNoGen2.cpp b/Tests/QtAutogen/UicSkipSource/skipUicNoGen2.cpp
new file mode 100644
index 000000000..8c1c3241c
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/skipUicNoGen2.cpp
@@ -0,0 +1,7 @@
+
+#include "skipUicNoGen2.hpp"
+#include "ui_nogen2.h"
+
+void skipNoGen2()
+{
+}
diff --git a/Tests/QtAutogen/UicSkipSource/skipUicNoGen2.hpp b/Tests/QtAutogen/UicSkipSource/skipUicNoGen2.hpp
new file mode 100644
index 000000000..7c381938c
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/skipUicNoGen2.hpp
@@ -0,0 +1,8 @@
+#ifndef SKIPUICNOGEN2_H
+#define SKIPUICNOGEN2_H
+
+#include "ui_nogen1.h"
+
+void skipNoGen2();
+
+#endif
diff --git a/Tests/QtAutogen/UicSkipSource/ui_nogen1.h b/Tests/QtAutogen/UicSkipSource/ui_nogen1.h
new file mode 100644
index 000000000..a7be52bce
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/ui_nogen1.h
@@ -0,0 +1,6 @@
+#ifndef UI_NOGEN1_H
+#define UI_NOGEN1_H
+
+void ui_nogen1();
+
+#endif
diff --git a/Tests/QtAutogen/UicSkipSource/ui_nogen2.h b/Tests/QtAutogen/UicSkipSource/ui_nogen2.h
new file mode 100644
index 000000000..4e500a44d
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/ui_nogen2.h
@@ -0,0 +1,6 @@
+#ifndef UI_NOGEN2_H
+#define UI_NOGEN2_H
+
+void ui_nogen2();
+
+#endif
diff --git a/Tests/QtAutogen/UicSkipSource/uigen1.ui b/Tests/QtAutogen/UicSkipSource/uigen1.ui
new file mode 100644
index 000000000..fc7cb8219
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/uigen1.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>UiGen1</class>
+ <widget class="QWidget" name="UiGen1">
+ <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/UicSkipSource/uigen2.ui b/Tests/QtAutogen/UicSkipSource/uigen2.ui
new file mode 100644
index 000000000..01f08d2ef
--- /dev/null
+++ b/Tests/QtAutogen/UicSkipSource/uigen2.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>UiGen2</class>
+ <widget class="QWidget" name="UiGen2">
+ <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/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/Android/android_lib.cxx b/Tests/RunCMake/Android/android_lib.cxx
new file mode 100644
index 000000000..82f9d27bb
--- /dev/null
+++ b/Tests/RunCMake/Android/android_lib.cxx
@@ -0,0 +1,4 @@
+int android_lib()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/Android/check_binary.cmake b/Tests/RunCMake/Android/check_binary.cmake
new file mode 100644
index 000000000..1d1b01a5d
--- /dev/null
+++ b/Tests/RunCMake/Android/check_binary.cmake
@@ -0,0 +1,8 @@
+if(NOT EXISTS "${file}")
+ message(FATAL_ERROR "Missing file:\n ${file}")
+endif()
+execute_process(COMMAND "${objdump}" -p ${file} OUTPUT_VARIABLE out)
+if(out MATCHES "NEEDED[^\n]*stdc\\+\\+")
+ string(REPLACE "\n" "\n " out " ${out}")
+ message(FATAL_ERROR "File:\n ${file}\ndepends on libstdc++:\n${out}")
+endif()
diff --git a/Tests/RunCMake/Autogen/CMakeLists.txt b/Tests/RunCMake/Autogen/CMakeLists.txt
new file mode 100644
index 000000000..9a66cde9b
--- /dev/null
+++ b/Tests/RunCMake/Autogen/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.13)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/Autogen/NoQt-stderr.txt b/Tests/RunCMake/Autogen/NoQt-stderr.txt
new file mode 100644
index 000000000..1c6660a5e
--- /dev/null
+++ b/Tests/RunCMake/Autogen/NoQt-stderr.txt
@@ -0,0 +1,8 @@
+^CMake Warning \(dev\) in CMakeLists.txt:
+ AUTOGEN: No valid Qt version found for target main. AUTOMOC, AUTOUIC and
+ AUTORCC disabled. Consider adding:
+
+ find_package\(Qt<QTVERSION> COMPONENTS Widgets\)
+
+ to your CMakeLists.txt file.
+This warning is for project developers. Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/Autogen/NoQt.cmake b/Tests/RunCMake/Autogen/NoQt.cmake
new file mode 100644
index 000000000..b2d375ac6
--- /dev/null
+++ b/Tests/RunCMake/Autogen/NoQt.cmake
@@ -0,0 +1,6 @@
+enable_language(CXX)
+
+add_executable(main empty.cpp)
+set_property(TARGET main PROPERTY AUTOMOC 1)
+set_property(TARGET main PROPERTY AUTORCC 1)
+set_property(TARGET main PROPERTY AUTOUIC 1)
diff --git a/Tests/RunCMake/Autogen/QtInFunction.cmake b/Tests/RunCMake/Autogen/QtInFunction.cmake
new file mode 100644
index 000000000..a44bc5ab4
--- /dev/null
+++ b/Tests/RunCMake/Autogen/QtInFunction.cmake
@@ -0,0 +1,13 @@
+enable_language(CXX)
+
+function (use_autogen target)
+ find_package(Qt5 REQUIRED COMPONENTS Core Widgets)
+ set(Qt5Core_VERSION_MAJOR "${Qt5Core_VERSION_MAJOR}" PARENT_SCOPE)
+ set(Qt5Core_VERSION_MINOR "${Qt5Core_VERSION_MINOR}" PARENT_SCOPE)
+ set_property(TARGET "${target}" PROPERTY AUTOMOC 1)
+ set_property(TARGET "${target}" PROPERTY AUTORCC 1)
+ set_property(TARGET "${target}" PROPERTY AUTOUIC 1)
+endfunction ()
+
+add_executable(main empty.cpp)
+use_autogen(main)
diff --git a/Tests/RunCMake/Autogen/QtInFunctionNested-stderr.txt b/Tests/RunCMake/Autogen/QtInFunctionNested-stderr.txt
new file mode 100644
index 000000000..1c6660a5e
--- /dev/null
+++ b/Tests/RunCMake/Autogen/QtInFunctionNested-stderr.txt
@@ -0,0 +1,8 @@
+^CMake Warning \(dev\) in CMakeLists.txt:
+ AUTOGEN: No valid Qt version found for target main. AUTOMOC, AUTOUIC and
+ AUTORCC disabled. Consider adding:
+
+ find_package\(Qt<QTVERSION> COMPONENTS Widgets\)
+
+ to your CMakeLists.txt file.
+This warning is for project developers. Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/Autogen/QtInFunctionNested.cmake b/Tests/RunCMake/Autogen/QtInFunctionNested.cmake
new file mode 100644
index 000000000..5421ba00d
--- /dev/null
+++ b/Tests/RunCMake/Autogen/QtInFunctionNested.cmake
@@ -0,0 +1,17 @@
+enable_language(CXX)
+
+function (use_autogen target)
+ find_package(Qt5 REQUIRED COMPONENTS Core Widgets)
+ set(Qt5Core_VERSION_MAJOR "${Qt5Core_VERSION_MAJOR}" PARENT_SCOPE)
+ set(Qt5Core_VERSION_MINOR "${Qt5Core_VERSION_MINOR}" PARENT_SCOPE)
+ set_property(TARGET "${target}" PROPERTY AUTOMOC 1)
+ set_property(TARGET "${target}" PROPERTY AUTORCC 1)
+ set_property(TARGET "${target}" PROPERTY AUTOUIC 1)
+endfunction ()
+
+function (wrap_autogen target)
+ use_autogen("${target}")
+endfunction ()
+
+add_executable(main empty.cpp)
+wrap_autogen(main)
diff --git a/Tests/RunCMake/Autogen/QtInFunctionProperty.cmake b/Tests/RunCMake/Autogen/QtInFunctionProperty.cmake
new file mode 100644
index 000000000..35f1cd16c
--- /dev/null
+++ b/Tests/RunCMake/Autogen/QtInFunctionProperty.cmake
@@ -0,0 +1,21 @@
+enable_language(CXX)
+
+function (use_autogen target)
+ find_package(Qt5 REQUIRED COMPONENTS Core Widgets)
+ set_property(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+ PROPERTY
+ Qt5Core_VERSION_MAJOR "${Qt5Core_VERSION_MAJOR}")
+ set_property(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+ PROPERTY
+ Qt5Core_VERSION_MINOR "${Qt5Core_VERSION_MINOR}")
+ set_property(TARGET "${target}" PROPERTY AUTOMOC 1)
+ set_property(TARGET "${target}" PROPERTY AUTORCC 1)
+ set_property(TARGET "${target}" PROPERTY AUTOUIC 1)
+endfunction ()
+
+function (wrap_autogen target)
+ use_autogen("${target}")
+endfunction ()
+
+add_executable(main empty.cpp)
+wrap_autogen(main)
diff --git a/Tests/RunCMake/Autogen/RunCMakeTest.cmake b/Tests/RunCMake/Autogen/RunCMakeTest.cmake
new file mode 100644
index 000000000..a31b67cd7
--- /dev/null
+++ b/Tests/RunCMake/Autogen/RunCMakeTest.cmake
@@ -0,0 +1,8 @@
+include(RunCMake)
+
+run_cmake(NoQt)
+if (with_qt5)
+ run_cmake(QtInFunction)
+ run_cmake(QtInFunctionNested)
+ run_cmake(QtInFunctionProperty)
+endif ()
diff --git a/Tests/RunCMake/Autogen/empty.cpp b/Tests/RunCMake/Autogen/empty.cpp
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/Autogen/empty.cpp
diff --git a/Tests/RunCMake/BuildDepends/BuildUnderSource.c b/Tests/RunCMake/BuildDepends/BuildUnderSource.c
new file mode 100644
index 000000000..688a040b7
--- /dev/null
+++ b/Tests/RunCMake/BuildDepends/BuildUnderSource.c
@@ -0,0 +1,5 @@
+#include "BuildUnderSource.h"
+int main(void)
+{
+ return BUILD_UNDER_SOURCE;
+}
diff --git a/Tests/RunCMake/BuildDepends/BuildUnderSource.cmake b/Tests/RunCMake/BuildDepends/BuildUnderSource.cmake
new file mode 100644
index 000000000..aa2a44f46
--- /dev/null
+++ b/Tests/RunCMake/BuildDepends/BuildUnderSource.cmake
@@ -0,0 +1,9 @@
+enable_language(C)
+include_directories(include)
+add_executable(BuildUnderSource BuildUnderSource.c)
+
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
+set(check_pairs
+ \"$<TARGET_FILE:BuildUnderSource>|${CMAKE_CURRENT_SOURCE_DIR}/include/BuildUnderSource.h\"
+ )
+")
diff --git a/Tests/RunCMake/BuildDepends/BuildUnderSource.step1.cmake b/Tests/RunCMake/BuildDepends/BuildUnderSource.step1.cmake
new file mode 100644
index 000000000..2cdd32be9
--- /dev/null
+++ b/Tests/RunCMake/BuildDepends/BuildUnderSource.step1.cmake
@@ -0,0 +1,3 @@
+file(WRITE "${RunCMake_TEST_SOURCE_DIR}/include/BuildUnderSource.h" [[
+#define BUILD_UNDER_SOURCE 1
+]])
diff --git a/Tests/RunCMake/BuildDepends/BuildUnderSource.step2.cmake b/Tests/RunCMake/BuildDepends/BuildUnderSource.step2.cmake
new file mode 100644
index 000000000..8e4b858e5
--- /dev/null
+++ b/Tests/RunCMake/BuildDepends/BuildUnderSource.step2.cmake
@@ -0,0 +1,3 @@
+file(WRITE "${RunCMake_TEST_SOURCE_DIR}/include/BuildUnderSource.h" [[
+#define BUILD_UNDER_SOURCE 2
+]])
diff --git a/Tests/RunCMake/BundleUtilities/CMP0080-COMMAND.cmake b/Tests/RunCMake/BundleUtilities/CMP0080-COMMAND.cmake
new file mode 100644
index 000000000..063a7f3a7
--- /dev/null
+++ b/Tests/RunCMake/BundleUtilities/CMP0080-COMMAND.cmake
@@ -0,0 +1,5 @@
+if(DEFINED CMP0080_VALUE)
+ cmake_policy(SET CMP0080 ${CMP0080_VALUE})
+endif()
+
+include(BundleUtilities)
diff --git a/Tests/RunCMake/BundleUtilities/CMP0080-NEW-result.txt b/Tests/RunCMake/BundleUtilities/CMP0080-NEW-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/BundleUtilities/CMP0080-NEW-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/BundleUtilities/CMP0080-NEW-stderr.txt b/Tests/RunCMake/BundleUtilities/CMP0080-NEW-stderr.txt
new file mode 100644
index 000000000..1454b0c82
--- /dev/null
+++ b/Tests/RunCMake/BundleUtilities/CMP0080-NEW-stderr.txt
@@ -0,0 +1,2 @@
+CMake Error at .*/Modules/BundleUtilities\.cmake:[0-9]+ \(message\):
+ BundleUtilities cannot be included at configure time!
diff --git a/Tests/RunCMake/BundleUtilities/CMP0080-NEW.cmake b/Tests/RunCMake/BundleUtilities/CMP0080-NEW.cmake
new file mode 100644
index 000000000..558c16d16
--- /dev/null
+++ b/Tests/RunCMake/BundleUtilities/CMP0080-NEW.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0080 NEW)
+include(BundleUtilities)
diff --git a/Tests/RunCMake/BundleUtilities/CMP0080-OLD.cmake b/Tests/RunCMake/BundleUtilities/CMP0080-OLD.cmake
new file mode 100644
index 000000000..a65d92f11
--- /dev/null
+++ b/Tests/RunCMake/BundleUtilities/CMP0080-OLD.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0080 OLD)
+include(BundleUtilities)
diff --git a/Tests/RunCMake/BundleUtilities/CMP0080-WARN-stderr.txt b/Tests/RunCMake/BundleUtilities/CMP0080-WARN-stderr.txt
new file mode 100644
index 000000000..c3d541e47
--- /dev/null
+++ b/Tests/RunCMake/BundleUtilities/CMP0080-WARN-stderr.txt
@@ -0,0 +1,10 @@
+CMake Warning \(dev\) at .*/Modules/BundleUtilities\.cmake:[0-9]+ \(message\):
+ Policy CMP0080 is not set: BundleUtilities cannot be included at configure
+ time\. Run "cmake --help-policy CMP0080" for policy details\. Use the
+ cmake_policy command to set the policy and suppress this warning\.
+
+Call Stack \(most recent call first\):
+ .*/Modules/BundleUtilities\.cmake:[0-9]+ \(_warn_cmp0080\)
+ CMP0080-WARN\.cmake:[0-9]+ \(include\)
+ CMakeLists\.txt:[0-9]+ \(include\)
+This warning is for project developers\. Use -Wno-dev to suppress it\.
diff --git a/Tests/RunCMake/BundleUtilities/CMP0080-WARN.cmake b/Tests/RunCMake/BundleUtilities/CMP0080-WARN.cmake
new file mode 100644
index 000000000..45f6f92b9
--- /dev/null
+++ b/Tests/RunCMake/BundleUtilities/CMP0080-WARN.cmake
@@ -0,0 +1 @@
+include(BundleUtilities)
diff --git a/Tests/RunCMake/BundleUtilities/CMakeLists.txt b/Tests/RunCMake/BundleUtilities/CMakeLists.txt
new file mode 100644
index 000000000..6dd8cdf55
--- /dev/null
+++ b/Tests/RunCMake/BundleUtilities/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.4)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/BundleUtilities/RunCMakeTest.cmake b/Tests/RunCMake/BundleUtilities/RunCMakeTest.cmake
new file mode 100644
index 000000000..14aaff197
--- /dev/null
+++ b/Tests/RunCMake/BundleUtilities/RunCMakeTest.cmake
@@ -0,0 +1,11 @@
+cmake_minimum_required(VERSION 3.4)
+include(RunCMake)
+
+# TODO Migrate Tests/BundleUtilities here
+
+run_cmake(CMP0080-OLD)
+run_cmake(CMP0080-NEW)
+run_cmake(CMP0080-WARN)
+run_cmake_command(CMP0080-COMMAND-OLD ${CMAKE_COMMAND} -DCMP0080_VALUE:STRING=OLD -P ${RunCMake_SOURCE_DIR}/CMP0080-COMMAND.cmake)
+run_cmake_command(CMP0080-COMMAND-NEW ${CMAKE_COMMAND} -DCMP0080_VALUE:STRING=NEW -P ${RunCMake_SOURCE_DIR}/CMP0080-COMMAND.cmake)
+run_cmake_command(CMP0080-COMMAND-WARN ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/CMP0080-COMMAND.cmake)
diff --git a/Tests/RunCMake/Byproducts/CMakeLists.txt b/Tests/RunCMake/Byproducts/CMakeLists.txt
new file mode 100644
index 000000000..bf2ef1506
--- /dev/null
+++ b/Tests/RunCMake/Byproducts/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/Byproducts/CleanByproducts.cmake b/Tests/RunCMake/Byproducts/CleanByproducts.cmake
new file mode 100644
index 000000000..85d958295
--- /dev/null
+++ b/Tests/RunCMake/Byproducts/CleanByproducts.cmake
@@ -0,0 +1,93 @@
+cmake_minimum_required(VERSION 3.10)
+project(CleanByproducts)
+
+# Configurable parameters
+set(TEST_CLEAN_NO_CUSTOM FALSE CACHE BOOL "Value for the CLEAN_NO_CUSTOM PROPERTY")
+set(TEST_BUILD_EVENTS TRUE CACHE BOOL "Create byproducts with build events")
+set(TEST_CUSTOM_TARGET TRUE CACHE BOOL "Create a byproduct with a custom target")
+set(TEST_CUSTOM_COMMAND TRUE CACHE BOOL "Create a byproduct with a custom command")
+
+set_property(DIRECTORY PROPERTY CLEAN_NO_CUSTOM ${TEST_CLEAN_NO_CUSTOM})
+
+macro(add_build_event)
+ set(oneValueArgs EVENT)
+
+ cmake_parse_Arguments(ABE "" "${oneValueArgs}" "" ${ARGN})
+
+ # Create two byproducts and only declare one
+ add_custom_command(TARGET foo
+ ${ABE_EVENT}
+ COMMAND ${CMAKE_COMMAND} -E touch foo.${ABE_EVENT}
+ COMMAND ${CMAKE_COMMAND} -E touch foo.${ABE_EVENT}.notdeclared
+ COMMENT "Creating byproducts with ${ABE_EVENT}"
+ BYPRODUCTS foo.${ABE_EVENT}
+ )
+
+ # The nondeclared byproduct should always be present
+ list(APPEND EXPECTED_PRESENT foo.${ABE_EVENT}.notdeclared)
+
+ # If CLEAN_NO_CUSTOM is set, the declared byproduct should be present
+ if(TEST_CLEAN_NO_CUSTOM)
+ list(APPEND EXPECTED_PRESENT foo.${ABE_EVENT})
+ else()
+ list(APPEND EXPECTED_DELETED foo.${ABE_EVENT})
+ endif()
+endmacro()
+
+add_executable(foo foo.cpp)
+
+# Test build events
+if(TEST_BUILD_EVENTS)
+ add_build_event(EVENT "PRE_BUILD" ENABLE ${TEST_PRE_BUILD})
+ add_build_event(EVENT "PRE_LINK" ENABLE ${TEST_PRE_LINK})
+ add_build_event(EVENT "POST_BUILD" ENABLE ${TEST_POST_BUILD})
+endif()
+
+# Custom command that generates byproducts
+if(TEST_CUSTOM_COMMAND)
+ file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/bar.cpp.in "void bar() {}\n")
+ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/bar.cpp
+ COMMAND ${CMAKE_COMMAND} -E touch foo.customcommand
+ COMMAND ${CMAKE_COMMAND} -E touch foo.customcommand.notdeclared
+ COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/bar.cpp.in ${CMAKE_CURRENT_BINARY_DIR}/bar.cpp
+ BYPRODUCTS foo.customcommand
+ COMMENT "Creating byproducts with a custom command"
+ )
+
+ # The nondeclared byproduct should always be present
+ list(APPEND EXPECTED_PRESENT "foo.customcommand.notdeclared")
+
+ # If CLEAN_NO_CUSTOM is set, both the output and byproduct should be present
+ if(TEST_CLEAN_NO_CUSTOM)
+ list(APPEND EXPECTED_PRESENT "bar.cpp")
+ list(APPEND EXPECTED_PRESENT "foo.customcommand")
+ else()
+ list(APPEND EXPECTED_DELETED "bar.cpp")
+ list(APPEND EXPECTED_DELETED "foo.customcommand")
+ endif()
+
+ target_sources(foo PUBLIC "${CMAKE_CURRENT_BINARY_DIR}/bar.cpp")
+endif()
+
+# Custom target that generates byproducts
+if(TEST_CUSTOM_TARGET)
+ add_custom_target(foo_file ALL
+ DEPENDS foo
+ COMMAND ${CMAKE_COMMAND} -E touch foo.customtarget
+ COMMAND ${CMAKE_COMMAND} -E touch foo.customtarget.notdeclared
+ BYPRODUCTS foo.customtarget
+ COMMENT "Creating byproducts with a custom target"
+ )
+
+ # The nondeclared byproduct should always be present
+ list(APPEND EXPECTED_PRESENT "foo.customtarget.notdeclared")
+
+ # If CLEAN_NO_CUSTOM is set, the declared byproduct should be present
+ if(TEST_CLEAN_NO_CUSTOM)
+ list(APPEND EXPECTED_PRESENT "foo.customtarget")
+ else()
+ list(APPEND EXPECTED_DELETED "foo.customtarget")
+ endif()
+endif()
+
+configure_file(files.cmake.in files.cmake)
diff --git a/Tests/RunCMake/Byproducts/RunCMakeTest.cmake b/Tests/RunCMake/Byproducts/RunCMakeTest.cmake
new file mode 100644
index 000000000..a7584ee4b
--- /dev/null
+++ b/Tests/RunCMake/Byproducts/RunCMakeTest.cmake
@@ -0,0 +1,58 @@
+include(RunCMake)
+
+function(run_CleanByproducts case)
+ set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/CleanByproducts-${case}-build)
+ set(RunCMake_TEST_OPTIONS "${ARGN}")
+
+ run_cmake(CleanByproducts)
+ set(RunCMake_TEST_NO_CLEAN 1)
+
+ run_cmake_command(CleanByProducts-build ${CMAKE_COMMAND} --build .)
+ include("${RunCMake_TEST_BINARY_DIR}/files.cmake")
+
+ message("Checking that all expected files are present")
+ check_files(EXPECTED_PRESENT "${RunCMake_TEST_BINARY_DIR}" TRUE)
+ check_files(EXPECTED_DELETED "${RunCMake_TEST_BINARY_DIR}" TRUE)
+
+ run_cmake_command(CleanByProducts-clean ${CMAKE_COMMAND} --build . --target clean)
+
+ message("Checking that only the expected files are present after cleaning")
+ check_files(EXPECTED_PRESENT "${RunCMake_TEST_BINARY_DIR}" TRUE)
+ check_files(EXPECTED_DELETED "${RunCMake_TEST_BINARY_DIR}" FALSE)
+endfunction()
+
+function(check_files list path has_to_exist)
+ foreach(file IN LISTS ${list})
+ message("Checking ${file}")
+ set(file_exists FALSE)
+ if(EXISTS "${path}/${file}")
+ set(file_exists TRUE)
+ endif()
+
+ if(file_exists AND NOT has_to_exist)
+ message(FATAL_ERROR "${file} should have been deleted")
+ elseif(NOT file_exists AND has_to_exist)
+ message(FATAL_ERROR "${file} does not exist")
+ elseif(file_exists AND has_to_exist)
+ message("${file} found as expected")
+ elseif(NOT file_exists AND NOT has_to_exist)
+ message("${file} deleted as expected")
+ endif()
+
+ endforeach()
+endfunction()
+
+
+# Iterate through all possible test values
+set(counter 0)
+foreach(test_clean_no_custom TRUE FALSE)
+ foreach(test_build_events TRUE FALSE)
+ foreach(test_custom_command TRUE FALSE)
+ foreach(test_custom_target TRUE FALSE)
+ math(EXPR counter "${counter} + 1")
+ message("Test ${counter} - CLEAN_NO_CUSTOM: ${test_clean_no_custom}, Build events: ${test_build_events}, Custom command: ${test_custom_command}, Custom target: ${test_custom_target}")
+ run_CleanByproducts("buildevents${counter}" -DCLEAN_NO_CUSTOM=${test_clean_no_custom} -DTEST_BUILD_EVENTS=${test_build_events} -DTEST_CUSTOM_COMMAND=${test_custom_command} -DTEST_CUSTOM_TARGET=${test_custom_target})
+ endforeach()
+ endforeach()
+ endforeach()
+endforeach()
diff --git a/Tests/RunCMake/Byproducts/files.cmake.in b/Tests/RunCMake/Byproducts/files.cmake.in
new file mode 100644
index 000000000..a7d4831fc
--- /dev/null
+++ b/Tests/RunCMake/Byproducts/files.cmake.in
@@ -0,0 +1,2 @@
+set(EXPECTED_PRESENT "@EXPECTED_PRESENT@")
+set(EXPECTED_DELETED "@EXPECTED_DELETED@")
diff --git a/Tests/RunCMake/Byproducts/foo.cpp b/Tests/RunCMake/Byproducts/foo.cpp
new file mode 100644
index 000000000..d47cb91a6
--- /dev/null
+++ b/Tests/RunCMake/Byproducts/foo.cpp
@@ -0,0 +1,14 @@
+int bar(int y)
+{
+ return y * 6;
+}
+
+int foo(int x)
+{
+ return x * bar(x);
+}
+
+int main()
+{
+ return foo(4);
+}
diff --git a/Tests/RunCMake/CMP0037/CMP0037-OLD-reserved-stderr.txt b/Tests/RunCMake/CMP0037/CMP0037-OLD-reserved-stderr.txt
new file mode 100644
index 000000000..de093517e
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/CMP0037-OLD-reserved-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0037-OLD-reserved.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0037 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0037/CMP0037-OLD-space-stderr.txt b/Tests/RunCMake/CMP0037/CMP0037-OLD-space-stderr.txt
new file mode 100644
index 000000000..4d13e59ef
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/CMP0037-OLD-space-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0037-OLD-space.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0037 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0037/CMP0037-WARN-reserved-stderr.txt b/Tests/RunCMake/CMP0037/CMP0037-WARN-reserved-stderr.txt
new file mode 100644
index 000000000..2d556a7e8
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/CMP0037-WARN-reserved-stderr.txt
@@ -0,0 +1,36 @@
+CMake Warning \(dev\) at CMP0037-WARN-reserved.cmake:2 \(add_library\):
+ Policy CMP0037 is not set: Target names should not be reserved and should
+ match a validity pattern. Run "cmake --help-policy CMP0037" for policy
+ details. Use the cmake_policy command to set the policy and suppress this
+ warning.
+
+ The target name "all" is reserved or not valid for certain CMake features,
+ such as generator expressions, and may result in undefined behavior.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
++
+CMake Warning \(dev\) at CMP0037-WARN-reserved.cmake:3 \(add_executable\):
+ Policy CMP0037 is not set: Target names should not be reserved and should
+ match a validity pattern. Run "cmake --help-policy CMP0037" for policy
+ details. Use the cmake_policy command to set the policy and suppress this
+ warning.
+
+ The target name "clean" is reserved or not valid for certain CMake
+ features, such as generator expressions, and may result in undefined
+ behavior.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
++
+CMake Warning \(dev\) at CMP0037-WARN-reserved.cmake:4 \(add_custom_target\):
+ Policy CMP0037 is not set: Target names should not be reserved and should
+ match a validity pattern. Run "cmake --help-policy CMP0037" for policy
+ details. Use the cmake_policy command to set the policy and suppress this
+ warning.
+
+ The target name "help" is reserved or not valid for certain CMake features,
+ such as generator expressions, and may result in undefined behavior.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/CMP0037/CMP0037-WARN-reserved.cmake b/Tests/RunCMake/CMP0037/CMP0037-WARN-reserved.cmake
new file mode 100644
index 000000000..a5e0f10dd
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/CMP0037-WARN-reserved.cmake
@@ -0,0 +1,4 @@
+enable_language(CXX)
+add_library(all empty.cpp)
+add_executable(clean empty.cpp)
+add_custom_target(help)
diff --git a/Tests/RunCMake/CMP0037/NEW-cond-package-result.txt b/Tests/RunCMake/CMP0037/NEW-cond-package-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/NEW-cond-package-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CMP0037/NEW-cond-package-stderr.txt b/Tests/RunCMake/CMP0037/NEW-cond-package-stderr.txt
new file mode 100644
index 000000000..270fa6db2
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/NEW-cond-package-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at NEW-cond-package.cmake:4 \(add_custom_target\):
+ The target name "package" is reserved when CPack packaging is enabled.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0037/NEW-cond-package.cmake b/Tests/RunCMake/CMP0037/NEW-cond-package.cmake
new file mode 100644
index 000000000..ceea90783
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/NEW-cond-package.cmake
@@ -0,0 +1,5 @@
+cmake_policy(SET CMP0037 NEW)
+file(WRITE "${CMAKE_BINARY_DIR}/CPackConfig.cmake" "")
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/NEW-cond-package_source-result.txt b/Tests/RunCMake/CMP0037/NEW-cond-package_source-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/NEW-cond-package_source-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CMP0037/NEW-cond-package_source-stderr.txt b/Tests/RunCMake/CMP0037/NEW-cond-package_source-stderr.txt
new file mode 100644
index 000000000..2d321473b
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/NEW-cond-package_source-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at NEW-cond-package_source.cmake:5 \(add_custom_target\):
+ The target name "package_source" is reserved when CPack source packaging is
+ enabled.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0037/NEW-cond-package_source.cmake b/Tests/RunCMake/CMP0037/NEW-cond-package_source.cmake
new file mode 100644
index 000000000..3f8883b3d
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/NEW-cond-package_source.cmake
@@ -0,0 +1,5 @@
+cmake_policy(SET CMP0037 NEW)
+file(WRITE "${CMAKE_BINARY_DIR}/CPackSourceConfig.cmake" "")
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/NEW-cond-test-result.txt b/Tests/RunCMake/CMP0037/NEW-cond-test-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/NEW-cond-test-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CMP0037/NEW-cond-test-stderr.txt b/Tests/RunCMake/CMP0037/NEW-cond-test-stderr.txt
new file mode 100644
index 000000000..44b4741ea
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/NEW-cond-test-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at NEW-cond-test.cmake:3 \(add_custom_target\):
+ The target name "test" is reserved when CTest testing is enabled.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0037/NEW-cond-test.cmake b/Tests/RunCMake/CMP0037/NEW-cond-test.cmake
new file mode 100644
index 000000000..7eeaffcc3
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/NEW-cond-test.cmake
@@ -0,0 +1,5 @@
+cmake_policy(SET CMP0037 NEW)
+enable_testing()
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/NEW-cond.cmake b/Tests/RunCMake/CMP0037/NEW-cond.cmake
new file mode 100644
index 000000000..d0dc77af3
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/NEW-cond.cmake
@@ -0,0 +1,4 @@
+cmake_policy(SET CMP0037 NEW)
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/OLD-cond-package-stderr.txt b/Tests/RunCMake/CMP0037/OLD-cond-package-stderr.txt
new file mode 100644
index 000000000..5a29a49c3
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/OLD-cond-package-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at OLD-cond-package.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0037 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0037/OLD-cond-package.cmake b/Tests/RunCMake/CMP0037/OLD-cond-package.cmake
new file mode 100644
index 000000000..7a0afbe10
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/OLD-cond-package.cmake
@@ -0,0 +1,5 @@
+cmake_policy(SET CMP0037 OLD)
+file(WRITE "${CMAKE_BINARY_DIR}/CPackConfig.cmake" "")
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/OLD-cond-package_source-stderr.txt b/Tests/RunCMake/CMP0037/OLD-cond-package_source-stderr.txt
new file mode 100644
index 000000000..5f72e1675
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/OLD-cond-package_source-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at OLD-cond-package_source.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0037 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0037/OLD-cond-package_source.cmake b/Tests/RunCMake/CMP0037/OLD-cond-package_source.cmake
new file mode 100644
index 000000000..95616b685
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/OLD-cond-package_source.cmake
@@ -0,0 +1,5 @@
+cmake_policy(SET CMP0037 OLD)
+file(WRITE "${CMAKE_BINARY_DIR}/CPackSourceConfig.cmake" "")
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/OLD-cond-stderr.txt b/Tests/RunCMake/CMP0037/OLD-cond-stderr.txt
new file mode 100644
index 000000000..94e4575c0
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/OLD-cond-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at OLD-cond.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0037 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0037/OLD-cond-test-stderr.txt b/Tests/RunCMake/CMP0037/OLD-cond-test-stderr.txt
new file mode 100644
index 000000000..81e10ce42
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/OLD-cond-test-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at OLD-cond-test.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0037 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0037/OLD-cond-test.cmake b/Tests/RunCMake/CMP0037/OLD-cond-test.cmake
new file mode 100644
index 000000000..bfa32a954
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/OLD-cond-test.cmake
@@ -0,0 +1,5 @@
+cmake_policy(SET CMP0037 OLD)
+enable_testing()
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/OLD-cond.cmake b/Tests/RunCMake/CMP0037/OLD-cond.cmake
new file mode 100644
index 000000000..abad68053
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/OLD-cond.cmake
@@ -0,0 +1,5 @@
+cmake_policy(SET CMP0037 OLD)
+
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/WARN-cond-package-stderr.txt b/Tests/RunCMake/CMP0037/WARN-cond-package-stderr.txt
new file mode 100644
index 000000000..5960e5149
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/WARN-cond-package-stderr.txt
@@ -0,0 +1,11 @@
+^CMake Warning \(dev\) at WARN-cond-package.cmake:4 \(add_custom_target\):
+ Policy CMP0037 is not set: Target names should not be reserved and should
+ match a validity pattern. Run "cmake --help-policy CMP0037" for policy
+ details. Use the cmake_policy command to set the policy and suppress this
+ warning.
+
+ The target name "package" is reserved when CPack packaging is enabled. It
+ may result in undefined behavior.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/CMP0037/WARN-cond-package.cmake b/Tests/RunCMake/CMP0037/WARN-cond-package.cmake
new file mode 100644
index 000000000..61cdc6834
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/WARN-cond-package.cmake
@@ -0,0 +1,5 @@
+
+file(WRITE "${CMAKE_BINARY_DIR}/CPackConfig.cmake" "")
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/WARN-cond-package_source-stderr.txt b/Tests/RunCMake/CMP0037/WARN-cond-package_source-stderr.txt
new file mode 100644
index 000000000..ae729092b
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/WARN-cond-package_source-stderr.txt
@@ -0,0 +1,11 @@
+^CMake Warning \(dev\) at WARN-cond-package_source.cmake:5 \(add_custom_target\):
+ Policy CMP0037 is not set: Target names should not be reserved and should
+ match a validity pattern. Run "cmake --help-policy CMP0037" for policy
+ details. Use the cmake_policy command to set the policy and suppress this
+ warning.
+
+ The target name "package_source" is reserved when CPack source packaging is
+ enabled. It may result in undefined behavior.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/CMP0037/WARN-cond-package_source.cmake b/Tests/RunCMake/CMP0037/WARN-cond-package_source.cmake
new file mode 100644
index 000000000..468380c36
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/WARN-cond-package_source.cmake
@@ -0,0 +1,5 @@
+
+file(WRITE "${CMAKE_BINARY_DIR}/CPackSourceConfig.cmake" "")
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/WARN-cond-test-stderr.txt b/Tests/RunCMake/CMP0037/WARN-cond-test-stderr.txt
new file mode 100644
index 000000000..e7a3ee594
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/WARN-cond-test-stderr.txt
@@ -0,0 +1,11 @@
+^CMake Warning \(dev\) at WARN-cond-test.cmake:3 \(add_custom_target\):
+ Policy CMP0037 is not set: Target names should not be reserved and should
+ match a validity pattern. Run "cmake --help-policy CMP0037" for policy
+ details. Use the cmake_policy command to set the policy and suppress this
+ warning.
+
+ The target name "test" is reserved when CTest testing is enabled. It may
+ result in undefined behavior.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/CMP0037/WARN-cond-test.cmake b/Tests/RunCMake/CMP0037/WARN-cond-test.cmake
new file mode 100644
index 000000000..982af369e
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/WARN-cond-test.cmake
@@ -0,0 +1,5 @@
+
+enable_testing()
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0037/WARN-cond.cmake b/Tests/RunCMake/CMP0037/WARN-cond.cmake
new file mode 100644
index 000000000..04a7f9da2
--- /dev/null
+++ b/Tests/RunCMake/CMP0037/WARN-cond.cmake
@@ -0,0 +1,4 @@
+
+add_custom_target(test)
+add_custom_target(package)
+add_custom_target(package_source)
diff --git a/Tests/RunCMake/CMP0038/CMP0038-OLD-stderr.txt b/Tests/RunCMake/CMP0038/CMP0038-OLD-stderr.txt
new file mode 100644
index 000000000..c75412861
--- /dev/null
+++ b/Tests/RunCMake/CMP0038/CMP0038-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0038-OLD.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0038 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0039/CMP0039-OLD-stderr.txt b/Tests/RunCMake/CMP0039/CMP0039-OLD-stderr.txt
new file mode 100644
index 000000000..d7863fd3c
--- /dev/null
+++ b/Tests/RunCMake/CMP0039/CMP0039-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0039-OLD.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0039 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0040/CMP0040-OLD-existing-target-stderr.txt b/Tests/RunCMake/CMP0040/CMP0040-OLD-existing-target-stderr.txt
new file mode 100644
index 000000000..f38c03d06
--- /dev/null
+++ b/Tests/RunCMake/CMP0040/CMP0040-OLD-existing-target-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0040-OLD-existing-target.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0040 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0040/CMP0040-OLD-missing-target-stderr.txt b/Tests/RunCMake/CMP0040/CMP0040-OLD-missing-target-stderr.txt
new file mode 100644
index 000000000..61f4f035d
--- /dev/null
+++ b/Tests/RunCMake/CMP0040/CMP0040-OLD-missing-target-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0040-OLD-missing-target.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0040 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0041/CMP0041-OLD-stderr.txt b/Tests/RunCMake/CMP0041/CMP0041-OLD-stderr.txt
new file mode 100644
index 000000000..1b736dadc
--- /dev/null
+++ b/Tests/RunCMake/CMP0041/CMP0041-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0041-OLD.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0041 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0041/CMP0041-tid-OLD-stderr.txt b/Tests/RunCMake/CMP0041/CMP0041-tid-OLD-stderr.txt
new file mode 100644
index 000000000..dbc51674f
--- /dev/null
+++ b/Tests/RunCMake/CMP0041/CMP0041-tid-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0041-tid-OLD.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0041 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0042/CMP0042-OLD-stderr.txt b/Tests/RunCMake/CMP0042/CMP0042-OLD-stderr.txt
new file mode 100644
index 000000000..9d1488d22
--- /dev/null
+++ b/Tests/RunCMake/CMP0042/CMP0042-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0042-OLD.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0042 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0043/CMP0043-OLD-stderr.txt b/Tests/RunCMake/CMP0043/CMP0043-OLD-stderr.txt
new file mode 100644
index 000000000..ebbb361ca
--- /dev/null
+++ b/Tests/RunCMake/CMP0043/CMP0043-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0043-OLD.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0043 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0045/CMP0045-OLD-stderr.txt b/Tests/RunCMake/CMP0045/CMP0045-OLD-stderr.txt
new file mode 100644
index 000000000..0dac20f4f
--- /dev/null
+++ b/Tests/RunCMake/CMP0045/CMP0045-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0045-OLD.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0045 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0046/CMP0046-OLD-existing-dependency-stderr.txt b/Tests/RunCMake/CMP0046/CMP0046-OLD-existing-dependency-stderr.txt
new file mode 100644
index 000000000..444411895
--- /dev/null
+++ b/Tests/RunCMake/CMP0046/CMP0046-OLD-existing-dependency-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0046-OLD-existing-dependency.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0046 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0046/CMP0046-OLD-missing-dependency-stderr.txt b/Tests/RunCMake/CMP0046/CMP0046-OLD-missing-dependency-stderr.txt
new file mode 100644
index 000000000..525954f63
--- /dev/null
+++ b/Tests/RunCMake/CMP0046/CMP0046-OLD-missing-dependency-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0046-OLD-missing-dependency.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0046 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0049/CMP0049-OLD-stderr.txt b/Tests/RunCMake/CMP0049/CMP0049-OLD-stderr.txt
new file mode 100644
index 000000000..b3739705b
--- /dev/null
+++ b/Tests/RunCMake/CMP0049/CMP0049-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0049-OLD.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0049 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0050/CMP0050-OLD-stderr.txt b/Tests/RunCMake/CMP0050/CMP0050-OLD-stderr.txt
new file mode 100644
index 000000000..3e7fa979c
--- /dev/null
+++ b/Tests/RunCMake/CMP0050/CMP0050-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0050-OLD.cmake:2 \(cmake_policy\):
+ The OLD behavior for policy CMP0050 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0055/CMP0055-OLD-Out-of-Scope-stderr.txt b/Tests/RunCMake/CMP0055/CMP0055-OLD-Out-of-Scope-stderr.txt
new file mode 100644
index 000000000..d0a156cbc
--- /dev/null
+++ b/Tests/RunCMake/CMP0055/CMP0055-OLD-Out-of-Scope-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0055-OLD-Out-of-Scope.cmake:[0-9]+ \(cmake_policy\):
+ The OLD behavior for policy CMP0055 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/CMP0055/CMP0055-OLD-Reject-Arguments-stderr.txt b/Tests/RunCMake/CMP0055/CMP0055-OLD-Reject-Arguments-stderr.txt
new file mode 100644
index 000000000..937b352da
--- /dev/null
+++ b/Tests/RunCMake/CMP0055/CMP0055-OLD-Reject-Arguments-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0055-OLD-Reject-Arguments.cmake:[0-9]+ \(cmake_policy\):
+ The OLD behavior for policy CMP0055 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/CMP0060/CMP0060-OLD-stderr.txt b/Tests/RunCMake/CMP0060/CMP0060-OLD-stderr.txt
new file mode 100644
index 000000000..465874736
--- /dev/null
+++ b/Tests/RunCMake/CMP0060/CMP0060-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0060-OLD.cmake:[0-9]+ \(cmake_policy\):
+ The OLD behavior for policy CMP0060 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/CMP0064/CMP0064-OLD-stderr.txt b/Tests/RunCMake/CMP0064/CMP0064-OLD-stderr.txt
new file mode 100644
index 000000000..987a50309
--- /dev/null
+++ b/Tests/RunCMake/CMP0064/CMP0064-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0064-OLD.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0064 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/CMP0081/CMP0081-Common.cmake b/Tests/RunCMake/CMP0081/CMP0081-Common.cmake
new file mode 100644
index 000000000..3ea5277f9
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/CMP0081-Common.cmake
@@ -0,0 +1,5 @@
+
+enable_language(CXX)
+
+add_library(foo SHARED empty.cpp)
+set_target_properties(foo PROPERTIES LINK_DIRECTORIES "../lib")
diff --git a/Tests/RunCMake/CMP0081/CMP0081-NEW-result.txt b/Tests/RunCMake/CMP0081/CMP0081-NEW-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/CMP0081-NEW-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CMP0081/CMP0081-NEW-stderr.txt b/Tests/RunCMake/CMP0081/CMP0081-NEW-stderr.txt
new file mode 100644
index 000000000..d31c149bd
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/CMP0081-NEW-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error in CMakeLists.txt:
+ Found relative path while evaluating link directories of "foo":
+
+ "../lib"
diff --git a/Tests/RunCMake/CMP0081/CMP0081-NEW.cmake b/Tests/RunCMake/CMP0081/CMP0081-NEW.cmake
new file mode 100644
index 000000000..9b927a2b4
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/CMP0081-NEW.cmake
@@ -0,0 +1,4 @@
+
+cmake_policy(SET CMP0081 NEW)
+
+include (CMP0081-Common.cmake)
diff --git a/Tests/RunCMake/CMP0081/CMP0081-OLD-result.txt b/Tests/RunCMake/CMP0081/CMP0081-OLD-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/CMP0081-OLD-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/CMP0081/CMP0081-OLD.cmake b/Tests/RunCMake/CMP0081/CMP0081-OLD.cmake
new file mode 100644
index 000000000..2e91bf6ae
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/CMP0081-OLD.cmake
@@ -0,0 +1,4 @@
+
+cmake_policy(SET CMP0081 OLD)
+
+include (CMP0081-Common.cmake)
diff --git a/Tests/RunCMake/CMP0081/CMP0081-WARN-result.txt b/Tests/RunCMake/CMP0081/CMP0081-WARN-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/CMP0081-WARN-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/CMP0081/CMP0081-WARN-stderr.txt b/Tests/RunCMake/CMP0081/CMP0081-WARN-stderr.txt
new file mode 100644
index 000000000..eac064829
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/CMP0081-WARN-stderr.txt
@@ -0,0 +1,10 @@
+CMake Warning \(dev\) in CMakeLists.txt:
+ Policy CMP0081 is not set: Relative paths not allowed in LINK_DIRECTORIES
+ target property. Run "cmake --help-policy CMP0081" for policy details.
+ Use the cmake_policy command to set the policy and suppress this warning.
+
+ Found relative path while evaluating link directories of "foo":
+
+ "../lib"
+
+This warning is for project developers. Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/CMP0081/CMP0081-WARN.cmake b/Tests/RunCMake/CMP0081/CMP0081-WARN.cmake
new file mode 100644
index 000000000..33bb21db1
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/CMP0081-WARN.cmake
@@ -0,0 +1,2 @@
+
+include (CMP0081-Common.cmake)
diff --git a/Tests/RunCMake/CMP0081/CMakeLists.txt b/Tests/RunCMake/CMP0081/CMakeLists.txt
new file mode 100644
index 000000000..ef2163c29
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/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/CMP0081/RunCMakeTest.cmake b/Tests/RunCMake/CMP0081/RunCMakeTest.cmake
new file mode 100644
index 000000000..335d8c5ba
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/RunCMakeTest.cmake
@@ -0,0 +1,5 @@
+include(RunCMake)
+
+run_cmake(CMP0081-OLD)
+run_cmake(CMP0081-NEW)
+run_cmake(CMP0081-WARN)
diff --git a/Tests/RunCMake/CMP0081/empty.cpp b/Tests/RunCMake/CMP0081/empty.cpp
new file mode 100644
index 000000000..11ec041d1
--- /dev/null
+++ b/Tests/RunCMake/CMP0081/empty.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/CMakeRoleGlobalProperty/BuildAndTest/CMakeLists.txt b/Tests/RunCMake/CMakeRoleGlobalProperty/BuildAndTest/CMakeLists.txt
new file mode 100644
index 000000000..332b0230d
--- /dev/null
+++ b/Tests/RunCMake/CMakeRoleGlobalProperty/BuildAndTest/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.12)
+project(CMakeRoleGlobalPropertyBuildAndTest NONE)
+include(CTest)
+
+get_property(role GLOBAL PROPERTY CMAKE_ROLE)
+if(NOT role STREQUAL "PROJECT")
+ message(SEND_ERROR "CMAKE_ROLE property is \"${role}\", should be \"PROJECT\"")
+endif()
+
+add_test(NAME RunCMakeVersion COMMAND "${CMAKE_COMMAND}" --version)
diff --git a/Tests/RunCMake/CMakeRoleGlobalProperty/CMakeLists.txt b/Tests/RunCMake/CMakeRoleGlobalProperty/CMakeLists.txt
new file mode 100644
index 000000000..44025d3bd
--- /dev/null
+++ b/Tests/RunCMake/CMakeRoleGlobalProperty/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.12)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/CMakeRoleGlobalProperty/CMakeLists.txt.in b/Tests/RunCMake/CMakeRoleGlobalProperty/CMakeLists.txt.in
new file mode 100644
index 000000000..bb8f9c140
--- /dev/null
+++ b/Tests/RunCMake/CMakeRoleGlobalProperty/CMakeLists.txt.in
@@ -0,0 +1,4 @@
+cmake_minimum_required(VERSION 3.12)
+project(CMakeRoleGlobalProperty@CASE_NAME@ NONE)
+include(CTest)
+add_test(NAME RunCMakeVersion COMMAND "${CMAKE_COMMAND}" --version)
diff --git a/Tests/RunCMake/CMakeRoleGlobalProperty/FindDummyPackage.cmake b/Tests/RunCMake/CMakeRoleGlobalProperty/FindDummyPackage.cmake
new file mode 100644
index 000000000..8299042f3
--- /dev/null
+++ b/Tests/RunCMake/CMakeRoleGlobalProperty/FindDummyPackage.cmake
@@ -0,0 +1,8 @@
+cmake_minimum_required(VERSION 3.12)
+
+get_property(role GLOBAL PROPERTY CMAKE_ROLE)
+if(NOT role STREQUAL "FIND_PACKAGE")
+ message(SEND_ERROR "CMAKE_ROLE property is \"${role}\", should be \"FIND_PACKAGE\"")
+endif()
+
+set(DummyPackage_FOUND 1)
diff --git a/Tests/RunCMake/CMakeRoleGlobalProperty/Project.cmake b/Tests/RunCMake/CMakeRoleGlobalProperty/Project.cmake
new file mode 100644
index 000000000..22cad2bba
--- /dev/null
+++ b/Tests/RunCMake/CMakeRoleGlobalProperty/Project.cmake
@@ -0,0 +1,10 @@
+get_property(role GLOBAL PROPERTY CMAKE_ROLE)
+
+file(WRITE "${CMAKE_BINARY_DIR}/test.cmake" "# a")
+include("${CMAKE_BINARY_DIR}/test.cmake")
+
+if(NOT role STREQUAL "PROJECT")
+ message(SEND_ERROR "CMAKE_ROLE property is \"${role}\", should be \"PROJECT\"")
+endif()
+
+add_subdirectory(sub)
diff --git a/Tests/RunCMake/CMakeRoleGlobalProperty/RunCMakeTest.cmake b/Tests/RunCMake/CMakeRoleGlobalProperty/RunCMakeTest.cmake
new file mode 100644
index 000000000..7b29c28b8
--- /dev/null
+++ b/Tests/RunCMake/CMakeRoleGlobalProperty/RunCMakeTest.cmake
@@ -0,0 +1,17 @@
+include(RunCMake)
+include(RunCTest)
+
+run_cmake(Project)
+file(WRITE "${RunCMake_BINARY_DIR}/Project-build/test.cmake" "# b")
+run_cmake_command(ProjectBuild "${CMAKE_COMMAND}" --build "${RunCMake_BINARY_DIR}/Project-build")
+
+run_cmake_command(Script "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_LIST_DIR}/Script.cmake")
+run_cmake_command(FindPackage "${CMAKE_COMMAND}" --find-package -DNAME=DummyPackage -DCOMPILER_ID=GNU -DLANGUAGE=CXX -DMODE=EXIST "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}")
+run_ctest(CTest)
+run_cmake_command(BuildAndTest "${CMAKE_CTEST_COMMAND}"
+ --build-and-test
+ "${RunCMake_SOURCE_DIR}/BuildAndTest"
+ "${RunCMake_BINARY_DIR}/BuildAndTest-build"
+ --build-project CMakeRoleGlobalPropertyBuildAndTest
+ --build-generator "${RunCMake_GENERATOR}"
+ )
diff --git a/Tests/RunCMake/CMakeRoleGlobalProperty/Script.cmake b/Tests/RunCMake/CMakeRoleGlobalProperty/Script.cmake
new file mode 100644
index 000000000..371edbc5c
--- /dev/null
+++ b/Tests/RunCMake/CMakeRoleGlobalProperty/Script.cmake
@@ -0,0 +1,6 @@
+cmake_minimum_required(VERSION 3.12)
+
+get_property(role GLOBAL PROPERTY CMAKE_ROLE)
+if(NOT role STREQUAL "SCRIPT")
+ message(SEND_ERROR "CMAKE_ROLE property is \"${role}\", should be \"SCRIPT\"")
+endif()
diff --git a/Tests/RunCMake/CMakeRoleGlobalProperty/sub/CMakeLists.txt b/Tests/RunCMake/CMakeRoleGlobalProperty/sub/CMakeLists.txt
new file mode 100644
index 000000000..8ecf671e5
--- /dev/null
+++ b/Tests/RunCMake/CMakeRoleGlobalProperty/sub/CMakeLists.txt
@@ -0,0 +1,4 @@
+get_property(role GLOBAL PROPERTY CMAKE_ROLE)
+if(NOT role STREQUAL "PROJECT")
+ message(SEND_ERROR "CMAKE_ROLE property is \"${role}\", should be \"PROJECT\"")
+endif()
diff --git a/Tests/RunCMake/CMakeRoleGlobalProperty/test.cmake.in b/Tests/RunCMake/CMakeRoleGlobalProperty/test.cmake.in
new file mode 100644
index 000000000..4e2c0859e
--- /dev/null
+++ b/Tests/RunCMake/CMakeRoleGlobalProperty/test.cmake.in
@@ -0,0 +1,7 @@
+cmake_minimum_required(VERSION 3.12)
+set(CTEST_RUN_CURRENT_SCRIPT 0)
+
+get_property(role GLOBAL PROPERTY CMAKE_ROLE)
+if(NOT role STREQUAL "CTEST")
+ message(SEND_ERROR "CMAKE_ROLE property is \"${role}\", should be \"CTEST\"")
+endif()
diff --git a/Tests/RunCMake/CPack/External/Helpers.cmake b/Tests/RunCMake/CPack/External/Helpers.cmake
new file mode 100644
index 000000000..2c67e0644
--- /dev/null
+++ b/Tests/RunCMake/CPack/External/Helpers.cmake
@@ -0,0 +1,31 @@
+function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_VAR)
+ set(${RESULT_VAR} "${NAME}-${VERSION}-*.json" PARENT_SCOPE)
+endfunction()
+
+function(getPackageContentList FILE RESULT_VAR)
+ set("${RESULT_VAR}" "" PARENT_SCOPE)
+endfunction()
+
+function(toExpectedContentList FILE_NO CONTENT_VAR)
+ set("${CONTENT_VAR}" "" PARENT_SCOPE)
+endfunction()
+
+set(ALL_FILES_GLOB "*.json")
+
+function(check_ext_json EXPECTED_FILE ACTUAL_FILE)
+ file(READ "${EXPECTED_FILE}" _expected_regex)
+ file(READ "${ACTUAL_FILE}" _actual_contents)
+
+ string(REGEX REPLACE "\n+$" "" _expected_regex "${_expected_regex}")
+ string(REGEX REPLACE "\n+$" "" _actual_contents "${_actual_contents}")
+
+ if(NOT "${_actual_contents}" MATCHES "${_expected_regex}")
+ message(FATAL_ERROR
+ "Output JSON does not match expected regex.\n"
+ "Expected regex:\n"
+ "${_expected_regex}\n"
+ "Actual output:\n"
+ "${_actual_contents}\n"
+ )
+ endif()
+endfunction()
diff --git a/Tests/RunCMake/CPack/External/Prerequirements.cmake b/Tests/RunCMake/CPack/External/Prerequirements.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/CPack/External/Prerequirements.cmake
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..02a78215b
--- /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 "/foo;/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..d1a3a5fb2
--- /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 "/foo;/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/DEFAULT_PERMISSIONS/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/ExpectedFiles.cmake
new file mode 100644
index 000000000..b6fcc175a
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/ExpectedFiles.cmake
@@ -0,0 +1,6 @@
+if(${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid_.*_var")
+ set(EXPECTED_FILES_COUNT "0")
+else()
+ set(EXPECTED_FILES_COUNT "1")
+ set(EXPECTED_FILE_CONTENT_1_LIST "/foo;/foo/CMakeLists.txt")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/VerifyResult.cmake
new file mode 100644
index 000000000..16ebcdc5e
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/VerifyResult.cmake
@@ -0,0 +1,39 @@
+if(NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid_.*_var")
+ if(GENERATOR_TYPE STREQUAL "RPM")
+ function(checkContentPermissions_ FILE REGEX)
+ execute_process(COMMAND ${RPM_EXECUTABLE} -qp --dump ${FILE}
+ WORKING_DIRECTORY "${CPACK_TEMPORARY_DIRECTORY}"
+ OUTPUT_VARIABLE PERMISSIONS_
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+
+ if(NOT PERMISSIONS_ MATCHES "${REGEX}")
+ message(FATAL_ERROR "Permissions in '${FILE}'. Permissions: '${PERMISSIONS_}'")
+ endif()
+ endfunction()
+
+ if(${RunCMake_SUBTEST_SUFFIX} MATCHES "CMAKE_var_set")
+ checkContentPermissions_("${FOUND_FILE_1}"
+ "/usr/foo .*740 root root.*")
+ else()
+ checkContentPermissions_("${FOUND_FILE_1}"
+ "/usr/foo .*700 root root.*")
+ endif()
+ else() # DEB
+ function(checkContentPermissions_ FILE REGEX)
+ getPackageContent("${FILE}" PERMISSIONS_)
+
+ if(NOT PERMISSIONS_ MATCHES "${REGEX}")
+ message(FATAL_ERROR "Permissions in '${FILE}'. Permissions: '${PERMISSIONS_}'")
+ endif()
+ endfunction()
+
+ if(${RunCMake_SUBTEST_SUFFIX} MATCHES "CMAKE_var_set")
+ checkContentPermissions_("${FOUND_FILE_1}"
+ "drwxr----- root/root .* ./usr/\ndrwxr----- root/root .* ./usr/foo/\n.*")
+ else()
+ checkContentPermissions_("${FOUND_FILE_1}"
+ "drwx------ root/root .* ./usr/\ndrwx------ root/root .* ./usr/foo/\n.*")
+ endif()
+ endif()
+endif()
diff --git a/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/invalid_CMAKE_var-stderr.txt b/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/invalid_CMAKE_var-stderr.txt
new file mode 100644
index 000000000..541763a29
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/invalid_CMAKE_var-stderr.txt
@@ -0,0 +1 @@
+.*CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS value is invalid.*
diff --git a/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/invalid_CPACK_var-stderr.txt b/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/invalid_CPACK_var-stderr.txt
new file mode 100644
index 000000000..541763a29
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/invalid_CPACK_var-stderr.txt
@@ -0,0 +1 @@
+.*CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS value is invalid.*
diff --git a/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/test.cmake b/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/test.cmake
new file mode 100644
index 000000000..afe939074
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEFAULT_PERMISSIONS/test.cmake
@@ -0,0 +1,34 @@
+if(${RunCMake_SUBTEST_SUFFIX} MATCHES "CMAKE_var_set" OR
+ ${RunCMake_SUBTEST_SUFFIX} MATCHES "both_set")
+
+ set(CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS
+ OWNER_READ
+ OWNER_WRITE
+ OWNER_EXECUTE
+ GROUP_READ
+ )
+endif()
+
+if(${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid_CMAKE_var")
+ list(APPEND CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS "INVALID")
+endif()
+
+if(${RunCMake_SUBTEST_SUFFIX} MATCHES "CPACK_var_set" OR
+ ${RunCMake_SUBTEST_SUFFIX} MATCHES "both_set")
+
+ set(CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS
+ OWNER_READ
+ OWNER_WRITE
+ OWNER_EXECUTE
+ )
+endif()
+
+if(${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid_CPACK_var")
+ list(APPEND CPACK_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS "INVALID")
+endif()
+
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
+
+if(PACKAGING_TYPE STREQUAL "COMPONENT")
+ set(CPACK_COMPONENTS_ALL test)
+endif()
diff --git a/Tests/RunCMake/CPack/tests/EXTERNAL/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/EXTERNAL/ExpectedFiles.cmake
new file mode 100644
index 000000000..91608c9fe
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTERNAL/ExpectedFiles.cmake
@@ -0,0 +1,7 @@
+if(RunCMake_SUBTEST_SUFFIX MATCHES "^(none|good(_multi)?|invalid_good)$"
+ OR RunCMake_SUBTEST_SUFFIX STREQUAL "stage_and_package")
+ set(EXPECTED_FILES_COUNT "1")
+ set(EXPECTED_FILE_CONTENT_1_LIST "/share;/share/cpack-test;/share/cpack-test/f1.txt;/share/cpack-test/f2.txt;/share/cpack-test/f3.txt;/share/cpack-test/f4.txt")
+else()
+ set(EXPECTED_FILES_COUNT "0")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/EXTERNAL/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/EXTERNAL/VerifyResult.cmake
new file mode 100644
index 000000000..bc19d7efb
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTERNAL/VerifyResult.cmake
@@ -0,0 +1,3 @@
+if(RunCMake_SUBTEST_SUFFIX MATCHES "^(none|good(_multi)?|invalid_good)")
+ check_ext_json("${src_dir}/tests/EXTERNAL/expected-json-1.0.txt" "${FOUND_FILE_1}")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/EXTERNAL/bad_major-stderr.txt b/Tests/RunCMake/CPack/tests/EXTERNAL/bad_major-stderr.txt
new file mode 100644
index 000000000..f2e160e20
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTERNAL/bad_major-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at .*/Modules/Internal/CPack/CPackExternal\.cmake:[0-9]+ \(message\):
+ Could not find a suitable version in CPACK_EXTERNAL_REQUESTED_VERSIONS
+
+
+CPack Error: Error while executing CPackExternal\.cmake
+CPack Error: Cannot initialize the generator External
diff --git a/Tests/RunCMake/CPack/tests/EXTERNAL/bad_minor-stderr.txt b/Tests/RunCMake/CPack/tests/EXTERNAL/bad_minor-stderr.txt
new file mode 100644
index 000000000..f2e160e20
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTERNAL/bad_minor-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at .*/Modules/Internal/CPack/CPackExternal\.cmake:[0-9]+ \(message\):
+ Could not find a suitable version in CPACK_EXTERNAL_REQUESTED_VERSIONS
+
+
+CPack Error: Error while executing CPackExternal\.cmake
+CPack Error: Cannot initialize the generator External
diff --git a/Tests/RunCMake/CPack/tests/EXTERNAL/create_package.cmake b/Tests/RunCMake/CPack/tests/EXTERNAL/create_package.cmake
new file mode 100644
index 000000000..6f7c4c224
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTERNAL/create_package.cmake
@@ -0,0 +1,31 @@
+message("This script could run an external packaging tool")
+
+get_property(role GLOBAL PROPERTY CMAKE_ROLE)
+if(NOT role STREQUAL "CPACK")
+ message(SEND_ERROR "CMAKE_ROLE property is \"${role}\", should be \"CPACK\"")
+endif()
+
+function(expect_variable VAR)
+ if(NOT ${VAR})
+ message(FATAL_ERROR "${VAR} is unexpectedly not set")
+ endif()
+endfunction()
+
+function(expect_file FILE)
+ if(NOT EXISTS "${FILE}")
+ message(FATAL_ERROR "${FILE} is unexpectedly missing")
+ endif()
+endfunction()
+
+expect_variable(CPACK_COMPONENTS_ALL)
+expect_variable(CPACK_TOPLEVEL_DIRECTORY)
+expect_variable(CPACK_TEMPORARY_DIRECTORY)
+expect_variable(CPACK_PACKAGE_DIRECTORY)
+expect_variable(CPACK_PACKAGE_FILE_NAME)
+
+expect_file(${CPACK_TEMPORARY_DIRECTORY}/f1/share/cpack-test/f1.txt)
+expect_file(${CPACK_TEMPORARY_DIRECTORY}/f2/share/cpack-test/f2.txt)
+expect_file(${CPACK_TEMPORARY_DIRECTORY}/f3/share/cpack-test/f3.txt)
+expect_file(${CPACK_TEMPORARY_DIRECTORY}/f4/share/cpack-test/f4.txt)
+
+message(STATUS "This status message is expected to be visible")
diff --git a/Tests/RunCMake/CPack/tests/EXTERNAL/expected-json-1.0.txt b/Tests/RunCMake/CPack/tests/EXTERNAL/expected-json-1.0.txt
new file mode 100644
index 000000000..18bf61784
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTERNAL/expected-json-1.0.txt
@@ -0,0 +1,176 @@
+^\{
+ "componentGroups" :[ ]
+ \{
+ "f12" :[ ]
+ \{
+ "components" :[ ]
+ \[
+ "f1",
+ "f2"
+ \],
+ "description" : "Component group for files 1 and 2",
+ "displayName" : "Files 1 and 2",
+ "isBold" : false,
+ "isExpandedByDefault" : false,
+ "name" : "f12",
+ "parentGroup" : "f1234",
+ "subgroups" : \[\]
+ \},
+ "f1234" :[ ]
+ \{
+ "components" : \[\],
+ "description" : "Component group for all files",
+ "displayName" : "Files 1-4",
+ "isBold" : false,
+ "isExpandedByDefault" : false,
+ "name" : "f1234",
+ "subgroups" :[ ]
+ \[
+ "f12",
+ "f34"
+ \]
+ \},
+ "f34" :[ ]
+ \{
+ "components" :[ ]
+ \[
+ "f3",
+ "f4"
+ \],
+ "description" : "Component group for files 3 and 4",
+ "displayName" : "Files 3 and 4",
+ "isBold" : false,
+ "isExpandedByDefault" : false,
+ "name" : "f34",
+ "parentGroup" : "f1234",
+ "subgroups" : \[\]
+ \}
+ \},
+ "components" :[ ]
+ \{
+ "f1" :[ ]
+ \{
+ "archiveFile" : "",
+ "dependencies" : \[\],
+ "description" : "Component for file 1",
+ "displayName" : "File 1",
+ "group" : "f12",
+ "installationTypes" :[ ]
+ \[
+ "full",
+ "f12"
+ \],
+ "isDisabledByDefault" : false,
+ "isDownloaded" : false,
+ "isHidden" : false,
+ "isRequired" : false,
+ "name" : "f1"
+ \},
+ "f2" :[ ]
+ \{
+ "archiveFile" : "",
+ "dependencies" :[ ]
+ \[
+ "f1"
+ \],
+ "description" : "Component for file 2",
+ "displayName" : "File 2",
+ "group" : "f12",
+ "installationTypes" :[ ]
+ \[
+ "full",
+ "f12"
+ \],
+ "isDisabledByDefault" : false,
+ "isDownloaded" : false,
+ "isHidden" : false,
+ "isRequired" : false,
+ "name" : "f2"
+ \},
+ "f3" :[ ]
+ \{
+ "archiveFile" : "",
+ "dependencies" :[ ]
+ \[
+ "f1",
+ "f2"
+ \],
+ "description" : "Component for file 3",
+ "displayName" : "File 3",
+ "group" : "f34",
+ "installationTypes" :[ ]
+ \[
+ "full"
+ \],
+ "isDisabledByDefault" : false,
+ "isDownloaded" : false,
+ "isHidden" : false,
+ "isRequired" : false,
+ "name" : "f3"
+ \},
+ "f4" :[ ]
+ \{
+ "archiveFile" : "",
+ "dependencies" :[ ]
+ \[
+ "f2",
+ "f3",
+ "f1"
+ \],
+ "description" : "Component for file 4",
+ "displayName" : "File 4",
+ "group" : "f34",
+ "installationTypes" :[ ]
+ \[
+ "full"
+ \],
+ "isDisabledByDefault" : false,
+ "isDownloaded" : false,
+ "isHidden" : false,
+ "isRequired" : false,
+ "name" : "f4"
+ \}
+ \},
+ "errorOnAbsoluteInstallDestination" : false,
+ "formatVersionMajor" : 1,
+ "formatVersionMinor" : 0,
+ "installationTypes" :[ ]
+ \{
+ "f12" :[ ]
+ \{
+ "displayName" : "Only files 1 and 2",
+ "index" : 2,
+ "name" : "f12"
+ \},
+ "full" :[ ]
+ \{
+ "displayName" : "Full installation",
+ "index" : 1,
+ "name" : "full"
+ \}
+ \},
+ "packageDescriptionFile" : ".*/Templates/CPack\.GenericDescription\.txt",
+ "packageDescriptionSummary" : "EXTERNAL-(none|good(_multi)?|invalid_good)-subtest-(MONOLITHIC|COMPONENT)-type built using CMake",
+ "packageName" : "external",
+ "packageVersion" : "0\.1\.1",
+ "projects" :[ ]
+ \[
+ \{
+ "component" : "ALL",
+ "components" :[ ]
+ \[
+ "f1",
+ "f2",
+ "f3",
+ "f4"
+ \],
+ "directory" : ".*/Tests/RunCMake/External/CPack/EXTERNAL-build-(none|good(_multi)?|invalid_good)-subtest",
+ "installationTypes" : \[\],
+ "projectName" : "EXTERNAL-(none|good(_multi)?|invalid_good)-subtest-(MONOLITHIC|COMPONENT)-type",
+ "subDirectory" : "/"
+ \}
+ \],
+ "setDestdir" : false,
+ "stripFiles" : false,
+ "warnOnAbsoluteInstallDestination" : false
+\}$
diff --git a/Tests/RunCMake/CPack/tests/EXTERNAL/invalid_bad-stderr.txt b/Tests/RunCMake/CPack/tests/EXTERNAL/invalid_bad-stderr.txt
new file mode 100644
index 000000000..f2e160e20
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTERNAL/invalid_bad-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at .*/Modules/Internal/CPack/CPackExternal\.cmake:[0-9]+ \(message\):
+ Could not find a suitable version in CPACK_EXTERNAL_REQUESTED_VERSIONS
+
+
+CPack Error: Error while executing CPackExternal\.cmake
+CPack Error: Cannot initialize the generator External
diff --git a/Tests/RunCMake/CPack/tests/EXTERNAL/stage_and_package-stderr.txt b/Tests/RunCMake/CPack/tests/EXTERNAL/stage_and_package-stderr.txt
new file mode 100644
index 000000000..40f2743e2
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTERNAL/stage_and_package-stderr.txt
@@ -0,0 +1 @@
+^This script could run an external packaging tool$
diff --git a/Tests/RunCMake/CPack/tests/EXTERNAL/stage_and_package-stdout.txt b/Tests/RunCMake/CPack/tests/EXTERNAL/stage_and_package-stdout.txt
new file mode 100644
index 000000000..37d635fa4
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTERNAL/stage_and_package-stdout.txt
@@ -0,0 +1 @@
+-- This status message is expected to be visible
diff --git a/Tests/RunCMake/CPack/tests/EXTERNAL/test.cmake b/Tests/RunCMake/CPack/tests/EXTERNAL/test.cmake
new file mode 100644
index 000000000..bc9766b15
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/EXTERNAL/test.cmake
@@ -0,0 +1,86 @@
+include(CPackComponent)
+
+if(RunCMake_SUBTEST_SUFFIX STREQUAL "none")
+ unset(CPACK_EXTERNAL_REQUESTED_VERSIONS)
+elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "good")
+ set(CPACK_EXTERNAL_REQUESTED_VERSIONS "1.0")
+elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "good_multi")
+ set(CPACK_EXTERNAL_REQUESTED_VERSIONS "1.0;2.0")
+elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "bad_major")
+ set(CPACK_EXTERNAL_REQUESTED_VERSIONS "2.0")
+elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "bad_minor")
+ set(CPACK_EXTERNAL_REQUESTED_VERSIONS "1.1")
+elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "invalid_good")
+ set(CPACK_EXTERNAL_REQUESTED_VERSIONS "1;1.0")
+elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "invalid_bad")
+ set(CPACK_EXTERNAL_REQUESTED_VERSIONS "1")
+elseif(RunCMake_SUBTEST_SUFFIX STREQUAL "stage_and_package")
+ set(CPACK_EXTERNAL_ENABLE_STAGING 1)
+ set(CPACK_EXTERNAL_PACKAGE_SCRIPT "${CMAKE_CURRENT_LIST_DIR}/create_package.cmake")
+endif()
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/f1.txt" test1)
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/f2.txt" test2)
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/f3.txt" test3)
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/f4.txt" test4)
+
+install(FILES "${CMAKE_CURRENT_BINARY_DIR}/f1.txt" DESTINATION share/cpack-test COMPONENT f1)
+install(FILES "${CMAKE_CURRENT_BINARY_DIR}/f2.txt" DESTINATION share/cpack-test COMPONENT f2)
+install(FILES "${CMAKE_CURRENT_BINARY_DIR}/f3.txt" DESTINATION share/cpack-test COMPONENT f3)
+install(FILES "${CMAKE_CURRENT_BINARY_DIR}/f4.txt" DESTINATION share/cpack-test COMPONENT f4)
+
+cpack_add_component(f1
+ DISPLAY_NAME "File 1"
+ DESCRIPTION "Component for file 1"
+ GROUP f12
+ INSTALL_TYPES full f12
+)
+
+cpack_add_component(f2
+ DISPLAY_NAME "File 2"
+ DESCRIPTION "Component for file 2"
+ GROUP f12
+ DEPENDS f1
+ INSTALL_TYPES full f12
+)
+
+cpack_add_component(f3
+ DISPLAY_NAME "File 3"
+ DESCRIPTION "Component for file 3"
+ GROUP f34
+ DEPENDS f1 f2
+ INSTALL_TYPES full
+)
+
+cpack_add_component(f4
+ DISPLAY_NAME "File 4"
+ DESCRIPTION "Component for file 4"
+ GROUP f34
+ DEPENDS f2 f3 f1
+ INSTALL_TYPES full
+)
+
+cpack_add_component_group(f12
+ DISPLAY_NAME "Files 1 and 2"
+ DESCRIPTION "Component group for files 1 and 2"
+ PARENT_GROUP f1234
+)
+
+cpack_add_component_group(f34
+ DISPLAY_NAME "Files 3 and 4"
+ DESCRIPTION "Component group for files 3 and 4"
+ PARENT_GROUP f1234
+)
+
+cpack_add_component_group(f1234
+ DISPLAY_NAME "Files 1-4"
+ DESCRIPTION "Component group for all files"
+)
+
+cpack_add_install_type(full
+ DISPLAY_NAME "Full installation"
+)
+
+cpack_add_install_type(f12
+ DISPLAY_NAME "Only files 1 and 2"
+)
diff --git a/Tests/RunCMake/CPack/tests/TIMESTAMPS/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/TIMESTAMPS/ExpectedFiles.cmake
new file mode 100644
index 000000000..d1a3a5fb2
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/TIMESTAMPS/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/foo;/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/tests/TIMESTAMPS/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/TIMESTAMPS/VerifyResult.cmake
new file mode 100644
index 000000000..e7e2645aa
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/TIMESTAMPS/VerifyResult.cmake
@@ -0,0 +1,58 @@
+macro(getFileMetadata_ FILE RESULT_VAR)
+ if(GENERATOR_TYPE STREQUAL "TGZ")
+ # getPackageContent defined for archives omit the metadata (non-verbose)
+ execute_process(COMMAND ${CMAKE_COMMAND} -E env TZ=Etc/UTC ${CMAKE_COMMAND} -E tar -xtvf ${FILE}
+ OUTPUT_VARIABLE ${RESULT_VAR}
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ else()
+ getPackageContent("${FILE}" ${RESULT_VAR})
+ endif()
+endmacro()
+
+function(checkContentTimestamp FILE REGEX)
+ getFileMetadata_("${FILE}" METADATA_)
+
+ if(NOT METADATA_ MATCHES "${REGEX}")
+ string(REPLACE "\n" "\n " metadata_indented "${METADATA_}")
+ message(FATAL_ERROR
+ "Wrong timestamps in file:\n"
+ " ${FILE}\n"
+ "Expected timestamps to match:\n"
+ " ${REGEX}\n"
+ "Actual timestamps:\n"
+ " ${metadata_indented}")
+ endif()
+endfunction()
+
+function(checkTimestamp FILE_NAME)
+ file(READ ${FILE_NAME} ACTUAL_TIMESTAMP OFFSET 4 LIMIT 4 HEX)
+
+ if(NOT ACTUAL_TIMESTAMP STREQUAL "00000000")
+ message(FATAL_ERROR "${FILE_NAME} contains a timestamp [0x${ACTUAL_TIMESTAMP}]")
+ endif()
+endfunction()
+
+# Expected timestamp is UNIX time 123456789
+if(GENERATOR_TYPE STREQUAL "TGZ")
+ set(EXPECTED_TIMESTAMP "29 Nov +1973")
+ set(EXPECTED_FILES foo/ foo/CMakeLists.txt)
+else()
+ set(EXPECTED_TIMESTAMP "1973-11-29 21:33")
+ set(EXPECTED_FILES ./usr/ ./usr/foo/ ./usr/foo/CMakeLists.txt)
+endif()
+
+set(EXPECTED_METADATA)
+foreach(FILE ${EXPECTED_FILES})
+ list(APPEND EXPECTED_METADATA ".* ${EXPECTED_TIMESTAMP} ${FILE}")
+endforeach()
+list(JOIN EXPECTED_METADATA ".*" EXPECTED_REGEX)
+checkContentTimestamp("${FOUND_FILE_1}" "${EXPECTED_REGEX}")
+
+if(GENERATOR_TYPE STREQUAL "TGZ")
+ checkTimestamp("${FOUND_FILE_1}")
+else()
+ execute_process(COMMAND ${CMAKE_COMMAND} -E tar xf "${FOUND_FILE_1}")
+ checkTimestamp("data.tar.gz")
+ checkTimestamp("control.tar.gz")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/TIMESTAMPS/test.cmake b/Tests/RunCMake/CPack/tests/TIMESTAMPS/test.cmake
new file mode 100644
index 000000000..a19385214
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/TIMESTAMPS/test.cmake
@@ -0,0 +1,3 @@
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
+
+set(CPACK_COMPONENTS_ALL test)
diff --git a/Tests/RunCMake/CPack/tests/VERSION/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/VERSION/ExpectedFiles.cmake
new file mode 100644
index 000000000..372f71bad
--- /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 "/foo;/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/CPackCommandLine/NotAGenerator-result.txt b/Tests/RunCMake/CPackCommandLine/NotAGenerator-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CPackCommandLine/NotAGenerator-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CPackCommandLine/NotAGenerator-stderr.txt b/Tests/RunCMake/CPackCommandLine/NotAGenerator-stderr.txt
new file mode 100644
index 000000000..a553bde5b
--- /dev/null
+++ b/Tests/RunCMake/CPackCommandLine/NotAGenerator-stderr.txt
@@ -0,0 +1 @@
+^CPack Error: Could not create CPack generator: NotAGenerator
diff --git a/Tests/RunCMake/CPackCommandLine/RunCMakeTest.cmake b/Tests/RunCMake/CPackCommandLine/RunCMakeTest.cmake
new file mode 100644
index 000000000..991146c8e
--- /dev/null
+++ b/Tests/RunCMake/CPackCommandLine/RunCMakeTest.cmake
@@ -0,0 +1,10 @@
+include(RunCMake)
+set(RunCMake_TEST_TIMEOUT 60)
+
+file(WRITE "${RunCMake_BINARY_DIR}/NotAGenerator-build/CPackConfig.cmake" [[
+set(CPACK_PACKAGE_NAME "Test")
+set(CPACK_PACKAGE_VERSION "1")
+]])
+set(RunCMake_TEST_NO_CLEAN 1)
+run_cmake_command(NotAGenerator ${CMAKE_CPACK_COMMAND} -G NotAGenerator)
+unset(RunCMake_TEST_NO_CLEAN)
diff --git a/Tests/RunCMake/CPackConfig/Version1-check.cmake b/Tests/RunCMake/CPackConfig/Version1-check.cmake
new file mode 100644
index 000000000..0f5347f78
--- /dev/null
+++ b/Tests/RunCMake/CPackConfig/Version1-check.cmake
@@ -0,0 +1,6 @@
+include(${RunCMake_SOURCE_DIR}/check.cmake)
+
+test_variable(CPACK_PACKAGE_VERSION "0")
+test_variable(CPACK_PACKAGE_VERSION_MAJOR "0")
+test_variable(CPACK_PACKAGE_VERSION_MINOR "")
+test_variable(CPACK_PACKAGE_VERSION_PATCH "")
diff --git a/Tests/RunCMake/CPackConfig/Version1.cmake b/Tests/RunCMake/CPackConfig/Version1.cmake
new file mode 100644
index 000000000..703485c98
--- /dev/null
+++ b/Tests/RunCMake/CPackConfig/Version1.cmake
@@ -0,0 +1 @@
+project(Version LANGUAGES NONE VERSION 0)
diff --git a/Tests/RunCMake/CPackConfig/Version2-check.cmake b/Tests/RunCMake/CPackConfig/Version2-check.cmake
new file mode 100644
index 000000000..3a2d572df
--- /dev/null
+++ b/Tests/RunCMake/CPackConfig/Version2-check.cmake
@@ -0,0 +1,6 @@
+include(${RunCMake_SOURCE_DIR}/check.cmake)
+
+test_variable(CPACK_PACKAGE_VERSION "1.0")
+test_variable(CPACK_PACKAGE_VERSION_MAJOR "1")
+test_variable(CPACK_PACKAGE_VERSION_MINOR "0")
+test_variable(CPACK_PACKAGE_VERSION_PATCH "")
diff --git a/Tests/RunCMake/CPackConfig/Version2.cmake b/Tests/RunCMake/CPackConfig/Version2.cmake
new file mode 100644
index 000000000..c084137b4
--- /dev/null
+++ b/Tests/RunCMake/CPackConfig/Version2.cmake
@@ -0,0 +1 @@
+project(Version LANGUAGES NONE VERSION 1.0)
diff --git a/Tests/RunCMake/CPackConfig/Version3-check.cmake b/Tests/RunCMake/CPackConfig/Version3-check.cmake
new file mode 100644
index 000000000..d4a3983dd
--- /dev/null
+++ b/Tests/RunCMake/CPackConfig/Version3-check.cmake
@@ -0,0 +1,6 @@
+include(${RunCMake_SOURCE_DIR}/check.cmake)
+
+test_variable(CPACK_PACKAGE_VERSION "1.1.0")
+test_variable(CPACK_PACKAGE_VERSION_MAJOR "1")
+test_variable(CPACK_PACKAGE_VERSION_MINOR "1")
+test_variable(CPACK_PACKAGE_VERSION_PATCH "0")
diff --git a/Tests/RunCMake/CPackConfig/Version3.cmake b/Tests/RunCMake/CPackConfig/Version3.cmake
new file mode 100644
index 000000000..4df28bbe1
--- /dev/null
+++ b/Tests/RunCMake/CPackConfig/Version3.cmake
@@ -0,0 +1 @@
+project(Version LANGUAGES NONE VERSION 1.1.0)
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..ab3e51b59
--- /dev/null
+++ b/Tests/RunCMake/CSharpCustomCommand/RunCMakeTest.cmake
@@ -0,0 +1,42 @@
+include(RunCMake)
+
+function(run_TargetWithCommand)
+ set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/TargetWithCommand-build)
+ run_cmake(TargetWithCommand)
+ set(RunCMake_TEST_NO_CLEAN 1)
+ run_cmake_command(TargetWithCommand-build ${CMAKE_COMMAND} --build . --config Debug)
+endfunction()
+run_TargetWithCommand()
+
+# 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/TargetWithCommand-build-stdout.txt b/Tests/RunCMake/CSharpCustomCommand/TargetWithCommand-build-stdout.txt
new file mode 100644
index 000000000..c212a8fe4
--- /dev/null
+++ b/Tests/RunCMake/CSharpCustomCommand/TargetWithCommand-build-stdout.txt
@@ -0,0 +1 @@
+Custom target with CSharp source
diff --git a/Tests/RunCMake/CSharpCustomCommand/TargetWithCommand.cmake b/Tests/RunCMake/CSharpCustomCommand/TargetWithCommand.cmake
new file mode 100644
index 000000000..fdaea5cb2
--- /dev/null
+++ b/Tests/RunCMake/CSharpCustomCommand/TargetWithCommand.cmake
@@ -0,0 +1,4 @@
+enable_language(CSharp)
+
+add_custom_target(drive ALL SOURCES dummy.cs
+ COMMAND ${CMAKE_COMMAND} -E echo "Custom target with CSharp source")
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/CSharpReferenceImport/CMakeLists.txt b/Tests/RunCMake/CSharpReferenceImport/CMakeLists.txt
new file mode 100644
index 000000000..74b3ff8de
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/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/CSharpReferenceImport/ImportLib.cmake b/Tests/RunCMake/CSharpReferenceImport/ImportLib.cmake
new file mode 100644
index 000000000..5ad6e76c7
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ImportLib.cmake
@@ -0,0 +1,45 @@
+enable_language(CXX CSharp)
+
+if(NOT DEFINED exportFileName OR
+ NOT DEFINED exportNameSpace OR
+ NOT DEFINED exportTargetName)
+ message(FATAL_ERROR "export information missing")
+endif()
+
+add_library(${exportTargetName}CSharp SHARED
+ ImportLib.cs)
+
+# native c++ dll
+add_library(${exportTargetName}Native SHARED
+ ImportLibNative.h
+ ImportLibNative.cxx)
+
+# mixed c++ dll
+add_library(${exportTargetName}Mixed SHARED
+ ImportLibMixed.cxx
+ ImportLibMixedNative.h
+ ImportLibMixedNative.cxx)
+set_target_properties(${exportTargetName}Mixed PROPERTIES
+ COMMON_LANGUAGE_RUNTIME "")
+
+# pure c++ dll
+add_library(${exportTargetName}Pure SHARED
+ ImportLibPure.cxx)
+set_target_properties(${exportTargetName}Pure PROPERTIES
+ COMMON_LANGUAGE_RUNTIME "pure")
+
+# safe c++ dll
+add_library(${exportTargetName}Safe SHARED
+ ImportLibSafe.cxx)
+set_target_properties(${exportTargetName}Safe PROPERTIES
+ COMMON_LANGUAGE_RUNTIME "safe")
+
+# generate export file
+export(TARGETS
+ ${exportTargetName}CSharp
+ ${exportTargetName}Native
+ ${exportTargetName}Mixed
+ ${exportTargetName}Pure
+ ${exportTargetName}Safe
+ NAMESPACE "${exportNameSpace}:"
+ FILE "${exportFileName}")
diff --git a/Tests/RunCMake/CSharpReferenceImport/ImportLib.cs b/Tests/RunCMake/CSharpReferenceImport/ImportLib.cs
new file mode 100644
index 000000000..4eb28afac
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ImportLib.cs
@@ -0,0 +1,8 @@
+using System;
+
+public
+class ImportLibCSharp
+{
+public
+ static void Message() { Console.WriteLine("ImportLibCSharp"); }
+}
diff --git a/Tests/RunCMake/CSharpReferenceImport/ImportLibMixed.cxx b/Tests/RunCMake/CSharpReferenceImport/ImportLibMixed.cxx
new file mode 100644
index 000000000..d0b810ef8
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ImportLibMixed.cxx
@@ -0,0 +1,8 @@
+using namespace System;
+
+public
+ref class ImportLibMixed
+{
+public:
+ static void Message() { Console::WriteLine("ImportLibMixed"); }
+};
diff --git a/Tests/RunCMake/CSharpReferenceImport/ImportLibMixedNative.cxx b/Tests/RunCMake/CSharpReferenceImport/ImportLibMixedNative.cxx
new file mode 100644
index 000000000..c85a77631
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ImportLibMixedNative.cxx
@@ -0,0 +1,8 @@
+#include "ImportLibMixedNative.h"
+
+#include <iostream>
+
+void ImportLibMixedNative::Message()
+{
+ std::cout << "ImportLibMixedNative" << std::endl;
+}
diff --git a/Tests/RunCMake/CSharpReferenceImport/ImportLibMixedNative.h b/Tests/RunCMake/CSharpReferenceImport/ImportLibMixedNative.h
new file mode 100644
index 000000000..76b97c475
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ImportLibMixedNative.h
@@ -0,0 +1,13 @@
+#pragma once
+
+#ifdef ImportLibMixed_EXPORTS
+# define mixedAPI __declspec(dllexport)
+#else
+# define mixedAPI __declspec(dllimport)
+#endif
+
+class mixedAPI ImportLibMixedNative
+{
+public:
+ static void Message();
+};
diff --git a/Tests/RunCMake/CSharpReferenceImport/ImportLibNative.cxx b/Tests/RunCMake/CSharpReferenceImport/ImportLibNative.cxx
new file mode 100644
index 000000000..8e08b9a0f
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ImportLibNative.cxx
@@ -0,0 +1,8 @@
+#include "ImportLibNative.h"
+
+#include <iostream>
+
+void ImportLibNative::Message()
+{
+ std::cout << "ImportLibNative" << std::endl;
+}
diff --git a/Tests/RunCMake/CSharpReferenceImport/ImportLibNative.h b/Tests/RunCMake/CSharpReferenceImport/ImportLibNative.h
new file mode 100644
index 000000000..77bcb8222
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ImportLibNative.h
@@ -0,0 +1,13 @@
+#pragma once
+
+#ifdef ImportLibNative_EXPORTS
+# define nativeAPI __declspec(dllexport)
+#else
+# define nativeAPI __declspec(dllimport)
+#endif
+
+class nativeAPI ImportLibNative
+{
+public:
+ static void Message();
+};
diff --git a/Tests/RunCMake/CSharpReferenceImport/ImportLibPure.cxx b/Tests/RunCMake/CSharpReferenceImport/ImportLibPure.cxx
new file mode 100644
index 000000000..271e37572
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ImportLibPure.cxx
@@ -0,0 +1,8 @@
+using namespace System;
+
+public
+ref class ImportLibPure
+{
+public:
+ static void Message() { Console::WriteLine("ImportLibPure"); }
+};
diff --git a/Tests/RunCMake/CSharpReferenceImport/ImportLibSafe.cxx b/Tests/RunCMake/CSharpReferenceImport/ImportLibSafe.cxx
new file mode 100644
index 000000000..13b40da26
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ImportLibSafe.cxx
@@ -0,0 +1,8 @@
+using namespace System;
+
+public
+ref class ImportLibSafe
+{
+public:
+ static void Message() { Console::WriteLine("ImportLibSafe"); }
+};
diff --git a/Tests/RunCMake/CSharpReferenceImport/ReferenceImport.cmake b/Tests/RunCMake/CSharpReferenceImport/ReferenceImport.cmake
new file mode 100644
index 000000000..c65f623a0
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ReferenceImport.cmake
@@ -0,0 +1,88 @@
+enable_language(CXX CSharp)
+
+if(NOT DEFINED exportFileName OR
+ NOT DEFINED exportNameSpace OR
+ NOT DEFINED exportTargetName)
+ message(FATAL_ERROR "export information missing")
+endif()
+
+# Include generated export file.
+if(NOT EXISTS "${exportFileName}")
+ message(FATAL_ERROR "exportFileNameCSharp does not exist: ${exportFileName}")
+endif()
+include(${exportFileName})
+
+# Verify expected targets are imported
+set(linkNames linkNameCSharp linkNameNative linkNameMixed
+ linkNamePure linkNameSafe)
+set(linkNameCSharp "${exportNameSpace}:${exportTargetName}CSharp")
+set(linkNameNative "${exportNameSpace}:${exportTargetName}Native")
+set(linkNameMixed "${exportNameSpace}:${exportTargetName}Mixed")
+set(linkNamePure "${exportNameSpace}:${exportTargetName}Pure")
+set(linkNameSafe "${exportNameSpace}:${exportTargetName}Safe")
+foreach(l ${linkNames})
+ if(NOT TARGET ${${l}})
+ message(FATAL_ERROR "imported target not found (${${l}})")
+ endif()
+endforeach()
+
+# Test referencing managed assemblies from C# executable.
+add_executable(ReferenceImportCSharp ReferenceImport.cs)
+target_link_libraries(ReferenceImportCSharp
+ ${linkNameCSharp}
+ ${linkNameNative} # ignored
+ ${linkNameMixed}
+ ${linkNamePure}
+ ${linkNameSafe}
+ )
+
+# native C++ executable.
+add_executable(ReferenceImportNative ReferenceImportNative.cxx)
+target_link_libraries(ReferenceImportNative
+ ${linkNameCSharp} # ignored
+ ${linkNameNative}
+ ${linkNameMixed}
+ ${linkNamePure} # ignored
+ ${linkNameSafe} # ignored
+ )
+add_custom_command(TARGET ReferenceImportNative POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ "$<TARGET_FILE:${linkNameNative}>"
+ "${CMAKE_BINARY_DIR}/$<CONFIG>"
+ )
+
+# mixed C++ executable.
+add_executable(ReferenceImportMixed ReferenceImportMixed.cxx)
+target_link_libraries(ReferenceImportMixed
+ ${linkNameCSharp}
+ ${linkNameNative}
+ ${linkNameMixed}
+ ${linkNamePure}
+ ${linkNameSafe}
+ )
+set_target_properties(ReferenceImportMixed PROPERTIES
+ COMMON_LANGUAGE_RUNTIME "")
+
+# pure C++ executable.
+add_executable(ReferenceImportPure ReferenceImportPure.cxx)
+target_link_libraries(ReferenceImportPure
+ ${linkNameCSharp}
+ ${linkNameNative} # ignored
+ ${linkNameMixed}
+ ${linkNamePure}
+ ${linkNameSafe}
+ )
+set_target_properties(ReferenceImportPure PROPERTIES
+ COMMON_LANGUAGE_RUNTIME "pure")
+
+# native C++ executable.
+add_executable(ReferenceImportSafe ReferenceImportSafe.cxx)
+target_link_libraries(ReferenceImportSafe
+ ${linkNameCSharp}
+ ${linkNameNative} # ignored
+ ${linkNameMixed}
+ ${linkNamePure}
+ ${linkNameSafe}
+ )
+set_target_properties(ReferenceImportSafe PROPERTIES
+ COMMON_LANGUAGE_RUNTIME "safe")
diff --git a/Tests/RunCMake/CSharpReferenceImport/ReferenceImport.cs b/Tests/RunCMake/CSharpReferenceImport/ReferenceImport.cs
new file mode 100644
index 000000000..24175f6d7
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ReferenceImport.cs
@@ -0,0 +1,13 @@
+using System;
+
+public class ReferenceImport
+{
+ public static void Main()
+ {
+ Console.WriteLine("ReferenceImportCSharp");
+ ImportLibMixed.Message();
+ ImportLibPure.Message();
+ ImportLibSafe.Message();
+ ImportLibCSharp.Message();
+ }
+}
diff --git a/Tests/RunCMake/CSharpReferenceImport/ReferenceImportMixed.cxx b/Tests/RunCMake/CSharpReferenceImport/ReferenceImportMixed.cxx
new file mode 100644
index 000000000..53ecd422e
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ReferenceImportMixed.cxx
@@ -0,0 +1,20 @@
+// clang-format off
+
+using namespace System;
+
+#using <ImportLibMixed.dll>
+#using <ImportLibPure.dll>
+#using <ImportLibSafe.dll>
+#using <ImportLibCSharp.dll>
+
+#include "ImportLibNative.h"
+
+int main()
+{
+ Console::WriteLine("ReferenceImportMixed");
+ ImportLibNative::Message();
+ ImportLibMixed::Message();
+ ImportLibPure::Message();
+ ImportLibSafe::Message();
+ ImportLibCSharp::Message();
+};
diff --git a/Tests/RunCMake/CSharpReferenceImport/ReferenceImportNative.cxx b/Tests/RunCMake/CSharpReferenceImport/ReferenceImportNative.cxx
new file mode 100644
index 000000000..831a2c4a1
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ReferenceImportNative.cxx
@@ -0,0 +1,13 @@
+// clang-format off
+
+#include "ImportLibNative.h"
+#include "ImportLibMixedNative.h"
+
+#include <iostream>
+
+int main()
+{
+ std::cout << "ReferenceImportNative" << std::endl;
+ ImportLibNative::Message();
+ ImportLibMixedNative::Message();
+};
diff --git a/Tests/RunCMake/CSharpReferenceImport/ReferenceImportPure.cxx b/Tests/RunCMake/CSharpReferenceImport/ReferenceImportPure.cxx
new file mode 100644
index 000000000..2c5dd66dd
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ReferenceImportPure.cxx
@@ -0,0 +1,17 @@
+// clang-format off
+
+using namespace System;
+
+#using <ImportLibMixed.dll>
+#using <ImportLibPure.dll>
+#using <ImportLibSafe.dll>
+#using <ImportLibCSharp.dll>
+
+int main()
+{
+ Console::WriteLine("ReferenceImportPure");
+ ImportLibMixed::Message();
+ ImportLibPure::Message();
+ ImportLibSafe::Message();
+ ImportLibCSharp::Message();
+};
diff --git a/Tests/RunCMake/CSharpReferenceImport/ReferenceImportSafe.cxx b/Tests/RunCMake/CSharpReferenceImport/ReferenceImportSafe.cxx
new file mode 100644
index 000000000..277c96f20
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/ReferenceImportSafe.cxx
@@ -0,0 +1,17 @@
+// clang-format off
+
+using namespace System;
+
+#using <ImportLibMixed.dll>
+#using <ImportLibPure.dll>
+#using <ImportLibSafe.dll>
+#using <ImportLibCSharp.dll>
+
+int main()
+{
+ Console::WriteLine("ReferenceImportSafe");
+ ImportLibMixed::Message();
+ ImportLibPure::Message();
+ ImportLibSafe::Message();
+ ImportLibCSharp::Message();
+};
diff --git a/Tests/RunCMake/CSharpReferenceImport/RunCMakeTest.cmake b/Tests/RunCMake/CSharpReferenceImport/RunCMakeTest.cmake
new file mode 100644
index 000000000..c44e59e0a
--- /dev/null
+++ b/Tests/RunCMake/CSharpReferenceImport/RunCMakeTest.cmake
@@ -0,0 +1,41 @@
+include(RunCMake)
+
+set(RunCMake_TEST_NO_CLEAN 1)
+
+set(exportFileName "${RunCMake_BINARY_DIR}/module.cmake")
+set(exportNameSpace "ex")
+set(exportTargetName "ImportLib")
+
+set(RunCMake_TEST_OPTIONS_BASE ${RunCMake_TEST_OPTIONS}
+ "-DexportNameSpace:INTERNAL=${exportNameSpace}"
+ "-DexportTargetName:INTERNAL=${exportTargetName}")
+
+file(REMOVE "${exportFileName}")
+
+# generate C# & C++ assemblies for use as imported target
+set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/ImportLib-build)
+file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+
+set(RunCMake_TEST_OPTIONS ${RunCMake_TEST_OPTIONS_BASE}
+ "-DexportFileName:INTERNAL=${exportFileName}"
+ # make sure we know the RunCMake_TEST if configuring the project again
+ # with cmake-gui for debugging.
+ "-DRunCMake_TEST:INTERNAL=ImportLib")
+
+run_cmake(ImportLib)
+run_cmake_command(ImportLib-build ${CMAKE_COMMAND} --build . --config Debug)
+
+# generate C# & managed C++ programs which reference imported managed assemblies.
+set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/ReferenceImport-build)
+file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+
+set(RunCMake_TEST_OPTIONS ${RunCMake_TEST_OPTIONS_BASE}
+ "-DexportFileName:INTERNAL=${exportFileName}"
+ # make sure we know the RunCMake_TEST if configuring the project again
+ # with cmake-gui for debugging.
+ "-DRunCMake_TEST:INTERNAL=ReferenceImport")
+
+run_cmake(ReferenceImport)
+run_cmake_command(ReferenceImport-build ${CMAKE_COMMAND} --build . --config Debug)
diff --git a/Tests/RunCMake/CTest/CTestTestfile.cmake.in b/Tests/RunCMake/CTest/CTestTestfile.cmake.in
new file mode 100644
index 000000000..07632445c
--- /dev/null
+++ b/Tests/RunCMake/CTest/CTestTestfile.cmake.in
@@ -0,0 +1 @@
+# Created manually
diff --git a/Tests/RunCMake/CTest/NotOn-check.cmake b/Tests/RunCMake/CTest/NotOn-check.cmake
new file mode 100644
index 000000000..b68218af0
--- /dev/null
+++ b/Tests/RunCMake/CTest/NotOn-check.cmake
@@ -0,0 +1,8 @@
+set(f "${RunCMake_TEST_BINARY_DIR}/CTestTestfile.cmake")
+if(NOT EXISTS "${f}")
+ set(RunCMake_TEST_FAILED "File does not exist:\n ${f}")
+endif()
+file(READ ${f} content)
+if(NOT "${content}" MATCHES "^# Created manually")
+ set(RunCMake_TEST_FAILED "File:\n ${f}\nhas unexpected content:\n ${content}")
+endif()
diff --git a/Tests/RunCMake/CTest/NotOn.cmake b/Tests/RunCMake/CTest/NotOn.cmake
new file mode 100644
index 000000000..7fba019b6
--- /dev/null
+++ b/Tests/RunCMake/CTest/NotOn.cmake
@@ -0,0 +1,3 @@
+set(BUILD_TESTING OFF CACHE BOOL "Build the testing tree.")
+include(CTest)
+configure_file(CTestTestfile.cmake.in CTestTestfile.cmake)
diff --git a/Tests/RunCMake/CTestCommandLine/TestAffinity-stdout.txt b/Tests/RunCMake/CTestCommandLine/TestAffinity-stdout.txt
new file mode 100644
index 000000000..e23d30bcf
--- /dev/null
+++ b/Tests/RunCMake/CTestCommandLine/TestAffinity-stdout.txt
@@ -0,0 +1 @@
+1: CPU affinity (mask count is '1'|not supported on this platform)\.
diff --git a/Tests/RunCMake/CTestCommandLine/TestStdin-stdin.txt b/Tests/RunCMake/CTestCommandLine/TestStdin-stdin.txt
new file mode 100644
index 000000000..d83b50a68
--- /dev/null
+++ b/Tests/RunCMake/CTestCommandLine/TestStdin-stdin.txt
@@ -0,0 +1 @@
+Content for TestStdin
diff --git a/Tests/RunCMake/CTestCommandLine/TestStdin-stdout.txt b/Tests/RunCMake/CTestCommandLine/TestStdin-stdout.txt
new file mode 100644
index 000000000..d83b50a68
--- /dev/null
+++ b/Tests/RunCMake/CTestCommandLine/TestStdin-stdout.txt
@@ -0,0 +1 @@
+Content for TestStdin
diff --git a/Tests/RunCMake/CTestCommandLine/show-only_bad-result.txt b/Tests/RunCMake/CTestCommandLine/show-only_bad-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CTestCommandLine/show-only_bad-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CTestCommandLine/show-only_bad-stderr.txt b/Tests/RunCMake/CTestCommandLine/show-only_bad-stderr.txt
new file mode 100644
index 000000000..cc55ab390
--- /dev/null
+++ b/Tests/RunCMake/CTestCommandLine/show-only_bad-stderr.txt
@@ -0,0 +1 @@
+^CMake Error: '--show-only=' given unknown value 'bad'$
diff --git a/Tests/RunCMake/CTestCommandLine/show-only_human-stdout.txt b/Tests/RunCMake/CTestCommandLine/show-only_human-stdout.txt
new file mode 100644
index 000000000..13321496c
--- /dev/null
+++ b/Tests/RunCMake/CTestCommandLine/show-only_human-stdout.txt
@@ -0,0 +1 @@
+Test #1: ShowOnly
diff --git a/Tests/RunCMake/CTestCommandLine/show-only_json-v1-check.cmake b/Tests/RunCMake/CTestCommandLine/show-only_json-v1-check.cmake
new file mode 100644
index 000000000..f9234f8d9
--- /dev/null
+++ b/Tests/RunCMake/CTestCommandLine/show-only_json-v1-check.cmake
@@ -0,0 +1 @@
+show_only_json_check_python(1)
diff --git a/Tests/RunCMake/CTestCommandLine/show-only_json-v1_check.py b/Tests/RunCMake/CTestCommandLine/show-only_json-v1_check.py
new file mode 100644
index 000000000..3ad576813
--- /dev/null
+++ b/Tests/RunCMake/CTestCommandLine/show-only_json-v1_check.py
@@ -0,0 +1,116 @@
+from show_only_json_check import *
+
+def check_kind(k):
+ assert is_string(k)
+ assert k == "ctestInfo"
+
+def check_version(v):
+ assert is_dict(v)
+ assert sorted(v.keys()) == ["major", "minor"]
+ assert is_int(v["major"])
+ assert is_int(v["minor"])
+ assert v["major"] == 1
+ assert v["minor"] == 0
+
+def check_backtracegraph(b):
+ assert is_dict(b)
+ assert sorted(b.keys()) == ["commands", "files", "nodes"]
+ check_backtracegraph_commands(b["commands"])
+ check_backtracegraph_files(b["files"])
+ check_backtracegraph_nodes(b["nodes"])
+
+def check_backtracegraph_commands(c):
+ assert is_list(c)
+ assert len(c) == 1
+ assert is_string(c[0])
+ assert c[0] == "add_test"
+
+def check_backtracegraph_files(f):
+ assert is_list(f)
+ assert len(f) == 2
+ assert is_string(f[0])
+ assert is_string(f[1])
+ assert f[0] == "file1"
+ assert f[1] == "file0"
+
+def check_backtracegraph_nodes(n):
+ assert is_list(n)
+ assert len(n) == 2
+ node = n[0]
+ assert is_dict(node)
+ assert sorted(node.keys()) == ["file"]
+ assert is_int(node["file"])
+ assert node["file"] == 1
+ node = n[1]
+ assert is_dict(node)
+ assert sorted(node.keys()) == ["command", "file", "line", "parent"]
+ assert is_int(node["command"])
+ assert is_int(node["file"])
+ assert is_int(node["line"])
+ assert is_int(node["parent"])
+ assert node["command"] == 0
+ assert node["file"] == 0
+ assert node["line"] == 1
+ assert node["parent"] == 0
+
+def check_command(c):
+ assert is_list(c)
+ assert len(c) == 3
+ assert is_string(c[0])
+ check_re(c[0], "/cmake(\.exe)?$")
+ assert is_string(c[1])
+ assert c[1] == "-E"
+ assert is_string(c[2])
+ assert c[2] == "echo"
+
+def check_reqfiles_property(p):
+ assert is_dict(p)
+ assert sorted(p.keys()) == ["name", "value"]
+ assert is_string(p["name"])
+ assert is_list(p["value"])
+ assert p["name"] == "REQUIRED_FILES"
+ assert len(p["value"]) == 1
+ assert p["value"][0] == "RequiredFileDoesNotExist"
+
+def check_willfail_property(p):
+ assert is_dict(p)
+ assert sorted(p.keys()) == ["name", "value"]
+ assert is_string(p["name"])
+ assert is_bool(p["value"])
+ assert p["name"] == "WILL_FAIL"
+ assert p["value"] == True
+
+def check_workingdir_property(p):
+ assert is_dict(p)
+ assert sorted(p.keys()) == ["name", "value"]
+ assert is_string(p["name"])
+ assert is_string(p["value"])
+ assert p["name"] == "WORKING_DIRECTORY"
+ assert p["value"].endswith("Tests/RunCMake/CTestCommandLine/ShowOnly")
+
+def check_properties(p):
+ assert is_list(p)
+ assert len(p) == 3
+ check_reqfiles_property(p[0])
+ check_willfail_property(p[1])
+ check_workingdir_property(p[2])
+
+def check_tests(t):
+ assert is_list(t)
+ assert len(t) == 1
+ test = t[0]
+ assert is_dict(test)
+ assert sorted(test.keys()) == ["backtrace", "command", "name", "properties"]
+ assert is_int(test["backtrace"])
+ assert test["backtrace"] == 1
+ check_command(test["command"])
+ assert is_string(test["name"])
+ assert test["name"] == "ShowOnly"
+ check_properties(test["properties"])
+
+assert is_dict(ctest_json)
+assert sorted(ctest_json.keys()) == ["backtraceGraph", "kind", "tests", "version"]
+check_backtracegraph(ctest_json["backtraceGraph"])
+check_kind(ctest_json["kind"])
+check_version(ctest_json["version"])
+check_tests(ctest_json["tests"])
diff --git a/Tests/RunCMake/CTestCommandLine/show_only_json_check.py b/Tests/RunCMake/CTestCommandLine/show_only_json_check.py
new file mode 100644
index 000000000..493c9e579
--- /dev/null
+++ b/Tests/RunCMake/CTestCommandLine/show_only_json_check.py
@@ -0,0 +1,24 @@
+import sys
+import json
+import re
+
+def is_bool(x):
+ return isinstance(x, bool)
+
+def is_dict(x):
+ return isinstance(x, dict)
+
+def is_list(x):
+ return isinstance(x, list)
+
+def is_int(x):
+ return isinstance(x, int) or isinstance(x, long)
+
+def is_string(x):
+ return isinstance(x, str) or isinstance(x, unicode)
+
+def check_re(x, regex):
+ assert re.search(regex, x)
+
+with open(sys.argv[1]) as f:
+ ctest_json = json.load(f)
diff --git a/Tests/RunCMake/CTestCommandLine/test-load-wait-stdout.txt b/Tests/RunCMake/CTestCommandLine/test-load-wait-stdout.txt
new file mode 100644
index 000000000..11a768a9c
--- /dev/null
+++ b/Tests/RunCMake/CTestCommandLine/test-load-wait-stdout.txt
@@ -0,0 +1,8 @@
+^Test project .*/Tests/RunCMake/CTestCommandLine/TestLoad
+\*\*\*\*\* WAITING, System Load: 5, Max Allowed Load: 3, Smallest test TestLoad[1-2] requires 1\*\*\*\*\*
+ Start 1: TestLoad1
+ Start 2: TestLoad2
+1/2 Test #[1-2]: TestLoad[1-2] ........................ Passed +[0-9.]+ sec
+2/2 Test #[1-2]: TestLoad[1-2] ........................ Passed +[0-9.]+ sec
++
+100% tests passed, 0 tests failed out of 2
diff --git a/Tests/RunCMake/CacheNewline/CMakeLists.txt b/Tests/RunCMake/CacheNewline/CMakeLists.txt
new file mode 100644
index 000000000..93ee9dfd5
--- /dev/null
+++ b/Tests/RunCMake/CacheNewline/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.5)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/CacheNewline/CacheNewline-check.cmake b/Tests/RunCMake/CacheNewline/CacheNewline-check.cmake
new file mode 100644
index 000000000..6534f6386
--- /dev/null
+++ b/Tests/RunCMake/CacheNewline/CacheNewline-check.cmake
@@ -0,0 +1,16 @@
+set(CACHE_EXPECTED_FILE "${RunCMake_TEST_SOURCE_DIR}/cache-regex.txt")
+set(CACHE_ACTUAL_FILE "${RunCMake_BINARY_DIR}/CacheNewline-build/CMakeCache.txt")
+
+file(READ ${CACHE_EXPECTED_FILE} CACHE_EXPECTED)
+string(REGEX REPLACE "\r\n" "\n" CACHE_EXPECTED "${CACHE_EXPECTED}")
+string(REGEX REPLACE "\n+$" "" CACHE_EXPECTED "${CACHE_EXPECTED}")
+file(READ ${CACHE_ACTUAL_FILE} CACHE_ACTUAL)
+string(REGEX REPLACE "\r\n" "\n" CACHE_ACTUAL "${CACHE_ACTUAL}")
+string(REGEX REPLACE "\n+$" "" CACHE_ACTUAL "${CACHE_ACTUAL}")
+
+if(NOT "${CACHE_ACTUAL}" MATCHES "${CACHE_EXPECTED}")
+ set(RunCMake_TEST_FAILED "${CACHE_ACTUAL_FILE} does not match ${CACHE_EXPECTED_FILE}:
+
+CMakeCache.txt contents = [\n${CACHE_ACTUAL}\n]
+Expected = [\n${CACHE_EXPECTED}\n]")
+endif()
diff --git a/Tests/RunCMake/CacheNewline/CacheNewline-stderr.txt b/Tests/RunCMake/CacheNewline/CacheNewline-stderr.txt
new file mode 100644
index 000000000..726c65ce0
--- /dev/null
+++ b/Tests/RunCMake/CacheNewline/CacheNewline-stderr.txt
@@ -0,0 +1,2 @@
+CMake Warning:
+ Value of NEWLINE_VARIABLE contained a newline; truncating
diff --git a/Tests/RunCMake/CacheNewline/CacheNewline.cmake b/Tests/RunCMake/CacheNewline/CacheNewline.cmake
new file mode 100644
index 000000000..81851dbe0
--- /dev/null
+++ b/Tests/RunCMake/CacheNewline/CacheNewline.cmake
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.5)
+
+project(CacheNewlineTest NONE)
+
+set(NEWLINE_VARIABLE "a\nb" CACHE STRING "Offending entry")
diff --git a/Tests/RunCMake/CacheNewline/RunCMakeTest.cmake b/Tests/RunCMake/CacheNewline/RunCMakeTest.cmake
new file mode 100644
index 000000000..5e3d2d499
--- /dev/null
+++ b/Tests/RunCMake/CacheNewline/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(CacheNewline)
diff --git a/Tests/RunCMake/CacheNewline/cache-regex.txt b/Tests/RunCMake/CacheNewline/cache-regex.txt
new file mode 100644
index 000000000..b239dbc82
--- /dev/null
+++ b/Tests/RunCMake/CacheNewline/cache-regex.txt
@@ -0,0 +1,6 @@
+//Offending entry
+NEWLINE_VARIABLE:STRING=a
+# WARNING: Value of NEWLINE_VARIABLE contained a newline and was
+# truncated\. Original value:
+# a
+# \\nb
diff --git a/Tests/RunCMake/CheckModules/CMP0075-stderr.txt b/Tests/RunCMake/CheckModules/CMP0075-stderr.txt
new file mode 100644
index 000000000..960fe9444
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CMP0075-stderr.txt
@@ -0,0 +1,50 @@
+^CMake Warning \(dev\) at [^
+]*/Modules/CheckIncludeFile.cmake:[0-9]+ \(message\):
+ Policy CMP0075 is not set: Include file check macros honor
+ CMAKE_REQUIRED_LIBRARIES. Run "cmake --help-policy CMP0075" for policy
+ details. Use the cmake_policy command to set the policy and suppress this
+ warning.
+
+ CMAKE_REQUIRED_LIBRARIES is set to:
+
+ does_not_exist
+
+ For compatibility with CMake 3.11 and below this check is ignoring it.
+Call Stack \(most recent call first\):
+ CMP0075.cmake:11 \(check_include_file\)
+ CMakeLists.txt:[0-9]+ \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
++
+CMake Warning \(dev\) at [^
+]*/Modules/CheckIncludeFileCXX.cmake:[0-9]+ \(message\):
+ Policy CMP0075 is not set: Include file check macros honor
+ CMAKE_REQUIRED_LIBRARIES. Run "cmake --help-policy CMP0075" for policy
+ details. Use the cmake_policy command to set the policy and suppress this
+ warning.
+
+ CMAKE_REQUIRED_LIBRARIES is set to:
+
+ does_not_exist
+
+ For compatibility with CMake 3.11 and below this check is ignoring it.
+Call Stack \(most recent call first\):
+ CMP0075.cmake:26 \(check_include_file_cxx\)
+ CMakeLists.txt:[0-9]+ \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
++
+CMake Warning \(dev\) at [^
+]*/Modules/CheckIncludeFiles.cmake:[0-9]+ \(message\):
+ Policy CMP0075 is not set: Include file check macros honor
+ CMAKE_REQUIRED_LIBRARIES. Run "cmake --help-policy CMP0075" for policy
+ details. Use the cmake_policy command to set the policy and suppress this
+ warning.
+
+ CMAKE_REQUIRED_LIBRARIES is set to:
+
+ does_not_exist
+
+ For compatibility with CMake 3.11 and below this check is ignoring it.
+Call Stack \(most recent call first\):
+ CMP0075.cmake:41 \(check_include_files\)
+ CMakeLists.txt:[0-9]+ \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/CheckModules/CMP0075.cmake b/Tests/RunCMake/CheckModules/CMP0075.cmake
new file mode 100644
index 000000000..4a3b7204a
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CMP0075.cmake
@@ -0,0 +1,124 @@
+enable_language(C)
+enable_language(CXX)
+include(CheckIncludeFile)
+include(CheckIncludeFileCXX)
+include(CheckIncludeFiles)
+
+set(CMAKE_REQUIRED_LIBRARIES does_not_exist)
+
+#============================================================================
+
+check_include_file("stddef.h" HAVE_STDDEF_H_1)
+if(NOT HAVE_STDDEF_H_1)
+ message(SEND_ERROR "HAVE_STDDEF_H_1 failed but should have passed.")
+endif()
+if(NOT _CIF_CMP0075_WARNED)
+ message(SEND_ERROR "HAVE_STDDEF_H_1 did not warn but should have")
+endif()
+check_include_file("stddef.h" HAVE_STDDEF_H_2) # second does not warn
+if(NOT HAVE_STDDEF_H_2)
+ message(SEND_ERROR "HAVE_STDDEF_H_2 failed but should have passed.")
+endif()
+unset(_CIF_CMP0075_WARNED)
+
+#----------------------------------------------------------------------------
+
+check_include_file_cxx("stddef.h" HAVE_STDDEF_H_CXX_1)
+if(NOT HAVE_STDDEF_H_CXX_1)
+ message(SEND_ERROR "HAVE_STDDEF_H_CXX_1 failed but should have passed.")
+endif()
+if(NOT _CIF_CMP0075_WARNED)
+ message(SEND_ERROR "HAVE_STDDEF_H_CXX_1 did not warn but should have")
+endif()
+check_include_file_cxx("stddef.h" HAVE_STDDEF_H_CXX_2) # second does not warn
+if(NOT HAVE_STDDEF_H_CXX_2)
+ message(SEND_ERROR "HAVE_STDDEF_H_CXX_2 failed but should have passed.")
+endif()
+unset(_CIF_CMP0075_WARNED)
+
+#----------------------------------------------------------------------------
+
+check_include_files("stddef.h;stdlib.h" HAVE_STDLIB_H_1)
+if(NOT HAVE_STDLIB_H_1)
+ message(SEND_ERROR "HAVE_STDLIB_H_1 failed but should have passed.")
+endif()
+if(NOT _CIF_CMP0075_WARNED)
+ message(SEND_ERROR "HAVE_STDLIB_H_1 did not warn but should have")
+endif()
+check_include_files("stddef.h;stdlib.h" HAVE_STDLIB_H_2) # second does not warn
+if(NOT HAVE_STDLIB_H_2)
+ message(SEND_ERROR "HAVE_STDLIB_H_2 failed but should have passed.")
+endif()
+unset(_CIF_CMP0075_WARNED)
+
+#============================================================================
+cmake_policy(SET CMP0075 OLD)
+# These should not warn.
+# These should pass the checks due to ignoring 'does_not_exist'.
+
+check_include_file("stddef.h" HAVE_STDDEF_H_3)
+if(NOT HAVE_STDDEF_H_3)
+ message(SEND_ERROR "HAVE_STDDEF_H_3 failed but should have passed.")
+endif()
+if(_CIF_CMP0075_WARNED)
+ message(SEND_ERROR "HAVE_STDDEF_H_3 warned but should not have")
+endif()
+unset(_CIF_CMP0075_WARNED)
+
+#----------------------------------------------------------------------------
+
+check_include_file_cxx("stddef.h" HAVE_STDDEF_H_CXX_3)
+if(NOT HAVE_STDDEF_H_CXX_3)
+ message(SEND_ERROR "HAVE_STDDEF_H_CXX_3 failed but should have passed.")
+endif()
+if(_CIF_CMP0075_WARNED)
+ message(SEND_ERROR "HAVE_STDDEF_H_CXX_3 warned but should not have")
+endif()
+unset(_CIF_CMP0075_WARNED)
+
+#----------------------------------------------------------------------------
+
+check_include_files("stddef.h;stdlib.h" HAVE_STDLIB_H_3)
+if(NOT HAVE_STDLIB_H_3)
+ message(SEND_ERROR "HAVE_STDLIB_H_3 failed but should have passed.")
+endif()
+if(_CIF_CMP0075_WARNED)
+ message(SEND_ERROR "HAVE_STDLIB_H_3 warned but should not have")
+endif()
+unset(_CIF_CMP0075_WARNED)
+
+#============================================================================
+cmake_policy(SET CMP0075 NEW)
+# These should not warn.
+# These should fail the checks due to requiring 'does_not_exist'.
+
+check_include_file("stddef.h" HAVE_STDDEF_H_4)
+if(HAVE_STDDEF_H_4)
+ message(SEND_ERROR "HAVE_STDDEF_H_4 passed but should have failed.")
+endif()
+if(_CIF_CMP0075_WARNED)
+ message(SEND_ERROR "HAVE_STDDEF_H_4 warned but should not have")
+endif()
+unset(_CIF_CMP0075_WARNED)
+
+#----------------------------------------------------------------------------
+
+check_include_file_cxx("stddef.h" HAVE_STDDEF_H_CXX_4)
+if(HAVE_STDDEF_H_CXX_4)
+ message(SEND_ERROR "HAVE_STDDEF_H_CXX_4 passed but should have failed.")
+endif()
+if(_CIF_CMP0075_WARNED)
+ message(SEND_ERROR "HAVE_STDDEF_H_CXX_4 warned but should not have")
+endif()
+unset(_CIF_CMP0075_WARNED)
+
+#----------------------------------------------------------------------------
+
+check_include_files("stddef.h;stdlib.h" HAVE_STDLIB_H_4)
+if(HAVE_STDLIB_H_4)
+ message(SEND_ERROR "HAVE_STDLIB_H_4 passed but should have failed.")
+endif()
+if(_CIF_CMP0075_WARNED)
+ message(SEND_ERROR "HAVE_STDLIB_H_4 warned but should not have")
+endif()
+unset(_CIF_CMP0075_WARNED)
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage-result.txt b/Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage-stderr.txt b/Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage-stderr.txt
new file mode 100644
index 000000000..36c28f9d2
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at .*/Modules/CheckIncludeFiles.cmake:[0-9]+. \(message\):
+ No languages listed for LANGUAGE option.
+
+ Supported languages: C, CXX.
+
+Call Stack \(most recent call first\):
+ CheckIncludeFilesMissingLanguage.cmake:[0-9]+ \(check_include_files\)
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage.cmake b/Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage.cmake
new file mode 100644
index 000000000..59accb084
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesMissingLanguage.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+include(CheckIncludeFiles)
+check_include_files("stddef.h;stdlib.h" HAVE_MISSING_ARGUMENT_H LANGUAGE)
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesOk.cmake b/Tests/RunCMake/CheckModules/CheckIncludeFilesOk.cmake
new file mode 100644
index 000000000..0891ec69a
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesOk.cmake
@@ -0,0 +1,6 @@
+enable_language(C)
+enable_language(CXX)
+include(CheckIncludeFiles)
+check_include_files("stddef.h;stdlib.h" HAVE_STDLIB_H)
+check_include_files("stddef.h;stdlib.h" HAVE_STDLIB_H2 LANGUAGE C)
+check_include_files("cstddef;cstdlib" HAVE_CSTDLIB_H LANGUAGE CXX)
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesOkNoC.cmake b/Tests/RunCMake/CheckModules/CheckIncludeFilesOkNoC.cmake
new file mode 100644
index 000000000..a1d2843df
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesOkNoC.cmake
@@ -0,0 +1,4 @@
+enable_language(CXX)
+include(CheckIncludeFiles)
+check_include_files("cstddef;cstdlib" HAVE_CSTDLIB_H3 LANGUAGE CXX)
+check_include_files("cstddef;cstdlib" HAVE_CSTDLIB_H4)
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument-result.txt b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument-stderr.txt b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument-stderr.txt
new file mode 100644
index 000000000..098da7913
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at .*/Modules/CheckIncludeFiles.cmake:[0-9]+. \(message\):
+ Unknown arguments:
+
+ FOOBAR
+
+Call Stack \(most recent call first\):
+ CheckIncludeFilesUnknownArgument.cmake:[0-9]+ \(check_include_files\)
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument.cmake b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument.cmake
new file mode 100644
index 000000000..dfc2b932c
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownArgument.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+include(CheckIncludeFiles)
+check_include_files("stddef.h;stdlib.h" HAVE_UNKNOWN_ARGUMENT_H FOOBAR)
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage-result.txt b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage-stderr.txt b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage-stderr.txt
new file mode 100644
index 000000000..5d4a9ecb2
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage-stderr.txt
@@ -0,0 +1,10 @@
+CMake Error at .*/Modules/CheckIncludeFiles.cmake:[0-9]+. \(message\):
+ Unknown language:
+
+ FOOBAR
+
+ Supported languages: C, CXX.
+
+Call Stack \(most recent call first\):
+ CheckIncludeFilesUnknownLanguage.cmake:[0-9]+ \(check_include_files\)
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage.cmake b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage.cmake
new file mode 100644
index 000000000..3a77cf93f
--- /dev/null
+++ b/Tests/RunCMake/CheckModules/CheckIncludeFilesUnknownLanguage.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+include(CheckIncludeFiles)
+check_include_files("stddef.h;stdlib.h" HAVE_UNKNOWN_ARGUMENT_H LANGUAGE FOOBAR)
diff --git a/Tests/RunCMake/CommandLine/B-no-arg-result.txt b/Tests/RunCMake/CommandLine/B-no-arg-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/B-no-arg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/B-no-arg-stderr.txt b/Tests/RunCMake/CommandLine/B-no-arg-stderr.txt
new file mode 100644
index 000000000..2309c5edd
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/B-no-arg-stderr.txt
@@ -0,0 +1 @@
+CMake Error: No build directory specified for -B
diff --git a/Tests/RunCMake/CommandLine/B-no-arg2-result.txt b/Tests/RunCMake/CommandLine/B-no-arg2-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/B-no-arg2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/B-no-arg2-stderr.txt b/Tests/RunCMake/CommandLine/B-no-arg2-stderr.txt
new file mode 100644
index 000000000..2309c5edd
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/B-no-arg2-stderr.txt
@@ -0,0 +1 @@
+CMake Error: No build directory specified for -B
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-bad-number-result.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-bad-number-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-bad-number-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-bad-number-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-bad-number-stderr.txt
new file mode 100644
index 000000000..e73d76020
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-bad-number-stderr.txt
@@ -0,0 +1,3 @@
+^'--parallel' invalid number '12ab' given\.
++
+Usage: cmake --build <dir> \[options\] \[-- \[native-options\]\]
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-good-number-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-good-number-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-good-number-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-good-number-trailing--target-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-good-number-trailing--target-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-good-number-trailing--target-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-large-result.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-large-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-large-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-large-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-large-stderr.txt
new file mode 100644
index 000000000..94fc15732
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-large-stderr.txt
@@ -0,0 +1,3 @@
+^The <jobs> value is too large\.
++
+Usage: cmake --build <dir> \[options\] \[-- \[native-options\]\]
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-number-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-number-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-number-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-number-trailing--target-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-number-trailing--target-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-number-trailing--target-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-bad-number-result.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-bad-number-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-bad-number-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-bad-number-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-bad-number-stderr.txt
new file mode 100644
index 000000000..e73d76020
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-bad-number-stderr.txt
@@ -0,0 +1,3 @@
+^'--parallel' invalid number '12ab' given\.
++
+Usage: cmake --build <dir> \[options\] \[-- \[native-options\]\]
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-good-number-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-good-number-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-good-number-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-good-number-trailing--target-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-good-number-trailing--target-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-no-space-good-number-trailing--target-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-zero-result.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-zero-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-zero-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build--parallel-zero-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-zero-stderr.txt
new file mode 100644
index 000000000..8ed4fee99
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build--parallel-zero-stderr.txt
@@ -0,0 +1,3 @@
+^The <jobs> value requires a positive integer argument\.
++
+Usage: cmake --build <dir> \[options\] \[-- \[native-options\]\]
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-bad-number-result.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-bad-number-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-bad-number-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-bad-number-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-bad-number-stderr.txt
new file mode 100644
index 000000000..c81008786
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-bad-number-stderr.txt
@@ -0,0 +1,3 @@
+^'-j' invalid number '12ab' given\.
++
+Usage: cmake --build <dir> \[options\] \[-- \[native-options\]\]
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-good-number-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-good-number-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-good-number-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-good-number-trailing--target-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-good-number-trailing--target-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-good-number-trailing--target-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-large-result.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-large-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-large-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-large-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-large-stderr.txt
new file mode 100644
index 000000000..94fc15732
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-large-stderr.txt
@@ -0,0 +1,3 @@
+^The <jobs> value is too large\.
++
+Usage: cmake --build <dir> \[options\] \[-- \[native-options\]\]
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-number-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-number-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-number-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-number-trailing--target-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-number-trailing--target-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-number-trailing--target-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-bad-number-result.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-bad-number-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-bad-number-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-bad-number-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-bad-number-stderr.txt
new file mode 100644
index 000000000..c81008786
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-bad-number-stderr.txt
@@ -0,0 +1,3 @@
+^'-j' invalid number '12ab' given\.
++
+Usage: cmake --build <dir> \[options\] \[-- \[native-options\]\]
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-good-number-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-good-number-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-good-number-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-good-number-trailing--target-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-good-number-trailing--target-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-no-space-good-number-trailing--target-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-zero-result.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-zero-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-zero-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-jobs-zero-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-zero-stderr.txt
new file mode 100644
index 000000000..8ed4fee99
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-jobs-zero-stderr.txt
@@ -0,0 +1,3 @@
+^The <jobs> value requires a positive integer argument\.
++
+Usage: cmake --build <dir> \[options\] \[-- \[native-options\]\]
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-jobs-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-jobs-stderr.txt
new file mode 100644
index 000000000..3c2c808e9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-jobs-stderr.txt
@@ -0,0 +1 @@
+(^$|^Warning: .* does not support parallel builds\. Ignoring parallel build command line option\.)
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-first-result.txt b/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-first-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-first-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-first-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-first-stderr.txt
new file mode 100644
index 000000000..40d9bec84
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-first-stderr.txt
@@ -0,0 +1,2 @@
+^Error: Building 'clean' and other targets together is not supported\.
+Usage: cmake --build <dir> \[options\] \[-- \[native-options\]\]
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-second-result.txt b/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-second-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-second-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-second-stderr.txt b/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-second-stderr.txt
new file mode 100644
index 000000000..40d9bec84
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/BuildDir--build-multiple-targets-with-clean-second-stderr.txt
@@ -0,0 +1,2 @@
+^Error: Building 'clean' and other targets together is not supported\.
+Usage: cmake --build <dir> \[options\] \[-- \[native-options\]\]
diff --git a/Tests/RunCMake/CommandLine/Cno-file-result.txt b/Tests/RunCMake/CommandLine/Cno-file-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Cno-file-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Cno-file-stderr.txt b/Tests/RunCMake/CommandLine/Cno-file-stderr.txt
new file mode 100644
index 000000000..67a20324c
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Cno-file-stderr.txt
@@ -0,0 +1,3 @@
+^CMake Error: Error processing file: nosuchcachefile.txt
+CMake Error: The source directory ".*/Tests/RunCMake/CommandLine/Cno-file-build" does not appear to contain CMakeLists.txt.
+Specify --help for usage, or press the help button on the CMake GUI.$
diff --git a/Tests/RunCMake/CommandLine/D-no-src-result.txt b/Tests/RunCMake/CommandLine/D-no-src-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/D-no-src-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/D-no-src-stderr.txt b/Tests/RunCMake/CommandLine/D-no-src-stderr.txt
new file mode 100644
index 000000000..b5ac69c3e
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/D-no-src-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error: The source directory ".*/Tests/RunCMake/CommandLine/D-no-src-build" does not appear to contain CMakeLists.txt.
+Specify --help for usage, or press the help button on the CMake GUI.$
diff --git a/Tests/RunCMake/CommandLine/Dno-src-result.txt b/Tests/RunCMake/CommandLine/Dno-src-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Dno-src-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Dno-src-stderr.txt b/Tests/RunCMake/CommandLine/Dno-src-stderr.txt
new file mode 100644
index 000000000..402c71409
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Dno-src-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error: The source directory ".*/Tests/RunCMake/CommandLine/Dno-src-build" does not appear to contain CMakeLists.txt.
+Specify --help for usage, or press the help button on the CMake GUI.$
diff --git a/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-stderr.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-stderr.txt
new file mode 100644
index 000000000..338f7c4e6
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-stderr.txt
@@ -0,0 +1,2 @@
+^Error running 'iwyu-does-not-exist': [^
+]+$
diff --git a/Tests/RunCMake/CommandLine/E___run_co_compile-no----result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no----result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no----result.txt
@@ -0,0 +1 @@
+1
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_co_compile-no-cc-result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-result.txt
@@ -0,0 +1 @@
+1
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_co_compile-no-iwyu-result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-result.txt
@@ -0,0 +1 @@
+1
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_compare_files-different-eol-result.txt b/Tests/RunCMake/CommandLine/E_compare_files-different-eol-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_compare_files-different-eol-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_compare_files-different-eol-stderr.txt b/Tests/RunCMake/CommandLine/E_compare_files-different-eol-stderr.txt
new file mode 100644
index 000000000..4729ccb8f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_compare_files-different-eol-stderr.txt
@@ -0,0 +1 @@
+^Files ".*/compare_files/lf" to ".*/compare_files/crlf" are different.$
diff --git a/Tests/RunCMake/CommandLine/E_compare_files-ignore-eol-nonexistent-result.txt b/Tests/RunCMake/CommandLine/E_compare_files-ignore-eol-nonexistent-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_compare_files-ignore-eol-nonexistent-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_compare_files-ignore-eol-nonexistent-stderr.txt b/Tests/RunCMake/CommandLine/E_compare_files-ignore-eol-nonexistent-stderr.txt
new file mode 100644
index 000000000..8a9ca81f8
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_compare_files-ignore-eol-nonexistent-stderr.txt
@@ -0,0 +1 @@
+^Files "nonexistent_a" to "nonexistent_b" are different.$
diff --git a/Tests/RunCMake/CommandLine/E_make_directory-directory-with-parent-check.cmake b/Tests/RunCMake/CommandLine/E_make_directory-directory-with-parent-check.cmake
new file mode 100644
index 000000000..ea3d161af
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_make_directory-directory-with-parent-check.cmake
@@ -0,0 +1,3 @@
+if(NOT IS_DIRECTORY ${out}/parent/child)
+ set(RunCMake_TEST_FAILED "child directory was not created")
+endif()
diff --git a/Tests/RunCMake/CommandLine/E_make_directory-three-directories-check.cmake b/Tests/RunCMake/CommandLine/E_make_directory-three-directories-check.cmake
new file mode 100644
index 000000000..c1e84744a
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_make_directory-three-directories-check.cmake
@@ -0,0 +1,6 @@
+if(NOT IS_DIRECTORY ${out}/d1)
+ set(RunCMake_TEST_FAILED "directory d1 was not created")
+endif()
+if(NOT IS_DIRECTORY ${out}/d2)
+ set(RunCMake_TEST_FAILED "directory d2 was not created")
+endif()
diff --git a/Tests/RunCMake/CommandLine/E_make_directory-two-directories-and-file-result.txt b/Tests/RunCMake/CommandLine/E_make_directory-two-directories-and-file-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_make_directory-two-directories-and-file-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_make_directory-two-directories-and-file-stderr.txt b/Tests/RunCMake/CommandLine/E_make_directory-two-directories-and-file-stderr.txt
new file mode 100644
index 000000000..08a9428f4
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_make_directory-two-directories-and-file-stderr.txt
@@ -0,0 +1 @@
+^Error creating directory .*file_for_test.txt\".$
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_remove_directory-directory-with-parent-check.cmake b/Tests/RunCMake/CommandLine/E_remove_directory-directory-with-parent-check.cmake
new file mode 100644
index 000000000..fd6ea111f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_remove_directory-directory-with-parent-check.cmake
@@ -0,0 +1,3 @@
+if(IS_DIRECTORY ${out}/parent/child)
+ set(RunCMake_TEST_FAILED "child directory was not removed")
+endif()
diff --git a/Tests/RunCMake/CommandLine/E_remove_directory-directory-with-parent-stderr.txt b/Tests/RunCMake/CommandLine/E_remove_directory-directory-with-parent-stderr.txt
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_remove_directory-directory-with-parent-stderr.txt
diff --git a/Tests/RunCMake/CommandLine/E_remove_directory-three-directories-check.cmake b/Tests/RunCMake/CommandLine/E_remove_directory-three-directories-check.cmake
new file mode 100644
index 000000000..2b7202ad5
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_remove_directory-three-directories-check.cmake
@@ -0,0 +1,6 @@
+if(IS_DIRECTORY ${out}/d1)
+ set(RunCMake_TEST_FAILED "directory d1 was not removed")
+endif()
+if(IS_DIRECTORY ${out}/d2)
+ set(RunCMake_TEST_FAILED "directory d2 was not removed")
+endif()
diff --git a/Tests/RunCMake/CommandLine/E_remove_directory-three-directories-stderr.txt b/Tests/RunCMake/CommandLine/E_remove_directory-three-directories-stderr.txt
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_remove_directory-three-directories-stderr.txt
diff --git a/Tests/RunCMake/CommandLine/E_remove_directory-two-directories-and-file-check.cmake b/Tests/RunCMake/CommandLine/E_remove_directory-two-directories-and-file-check.cmake
new file mode 100644
index 000000000..0aa4a5202
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_remove_directory-two-directories-and-file-check.cmake
@@ -0,0 +1,3 @@
+if(NOT EXISTS ${outfile})
+ set(RunCMake_TEST_FAILED "removed non-directory ${outfile}")
+endif()
diff --git a/Tests/RunCMake/CommandLine/E_remove_directory-two-directories-and-file-stderr.txt b/Tests/RunCMake/CommandLine/E_remove_directory-two-directories-and-file-stderr.txt
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_remove_directory-two-directories-and-file-stderr.txt
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/E_touch-nonexistent-dir-result.txt b/Tests/RunCMake/CommandLine/E_touch-nonexistent-dir-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_touch-nonexistent-dir-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_touch-nonexistent-dir-stderr.txt b/Tests/RunCMake/CommandLine/E_touch-nonexistent-dir-stderr.txt
new file mode 100644
index 000000000..470d8115d
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_touch-nonexistent-dir-stderr.txt
@@ -0,0 +1 @@
+^cmake -E touch: failed to update ".+/touch-nonexistent-dir/foo"\.$
diff --git a/Tests/RunCMake/CommandLine/EnvGenerator/CMakeLists.txt b/Tests/RunCMake/CommandLine/EnvGenerator/CMakeLists.txt
new file mode 100644
index 000000000..2b8c65c9b
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/EnvGenerator/CMakeLists.txt
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.14)
+project(EnvGenerator C)
+if(CMAKE_GENERATOR MATCHES "Visual Studio")
+ message(STATUS "CMAKE_VS_PLATFORM_NAME='${CMAKE_VS_PLATFORM_NAME}'")
+endif()
+add_custom_command(
+ OUTPUT output.txt
+ COMMAND ${CMAKE_COMMAND} -E echo CustomCommand > output.txt
+ )
+add_custom_target(CustomTarget ALL DEPENDS output.txt)
diff --git a/Tests/RunCMake/CommandLine/Envgen-A-platform-result.txt b/Tests/RunCMake/CommandLine/Envgen-A-platform-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-A-platform-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Envgen-A-platform-stderr-vs9.txt b/Tests/RunCMake/CommandLine/Envgen-A-platform-stderr-vs9.txt
new file mode 100644
index 000000000..4eae6aa10
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-A-platform-stderr-vs9.txt
@@ -0,0 +1,2 @@
+^CMake Error at CMakeLists.+
+ No CMAKE_C_COMPILER could be found.
diff --git a/Tests/RunCMake/CommandLine/Envgen-A-platform-stderr.txt b/Tests/RunCMake/CommandLine/Envgen-A-platform-stderr.txt
new file mode 100644
index 000000000..09c2d2ba1
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-A-platform-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error at CMakeLists.+
+.+Platform='fromcli'.+
diff --git a/Tests/RunCMake/CommandLine/Envgen-G-implicit-platform-stdout.txt b/Tests/RunCMake/CommandLine/Envgen-G-implicit-platform-stdout.txt
new file mode 100644
index 000000000..4dd6be1da
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-G-implicit-platform-stdout.txt
@@ -0,0 +1 @@
+-- CMAKE_VS_PLATFORM_NAME='(x64|Win32)'
diff --git a/Tests/RunCMake/CommandLine/Envgen-T-toolset-result.txt b/Tests/RunCMake/CommandLine/Envgen-T-toolset-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-T-toolset-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Envgen-T-toolset-stderr.txt b/Tests/RunCMake/CommandLine/Envgen-T-toolset-stderr.txt
new file mode 100644
index 000000000..b432c19d1
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-T-toolset-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error at CMakeLists.+
+.+(Platform Toolset = 'fromcli'|Specified platform toolset \(fromcli\) is not installed or invalid).+
diff --git a/Tests/RunCMake/CommandLine/Envgen-bad-result.txt b/Tests/RunCMake/CommandLine/Envgen-bad-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-bad-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Envgen-bad-stderr.txt b/Tests/RunCMake/CommandLine/Envgen-bad-stderr.txt
new file mode 100644
index 000000000..4a1215eb2
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-bad-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error: No generator specified for -G
+CMake Error: CMAKE_GENERATOR was set but the specified generator doesn't exist. Using CMake default.
+
+Generators.*
+\* (Unix Makefiles|Visual Studio).*
diff --git a/Tests/RunCMake/CommandLine/Envgen-instance-invalid-result.txt b/Tests/RunCMake/CommandLine/Envgen-instance-invalid-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-instance-invalid-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Envgen-instance-invalid-stderr.txt b/Tests/RunCMake/CommandLine/Envgen-instance-invalid-stderr.txt
new file mode 100644
index 000000000..d53daa5a2
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-instance-invalid-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error at CMakeLists.+
+ could not find specified instance of Visual Studio.+
diff --git a/Tests/RunCMake/CommandLine/Envgen-ninja-result.txt b/Tests/RunCMake/CommandLine/Envgen-ninja-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-ninja-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Envgen-ninja-stderr.txt b/Tests/RunCMake/CommandLine/Envgen-ninja-stderr.txt
new file mode 100644
index 000000000..0d455db74
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-ninja-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error: No generator specified for -G
+
+Generators.*
+\* Ninja.*
diff --git a/Tests/RunCMake/CommandLine/Envgen-platform-invalid-result.txt b/Tests/RunCMake/CommandLine/Envgen-platform-invalid-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-platform-invalid-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Envgen-platform-invalid-stderr-vs9.txt b/Tests/RunCMake/CommandLine/Envgen-platform-invalid-stderr-vs9.txt
new file mode 100644
index 000000000..4eae6aa10
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-platform-invalid-stderr-vs9.txt
@@ -0,0 +1,2 @@
+^CMake Error at CMakeLists.+
+ No CMAKE_C_COMPILER could be found.
diff --git a/Tests/RunCMake/CommandLine/Envgen-platform-invalid-stderr.txt b/Tests/RunCMake/CommandLine/Envgen-platform-invalid-stderr.txt
new file mode 100644
index 000000000..76a8f1cac
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-platform-invalid-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error at CMakeLists.+
+.+Platform='invalid'.+
diff --git a/Tests/RunCMake/CommandLine/Envgen-toolset-invalid-result.txt b/Tests/RunCMake/CommandLine/Envgen-toolset-invalid-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-toolset-invalid-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Envgen-toolset-invalid-stderr.txt b/Tests/RunCMake/CommandLine/Envgen-toolset-invalid-stderr.txt
new file mode 100644
index 000000000..51fce609d
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-toolset-invalid-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error at CMakeLists.+
+.+(Platform Toolset = 'invalid'|Specified platform toolset \(invalid\) is not installed or invalid).+
diff --git a/Tests/RunCMake/CommandLine/Envgen-unset-result.txt b/Tests/RunCMake/CommandLine/Envgen-unset-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-unset-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Envgen-unset-stderr.txt b/Tests/RunCMake/CommandLine/Envgen-unset-stderr.txt
new file mode 100644
index 000000000..ec6ec9253
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-unset-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error: No generator specified for -G
+
+Generators.*
+\* (Unix Makefiles|Visual Studio).*
diff --git a/Tests/RunCMake/CommandLine/Envgen-warnings-result.txt b/Tests/RunCMake/CommandLine/Envgen-warnings-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-warnings-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Envgen-warnings-stderr.txt b/Tests/RunCMake/CommandLine/Envgen-warnings-stderr.txt
new file mode 100644
index 000000000..47f9c9e0a
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Envgen-warnings-stderr.txt
@@ -0,0 +1,7 @@
+^Warning: Environment variable CMAKE_GENERATOR_INSTANCE will be ignored, because CMAKE_GENERATOR is not set.
+Warning: Environment variable CMAKE_GENERATOR_PLATFORM will be ignored, because CMAKE_GENERATOR is not set.
+Warning: Environment variable CMAKE_GENERATOR_TOOLSET will be ignored, because CMAKE_GENERATOR is not set.
+CMake Error: No generator specified for -G
+
+Generators.*
+\* (Unix Makefiles|Visual Studio).*
diff --git a/Tests/RunCMake/CommandLine/ExplicitDirs/CMakeLists.txt b/Tests/RunCMake/CommandLine/ExplicitDirs/CMakeLists.txt
new file mode 100644
index 000000000..fc6291445
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/ExplicitDirs/CMakeLists.txt
@@ -0,0 +1,9 @@
+cmake_minimum_required(VERSION 3.14)
+project(ExplicitDirs NONE)
+add_custom_command(
+ OUTPUT output.txt
+ COMMAND ${CMAKE_COMMAND} -E echo CustomCommand > output.txt
+ )
+add_custom_target(CustomTarget ALL DEPENDS output.txt)
+add_custom_target(CustomTarget2 ALL DEPENDS output.txt)
+add_custom_target(CustomTarget3 ALL DEPENDS output.txt)
diff --git a/Tests/RunCMake/CommandLine/S-no-arg-result.txt b/Tests/RunCMake/CommandLine/S-no-arg-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/S-no-arg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/S-no-arg-stderr.txt b/Tests/RunCMake/CommandLine/S-no-arg-stderr.txt
new file mode 100644
index 000000000..d1a2ce34f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/S-no-arg-stderr.txt
@@ -0,0 +1 @@
+CMake Error: No source directory specified for -S
diff --git a/Tests/RunCMake/CommandLine/S-no-arg2-result.txt b/Tests/RunCMake/CommandLine/S-no-arg2-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/S-no-arg2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/S-no-arg2-stderr.txt b/Tests/RunCMake/CommandLine/S-no-arg2-stderr.txt
new file mode 100644
index 000000000..d1a2ce34f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/S-no-arg2-stderr.txt
@@ -0,0 +1 @@
+CMake Error: No source directory specified for -S
diff --git a/Tests/RunCMake/CommandLine/U-no-src-result.txt b/Tests/RunCMake/CommandLine/U-no-src-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/U-no-src-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/U-no-src-stderr.txt b/Tests/RunCMake/CommandLine/U-no-src-stderr.txt
new file mode 100644
index 000000000..a3b4b12cc
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/U-no-src-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error: The source directory ".*/Tests/RunCMake/CommandLine/U-no-src-build" does not appear to contain CMakeLists.txt.
+Specify --help for usage, or press the help button on the CMake GUI.$
diff --git a/Tests/RunCMake/CommandLine/Uno-src-result.txt b/Tests/RunCMake/CommandLine/Uno-src-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Uno-src-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Uno-src-stderr.txt b/Tests/RunCMake/CommandLine/Uno-src-stderr.txt
new file mode 100644
index 000000000..baa8d63ef
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Uno-src-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error: The source directory ".*/Tests/RunCMake/CommandLine/Uno-src-build" does not appear to contain CMakeLists.txt.
+Specify --help for usage, or press the help button on the CMake GUI.$
diff --git a/Tests/RunCMake/CommandLine/Wizard-result.txt b/Tests/RunCMake/CommandLine/Wizard-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Wizard-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/Wizard-stderr.txt b/Tests/RunCMake/CommandLine/Wizard-stderr.txt
new file mode 100644
index 000000000..f757aff90
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/Wizard-stderr.txt
@@ -0,0 +1 @@
+^The "cmake -i" wizard mode is no longer supported\.
diff --git a/Tests/RunCMake/CommandLine/compare_files/crlf b/Tests/RunCMake/CommandLine/compare_files/crlf
new file mode 100644
index 000000000..495181cc2
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/compare_files/crlf
@@ -0,0 +1 @@
+line1
diff --git a/Tests/RunCMake/CommandLine/compare_files/empty1 b/Tests/RunCMake/CommandLine/compare_files/empty1
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/compare_files/empty1
diff --git a/Tests/RunCMake/CommandLine/compare_files/empty2 b/Tests/RunCMake/CommandLine/compare_files/empty2
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/compare_files/empty2
diff --git a/Tests/RunCMake/CommandLine/compare_files/lf b/Tests/RunCMake/CommandLine/compare_files/lf
new file mode 100644
index 000000000..a29bdeb43
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/compare_files/lf
@@ -0,0 +1 @@
+line1
diff --git a/Tests/RunCMake/CommandLine/dir-install-options-to-vars/cmake_install.cmake b/Tests/RunCMake/CommandLine/dir-install-options-to-vars/cmake_install.cmake
new file mode 100644
index 000000000..fd4e67df1
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/dir-install-options-to-vars/cmake_install.cmake
@@ -0,0 +1,15 @@
+if(CMAKE_INSTALL_PREFIX)
+ message("CMAKE_INSTALL_PREFIX is ${CMAKE_INSTALL_PREFIX}")
+endif()
+
+if(CMAKE_INSTALL_COMPONENT)
+ message("CMAKE_INSTALL_COMPONENT is ${CMAKE_INSTALL_COMPONENT}")
+endif()
+
+if(CMAKE_INSTALL_CONFIG_NAME)
+ message("CMAKE_INSTALL_CONFIG_NAME is ${CMAKE_INSTALL_CONFIG_NAME}")
+endif()
+
+if(CMAKE_INSTALL_DO_STRIP)
+ message("CMAKE_INSTALL_DO_STRIP is ${CMAKE_INSTALL_DO_STRIP}")
+endif()
diff --git a/Tests/RunCMake/CommandLine/install-bad-dir-result.txt b/Tests/RunCMake/CommandLine/install-bad-dir-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/install-bad-dir-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/install-bad-dir-stderr.txt b/Tests/RunCMake/CommandLine/install-bad-dir-stderr.txt
new file mode 100644
index 000000000..320aecc8f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/install-bad-dir-stderr.txt
@@ -0,0 +1 @@
+^CMake Error: Error processing file:
diff --git a/Tests/RunCMake/CommandLine/install-no-dir-result.txt b/Tests/RunCMake/CommandLine/install-no-dir-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/install-no-dir-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/install-no-dir-stderr.txt b/Tests/RunCMake/CommandLine/install-no-dir-stderr.txt
new file mode 100644
index 000000000..d64f6385f
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/install-no-dir-stderr.txt
@@ -0,0 +1 @@
+^Usage: cmake --install <dir> \[options\]
diff --git a/Tests/RunCMake/CommandLine/install-options-to-vars-result.txt b/Tests/RunCMake/CommandLine/install-options-to-vars-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/install-options-to-vars-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/CommandLine/install-options-to-vars-stderr.txt b/Tests/RunCMake/CommandLine/install-options-to-vars-stderr.txt
new file mode 100644
index 000000000..f7b1583ad
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/install-options-to-vars-stderr.txt
@@ -0,0 +1,4 @@
+CMAKE_INSTALL_PREFIX is /var/test
+CMAKE_INSTALL_COMPONENT is pack
+CMAKE_INSTALL_CONFIG_NAME is sample
+CMAKE_INSTALL_DO_STRIP is 1
diff --git a/Tests/RunCMake/CommandLine/no-S-B-stderr.txt b/Tests/RunCMake/CommandLine/no-S-B-stderr.txt
new file mode 100644
index 000000000..c166dcf56
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/no-S-B-stderr.txt
@@ -0,0 +1,4 @@
+CMake Warning:
+ No source or binary directory provided. Both will be assumed to be the
+ same as the current working directory, but note that this warning will
+ become a fatal error in future CMake releases.
diff --git a/Tests/RunCMake/CommandLine/trace-expand-warn-uninitialized-stderr.txt b/Tests/RunCMake/CommandLine/trace-expand-warn-uninitialized-stderr.txt
new file mode 100644
index 000000000..74429b643
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/trace-expand-warn-uninitialized-stderr.txt
@@ -0,0 +1,2 @@
+^.*/Tests/RunCMake/CommandLine/CMakeLists.txt\(1\): cmake_minimum_required\(VERSION 3.0 \)
+.*/Tests/RunCMake/CommandLine/CMakeLists.txt\(2\): project\(trace-expand-warn-uninitialized NONE \)
diff --git a/Tests/RunCMake/CommandLine/trace-expand-warn-uninitialized.cmake b/Tests/RunCMake/CommandLine/trace-expand-warn-uninitialized.cmake
new file mode 100644
index 000000000..ec3e4d46d
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/trace-expand-warn-uninitialized.cmake
@@ -0,0 +1,4 @@
+cmake_policy(SET CMP0053 OLD)
+message(STATUS "'${uninitialized_variable}'")
+cmake_policy(SET CMP0053 NEW)
+message(STATUS "'${uninitialized_variable}'")
diff --git a/Tests/RunCMake/CommandLine/warn-uninitialized-stderr.txt b/Tests/RunCMake/CommandLine/warn-uninitialized-stderr.txt
new file mode 100644
index 000000000..41ba09898
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/warn-uninitialized-stderr.txt
@@ -0,0 +1,53 @@
+^CMake Warning \(dev\) at warn-uninitialized.cmake:3 \(set\):
+ uninitialized variable 'OLD_WARN_FROM_NORMAL_CMAKE_FILE_INSIDE_BRACES'
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
+
+CMake Warning \(dev\) at warn-uninitialized.cmake:4 \(set\):
+ uninitialized variable 'OLD_WARN_FROM_NORMAL_CMAKE_FILE_IN_ATS'
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
+
+CMake Warning \(dev\) at warn-uninitialized.cmake:5 \(string\):
+ uninitialized variable 'OLD_WARN_FROM_STRING_CONFIGURE_INSIDE_BRACES'
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
+
+CMake Warning \(dev\) at warn-uninitialized.cmake:7 \(configure_file\):
+ uninitialized variable 'OLD_WARN_FROM_CONFIGURE_FILE_INSIDE_AT'
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
+
+CMake Warning \(dev\) at warn-uninitialized.cmake:8 \(string\):
+ uninitialized variable 'OLD_WARN_FROM_STRING_CONFIGURE_INSIDE_AT'
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
+
+CMake Warning \(dev\) at warn-uninitialized.cmake:13 \(set\):
+ uninitialized variable 'NEW_WARN_FROM_NORMAL_CMAKE_FILE_INSIDE_BRACES'
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
+
+CMake Warning \(dev\) at warn-uninitialized.cmake:14 \(string\):
+ uninitialized variable 'NEW_WARN_FROM_STRING_CONFIGURE_INSIDE_BRACES'
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
+
+CMake Warning \(dev\) at warn-uninitialized.cmake:16 \(configure_file\):
+ uninitialized variable 'NEW_WARN_FROM_CONFIGURE_FILE_INSIDE_AT'
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
+
+CMake Warning \(dev\) at warn-uninitialized.cmake:17 \(string\):
+ uninitialized variable 'NEW_WARN_FROM_STRING_CONFIGURE_INSIDE_AT'
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/CommandLine/warn-uninitialized.cmake b/Tests/RunCMake/CommandLine/warn-uninitialized.cmake
new file mode 100644
index 000000000..ff65c1631
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/warn-uninitialized.cmake
@@ -0,0 +1,18 @@
+cmake_policy(PUSH)
+cmake_policy(SET CMP0053 OLD)
+set(FOO "${OLD_WARN_FROM_NORMAL_CMAKE_FILE_INSIDE_BRACES}")
+set(FOO "@OLD_WARN_FROM_NORMAL_CMAKE_FILE_IN_ATS@")
+string(CONFIGURE "\${OLD_WARN_FROM_STRING_CONFIGURE_INSIDE_BRACES}" OUT1)
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/file1.in "\@OLD_WARN_FROM_CONFIGURE_FILE_INSIDE_AT\@")
+configure_file(${CMAKE_CURRENT_BINARY_DIR}/file1.in file1.out)
+string(CONFIGURE "\@OLD_WARN_FROM_STRING_CONFIGURE_INSIDE_AT\@" OUT2)
+cmake_policy(POP)
+
+cmake_policy(PUSH)
+cmake_policy(SET CMP0053 NEW)
+set(FOO "${NEW_WARN_FROM_NORMAL_CMAKE_FILE_INSIDE_BRACES}")
+string(CONFIGURE "\${NEW_WARN_FROM_STRING_CONFIGURE_INSIDE_BRACES}" OUT3)
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/file2.in "\@NEW_WARN_FROM_CONFIGURE_FILE_INSIDE_AT\@")
+configure_file(${CMAKE_CURRENT_BINARY_DIR}/file2.in file2.out)
+string(CONFIGURE "@NEW_WARN_FROM_STRING_CONFIGURE_INSIDE_AT@" OUT4)
+cmake_policy(POP)
diff --git a/Tests/RunCMake/CommandLineTar/bad-file-result.txt b/Tests/RunCMake/CommandLineTar/bad-file-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLineTar/bad-file-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLineTar/bad-file-stderr.txt b/Tests/RunCMake/CommandLineTar/bad-file-stderr.txt
new file mode 100644
index 000000000..1f9f748ce
--- /dev/null
+++ b/Tests/RunCMake/CommandLineTar/bad-file-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error: Unable to read from file 'badfile.txt': .*
+CMake Error: Problem creating tar: bad.tar$
diff --git a/Tests/RunCMake/CommandLineTar/bad-without-action-result.txt b/Tests/RunCMake/CommandLineTar/bad-without-action-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLineTar/bad-without-action-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLineTar/bad-without-action-stderr.txt b/Tests/RunCMake/CommandLineTar/bad-without-action-stderr.txt
new file mode 100644
index 000000000..2fec25467
--- /dev/null
+++ b/Tests/RunCMake/CommandLineTar/bad-without-action-stderr.txt
@@ -0,0 +1 @@
+^CMake Error: tar: No action specified. Please choose: 't' \(list\), 'c' \(create\) or 'x' \(extract\)$
diff --git a/Tests/RunCMake/CommandLineTar/bad-wrong-flag-stderr.txt b/Tests/RunCMake/CommandLineTar/bad-wrong-flag-stderr.txt
new file mode 100644
index 000000000..d5c1e0163
--- /dev/null
+++ b/Tests/RunCMake/CommandLineTar/bad-wrong-flag-stderr.txt
@@ -0,0 +1 @@
+^tar: Unknown argument: q
diff --git a/Tests/RunCMake/CommandLineTar/end-opt2-stderr.txt b/Tests/RunCMake/CommandLineTar/end-opt2-stderr.txt
new file mode 100644
index 000000000..70166f540
--- /dev/null
+++ b/Tests/RunCMake/CommandLineTar/end-opt2-stderr.txt
@@ -0,0 +1 @@
+^tar: No files or directories specified
diff --git a/Tests/RunCMake/CommandLineTar/pax-zstd.cmake b/Tests/RunCMake/CommandLineTar/pax-zstd.cmake
new file mode 100644
index 000000000..c2a304d80
--- /dev/null
+++ b/Tests/RunCMake/CommandLineTar/pax-zstd.cmake
@@ -0,0 +1,10 @@
+set(OUTPUT_NAME "test.tar.zstd")
+
+set(COMPRESSION_FLAGS cvf)
+set(COMPRESSION_OPTIONS --format=pax --zstd)
+
+set(DECOMPRESSION_FLAGS xvf)
+
+include(${CMAKE_CURRENT_LIST_DIR}/roundtrip.cmake)
+
+check_magic("28b52ffd0058" LIMIT 6 HEX)
diff --git a/Tests/RunCMake/CommandLineTar/test-file.txt b/Tests/RunCMake/CommandLineTar/test-file.txt
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/CommandLineTar/test-file.txt
diff --git a/Tests/RunCMake/CommandLineTar/without-files-stderr.txt b/Tests/RunCMake/CommandLineTar/without-files-stderr.txt
new file mode 100644
index 000000000..70166f540
--- /dev/null
+++ b/Tests/RunCMake/CommandLineTar/without-files-stderr.txt
@@ -0,0 +1 @@
+^tar: No files or directories specified
diff --git a/Tests/RunCMake/CommandLineTar/zip-filtered.cmake b/Tests/RunCMake/CommandLineTar/zip-filtered.cmake
new file mode 100644
index 000000000..c13210ef0
--- /dev/null
+++ b/Tests/RunCMake/CommandLineTar/zip-filtered.cmake
@@ -0,0 +1,28 @@
+set(OUTPUT_NAME "test.zip")
+
+set(COMPRESSION_FLAGS cvf)
+set(COMPRESSION_OPTIONS --format=zip)
+
+set(DECOMPRESSION_FLAGS xvf)
+set(LIST_ARCHIVE TRUE)
+set(DECOMPRESSION_PATHNAMES
+ compress_dir/f1.txt # Decompress only file
+ compress_dir/d1 # and whole directory
+)
+
+set(CUSTOM_CHECK_FILES
+ "f1.txt"
+ "d1/f1.txt"
+)
+
+# This files shouldn't exists
+set(NOT_EXISTING_FILES_CHECK
+ "d 2/f1.txt"
+ "d + 3/f1.txt"
+ "d_4/f1.txt"
+ "d-4/f1.txt"
+)
+
+include(${CMAKE_CURRENT_LIST_DIR}/roundtrip.cmake)
+
+check_magic("504b0304" LIMIT 4 HEX)
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/Fortran-Build-stdout.txt b/Tests/RunCMake/CompilerLauncher/Fortran-Build-stdout.txt
new file mode 100644
index 000000000..3313e31f6
--- /dev/null
+++ b/Tests/RunCMake/CompilerLauncher/Fortran-Build-stdout.txt
@@ -0,0 +1 @@
+.*-E env USED_LAUNCHER=1.*
diff --git a/Tests/RunCMake/CompilerLauncher/Fortran-launch-Build-stdout.txt b/Tests/RunCMake/CompilerLauncher/Fortran-launch-Build-stdout.txt
new file mode 100644
index 000000000..3313e31f6
--- /dev/null
+++ b/Tests/RunCMake/CompilerLauncher/Fortran-launch-Build-stdout.txt
@@ -0,0 +1 @@
+.*-E env USED_LAUNCHER=1.*
diff --git a/Tests/RunCMake/CompilerLauncher/Fortran-launch.cmake b/Tests/RunCMake/CompilerLauncher/Fortran-launch.cmake
new file mode 100644
index 000000000..7e9a56479
--- /dev/null
+++ b/Tests/RunCMake/CompilerLauncher/Fortran-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(Fortran.cmake)
diff --git a/Tests/RunCMake/CompilerLauncher/Fortran.cmake b/Tests/RunCMake/CompilerLauncher/Fortran.cmake
new file mode 100644
index 000000000..72cc03ee6
--- /dev/null
+++ b/Tests/RunCMake/CompilerLauncher/Fortran.cmake
@@ -0,0 +1,4 @@
+enable_language(Fortran)
+set(CMAKE_Fortran_COMPILER_LAUNCHER "${CMAKE_COMMAND};-E;env;USED_LAUNCHER=1")
+set(CMAKE_VERBOSE_MAKEFILE TRUE)
+add_executable(main main.F)
diff --git a/Tests/RunCMake/CompilerLauncher/main.F b/Tests/RunCMake/CompilerLauncher/main.F
new file mode 100644
index 000000000..53ec0d10b
--- /dev/null
+++ b/Tests/RunCMake/CompilerLauncher/main.F
@@ -0,0 +1,2 @@
+ PROGRAM MAIN
+ END
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..d197c913c
--- /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-error-Build-result.txt b/Tests/RunCMake/Cppcheck/C-error-Build-result.txt
new file mode 100644
index 000000000..d197c913c
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/C-error-Build-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/Cppcheck/C-error-Build-stdout.txt b/Tests/RunCMake/Cppcheck/C-error-Build-stdout.txt
new file mode 100644
index 000000000..4a24c0ccd
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/C-error-Build-stdout.txt
@@ -0,0 +1 @@
+.*Error: cppcheck reported failure.*error.*warning.*style.*performance.*information.*
diff --git a/Tests/RunCMake/Cppcheck/C-error.cmake b/Tests/RunCMake/Cppcheck/C-error.cmake
new file mode 100644
index 000000000..2254d7511
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/C-error.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+set(CMAKE_C_CPPCHECK "${PSEUDO_CPPCHECK}" -error)
+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..e395f3696
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/RunCMakeTest.cmake
@@ -0,0 +1,24 @@
+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-error)
+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/CrosscompilingEmulator/AddCustomCommandWithArg-build-check.cmake b/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommandWithArg-build-check.cmake
new file mode 100644
index 000000000..9ca610660
--- /dev/null
+++ b/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommandWithArg-build-check.cmake
@@ -0,0 +1,3 @@
+if(NOT EXISTS "${RunCMake_TEST_BINARY_DIR}/output")
+ message(FATAL_ERROR "Failed to create output: ${RunCMake_TEST_BINARY_DIR}/output")
+endif()
diff --git a/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommandWithArg.cmake b/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommandWithArg.cmake
new file mode 100644
index 000000000..d9059ca6e
--- /dev/null
+++ b/Tests/RunCMake/CrosscompilingEmulator/AddCustomCommandWithArg.cmake
@@ -0,0 +1,14 @@
+set(CMAKE_CROSSCOMPILING 1)
+
+# Executable: Return error code different from 0
+add_executable(generated_exe_emulator_expected simple_src_exiterror.cxx)
+
+add_custom_command(OUTPUT output
+ COMMAND generated_exe_emulator_expected
+ COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/output
+ DEPENDS generated_exe_emulator_expected)
+
+add_custom_target(ensure_build ALL
+ SOURCES
+ ${CMAKE_CURRENT_BINARY_DIR}/output
+)
diff --git a/Tests/RunCMake/CrosscompilingEmulator/AddCustomTargetWithArg-build-check.cmake b/Tests/RunCMake/CrosscompilingEmulator/AddCustomTargetWithArg-build-check.cmake
new file mode 100644
index 000000000..13c0db96a
--- /dev/null
+++ b/Tests/RunCMake/CrosscompilingEmulator/AddCustomTargetWithArg-build-check.cmake
@@ -0,0 +1 @@
+include(${CMAKE_CURRENT_LIST_DIR}/AddCustomCommandWithArg-build-check.cmake)
diff --git a/Tests/RunCMake/CrosscompilingEmulator/AddCustomTargetWithArg.cmake b/Tests/RunCMake/CrosscompilingEmulator/AddCustomTargetWithArg.cmake
new file mode 100644
index 000000000..dcd80d53a
--- /dev/null
+++ b/Tests/RunCMake/CrosscompilingEmulator/AddCustomTargetWithArg.cmake
@@ -0,0 +1,9 @@
+set(CMAKE_CROSSCOMPILING 1)
+
+# Executable: Return error code different from 0
+add_executable(generated_exe_emulator_expected simple_src_exiterror.cxx)
+
+add_custom_target(generate_output ALL
+ generated_exe_emulator_expected
+ COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_BINARY_DIR}/output
+ DEPENDS generated_exe_emulator_expected)
diff --git a/Tests/RunCMake/ExternalProject/IncludeScope-Add-result.txt b/Tests/RunCMake/ExternalProject/IncludeScope-Add-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/IncludeScope-Add-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/ExternalProject/IncludeScope-Add-stderr.txt b/Tests/RunCMake/ExternalProject/IncludeScope-Add-stderr.txt
new file mode 100644
index 000000000..ff3e5c18e
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/IncludeScope-Add-stderr.txt
@@ -0,0 +1,7 @@
+^CMake Error at .*/Modules/ExternalProject.cmake:[0-9]+ \(message\):
+ error: ExternalProject module must be explicitly included before using
+ ExternalProject_Add function
+Call Stack \(most recent call first\):
+ .*/Modules/ExternalProject.cmake:[0-9]+ \(_ep_parse_arguments\)
+ IncludeScope-Add.cmake:[0-9]+ \(ExternalProject_Add\)
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/ExternalProject/IncludeScope-Add.cmake b/Tests/RunCMake/ExternalProject/IncludeScope-Add.cmake
new file mode 100644
index 000000000..1061ffddc
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/IncludeScope-Add.cmake
@@ -0,0 +1,12 @@
+function(IncludeScope_IncludeOnly)
+ include(ExternalProject)
+endfunction()
+
+IncludeScope_IncludeOnly()
+
+ExternalProject_Add(MyProj
+ SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND ""
+ INSTALL_COMMAND ""
+)
diff --git a/Tests/RunCMake/ExternalProject/IncludeScope-Add_Step-result.txt b/Tests/RunCMake/ExternalProject/IncludeScope-Add_Step-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/IncludeScope-Add_Step-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/ExternalProject/IncludeScope-Add_Step-stderr.txt b/Tests/RunCMake/ExternalProject/IncludeScope-Add_Step-stderr.txt
new file mode 100644
index 000000000..cbad4be61
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/IncludeScope-Add_Step-stderr.txt
@@ -0,0 +1,7 @@
+^CMake Error at .*/Modules/ExternalProject.cmake:[0-9]+ \(message\):
+ error: ExternalProject module must be explicitly included before using
+ ExternalProject_Add_Step function
+Call Stack \(most recent call first\):
+ .*/Modules/ExternalProject.cmake:[0-9]+ \(_ep_parse_arguments\)
+ IncludeScope-Add_Step.cmake:[0-9]+ \(ExternalProject_Add_Step\)
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/ExternalProject/IncludeScope-Add_Step.cmake b/Tests/RunCMake/ExternalProject/IncludeScope-Add_Step.cmake
new file mode 100644
index 000000000..2a820f8f2
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/IncludeScope-Add_Step.cmake
@@ -0,0 +1,13 @@
+function(IncludeScope_DefineProj)
+ include(ExternalProject)
+ ExternalProject_Add(MyProj
+ SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND ""
+ INSTALL_COMMAND ""
+ )
+endfunction()
+
+IncludeScope_DefineProj()
+
+ExternalProject_Add_Step(MyProj extraStep COMMENT "Foo")
diff --git a/Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-result.txt b/Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-result.txt
new file mode 100644
index 000000000..c20fd86c7
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-result.txt
@@ -0,0 +1 @@
+^[^0]
diff --git a/Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-stderr.txt b/Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-stderr.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-stderr.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-stdout.txt b/Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-stdout.txt
new file mode 100644
index 000000000..87e5384fa
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/LogOutputOnFailure-build-stdout.txt
@@ -0,0 +1,8 @@
+( )?-- stdout output is:
+( )?This is some dummy output with some long lines to ensure formatting is preserved
+( )? Including lines with leading spaces
+( )?
+( )?And also blank lines[
+ ]+
+( )?-- stderr output is:
+( )?cmake -E env: no command given
diff --git a/Tests/RunCMake/ExternalProject/LogOutputOnFailure.cmake b/Tests/RunCMake/ExternalProject/LogOutputOnFailure.cmake
new file mode 100644
index 000000000..863bbef9b
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/LogOutputOnFailure.cmake
@@ -0,0 +1,20 @@
+include(ExternalProject)
+
+set(dummyOutput [[
+This is some dummy output with some long lines to ensure formatting is preserved
+ Including lines with leading spaces
+
+And also blank lines
+]])
+
+ExternalProject_Add(FailsWithOutput
+ SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND ${CMAKE_COMMAND} -E echo ${dummyOutput}
+ COMMAND ${CMAKE_COMMAND} -E env # missing command, forces fail
+ TEST_COMMAND ""
+ INSTALL_COMMAND ""
+ LOG_BUILD YES
+ LOG_OUTPUT_ON_FAILURE YES
+ USES_TERMINAL_BUILD YES
+)
diff --git a/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-result.txt b/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-result.txt
new file mode 100644
index 000000000..c20fd86c7
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-result.txt
@@ -0,0 +1 @@
+^[^0]
diff --git a/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-stderr.txt b/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-stderr.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-stderr.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-stdout.txt b/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-stdout.txt
new file mode 100644
index 000000000..11c73176e
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged-build-stdout.txt
@@ -0,0 +1,7 @@
+( )?-- Log output is:
+( )?This is some dummy output with some long lines to ensure formatting is preserved
+( )? Including lines with leading spaces
+( )?
+( )?And also blank lines[
+ ]+
+( )?cmake -E env: no command given
diff --git a/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged.cmake b/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged.cmake
new file mode 100644
index 000000000..116448b8f
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/LogOutputOnFailureMerged.cmake
@@ -0,0 +1,21 @@
+include(ExternalProject)
+
+set(dummyOutput [[
+This is some dummy output with some long lines to ensure formatting is preserved
+ Including lines with leading spaces
+
+And also blank lines
+]])
+
+ExternalProject_Add(FailsWithOutput
+ SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND ${CMAKE_COMMAND} -E echo ${dummyOutput}
+ COMMAND ${CMAKE_COMMAND} -E env # missing command, forces fail
+ TEST_COMMAND ""
+ INSTALL_COMMAND ""
+ LOG_BUILD YES
+ LOG_OUTPUT_ON_FAILURE YES
+ LOG_MERGED_STDOUTERR YES
+ USES_TERMINAL_BUILD YES
+)
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/Substitutions-build-stdout.txt b/Tests/RunCMake/ExternalProject/Substitutions-build-stdout.txt
new file mode 100644
index 000000000..d6a823add
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/Substitutions-build-stdout.txt
@@ -0,0 +1,7 @@
+.*Download dir = .*/xxxx_dwn
+.*Download file = .*/zzzz_tmp.txt
+.*Source dir = .*/xxxx_src
+.*Source subdir = /yyyy_subdir
+.*Binary dir = .*/xxxx_bin
+.*Install dir = .*/xxxx_install
+.*Tmp dir = .*/xxxx_tmp
diff --git a/Tests/RunCMake/ExternalProject/Substitutions.cmake b/Tests/RunCMake/ExternalProject/Substitutions.cmake
new file mode 100644
index 000000000..db79491ee
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/Substitutions.cmake
@@ -0,0 +1,25 @@
+include(ExternalProject)
+
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/zzzz_tmp.txt "Dummy file")
+file(MD5 ${CMAKE_CURRENT_BINARY_DIR}/zzzz_tmp.txt md5hash)
+ExternalProject_Add(Subst
+ URL file://${CMAKE_CURRENT_BINARY_DIR}/zzzz_tmp.txt
+ URL_HASH MD5=${md5hash}
+ DOWNLOAD_NO_EXTRACT ON
+ DOWNLOAD_DIR ${CMAKE_CURRENT_BINARY_DIR}/xxxx_dwn
+ SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}/xxxx_src
+ SOURCE_SUBDIR yyyy_subdir
+ BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/xxxx_bin
+ INSTALL_DIR ${CMAKE_CURRENT_BINARY_DIR}/xxxx_install
+ TMP_DIR ${CMAKE_CURRENT_BINARY_DIR}/xxxx_tmp
+ CONFIGURE_COMMAND ${CMAKE_COMMAND} -E echo "Download dir = <DOWNLOAD_DIR>"
+ COMMAND ${CMAKE_COMMAND} -E echo "Download file = <DOWNLOADED_FILE>"
+ COMMAND ${CMAKE_COMMAND} -E echo "Source dir = <SOURCE_DIR>"
+ COMMAND ${CMAKE_COMMAND} -E echo "Source subdir = <SOURCE_SUBDIR>"
+ COMMAND ${CMAKE_COMMAND} -E echo "Binary dir = <BINARY_DIR>"
+ COMMAND ${CMAKE_COMMAND} -E echo "Install dir = <INSTALL_DIR>"
+ COMMAND ${CMAKE_COMMAND} -E echo "Tmp dir = <TMP_DIR>"
+ BUILD_COMMAND ""
+ INSTALL_COMMAND ""
+ TEST_COMMAND ""
+)
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/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/FetchContent/CMakeLists.txt b/Tests/RunCMake/FetchContent/CMakeLists.txt
new file mode 100644
index 000000000..3cc2e4364
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/CMakeLists.txt
@@ -0,0 +1,7 @@
+cmake_minimum_required(VERSION 3.9)
+project(${RunCMake_TEST} NONE)
+
+# Tests assume no previous downloads in the output directory
+file(REMOVE_RECURSE ${CMAKE_CURRENT_BINARY_DIR}/_deps)
+
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/FetchContent/DirOverrides.cmake b/Tests/RunCMake/FetchContent/DirOverrides.cmake
new file mode 100644
index 000000000..50eef161b
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/DirOverrides.cmake
@@ -0,0 +1,46 @@
+include(FetchContent)
+
+# Test using saved details
+FetchContent_Declare(
+ t1
+ SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}/savedSrc
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E make_directory <SOURCE_DIR>
+)
+FetchContent_Populate(t1)
+if(NOT IS_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/savedSrc)
+ message(FATAL_ERROR "Saved details SOURCE_DIR override failed")
+endif()
+
+# Test direct population
+FetchContent_Populate(
+ t2
+ SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}/directSrc
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E make_directory <SOURCE_DIR>
+)
+if(NOT IS_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/directSrc)
+ message(FATAL_ERROR "Direct details SOURCE_DIR override failed")
+endif()
+
+# Ensure setting BINARY_DIR to SOURCE_DIR works (a technique to
+# prevent an unwanted separate BINARY_DIR from being created, which
+# ExternalProject_Add() does whether we like it or not)
+FetchContent_Declare(
+ t3
+ SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}/savedNoBuildDir
+ BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/savedNoBuildDir
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E make_directory <SOURCE_DIR>
+)
+FetchContent_Populate(t3)
+if(IS_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/savedNobuildDir-build)
+ message(FATAL_ERROR "Saved details BINARY_DIR override failed")
+endif()
+
+FetchContent_Populate(
+ t4
+ SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}/directNoBuildDir
+ BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/directNoBuildDir
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E make_directory <SOURCE_DIR>
+)
+if(IS_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/savedNobuildDir-build)
+ message(FATAL_ERROR "Direct details BINARY_DIR override failed")
+endif()
diff --git a/Tests/RunCMake/FetchContent/DirectIgnoresDetails-stdout.txt b/Tests/RunCMake/FetchContent/DirectIgnoresDetails-stdout.txt
new file mode 100644
index 000000000..6fa5a57ec
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/DirectIgnoresDetails-stdout.txt
@@ -0,0 +1 @@
+Local details used
diff --git a/Tests/RunCMake/FetchContent/DirectIgnoresDetails.cmake b/Tests/RunCMake/FetchContent/DirectIgnoresDetails.cmake
new file mode 100644
index 000000000..0731b4390
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/DirectIgnoresDetails.cmake
@@ -0,0 +1,12 @@
+include(FetchContent)
+
+FetchContent_Declare(
+ t1
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E echo "Saved details used"
+)
+
+# No QUIET option given, so command output will be shown
+FetchContent_Populate(
+ t1
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E echo "Local details used"
+)
diff --git a/Tests/RunCMake/FetchContent/DownloadTwice-result.txt b/Tests/RunCMake/FetchContent/DownloadTwice-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/DownloadTwice-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FetchContent/DownloadTwice-stderr.txt b/Tests/RunCMake/FetchContent/DownloadTwice-stderr.txt
new file mode 100644
index 000000000..96fed483d
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/DownloadTwice-stderr.txt
@@ -0,0 +1 @@
+Content t1 already populated in
diff --git a/Tests/RunCMake/FetchContent/DownloadTwice.cmake b/Tests/RunCMake/FetchContent/DownloadTwice.cmake
new file mode 100644
index 000000000..6863c305f
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/DownloadTwice.cmake
@@ -0,0 +1,9 @@
+include(FetchContent)
+
+FetchContent_Declare(
+ t1
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E echo "Download command executed"
+)
+
+FetchContent_Populate(t1)
+FetchContent_Populate(t1) # Triggers error
diff --git a/Tests/RunCMake/FetchContent/FirstDetailsWin-stdout.txt b/Tests/RunCMake/FetchContent/FirstDetailsWin-stdout.txt
new file mode 100644
index 000000000..7a8bf18b2
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/FirstDetailsWin-stdout.txt
@@ -0,0 +1 @@
+First details used
diff --git a/Tests/RunCMake/FetchContent/FirstDetailsWin.cmake b/Tests/RunCMake/FetchContent/FirstDetailsWin.cmake
new file mode 100644
index 000000000..208b12db0
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/FirstDetailsWin.cmake
@@ -0,0 +1,16 @@
+include(FetchContent)
+
+# Need to see the download command output
+set(FETCHCONTENT_QUIET OFF)
+
+FetchContent_Declare(
+ t1
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E echo "First details used"
+)
+
+FetchContent_Declare(
+ t1
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E echo "Second details used"
+)
+
+FetchContent_Populate(t1)
diff --git a/Tests/RunCMake/FetchContent/GetProperties.cmake b/Tests/RunCMake/FetchContent/GetProperties.cmake
new file mode 100644
index 000000000..61c99fec3
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/GetProperties.cmake
@@ -0,0 +1,67 @@
+include(FetchContent)
+
+# First confirm properties are empty even before declare
+FetchContent_GetProperties(t1)
+if(t1_POPULATED)
+ message(FATAL_ERROR "Property says populated before doing anything")
+endif()
+if(t1_SOURCE_DIR)
+ message(FATAL_ERROR "SOURCE_DIR property not initially empty")
+endif()
+if(t1_BINARY_DIR)
+ message(FATAL_ERROR "BINARY_DIR property not initially empty")
+endif()
+
+# Declare, but no properties should change yet
+FetchContent_Declare(
+ t1
+ SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}/savedSrc
+ BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/savedBin
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E echo "Do nothing"
+)
+
+FetchContent_GetProperties(t1)
+if(t1_POPULATED)
+ message(FATAL_ERROR "Property says populated after only declaring details")
+endif()
+if(t1_SOURCE_DIR)
+ message(FATAL_ERROR "SOURCE_DIR property not empty after declare")
+endif()
+if(t1_BINARY_DIR)
+ message(FATAL_ERROR "BINARY_DIR property not empty after declare")
+endif()
+
+# Populate should make all properties non-empty/set
+FetchContent_Populate(t1)
+
+FetchContent_GetProperties(t1)
+if(NOT t1_POPULATED)
+ message(FATAL_ERROR "Population did not set POPULATED property")
+endif()
+if(NOT "${t1_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}/savedSrc")
+ message(FATAL_ERROR "SOURCE_DIR property not correct after population: "
+ "${t1_SOURCE_DIR}\n"
+ " Expected: ${CMAKE_CURRENT_BINARY_DIR}/savedSrc")
+endif()
+if(NOT "${t1_BINARY_DIR}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}/savedBin")
+ message(FATAL_ERROR "BINARY_DIR property not correct after population: "
+ "${t1_BINARY_DIR}\n"
+ " Expected: ${CMAKE_CURRENT_BINARY_DIR}/savedBin")
+endif()
+
+# Verify we can retrieve properties individually too
+FetchContent_GetProperties(t1 POPULATED varPop)
+FetchContent_GetProperties(t1 SOURCE_DIR varSrc)
+FetchContent_GetProperties(t1 BINARY_DIR varBin)
+
+if(NOT varPop)
+ message(FATAL_ERROR "Failed to retrieve POPULATED property")
+endif()
+if(NOT "${varSrc}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}/savedSrc")
+ message(FATAL_ERROR "SOURCE_DIR property not retrieved correctly: ${varSrc}\n"
+ " Expected: ${CMAKE_CURRENT_BINARY_DIR}/savedSrc")
+endif()
+if(NOT "${varBin}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}/savedBin")
+ message(FATAL_ERROR "BINARY_DIR property not retrieved correctly: ${varBin}\n"
+ " Expected: ${CMAKE_CURRENT_BINARY_DIR}/savedBin")
+endif()
diff --git a/Tests/RunCMake/FetchContent/MakeAvailable-stdout.txt b/Tests/RunCMake/FetchContent/MakeAvailable-stdout.txt
new file mode 100644
index 000000000..6e6c73062
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/MakeAvailable-stdout.txt
@@ -0,0 +1,2 @@
+Confirmation project has been added
+.*Confirmation script has been called
diff --git a/Tests/RunCMake/FetchContent/MakeAvailable.cmake b/Tests/RunCMake/FetchContent/MakeAvailable.cmake
new file mode 100644
index 000000000..a93f1f70d
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/MakeAvailable.cmake
@@ -0,0 +1,20 @@
+include(FetchContent)
+
+FetchContent_Declare(
+ WithProject
+ SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/WithProject
+)
+FetchContent_Declare(
+ WithoutProject
+ SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/WithoutProject
+)
+
+# Order is important and will be verified by test output
+FetchContent_MakeAvailable(WithProject WithoutProject)
+
+get_property(addedWith GLOBAL PROPERTY FetchWithProject SET)
+if(NOT addedWith)
+ message(SEND_ERROR "Subdir with CMakeLists.txt not added")
+endif()
+
+include(${withoutproject_SOURCE_DIR}/confirmMessage.cmake)
diff --git a/Tests/RunCMake/FetchContent/MakeAvailableTwice-stdout.txt b/Tests/RunCMake/FetchContent/MakeAvailableTwice-stdout.txt
new file mode 100644
index 000000000..8d3b7c04f
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/MakeAvailableTwice-stdout.txt
@@ -0,0 +1,4 @@
+-- Before first[
+ ]+-- Confirmation project has been added[
+ ]+-- Between both[
+ ]+-- After last
diff --git a/Tests/RunCMake/FetchContent/MakeAvailableTwice.cmake b/Tests/RunCMake/FetchContent/MakeAvailableTwice.cmake
new file mode 100644
index 000000000..a9af02091
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/MakeAvailableTwice.cmake
@@ -0,0 +1,12 @@
+include(FetchContent)
+
+FetchContent_Declare(
+ WithProject
+ SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/WithProject
+)
+
+message(STATUS "Before first")
+FetchContent_MakeAvailable(WithProject)
+message(STATUS "Between both")
+FetchContent_MakeAvailable(WithProject)
+message(STATUS "After last")
diff --git a/Tests/RunCMake/FetchContent/MakeAvailableUndeclared-result.txt b/Tests/RunCMake/FetchContent/MakeAvailableUndeclared-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/MakeAvailableUndeclared-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FetchContent/MakeAvailableUndeclared-stderr.txt b/Tests/RunCMake/FetchContent/MakeAvailableUndeclared-stderr.txt
new file mode 100644
index 000000000..9715b7889
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/MakeAvailableUndeclared-stderr.txt
@@ -0,0 +1 @@
+No content details recorded for NoDetails
diff --git a/Tests/RunCMake/FetchContent/MakeAvailableUndeclared.cmake b/Tests/RunCMake/FetchContent/MakeAvailableUndeclared.cmake
new file mode 100644
index 000000000..bd57cbe1a
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/MakeAvailableUndeclared.cmake
@@ -0,0 +1,3 @@
+include(FetchContent)
+
+FetchContent_MakeAvailable(NoDetails)
diff --git a/Tests/RunCMake/FetchContent/MissingDetails-result.txt b/Tests/RunCMake/FetchContent/MissingDetails-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/MissingDetails-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/FetchContent/MissingDetails-stderr.txt b/Tests/RunCMake/FetchContent/MissingDetails-stderr.txt
new file mode 100644
index 000000000..c4f1daf58
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/MissingDetails-stderr.txt
@@ -0,0 +1 @@
+No content details recorded for t1
diff --git a/Tests/RunCMake/FetchContent/MissingDetails.cmake b/Tests/RunCMake/FetchContent/MissingDetails.cmake
new file mode 100644
index 000000000..ba8d12167
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/MissingDetails.cmake
@@ -0,0 +1,3 @@
+include(FetchContent)
+
+FetchContent_Populate(t1)
diff --git a/Tests/RunCMake/FetchContent/RunCMakeTest.cmake b/Tests/RunCMake/FetchContent/RunCMakeTest.cmake
new file mode 100644
index 000000000..e28ae96dd
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/RunCMakeTest.cmake
@@ -0,0 +1,32 @@
+include(RunCMake)
+
+unset(RunCMake_TEST_NO_CLEAN)
+
+run_cmake(MissingDetails)
+run_cmake(DirectIgnoresDetails)
+run_cmake(FirstDetailsWin)
+run_cmake(DownloadTwice)
+run_cmake(SameGenerator)
+run_cmake(VarDefinitions)
+run_cmake(GetProperties)
+run_cmake(DirOverrides)
+run_cmake(UsesTerminalOverride)
+run_cmake(MakeAvailable)
+run_cmake(MakeAvailableTwice)
+run_cmake(MakeAvailableUndeclared)
+
+# We need to pass through CMAKE_GENERATOR and CMAKE_MAKE_PROGRAM
+# to ensure the test can run on machines where the build tool
+# isn't on the PATH. Some build slaves explicitly test with such
+# an arrangement (e.g. to test with spaces in the path). We also
+# pass through the platform and toolset for completeness, even
+# though we don't build anything, just in case this somehow affects
+# the way the build tool is invoked.
+run_cmake_command(ScriptMode
+ ${CMAKE_COMMAND}
+ -DCMAKE_GENERATOR=${RunCMake_GENERATOR}
+ -DCMAKE_GENERATOR_PLATFORM=${RunCMake_GENERATOR_PLATFORM}
+ -DCMAKE_GENERATOR_TOOLSET=${RunCMake_GENERATOR_TOOLSET}
+ -DCMAKE_MAKE_PROGRAM=${RunCMake_MAKE_PROGRAM}
+ -P ${CMAKE_CURRENT_LIST_DIR}/ScriptMode.cmake
+)
diff --git a/Tests/RunCMake/FetchContent/SameGenerator.cmake b/Tests/RunCMake/FetchContent/SameGenerator.cmake
new file mode 100644
index 000000000..58204ef04
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/SameGenerator.cmake
@@ -0,0 +1,17 @@
+include(FetchContent)
+
+FetchContent_Declare(
+ t1
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E echo "Download command executed"
+)
+
+FetchContent_Populate(t1)
+
+file(STRINGS "${FETCHCONTENT_BASE_DIR}/t1-subbuild/CMakeCache.txt"
+ matchLine REGEX "^CMAKE_GENERATOR:.*="
+ LIMIT_COUNT 1
+)
+if(NOT matchLine MATCHES "${CMAKE_GENERATOR}")
+ message(FATAL_ERROR "Generator line mismatch: ${matchLine}\n"
+ " Expected type: ${CMAKE_GENERATOR}")
+endif()
diff --git a/Tests/RunCMake/FetchContent/ScriptMode.cmake b/Tests/RunCMake/FetchContent/ScriptMode.cmake
new file mode 100644
index 000000000..0a93d620e
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/ScriptMode.cmake
@@ -0,0 +1,35 @@
+include(FetchContent)
+
+file(WRITE tmpFile.txt "Generated contents, not important")
+
+FetchContent_Populate(
+ t1
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_CURRENT_BINARY_DIR}/tmpFile.txt
+ <SOURCE_DIR>/done1.txt
+)
+if(NOT EXISTS ${CMAKE_CURRENT_BINARY_DIR}/t1-src/done1.txt)
+ message(FATAL_ERROR "Default SOURCE_DIR doesn't contain done1.txt")
+endif()
+
+FetchContent_Populate(
+ t2
+ SOURCE_DIR ${CMAKE_CURRENT_BINARY_DIR}/mysrc
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_CURRENT_BINARY_DIR}/tmpFile.txt
+ <SOURCE_DIR>/done2.txt
+)
+if(NOT EXISTS ${CMAKE_CURRENT_BINARY_DIR}/mysrc/done2.txt)
+ message(FATAL_ERROR "Specified SOURCE_DIR doesn't contain done2.txt")
+endif()
+
+FetchContent_Populate(
+ t3
+ SOURCE_DIR myrelsrc
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_CURRENT_BINARY_DIR}/tmpFile.txt
+ <SOURCE_DIR>/done3.txt
+)
+if(NOT EXISTS ${CMAKE_CURRENT_BINARY_DIR}/myrelsrc/done3.txt)
+ message(FATAL_ERROR "Relative SOURCE_DIR doesn't contain done3.txt")
+endif()
diff --git a/Tests/RunCMake/FetchContent/UsesTerminalOverride-stdout.txt b/Tests/RunCMake/FetchContent/UsesTerminalOverride-stdout.txt
new file mode 100644
index 000000000..3718d6459
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/UsesTerminalOverride-stdout.txt
@@ -0,0 +1,2 @@
+Logged from t1 download step
++.*Logged from t2 download step
diff --git a/Tests/RunCMake/FetchContent/UsesTerminalOverride.cmake b/Tests/RunCMake/FetchContent/UsesTerminalOverride.cmake
new file mode 100644
index 000000000..99d9719e4
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/UsesTerminalOverride.cmake
@@ -0,0 +1,17 @@
+include(FetchContent)
+
+set(FETCHCONTENT_QUIET NO)
+
+FetchContent_Declare(
+ t1
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E echo "Logged from t1 download step"
+ USES_TERMINAL_DOWNLOAD NO
+
+)
+FetchContent_Populate(t1)
+
+FetchContent_Populate(
+ t2
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E echo "Logged from t2 download step"
+ USES_TERMINAL_DOWNLOAD NO
+)
diff --git a/Tests/RunCMake/FetchContent/VarDefinitions.cmake b/Tests/RunCMake/FetchContent/VarDefinitions.cmake
new file mode 100644
index 000000000..4d2a929af
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/VarDefinitions.cmake
@@ -0,0 +1,75 @@
+unset(FETCHCONTENT_FULLY_DISCONNECTED CACHE)
+unset(FETCHCONTENT_UPDATES_DISCONNECTED CACHE)
+unset(FETCHCONTENT_QUIET CACHE)
+unset(FETCHCONTENT_BASE_DIR CACHE)
+
+include(FetchContent)
+
+# Each of the cache entries should be defined and have the
+# expected value. Be careful to check unset separately from a
+# false value, since unset also equates to false.
+if(FETCHCONTENT_FULLY_DISCONNECTED STREQUAL "")
+ message(FATAL_ERROR "FETCHCONTENT_FULLY_DISCONNECTED not defined")
+elseif(FETCHCONTENT_FULLY_DISCONNECTED)
+ message(FATAL_ERROR "FETCHCONTENT_FULLY_DISCONNECTED not defaulted to OFF")
+endif()
+
+if(FETCHCONTENT_UPDATES_DISCONNECTED STREQUAL "")
+ message(FATAL_ERROR "FETCHCONTENT_UPDATES_DISCONNECTED not defined")
+elseif(FETCHCONTENT_UPDATES_DISCONNECTED)
+ message(FATAL_ERROR "FETCHCONTENT_UPDATES_DISCONNECTED not defaulted to OFF")
+endif()
+
+if(FETCHCONTENT_QUIET STREQUAL "")
+ message(FATAL_ERROR "FETCHCONTENT_QUIET not defined")
+elseif(NOT FETCHCONTENT_QUIET)
+ message(FATAL_ERROR "FETCHCONTENT_QUIET not defaulted to ON")
+endif()
+
+if(NOT FETCHCONTENT_BASE_DIR STREQUAL "${CMAKE_BINARY_DIR}/_deps")
+ message(FATAL_ERROR "FETCHCONTENT_BASE_DIR has default value: "
+ "${FETCHCONTENT_BASE_DIR}\n Expected: ${CMAKE_BINARY_DIR}/_deps")
+endif()
+
+file(REMOVE_RECURSE ${FETCHCONTENT_BASE_DIR}/t1-subbuild)
+
+# Use uppercase T1 test name to confirm conversion to lowercase
+# for the t1_... variable names that get set
+FetchContent_Declare(
+ T1
+ DOWNLOAD_COMMAND ${CMAKE_COMMAND} -E echo "Download command executed"
+)
+FetchContent_Populate(T1)
+
+# Be careful to check both regular and cache variables. Since they have
+# the same name, we can only confirm them separately by using get_property().
+get_property(srcRegVarSet VARIABLE PROPERTY t1_SOURCE_DIR SET)
+get_property(bldRegVarSet VARIABLE PROPERTY t1_BINARY_DIR SET)
+
+get_property(srcCacheVarSet CACHE t1_SOURCE_DIR PROPERTY VALUE SET)
+get_property(bldCacheVarSet CACHE t1_BINARY_DIR PROPERTY VALUE SET)
+
+if(NOT srcRegVarSet)
+ message(FATAL_ERROR "t1_SOURCE_DIR regular variable not set")
+endif()
+if(NOT bldRegVarSet)
+ message(FATAL_ERROR "t1_BINARY_DIR regular variable not set")
+endif()
+if(srcCacheVarSet)
+ message(FATAL_ERROR "t1_SOURCE_DIR cache variable unexpectedly set")
+endif()
+if(bldCacheVarSet)
+ message(FATAL_ERROR "t1_BINARY_DIR cache variable unexpectedly set")
+endif()
+
+set(srcRegVar ${t1_SOURCE_DIR})
+set(bldRegVar ${t1_BINARY_DIR})
+
+if(NOT srcRegVar STREQUAL "${CMAKE_BINARY_DIR}/_deps/t1-src")
+ message(FATAL_ERROR "Unexpected t1_SOURCE_DIR value: ${srcRegVar}\n"
+ " Expected: ${CMAKE_BINARY_DIR}/_deps/t1-src")
+endif()
+if(NOT bldRegVar STREQUAL "${CMAKE_BINARY_DIR}/_deps/t1-build")
+ message(FATAL_ERROR "Unexpected t1_BINARY_DIR value: ${bldRegVar}\n"
+ " Expected: ${CMAKE_BINARY_DIR}/_deps/t1-build")
+endif()
diff --git a/Tests/RunCMake/FetchContent/WithProject/CMakeLists.txt b/Tests/RunCMake/FetchContent/WithProject/CMakeLists.txt
new file mode 100644
index 000000000..b6a37508e
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/WithProject/CMakeLists.txt
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.13)
+project(WithProject LANGUAGES NONE)
+
+set_property(GLOBAL PROPERTY FetchWithProject YES)
+message(STATUS "Confirmation project has been added")
diff --git a/Tests/RunCMake/FetchContent/WithoutProject/confirmMessage.cmake b/Tests/RunCMake/FetchContent/WithoutProject/confirmMessage.cmake
new file mode 100644
index 000000000..a2f5c61d0
--- /dev/null
+++ b/Tests/RunCMake/FetchContent/WithoutProject/confirmMessage.cmake
@@ -0,0 +1 @@
+message(STATUS "Confirmation script has been called")
diff --git a/Tests/RunCMake/FileAPI/CMakeLists.txt b/Tests/RunCMake/FileAPI/CMakeLists.txt
new file mode 100644
index 000000000..44025d3bd
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.12)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/FileAPI/ClientStateful-check.cmake b/Tests/RunCMake/FileAPI/ClientStateful-check.cmake
new file mode 100644
index 000000000..1e9aab6d1
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/ClientStateful-check.cmake
@@ -0,0 +1,68 @@
+set(expect
+ query
+ query/client-client-member
+ query/client-client-member/query.json
+ query/client-empty-array
+ query/client-empty-array/query.json
+ query/client-empty-object
+ query/client-empty-object/query.json
+ query/client-json-bad-root
+ query/client-json-bad-root/query.json
+ query/client-json-empty
+ query/client-json-empty/query.json
+ query/client-json-extra
+ query/client-json-extra/query.json
+ query/client-not-file
+ query/client-not-file/query.json
+ query/client-request-array-negative-major-version
+ query/client-request-array-negative-major-version/query.json
+ query/client-request-array-negative-minor-version
+ query/client-request-array-negative-minor-version/query.json
+ query/client-request-array-negative-version
+ query/client-request-array-negative-version/query.json
+ query/client-request-array-no-major-version
+ query/client-request-array-no-major-version/query.json
+ query/client-request-array-no-supported-version
+ query/client-request-array-no-supported-version-among
+ query/client-request-array-no-supported-version-among/query.json
+ query/client-request-array-no-supported-version/query.json
+ query/client-request-array-version-1
+ query/client-request-array-version-1-1
+ query/client-request-array-version-1-1/query.json
+ query/client-request-array-version-1/query.json
+ query/client-request-array-version-2
+ query/client-request-array-version-2/query.json
+ query/client-request-negative-major-version
+ query/client-request-negative-major-version/query.json
+ query/client-request-negative-minor-version
+ query/client-request-negative-minor-version/query.json
+ query/client-request-negative-version
+ query/client-request-negative-version/query.json
+ query/client-request-no-major-version
+ query/client-request-no-major-version/query.json
+ query/client-request-no-version
+ query/client-request-no-version/query.json
+ query/client-request-version-1
+ query/client-request-version-1-1
+ query/client-request-version-1-1/query.json
+ query/client-request-version-1/query.json
+ query/client-request-version-2
+ query/client-request-version-2/query.json
+ query/client-requests-bad
+ query/client-requests-bad/query.json
+ query/client-requests-empty
+ query/client-requests-empty/query.json
+ query/client-requests-not-kinded
+ query/client-requests-not-kinded/query.json
+ query/client-requests-not-objects
+ query/client-requests-not-objects/query.json
+ query/client-requests-unknown
+ query/client-requests-unknown/query.json
+ reply
+ reply/__test-v1-[0-9a-f]+.json
+ reply/__test-v2-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(ClientStateful)
diff --git a/Tests/RunCMake/FileAPI/ClientStateful-check.py b/Tests/RunCMake/FileAPI/ClientStateful-check.py
new file mode 100644
index 000000000..f3d20d13e
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/ClientStateful-check.py
@@ -0,0 +1,258 @@
+from check_index import *
+
+def check_reply(q):
+ assert is_dict(q)
+ assert sorted(q.keys()) == [
+ "client-client-member",
+ "client-empty-array",
+ "client-empty-object",
+ "client-json-bad-root",
+ "client-json-empty",
+ "client-json-extra",
+ "client-not-file",
+ "client-request-array-negative-major-version",
+ "client-request-array-negative-minor-version",
+ "client-request-array-negative-version",
+ "client-request-array-no-major-version",
+ "client-request-array-no-supported-version",
+ "client-request-array-no-supported-version-among",
+ "client-request-array-version-1",
+ "client-request-array-version-1-1",
+ "client-request-array-version-2",
+ "client-request-negative-major-version",
+ "client-request-negative-minor-version",
+ "client-request-negative-version",
+ "client-request-no-major-version",
+ "client-request-no-version",
+ "client-request-version-1",
+ "client-request-version-1-1",
+ "client-request-version-2",
+ "client-requests-bad",
+ "client-requests-empty",
+ "client-requests-not-kinded",
+ "client-requests-not-objects",
+ "client-requests-unknown",
+ ]
+ expected = [
+ (check_query_client_member, "client-client-member"),
+ (check_query_empty_array, "client-empty-array"),
+ (check_query_empty_object, "client-empty-object"),
+ (check_query_json_bad_root, "client-json-bad-root"),
+ (check_query_json_empty, "client-json-empty"),
+ (check_query_json_extra, "client-json-extra"),
+ (check_query_not_file, "client-not-file"),
+ (check_query_requests_bad, "client-requests-bad"),
+ (check_query_requests_empty, "client-requests-empty"),
+ (check_query_requests_not_kinded, "client-requests-not-kinded"),
+ (check_query_requests_not_objects, "client-requests-not-objects"),
+ (check_query_requests_unknown, "client-requests-unknown"),
+ ]
+ for (f, k) in expected:
+ assert is_dict(q[k])
+ assert sorted(q[k].keys()) == ["query.json"]
+ f(q[k]["query.json"])
+ expected = [
+ (check_query_response_array_negative_major_version, "client-request-array-negative-major-version"),
+ (check_query_response_array_negative_minor_version, "client-request-array-negative-minor-version"),
+ (check_query_response_array_negative_version, "client-request-array-negative-version"),
+ (check_query_response_array_no_major_version, "client-request-array-no-major-version"),
+ (check_query_response_array_no_supported_version, "client-request-array-no-supported-version"),
+ (check_query_response_array_no_supported_version_among, "client-request-array-no-supported-version-among"),
+ (check_query_response_array_version_1, "client-request-array-version-1"),
+ (check_query_response_array_version_1_1, "client-request-array-version-1-1"),
+ (check_query_response_array_version_2, "client-request-array-version-2"),
+ (check_query_response_negative_major_version, "client-request-negative-major-version"),
+ (check_query_response_negative_minor_version, "client-request-negative-minor-version"),
+ (check_query_response_negative_version, "client-request-negative-version"),
+ (check_query_response_no_major_version, "client-request-no-major-version"),
+ (check_query_response_no_version, "client-request-no-version"),
+ (check_query_response_version_1, "client-request-version-1"),
+ (check_query_response_version_1_1, "client-request-version-1-1"),
+ (check_query_response_version_2, "client-request-version-2"),
+ ]
+ for (f, k) in expected:
+ assert is_dict(q[k])
+ assert sorted(q[k].keys()) == ["query.json"]
+ assert is_dict(q[k]["query.json"])
+ assert sorted(q[k]["query.json"].keys()) == ["requests", "responses"]
+ r = q[k]["query.json"]["requests"]
+ assert is_list(r)
+ assert len(r) == 1
+ assert is_dict(r[0])
+ assert r[0]["kind"] == "__test"
+ r = q[k]["query.json"]["responses"]
+ assert is_list(r)
+ assert len(r) == 1
+ assert is_dict(r[0])
+ f(r[0])
+
+def check_query_client_member(q):
+ assert is_dict(q)
+ assert sorted(q.keys()) == ["client", "responses"]
+ assert is_dict(q["client"])
+ assert sorted(q["client"].keys()) == []
+ check_error(q["responses"], "'requests' member missing")
+
+def check_query_empty_array(q):
+ check_error(q, "query root is not an object")
+
+def check_query_empty_object(q):
+ assert is_dict(q)
+ assert sorted(q.keys()) == ["responses"]
+ check_error(q["responses"], "'requests' member missing")
+
+def check_query_json_bad_root(q):
+ check_error_re(q, "A valid JSON document must be either an array or an object value")
+
+def check_query_json_empty(q):
+ check_error_re(q, "value, object or array expected")
+
+def check_query_json_extra(q):
+ check_error_re(q, "Extra non-whitespace after JSON value")
+
+def check_query_not_file(q):
+ check_error_re(q, "failed to read from file")
+
+def check_query_requests_bad(q):
+ assert is_dict(q)
+ assert sorted(q.keys()) == ["requests", "responses"]
+ r = q["requests"]
+ assert is_dict(r)
+ assert sorted(r.keys()) == []
+ check_error(q["responses"], "'requests' member is not an array")
+
+def check_query_requests_empty(q):
+ assert is_dict(q)
+ assert sorted(q.keys()) == ["requests", "responses"]
+ r = q["requests"]
+ assert is_list(r)
+ assert len(r) == 0
+ r = q["responses"]
+ assert is_list(r)
+ assert len(r) == 0
+
+def check_query_requests_not_kinded(q):
+ assert is_dict(q)
+ assert sorted(q.keys()) == ["requests", "responses"]
+ r = q["requests"]
+ assert is_list(r)
+ assert len(r) == 4
+ assert is_dict(r[0])
+ assert sorted(r[0].keys()) == []
+ assert is_dict(r[1])
+ assert sorted(r[1].keys()) == ["kind"]
+ assert is_dict(r[1]["kind"])
+ assert is_dict(r[2])
+ assert sorted(r[2].keys()) == ["kind"]
+ assert is_list(r[2]["kind"])
+ assert is_dict(r[3])
+ assert sorted(r[3].keys()) == ["kind"]
+ assert is_int(r[3]["kind"])
+ r = q["responses"]
+ assert is_list(r)
+ assert len(r) == 4
+ check_error(r[0], "'kind' member missing")
+ check_error(r[1], "'kind' member is not a string")
+ check_error(r[2], "'kind' member is not a string")
+ check_error(r[3], "'kind' member is not a string")
+
+def check_query_requests_not_objects(q):
+ assert is_dict(q)
+ assert sorted(q.keys()) == ["requests", "responses"]
+ r = q["requests"]
+ assert is_list(r)
+ assert len(r) == 3
+ assert is_int(r[0])
+ assert is_string(r[1])
+ assert is_list(r[2])
+ r = q["responses"]
+ assert is_list(r)
+ assert len(r) == 3
+ check_error(r[0], "request is not an object")
+ check_error(r[1], "request is not an object")
+ check_error(r[2], "request is not an object")
+
+def check_query_requests_unknown(q):
+ assert is_dict(q)
+ assert sorted(q.keys()) == ["requests", "responses"]
+ r = q["requests"]
+ assert is_list(r)
+ assert len(r) == 3
+ assert is_dict(r[0])
+ assert sorted(r[0].keys()) == ["kind"]
+ assert r[0]["kind"] == "unknownC"
+ assert is_dict(r[1])
+ assert sorted(r[1].keys()) == ["kind"]
+ assert r[1]["kind"] == "unknownB"
+ assert is_dict(r[2])
+ assert sorted(r[2].keys()) == ["kind"]
+ assert r[2]["kind"] == "unknownA"
+ r = q["responses"]
+ assert is_list(r)
+ assert len(r) == 3
+ check_error(r[0], "unknown request kind 'unknownC'")
+ check_error(r[1], "unknown request kind 'unknownB'")
+ check_error(r[2], "unknown request kind 'unknownA'")
+
+def check_query_response_array_negative_major_version(r):
+ check_error(r, "'version' object 'major' member is not a non-negative integer")
+
+def check_query_response_array_negative_minor_version(r):
+ check_error(r, "'version' object 'minor' member is not a non-negative integer")
+
+def check_query_response_array_negative_version(r):
+ check_error(r, "'version' array entry is not a non-negative integer or object")
+
+def check_query_response_array_no_major_version(r):
+ check_error(r, "'version' object 'major' member missing")
+
+def check_query_response_array_no_supported_version(r):
+ check_error(r, "no supported version specified")
+
+def check_query_response_array_no_supported_version_among(r):
+ check_error(r, "no supported version specified among: 4.0 3.0")
+
+def check_query_response_array_version_1(r):
+ check_index__test(r, 1, 3)
+
+def check_query_response_array_version_1_1(r):
+ check_index__test(r, 1, 3) # always uses latest minor version
+
+def check_query_response_array_version_2(r):
+ check_index__test(r, 2, 0)
+
+def check_query_response_negative_major_version(r):
+ check_error(r, "'version' object 'major' member is not a non-negative integer")
+
+def check_query_response_negative_minor_version(r):
+ check_error(r, "'version' object 'minor' member is not a non-negative integer")
+
+def check_query_response_negative_version(r):
+ check_error(r, "'version' member is not a non-negative integer, object, or array")
+
+def check_query_response_no_major_version(r):
+ check_error(r, "'version' object 'major' member missing")
+
+def check_query_response_no_version(r):
+ check_error(r, "'version' member missing")
+
+def check_query_response_version_1(r):
+ check_index__test(r, 1, 3)
+
+def check_query_response_version_1_1(r):
+ check_index__test(r, 1, 3) # always uses latest minor version
+
+def check_query_response_version_2(r):
+ check_index__test(r, 2, 0)
+
+def check_objects(o):
+ assert is_list(o)
+ assert len(o) == 2
+ check_index__test(o[0], 1, 3)
+ check_index__test(o[1], 2, 0)
+
+assert is_dict(index)
+assert sorted(index.keys()) == ["cmake", "objects", "reply"]
+check_cmake(index["cmake"])
+check_reply(index["reply"])
+check_objects(index["objects"])
diff --git a/Tests/RunCMake/FileAPI/ClientStateful-prep.cmake b/Tests/RunCMake/FileAPI/ClientStateful-prep.cmake
new file mode 100644
index 000000000..5b41d7afb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/ClientStateful-prep.cmake
@@ -0,0 +1,73 @@
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-client-member/query.json" [[{ "client": {} }]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-empty-array/query.json" "[]")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-empty-object/query.json" "{}")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-json-bad-root/query.json" [["invalid root"]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-json-empty/query.json" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-json-extra/query.json" "{}x")
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-not-file/query.json")
+
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-requests-bad/query.json" [[{ "requests": {} }]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-requests-empty/query.json" [[{ "requests": [] }]])
+
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-requests-not-objects/query.json" [[
+{ "requests": [ 0, "", [] ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-requests-not-kinded/query.json" [[
+{ "requests": [ {}, { "kind": {} }, { "kind": [] }, { "kind": 0 } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-requests-unknown/query.json" [[
+{ "requests": [ { "kind": "unknownC" }, { "kind": "unknownB" }, { "kind": "unknownA" } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-no-version/query.json" [[
+{ "requests": [ { "kind": "__test" } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-negative-version/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : -1 } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-no-major-version/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : {} } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-negative-major-version/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : { "major": -1 } } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-negative-minor-version/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : { "major": 0, "minor": -1 } } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-array-negative-version/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : [ 1, -1 ] } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-array-no-major-version/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : [ 1, {} ] } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-array-negative-major-version/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : [ 1, { "major": -1 } ] } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-array-negative-minor-version/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : [ 1, { "major": 0, "minor": -1 } ] } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-array-no-supported-version/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : [] } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-array-no-supported-version-among/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : [4, 3] } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-version-1/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : 1 } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-version-1-1/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : { "major": 1, "minor": 1 } } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-version-2/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : { "major": 2 } } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-array-version-1/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : [3, 1] } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-array-version-1-1/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : [3, { "major": 1, "minor": 1 }, 2 ] } ] }
+]])
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-request-array-version-2/query.json" [[
+{ "requests": [ { "kind": "__test", "version" : [3, { "major": 2 } ] } ] }
+]])
+
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/reply/object-to-be-deleted.json" "")
diff --git a/Tests/RunCMake/FileAPI/ClientStateful.cmake b/Tests/RunCMake/FileAPI/ClientStateful.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/ClientStateful.cmake
diff --git a/Tests/RunCMake/FileAPI/ClientStateless-check.cmake b/Tests/RunCMake/FileAPI/ClientStateless-check.cmake
new file mode 100644
index 000000000..955d9bea4
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/ClientStateless-check.cmake
@@ -0,0 +1,15 @@
+set(expect
+ query
+ query/client-foo
+ query/client-foo/__test-v1
+ query/client-foo/__test-v2
+ query/client-foo/__test-v3
+ query/client-foo/unknown
+ reply
+ reply/__test-v1-[0-9a-f]+.json
+ reply/__test-v2-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(ClientStateless)
diff --git a/Tests/RunCMake/FileAPI/ClientStateless-check.py b/Tests/RunCMake/FileAPI/ClientStateless-check.py
new file mode 100644
index 000000000..b7da314ce
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/ClientStateless-check.py
@@ -0,0 +1,26 @@
+from check_index import *
+
+def check_reply(r):
+ assert is_dict(r)
+ assert sorted(r.keys()) == ["client-foo"]
+ check_reply_client_foo(r["client-foo"])
+
+def check_reply_client_foo(r):
+ assert is_dict(r)
+ assert sorted(r.keys()) == ["__test-v1", "__test-v2", "__test-v3", "unknown"]
+ check_index__test(r["__test-v1"], 1, 3)
+ check_index__test(r["__test-v2"], 2, 0)
+ check_error(r["__test-v3"], "unknown query file")
+ check_error(r["unknown"], "unknown query file")
+
+def check_objects(o):
+ assert is_list(o)
+ assert len(o) == 2
+ check_index__test(o[0], 1, 3)
+ check_index__test(o[1], 2, 0)
+
+assert is_dict(index)
+assert sorted(index.keys()) == ["cmake", "objects", "reply"]
+check_cmake(index["cmake"])
+check_reply(index["reply"])
+check_objects(index["objects"])
diff --git a/Tests/RunCMake/FileAPI/ClientStateless-prep.cmake b/Tests/RunCMake/FileAPI/ClientStateless-prep.cmake
new file mode 100644
index 000000000..1b8d772fa
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/ClientStateless-prep.cmake
@@ -0,0 +1,5 @@
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/__test-v1" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/__test-v2" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/__test-v3" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/unknown" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/reply/object-to-be-deleted.json" "")
diff --git a/Tests/RunCMake/FileAPI/ClientStateless.cmake b/Tests/RunCMake/FileAPI/ClientStateless.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/ClientStateless.cmake
diff --git a/Tests/RunCMake/FileAPI/DuplicateStateless-check.cmake b/Tests/RunCMake/FileAPI/DuplicateStateless-check.cmake
new file mode 100644
index 000000000..4959c1eaa
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/DuplicateStateless-check.cmake
@@ -0,0 +1,20 @@
+set(expect
+ query
+ query/__test-v1
+ query/__test-v2
+ query/__test-v3
+ query/client-foo
+ query/client-foo/__test-v1
+ query/client-foo/__test-v2
+ query/client-foo/__test-v3
+ query/client-foo/unknown
+ query/query.json
+ query/unknown
+ reply
+ reply/__test-v1-[0-9a-f]+.json
+ reply/__test-v2-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(DuplicateStateless)
diff --git a/Tests/RunCMake/FileAPI/DuplicateStateless-check.py b/Tests/RunCMake/FileAPI/DuplicateStateless-check.py
new file mode 100644
index 000000000..33354794c
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/DuplicateStateless-check.py
@@ -0,0 +1,31 @@
+from check_index import *
+
+def check_reply(r):
+ assert is_dict(r)
+ assert sorted(r.keys()) == ["__test-v1", "__test-v2", "__test-v3", "client-foo", "query.json", "unknown"]
+ check_index__test(r["__test-v1"], 1, 3)
+ check_index__test(r["__test-v2"], 2, 0)
+ check_error(r["__test-v3"], "unknown query file")
+ check_reply_client_foo(r["client-foo"])
+ check_error(r["query.json"], "unknown query file")
+ check_error(r["unknown"], "unknown query file")
+
+def check_reply_client_foo(r):
+ assert is_dict(r)
+ assert sorted(r.keys()) == ["__test-v1", "__test-v2", "__test-v3", "unknown"]
+ check_index__test(r["__test-v1"], 1, 3)
+ check_index__test(r["__test-v2"], 2, 0)
+ check_error(r["__test-v3"], "unknown query file")
+ check_error(r["unknown"], "unknown query file")
+
+def check_objects(o):
+ assert is_list(o)
+ assert len(o) == 2
+ check_index__test(o[0], 1, 3)
+ check_index__test(o[1], 2, 0)
+
+assert is_dict(index)
+assert sorted(index.keys()) == ["cmake", "objects", "reply"]
+check_cmake(index["cmake"])
+check_reply(index["reply"])
+check_objects(index["objects"])
diff --git a/Tests/RunCMake/FileAPI/DuplicateStateless-prep.cmake b/Tests/RunCMake/FileAPI/DuplicateStateless-prep.cmake
new file mode 100644
index 000000000..51b985281
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/DuplicateStateless-prep.cmake
@@ -0,0 +1,10 @@
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/__test-v1" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/__test-v2" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/__test-v3" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/query.json" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/unknown" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/__test-v1" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/__test-v2" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/__test-v3" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/unknown" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/reply/object-to-be-deleted.json" "")
diff --git a/Tests/RunCMake/FileAPI/DuplicateStateless.cmake b/Tests/RunCMake/FileAPI/DuplicateStateless.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/DuplicateStateless.cmake
diff --git a/Tests/RunCMake/FileAPI/Empty-check.cmake b/Tests/RunCMake/FileAPI/Empty-check.cmake
new file mode 100644
index 000000000..2764b4297
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/Empty-check.cmake
@@ -0,0 +1,8 @@
+set(expect
+ query
+ reply
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(Empty)
diff --git a/Tests/RunCMake/FileAPI/Empty-check.py b/Tests/RunCMake/FileAPI/Empty-check.py
new file mode 100644
index 000000000..75bf096d0
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/Empty-check.py
@@ -0,0 +1,15 @@
+from check_index import *
+
+def check_reply(r):
+ assert is_dict(r)
+ assert sorted(r.keys()) == []
+
+def check_objects(o):
+ assert is_list(o)
+ assert len(o) == 0
+
+assert is_dict(index)
+assert sorted(index.keys()) == ["cmake", "objects", "reply"]
+check_cmake(index["cmake"])
+check_reply(index["reply"])
+check_objects(index["objects"])
diff --git a/Tests/RunCMake/FileAPI/Empty-prep.cmake b/Tests/RunCMake/FileAPI/Empty-prep.cmake
new file mode 100644
index 000000000..1d1f69e23
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/Empty-prep.cmake
@@ -0,0 +1 @@
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query")
diff --git a/Tests/RunCMake/FileAPI/Empty.cmake b/Tests/RunCMake/FileAPI/Empty.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/Empty.cmake
diff --git a/Tests/RunCMake/FileAPI/EmptyClient-check.cmake b/Tests/RunCMake/FileAPI/EmptyClient-check.cmake
new file mode 100644
index 000000000..4e5745cdb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/EmptyClient-check.cmake
@@ -0,0 +1,9 @@
+set(expect
+ query
+ query/client-foo
+ reply
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(EmptyClient)
diff --git a/Tests/RunCMake/FileAPI/EmptyClient-check.py b/Tests/RunCMake/FileAPI/EmptyClient-check.py
new file mode 100644
index 000000000..f88790818
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/EmptyClient-check.py
@@ -0,0 +1,20 @@
+from check_index import *
+
+def check_reply(r):
+ assert is_dict(r)
+ assert sorted(r.keys()) == ["client-foo"]
+ check_reply_client_foo(r["client-foo"])
+
+def check_reply_client_foo(r):
+ assert is_dict(r)
+ assert sorted(r.keys()) == []
+
+def check_objects(o):
+ assert is_list(o)
+ assert len(o) == 0
+
+assert is_dict(index)
+assert sorted(index.keys()) == ["cmake", "objects", "reply"]
+check_cmake(index["cmake"])
+check_reply(index["reply"])
+check_objects(index["objects"])
diff --git a/Tests/RunCMake/FileAPI/EmptyClient-prep.cmake b/Tests/RunCMake/FileAPI/EmptyClient-prep.cmake
new file mode 100644
index 000000000..31512fd0c
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/EmptyClient-prep.cmake
@@ -0,0 +1,2 @@
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/reply/object-to-be-deleted.json" "")
diff --git a/Tests/RunCMake/FileAPI/EmptyClient.cmake b/Tests/RunCMake/FileAPI/EmptyClient.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/EmptyClient.cmake
diff --git a/Tests/RunCMake/FileAPI/MixedStateless-check.cmake b/Tests/RunCMake/FileAPI/MixedStateless-check.cmake
new file mode 100644
index 000000000..57956143e
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/MixedStateless-check.cmake
@@ -0,0 +1,16 @@
+set(expect
+ query
+ query/__test-v1
+ query/__test-v3
+ query/client-foo
+ query/client-foo/__test-v2
+ query/client-foo/unknown
+ query/query.json
+ reply
+ reply/__test-v1-[0-9a-f]+.json
+ reply/__test-v2-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(MixedStateless)
diff --git a/Tests/RunCMake/FileAPI/MixedStateless-check.py b/Tests/RunCMake/FileAPI/MixedStateless-check.py
new file mode 100644
index 000000000..be019ab72
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/MixedStateless-check.py
@@ -0,0 +1,27 @@
+from check_index import *
+
+def check_reply(r):
+ assert is_dict(r)
+ assert sorted(r.keys()) == ["__test-v1", "__test-v3", "client-foo", "query.json"]
+ check_index__test(r["__test-v1"], 1, 3)
+ check_error(r["__test-v3"], "unknown query file")
+ check_reply_client_foo(r["client-foo"])
+ check_error(r["query.json"], "unknown query file")
+
+def check_reply_client_foo(r):
+ assert is_dict(r)
+ assert sorted(r.keys()) == ["__test-v2", "unknown"]
+ check_index__test(r["__test-v2"], 2, 0)
+ check_error(r["unknown"], "unknown query file")
+
+def check_objects(o):
+ assert is_list(o)
+ assert len(o) == 2
+ check_index__test(o[0], 1, 3)
+ check_index__test(o[1], 2, 0)
+
+assert is_dict(index)
+assert sorted(index.keys()) == ["cmake", "objects", "reply"]
+check_cmake(index["cmake"])
+check_reply(index["reply"])
+check_objects(index["objects"])
diff --git a/Tests/RunCMake/FileAPI/MixedStateless-prep.cmake b/Tests/RunCMake/FileAPI/MixedStateless-prep.cmake
new file mode 100644
index 000000000..030baac5b
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/MixedStateless-prep.cmake
@@ -0,0 +1,6 @@
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/__test-v1" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/__test-v2" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/__test-v3" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/query.json" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/unknown" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/reply/object-to-be-deleted.json" "")
diff --git a/Tests/RunCMake/FileAPI/MixedStateless.cmake b/Tests/RunCMake/FileAPI/MixedStateless.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/MixedStateless.cmake
diff --git a/Tests/RunCMake/FileAPI/Nothing-check.cmake b/Tests/RunCMake/FileAPI/Nothing-check.cmake
new file mode 100644
index 000000000..cd4f42efc
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/Nothing-check.cmake
@@ -0,0 +1 @@
+check_api("^$")
diff --git a/Tests/RunCMake/FileAPI/Nothing-prep.cmake b/Tests/RunCMake/FileAPI/Nothing-prep.cmake
new file mode 100644
index 000000000..b850d47a8
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/Nothing-prep.cmake
@@ -0,0 +1 @@
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1")
diff --git a/Tests/RunCMake/FileAPI/Nothing.cmake b/Tests/RunCMake/FileAPI/Nothing.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/Nothing.cmake
diff --git a/Tests/RunCMake/FileAPI/RunCMakeTest.cmake b/Tests/RunCMake/FileAPI/RunCMakeTest.cmake
new file mode 100644
index 000000000..f8adb644a
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/RunCMakeTest.cmake
@@ -0,0 +1,58 @@
+include(RunCMake)
+
+# Function called in *-check.cmake scripts to check api files.
+function(check_api expect)
+ file(GLOB_RECURSE actual
+ LIST_DIRECTORIES TRUE
+ RELATIVE ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1
+ ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/*
+ )
+ if(NOT "${actual}" MATCHES "${expect}")
+ set(RunCMake_TEST_FAILED "API files:
+ ${actual}
+do not match what we expected:
+ ${expect}
+in directory:
+ ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1" PARENT_SCOPE)
+ endif()
+endfunction()
+
+function(check_python case)
+ if(RunCMake_TEST_FAILED OR NOT PYTHON_EXECUTABLE)
+ return()
+ endif()
+ file(GLOB index ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/reply/index-*.json)
+ execute_process(
+ COMMAND ${PYTHON_EXECUTABLE} "${RunCMake_SOURCE_DIR}/${case}-check.py" "${index}"
+ RESULT_VARIABLE result
+ OUTPUT_VARIABLE output
+ ERROR_VARIABLE output
+ )
+ if(NOT result EQUAL 0)
+ string(REPLACE "\n" "\n " output " ${output}")
+ set(RunCMake_TEST_FAILED "Unexpected index:\n${output}" PARENT_SCOPE)
+ endif()
+endfunction()
+
+run_cmake(Nothing)
+run_cmake(Empty)
+run_cmake(EmptyClient)
+run_cmake(Stale)
+run_cmake(SharedStateless)
+run_cmake(ClientStateless)
+run_cmake(MixedStateless)
+run_cmake(DuplicateStateless)
+run_cmake(ClientStateful)
+
+function(run_object object)
+ set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${object}-build)
+ run_cmake(${object})
+ set(RunCMake_TEST_NO_CLEAN 1)
+ run_cmake_command(${object}-SharedStateless ${CMAKE_COMMAND} .)
+ run_cmake_command(${object}-ClientStateless ${CMAKE_COMMAND} .)
+ run_cmake_command(${object}-ClientStateful ${CMAKE_COMMAND} .)
+endfunction()
+
+run_object(codemodel-v2)
+run_object(cache-v2)
+run_object(cmakeFiles-v1)
diff --git a/Tests/RunCMake/FileAPI/SharedStateless-check.cmake b/Tests/RunCMake/FileAPI/SharedStateless-check.cmake
new file mode 100644
index 000000000..7f3bb23dc
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/SharedStateless-check.cmake
@@ -0,0 +1,15 @@
+set(expect
+ query
+ query/__test-v1
+ query/__test-v2
+ query/__test-v3
+ query/query.json
+ query/unknown
+ reply
+ reply/__test-v1-[0-9a-f]+.json
+ reply/__test-v2-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(SharedStateless)
diff --git a/Tests/RunCMake/FileAPI/SharedStateless-check.py b/Tests/RunCMake/FileAPI/SharedStateless-check.py
new file mode 100644
index 000000000..79f52d712
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/SharedStateless-check.py
@@ -0,0 +1,22 @@
+from check_index import *
+
+def check_reply(r):
+ assert is_dict(r)
+ assert sorted(r.keys()) == ["__test-v1", "__test-v2", "__test-v3", "query.json", "unknown"]
+ check_index__test(r["__test-v1"], 1, 3)
+ check_index__test(r["__test-v2"], 2, 0)
+ check_error(r["__test-v3"], "unknown query file")
+ check_error(r["query.json"], "unknown query file")
+ check_error(r["unknown"], "unknown query file")
+
+def check_objects(o):
+ assert is_list(o)
+ assert len(o) == 2
+ check_index__test(o[0], 1, 3)
+ check_index__test(o[1], 2, 0)
+
+assert is_dict(index)
+assert sorted(index.keys()) == ["cmake", "objects", "reply"]
+check_cmake(index["cmake"])
+check_reply(index["reply"])
+check_objects(index["objects"])
diff --git a/Tests/RunCMake/FileAPI/SharedStateless-prep.cmake b/Tests/RunCMake/FileAPI/SharedStateless-prep.cmake
new file mode 100644
index 000000000..b2804140e
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/SharedStateless-prep.cmake
@@ -0,0 +1,6 @@
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/__test-v1" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/__test-v2" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/__test-v3" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/query.json" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/unknown" "")
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/reply/object-to-be-deleted.json" "")
diff --git a/Tests/RunCMake/FileAPI/SharedStateless.cmake b/Tests/RunCMake/FileAPI/SharedStateless.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/SharedStateless.cmake
diff --git a/Tests/RunCMake/FileAPI/Stale-check.cmake b/Tests/RunCMake/FileAPI/Stale-check.cmake
new file mode 100644
index 000000000..7ee2c9e7f
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/Stale-check.cmake
@@ -0,0 +1,4 @@
+set(expect
+ reply
+ )
+check_api("^${expect}$")
diff --git a/Tests/RunCMake/FileAPI/Stale-prep.cmake b/Tests/RunCMake/FileAPI/Stale-prep.cmake
new file mode 100644
index 000000000..e920925f0
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/Stale-prep.cmake
@@ -0,0 +1 @@
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/reply/object-to-be-deleted.json" "")
diff --git a/Tests/RunCMake/FileAPI/Stale.cmake b/Tests/RunCMake/FileAPI/Stale.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/Stale.cmake
diff --git a/Tests/RunCMake/FileAPI/alias/CMakeLists.txt b/Tests/RunCMake/FileAPI/alias/CMakeLists.txt
new file mode 100644
index 000000000..549307dfb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/alias/CMakeLists.txt
@@ -0,0 +1,10 @@
+project(Alias)
+enable_language(CXX)
+
+add_library(c_alias_lib ALIAS c_lib)
+add_executable(c_alias_exe ../empty.c)
+target_link_libraries(c_alias_exe PRIVATE c_alias_lib)
+
+add_library(cxx_alias_lib ALIAS cxx_lib)
+add_executable(cxx_alias_exe ../empty.cxx)
+target_link_libraries(cxx_alias_exe PRIVATE cxx_alias_lib)
diff --git a/Tests/RunCMake/FileAPI/cache-v2-ClientStateful-check.cmake b/Tests/RunCMake/FileAPI/cache-v2-ClientStateful-check.cmake
new file mode 100644
index 000000000..0f5ef28a6
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cache-v2-ClientStateful-check.cmake
@@ -0,0 +1,11 @@
+set(expect
+ query
+ query/client-foo
+ query/client-foo/query.json
+ reply
+ reply/cache-v2-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(cache-v2)
diff --git a/Tests/RunCMake/FileAPI/cache-v2-ClientStateful-prep.cmake b/Tests/RunCMake/FileAPI/cache-v2-ClientStateful-prep.cmake
new file mode 100644
index 000000000..9329280b1
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cache-v2-ClientStateful-prep.cmake
@@ -0,0 +1,4 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query)
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/query.json" [[
+{ "requests": [ { "kind": "cache", "version" : 2 } ] }
+]])
diff --git a/Tests/RunCMake/FileAPI/cache-v2-ClientStateless-check.cmake b/Tests/RunCMake/FileAPI/cache-v2-ClientStateless-check.cmake
new file mode 100644
index 000000000..c406ec81b
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cache-v2-ClientStateless-check.cmake
@@ -0,0 +1,11 @@
+set(expect
+ query
+ query/client-foo
+ query/client-foo/cache-v2
+ reply
+ reply/cache-v2-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(cache-v2)
diff --git a/Tests/RunCMake/FileAPI/cache-v2-ClientStateless-prep.cmake b/Tests/RunCMake/FileAPI/cache-v2-ClientStateless-prep.cmake
new file mode 100644
index 000000000..dccafa545
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cache-v2-ClientStateless-prep.cmake
@@ -0,0 +1,2 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query)
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/cache-v2" "")
diff --git a/Tests/RunCMake/FileAPI/cache-v2-SharedStateless-check.cmake b/Tests/RunCMake/FileAPI/cache-v2-SharedStateless-check.cmake
new file mode 100644
index 000000000..f8337ebf5
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cache-v2-SharedStateless-check.cmake
@@ -0,0 +1,10 @@
+set(expect
+ query
+ query/cache-v2
+ reply
+ reply/cache-v2-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(cache-v2)
diff --git a/Tests/RunCMake/FileAPI/cache-v2-SharedStateless-prep.cmake b/Tests/RunCMake/FileAPI/cache-v2-SharedStateless-prep.cmake
new file mode 100644
index 000000000..ee5ac5762
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cache-v2-SharedStateless-prep.cmake
@@ -0,0 +1,2 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query)
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/cache-v2" "")
diff --git a/Tests/RunCMake/FileAPI/cache-v2-check.py b/Tests/RunCMake/FileAPI/cache-v2-check.py
new file mode 100644
index 000000000..756ef8080
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cache-v2-check.py
@@ -0,0 +1,134 @@
+from check_index import *
+
+def check_objects(o):
+ assert is_list(o)
+ assert len(o) == 1
+ check_index_object(o[0], "cache", 2, 0, check_object_cache)
+
+def check_cache_entry(actual, expected):
+ assert is_dict(actual)
+ assert sorted(actual.keys()) == ["name", "properties", "type", "value"]
+
+ assert is_string(actual["type"], expected["type"])
+ assert is_string(actual["value"], expected["value"])
+
+ def check_property(actual, expected):
+ assert is_dict(actual)
+ assert sorted(actual.keys()) == ["name", "value"]
+ assert is_string(actual["value"], expected["value"])
+
+ check_list_match(lambda a, e: is_string(a["name"], e["name"]), actual["properties"], expected["properties"], check=check_property)
+
+def check_object_cache(o):
+ assert sorted(o.keys()) == ["entries", "kind", "version"]
+ # The "kind" and "version" members are handled by check_index_object.
+ check_list_match(lambda a, e: is_string(a["name"], e["name"]), o["entries"], [
+ {
+ "name": "CM_OPTION_BOOL",
+ "type": "BOOL",
+ "value": "OFF",
+ "properties": [
+ {
+ "name": "HELPSTRING",
+ "value": "Testing option()",
+ },
+ ],
+ },
+ {
+ "name": "CM_SET_BOOL",
+ "type": "BOOL",
+ "value": "ON",
+ "properties": [
+ {
+ "name": "HELPSTRING",
+ "value": "Testing set(CACHE BOOL)",
+ },
+ {
+ "name": "ADVANCED",
+ "value": "1",
+ },
+ ],
+ },
+ {
+ "name": "CM_SET_FILEPATH",
+ "type": "FILEPATH",
+ "value": "dir1/dir2/empty.txt",
+ "properties": [
+ {
+ "name": "HELPSTRING",
+ "value": "Testing set(CACHE FILEPATH)",
+ },
+ ],
+ },
+ {
+ "name": "CM_SET_PATH",
+ "type": "PATH",
+ "value": "dir1/dir2",
+ "properties": [
+ {
+ "name": "HELPSTRING",
+ "value": "Testing set(CACHE PATH)",
+ },
+ {
+ "name": "ADVANCED",
+ "value": "ON",
+ },
+ ],
+ },
+ {
+ "name": "CM_SET_STRING",
+ "type": "STRING",
+ "value": "test",
+ "properties": [
+ {
+ "name": "HELPSTRING",
+ "value": "Testing set(CACHE STRING)",
+ },
+ ],
+ },
+ {
+ "name": "CM_SET_STRINGS",
+ "type": "STRING",
+ "value": "1",
+ "properties": [
+ {
+ "name": "HELPSTRING",
+ "value": "Testing set(CACHE STRING) with STRINGS",
+ },
+ {
+ "name": "STRINGS",
+ "value": "1;2;3;4",
+ },
+ ],
+ },
+ {
+ "name": "CM_SET_INTERNAL",
+ "type": "INTERNAL",
+ "value": "int2",
+ "properties": [
+ {
+ "name": "HELPSTRING",
+ "value": "Testing set(CACHE INTERNAL)",
+ },
+ ],
+ },
+ {
+ "name": "CM_SET_TYPE",
+ "type": "STRING",
+ "value": "1",
+ "properties": [
+ {
+ "name": "HELPSTRING",
+ "value": "Testing set(CACHE INTERNAL) with set_property(TYPE)",
+ },
+ {
+ "name": "ADVANCED",
+ "value": "0",
+ },
+ ],
+ },
+ ], check=check_cache_entry, allow_extra=True)
+
+assert is_dict(index)
+assert sorted(index.keys()) == ["cmake", "objects", "reply"]
+check_objects(index["objects"])
diff --git a/Tests/RunCMake/FileAPI/cache-v2.cmake b/Tests/RunCMake/FileAPI/cache-v2.cmake
new file mode 100644
index 000000000..45b402de6
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cache-v2.cmake
@@ -0,0 +1,14 @@
+option(CM_OPTION_BOOL "Testing option()" "OFF")
+set(CM_SET_BOOL "ON" CACHE BOOL "Testing set(CACHE BOOL)")
+mark_as_advanced(CM_SET_BOOL)
+set(CM_SET_FILEPATH "dir1/dir2/empty.txt" CACHE FILEPATH "Testing set(CACHE FILEPATH)")
+set(CM_SET_PATH "dir1/dir2" CACHE PATH "Testing set(CACHE PATH)")
+set_property(CACHE CM_SET_PATH PROPERTY ADVANCED ON)
+set(CM_SET_STRING "test" CACHE STRING "Testing set(CACHE STRING)")
+set(CM_SET_STRINGS "1" CACHE STRING "Testing set(CACHE STRING) with STRINGS")
+set_property(CACHE CM_SET_STRINGS PROPERTY STRINGS "1;2;3;4")
+set(CM_SET_INTERNAL "int" CACHE INTERNAL "Testing set(CACHE INTERNAL)")
+set_property(CACHE CM_SET_INTERNAL PROPERTY VALUE "int2")
+set(CM_SET_TYPE "1" CACHE INTERNAL "Testing set(CACHE INTERNAL) with set_property(TYPE)")
+set_property(CACHE CM_SET_TYPE PROPERTY TYPE "STRING")
+set_property(CACHE CM_SET_TYPE PROPERTY ADVANCED "0")
diff --git a/Tests/RunCMake/FileAPI/check_index.py b/Tests/RunCMake/FileAPI/check_index.py
new file mode 100644
index 000000000..cda72341c
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/check_index.py
@@ -0,0 +1,163 @@
+import sys
+import os
+import json
+import re
+
+if sys.version_info[0] >= 3:
+ unicode = str
+
+def is_bool(x, val=None):
+ return isinstance(x, bool) and (val is None or x == val)
+
+def is_dict(x):
+ return isinstance(x, dict)
+
+def is_list(x):
+ return isinstance(x, list)
+
+def is_int(x, val=None):
+ return (isinstance(x, int) or isinstance(x, long)) and (val is None or x == val)
+
+def is_string(x, val=None):
+ return (isinstance(x, str) or isinstance(x, unicode)) and (val is None or x == val)
+
+def matches(s, pattern):
+ return is_string(s) and bool(re.search(pattern, s))
+
+def check_list_match(match, actual, expected, check=None, check_exception=None, missing_exception=None, extra_exception=None, allow_extra=False):
+ """
+ Handle the common pattern of making sure every actual item "matches" some
+ item in the expected list, and that neither list has extra items after
+ matching is completed.
+
+ @param match: Callback to check if an actual item matches an expected
+ item. Return True if the item matches, return False if the item doesn't
+ match.
+ @param actual: List of actual items to search.
+ @param expected: List of expected items to match.
+ @param check: Optional function to check that the actual item is valid by
+ comparing it to the expected item.
+ @param check_exception: Optional function that returns an argument to
+ append to any exception thrown by the check function.
+ @param missing_exception: Optional function that returns an argument to
+ append to the exception thrown when an item is not found.
+ @param extra_exception: Optional function that returns an argument to
+ append to the exception thrown when an extra item is found.
+ @param allow_extra: Optional parameter allowing there to be extra actual
+ items after all the expected items have been found.
+ """
+ assert is_list(actual)
+ _actual = actual[:]
+ for expected_item in expected:
+ found = False
+ for i, actual_item in enumerate(_actual):
+ if match(actual_item, expected_item):
+ if check:
+ try:
+ check(actual_item, expected_item)
+ except BaseException as e:
+ if check_exception:
+ e.args += (check_exception(actual_item, expected_item),)
+ raise
+ found = True
+ del _actual[i]
+ break
+ if missing_exception:
+ assert found, missing_exception(expected_item)
+ else:
+ assert found
+ if not allow_extra:
+ if extra_exception:
+ assert len(_actual) == 0, [extra_exception(a) for a in _actual]
+ else:
+ assert len(_actual) == 0
+
+def filter_list(f, l):
+ if l is not None:
+ l = list(filter(f, l))
+ if l == []:
+ l = None
+ return l
+
+def check_cmake(cmake):
+ assert is_dict(cmake)
+ assert sorted(cmake.keys()) == ["generator", "paths", "version"]
+ check_cmake_version(cmake["version"])
+ check_cmake_paths(cmake["paths"])
+ check_cmake_generator(cmake["generator"])
+
+def check_cmake_version(v):
+ assert is_dict(v)
+ assert sorted(v.keys()) == ["isDirty", "major", "minor", "patch", "string", "suffix"]
+ assert is_string(v["string"])
+ assert is_int(v["major"])
+ assert is_int(v["minor"])
+ assert is_int(v["patch"])
+ assert is_string(v["suffix"])
+ assert is_bool(v["isDirty"])
+
+def check_cmake_paths(v):
+ assert is_dict(v)
+ assert sorted(v.keys()) == ["cmake", "cpack", "ctest", "root"]
+ assert is_string(v["cmake"])
+ assert is_string(v["cpack"])
+ assert is_string(v["ctest"])
+ assert is_string(v["root"])
+
+def check_cmake_generator(g):
+ assert is_dict(g)
+ name = g.get("name", None)
+ assert is_string(name)
+ if name.startswith("Visual Studio"):
+ assert sorted(g.keys()) == ["name", "platform"]
+ assert is_string(g["platform"])
+ else:
+ assert sorted(g.keys()) == ["name"]
+
+def check_index_object(indexEntry, kind, major, minor, check):
+ assert is_dict(indexEntry)
+ assert sorted(indexEntry.keys()) == ["jsonFile", "kind", "version"]
+ assert is_string(indexEntry["kind"])
+ assert indexEntry["kind"] == kind
+ assert is_dict(indexEntry["version"])
+ assert sorted(indexEntry["version"].keys()) == ["major", "minor"]
+ assert indexEntry["version"]["major"] == major
+ assert indexEntry["version"]["minor"] == minor
+ assert is_string(indexEntry["jsonFile"])
+ filepath = os.path.join(reply_dir, indexEntry["jsonFile"])
+ with open(filepath) as f:
+ object = json.load(f)
+ assert is_dict(object)
+ assert "kind" in object
+ assert is_string(object["kind"])
+ assert object["kind"] == kind
+ assert "version" in object
+ assert is_dict(object["version"])
+ assert sorted(object["version"].keys()) == ["major", "minor"]
+ assert object["version"]["major"] == major
+ assert object["version"]["minor"] == minor
+ if check:
+ check(object)
+
+def check_index__test(indexEntry, major, minor):
+ def check(object):
+ assert sorted(object.keys()) == ["kind", "version"]
+ check_index_object(indexEntry, "__test", major, minor, check)
+
+def check_error(value, error):
+ assert is_dict(value)
+ assert sorted(value.keys()) == ["error"]
+ assert is_string(value["error"])
+ assert value["error"] == error
+
+def check_error_re(value, error):
+ assert is_dict(value)
+ assert sorted(value.keys()) == ["error"]
+ assert is_string(value["error"])
+ assert re.search(error, value["error"])
+
+reply_index = sys.argv[1]
+reply_dir = os.path.dirname(reply_index)
+
+with open(reply_index) as f:
+ index = json.load(f)
diff --git a/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateful-check.cmake b/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateful-check.cmake
new file mode 100644
index 000000000..21e931e7b
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateful-check.cmake
@@ -0,0 +1,11 @@
+set(expect
+ query
+ query/client-foo
+ query/client-foo/query.json
+ reply
+ reply/cmakeFiles-v1-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(cmakeFiles-v1)
diff --git a/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateful-prep.cmake b/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateful-prep.cmake
new file mode 100644
index 000000000..7a726963e
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateful-prep.cmake
@@ -0,0 +1,4 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query)
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/query.json" [[
+{ "requests": [ { "kind": "cmakeFiles", "version" : 1 } ] }
+]])
diff --git a/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateless-check.cmake b/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateless-check.cmake
new file mode 100644
index 000000000..2ce2e79e4
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateless-check.cmake
@@ -0,0 +1,11 @@
+set(expect
+ query
+ query/client-foo
+ query/client-foo/cmakeFiles-v1
+ reply
+ reply/cmakeFiles-v1-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(cmakeFiles-v1)
diff --git a/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateless-prep.cmake b/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateless-prep.cmake
new file mode 100644
index 000000000..eb9649175
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cmakeFiles-v1-ClientStateless-prep.cmake
@@ -0,0 +1,2 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query)
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/cmakeFiles-v1" "")
diff --git a/Tests/RunCMake/FileAPI/cmakeFiles-v1-SharedStateless-check.cmake b/Tests/RunCMake/FileAPI/cmakeFiles-v1-SharedStateless-check.cmake
new file mode 100644
index 000000000..6e3b49a5c
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cmakeFiles-v1-SharedStateless-check.cmake
@@ -0,0 +1,10 @@
+set(expect
+ query
+ query/cmakeFiles-v1
+ reply
+ reply/cmakeFiles-v1-[0-9a-f]+.json
+ reply/index-[0-9.T-]+.json
+ )
+check_api("^${expect}$")
+
+check_python(cmakeFiles-v1)
diff --git a/Tests/RunCMake/FileAPI/cmakeFiles-v1-SharedStateless-prep.cmake b/Tests/RunCMake/FileAPI/cmakeFiles-v1-SharedStateless-prep.cmake
new file mode 100644
index 000000000..8c8bdef1c
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cmakeFiles-v1-SharedStateless-prep.cmake
@@ -0,0 +1,2 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query)
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/cmakeFiles-v1" "")
diff --git a/Tests/RunCMake/FileAPI/cmakeFiles-v1-check.py b/Tests/RunCMake/FileAPI/cmakeFiles-v1-check.py
new file mode 100644
index 000000000..49dfe87ab
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cmakeFiles-v1-check.py
@@ -0,0 +1,94 @@
+from check_index import *
+
+def check_objects(o):
+ assert is_list(o)
+ assert len(o) == 1
+ check_index_object(o[0], "cmakeFiles", 1, 0, check_object_cmakeFiles)
+
+def check_input(actual, expected):
+ assert is_dict(actual)
+ expected_keys = ["path"]
+
+ if expected["isGenerated"] is not None:
+ expected_keys.append("isGenerated")
+ assert is_bool(actual["isGenerated"], expected["isGenerated"])
+
+ if expected["isExternal"] is not None:
+ expected_keys.append("isExternal")
+ assert is_bool(actual["isExternal"], expected["isExternal"])
+
+ if expected["isCMake"] is not None:
+ expected_keys.append("isCMake")
+ assert is_bool(actual["isCMake"], expected["isCMake"])
+
+ assert sorted(actual.keys()) == sorted(expected_keys)
+
+def check_object_cmakeFiles(o):
+ assert sorted(o.keys()) == ["inputs", "kind", "paths", "version"]
+ # The "kind" and "version" members are handled by check_index_object.
+ assert is_dict(o["paths"])
+ assert sorted(o["paths"].keys()) == ["build", "source"]
+ assert matches(o["paths"]["build"], "^.*/Tests/RunCMake/FileAPI/cmakeFiles-v1-build$")
+ assert matches(o["paths"]["source"], "^.*/Tests/RunCMake/FileAPI$")
+
+ expected = [
+ {
+ "path": "^CMakeLists\\.txt$",
+ "isGenerated": None,
+ "isExternal": None,
+ "isCMake": None,
+ },
+ {
+ "path": "^cmakeFiles-v1\\.cmake$",
+ "isGenerated": None,
+ "isExternal": None,
+ "isCMake": None,
+ },
+ {
+ "path": "^dir/CMakeLists\\.txt$",
+ "isGenerated": None,
+ "isExternal": None,
+ "isCMake": None,
+ },
+ {
+ "path": "^dir/dir/CMakeLists\\.txt$",
+ "isGenerated": None,
+ "isExternal": None,
+ "isCMake": None,
+ },
+ {
+ "path": "^dir/dirtest\\.cmake$",
+ "isGenerated": None,
+ "isExternal": None,
+ "isCMake": None,
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPIDummyFile\\.cmake$",
+ "isGenerated": None,
+ "isExternal": True,
+ "isCMake": None,
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/cmakeFiles-v1-build/generated\\.cmake",
+ "isGenerated": True,
+ "isExternal": None,
+ "isCMake": None,
+ },
+ {
+ "path": "^.*/Modules/CMakeParseArguments\\.cmake$",
+ "isGenerated": None,
+ "isExternal": True,
+ "isCMake": True,
+ },
+ ]
+
+ inSource = os.path.dirname(o["paths"]["build"]) == o["paths"]["source"]
+ if inSource:
+ for e in expected:
+ e["path"] = e["path"].replace("^.*/Tests/RunCMake/FileAPI/", "^", 1)
+
+ check_list_match(lambda a, e: matches(a["path"], e["path"]), o["inputs"], expected, check=check_input, allow_extra=True)
+
+assert is_dict(index)
+assert sorted(index.keys()) == ["cmake", "objects", "reply"]
+check_objects(index["objects"])
diff --git a/Tests/RunCMake/FileAPI/cmakeFiles-v1.cmake b/Tests/RunCMake/FileAPI/cmakeFiles-v1.cmake
new file mode 100644
index 000000000..4d4d757c7
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cmakeFiles-v1.cmake
@@ -0,0 +1,8 @@
+include("${CMAKE_CURRENT_LIST_DIR}/dir/dirtest.cmake")
+include(CMakeParseArguments)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/generated.cmake" "")
+include("${CMAKE_CURRENT_BINARY_DIR}/generated.cmake")
+include("${CMAKE_CURRENT_LIST_DIR}/../FileAPIDummyFile.cmake")
+
+add_subdirectory(dir)
diff --git a/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateful-check.cmake b/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateful-check.cmake
new file mode 100644
index 000000000..fb78e8789
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateful-check.cmake
@@ -0,0 +1,12 @@
+set(expect
+ query
+ query/client-foo
+ query/client-foo/query.json
+ reply
+ reply/codemodel-v2-[0-9a-f]+\\.json
+ reply/index-[0-9.T-]+\\.json
+ .*
+ )
+check_api("^${expect}$")
+
+check_python(codemodel-v2)
diff --git a/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateful-prep.cmake b/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateful-prep.cmake
new file mode 100644
index 000000000..e2b38ff57
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateful-prep.cmake
@@ -0,0 +1,4 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query)
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/query.json" [[
+{ "requests": [ { "kind": "codemodel", "version" : 2 } ] }
+]])
diff --git a/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateless-check.cmake b/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateless-check.cmake
new file mode 100644
index 000000000..7c6a35ab5
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateless-check.cmake
@@ -0,0 +1,12 @@
+set(expect
+ query
+ query/client-foo
+ query/client-foo/codemodel-v2
+ reply
+ reply/codemodel-v2-[0-9a-f]+\\.json
+ reply/index-[0-9.T-]+\\.json
+ .*
+ )
+check_api("^${expect}$")
+
+check_python(codemodel-v2)
diff --git a/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateless-prep.cmake b/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateless-prep.cmake
new file mode 100644
index 000000000..d1ce2929e
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/codemodel-v2-ClientStateless-prep.cmake
@@ -0,0 +1,2 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query)
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/client-foo/codemodel-v2" "")
diff --git a/Tests/RunCMake/FileAPI/codemodel-v2-SharedStateless-check.cmake b/Tests/RunCMake/FileAPI/codemodel-v2-SharedStateless-check.cmake
new file mode 100644
index 000000000..cc2f31b94
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/codemodel-v2-SharedStateless-check.cmake
@@ -0,0 +1,11 @@
+set(expect
+ query
+ query/codemodel-v2
+ reply
+ reply/codemodel-v2-[0-9a-f]+\\.json
+ reply/index-[0-9.T-]+\\.json
+ .*
+ )
+check_api("^${expect}$")
+
+check_python(codemodel-v2)
diff --git a/Tests/RunCMake/FileAPI/codemodel-v2-SharedStateless-prep.cmake b/Tests/RunCMake/FileAPI/codemodel-v2-SharedStateless-prep.cmake
new file mode 100644
index 000000000..8a519d5cb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/codemodel-v2-SharedStateless-prep.cmake
@@ -0,0 +1,2 @@
+file(REMOVE_RECURSE ${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query)
+file(WRITE "${RunCMake_TEST_BINARY_DIR}/.cmake/api/v1/query/codemodel-v2" "")
diff --git a/Tests/RunCMake/FileAPI/codemodel-v2-check.py b/Tests/RunCMake/FileAPI/codemodel-v2-check.py
new file mode 100644
index 000000000..3096358dc
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/codemodel-v2-check.py
@@ -0,0 +1,5118 @@
+from check_index import *
+
+import sys
+import os
+
+def check_objects(o, g):
+ assert is_list(o)
+ assert len(o) == 1
+ check_index_object(o[0], "codemodel", 2, 0, check_object_codemodel(g))
+
+def check_backtrace(t, b, backtrace):
+ btg = t["backtraceGraph"]
+ for expected in backtrace:
+ assert is_int(b)
+ node = btg["nodes"][b]
+ expected_keys = ["file"]
+ assert matches(btg["files"][node["file"]], expected["file"])
+
+ if expected["line"] is not None:
+ expected_keys.append("line")
+ assert is_int(node["line"], expected["line"])
+
+ if expected["command"] is not None:
+ expected_keys.append("command")
+ assert is_int(node["command"])
+ assert is_string(btg["commands"][node["command"]], expected["command"])
+
+ if expected["hasParent"]:
+ expected_keys.append("parent")
+ assert is_int(node["parent"])
+ b = node["parent"]
+ else:
+ b = None
+
+ assert sorted(node.keys()) == sorted(expected_keys)
+
+ assert b is None
+
+def check_directory(c):
+ def _check(actual, expected):
+ assert is_dict(actual)
+ expected_keys = ["build", "source", "projectIndex"]
+ assert matches(actual["build"], expected["build"])
+
+ assert is_int(actual["projectIndex"])
+ assert is_string(c["projects"][actual["projectIndex"]]["name"], expected["projectName"])
+
+ if expected["parentSource"] is not None:
+ expected_keys.append("parentIndex")
+ assert is_int(actual["parentIndex"])
+ assert matches(c["directories"][actual["parentIndex"]]["source"], expected["parentSource"])
+
+ if expected["childSources"] is not None:
+ expected_keys.append("childIndexes")
+ check_list_match(lambda a, e: matches(c["directories"][a]["source"], e),
+ actual["childIndexes"], expected["childSources"],
+ missing_exception=lambda e: "Child source: %s" % e,
+ extra_exception=lambda a: "Child source: %s" % a["source"])
+
+ if expected["targetIds"] is not None:
+ expected_keys.append("targetIndexes")
+ check_list_match(lambda a, e: matches(c["targets"][a]["id"], e),
+ actual["targetIndexes"], expected["targetIds"],
+ missing_exception=lambda e: "Target ID: %s" % e,
+ extra_exception=lambda a: "Target ID: %s" % c["targets"][a]["id"])
+
+ if expected["minimumCMakeVersion"] is not None:
+ expected_keys.append("minimumCMakeVersion")
+ assert is_dict(actual["minimumCMakeVersion"])
+ assert sorted(actual["minimumCMakeVersion"].keys()) == ["string"]
+ assert is_string(actual["minimumCMakeVersion"]["string"], expected["minimumCMakeVersion"])
+
+ if expected["hasInstallRule"] is not None:
+ expected_keys.append("hasInstallRule")
+ assert is_bool(actual["hasInstallRule"], expected["hasInstallRule"])
+
+ assert sorted(actual.keys()) == sorted(expected_keys)
+
+ return _check
+
+def check_target_backtrace_graph(t):
+ btg = t["backtraceGraph"]
+ assert is_dict(btg)
+ assert sorted(btg.keys()) == ["commands", "files", "nodes"]
+ assert is_list(btg["commands"])
+
+ for c in btg["commands"]:
+ assert is_string(c)
+
+ for f in btg["files"]:
+ assert is_string(f)
+
+ for n in btg["nodes"]:
+ expected_keys = ["file"]
+ assert is_dict(n)
+ assert is_int(n["file"])
+ assert 0 <= n["file"] < len(btg["files"])
+
+ if "line" in n:
+ expected_keys.append("line")
+ assert is_int(n["line"])
+
+ if "command" in n:
+ expected_keys.append("command")
+ assert is_int(n["command"])
+ assert 0 <= n["command"] < len(btg["commands"])
+
+ if "parent" in n:
+ expected_keys.append("parent")
+ assert is_int(n["parent"])
+ assert 0 <= n["parent"] < len(btg["nodes"])
+
+ assert sorted(n.keys()) == sorted(expected_keys)
+
+def check_target(c):
+ def _check(actual, expected):
+ assert is_dict(actual)
+ assert sorted(actual.keys()) == ["directoryIndex", "id", "jsonFile", "name", "projectIndex"]
+ assert is_int(actual["directoryIndex"])
+ assert matches(c["directories"][actual["directoryIndex"]]["source"], expected["directorySource"])
+ assert is_string(actual["name"], expected["name"])
+ assert is_string(actual["jsonFile"])
+ assert is_int(actual["projectIndex"])
+ assert is_string(c["projects"][actual["projectIndex"]]["name"], expected["projectName"])
+
+ filepath = os.path.join(reply_dir, actual["jsonFile"])
+ with open(filepath) as f:
+ obj = json.load(f)
+
+ expected_keys = ["name", "id", "type", "backtraceGraph", "paths", "sources"]
+ assert is_dict(obj)
+ assert is_string(obj["name"], expected["name"])
+ assert matches(obj["id"], expected["id"])
+ assert is_string(obj["type"], expected["type"])
+ check_target_backtrace_graph(obj)
+
+ assert is_dict(obj["paths"])
+ assert sorted(obj["paths"].keys()) == ["build", "source"]
+ assert matches(obj["paths"]["build"], expected["build"])
+ assert matches(obj["paths"]["source"], expected["source"])
+
+ def check_source(actual, expected):
+ assert is_dict(actual)
+ expected_keys = ["path"]
+
+ if expected["compileGroupLanguage"] is not None:
+ expected_keys.append("compileGroupIndex")
+ assert is_string(obj["compileGroups"][actual["compileGroupIndex"]]["language"], expected["compileGroupLanguage"])
+
+ if expected["sourceGroupName"] is not None:
+ expected_keys.append("sourceGroupIndex")
+ assert is_string(obj["sourceGroups"][actual["sourceGroupIndex"]]["name"], expected["sourceGroupName"])
+
+ if expected["isGenerated"] is not None:
+ expected_keys.append("isGenerated")
+ assert is_bool(actual["isGenerated"], expected["isGenerated"])
+
+ if expected["backtrace"] is not None:
+ expected_keys.append("backtrace")
+ check_backtrace(obj, actual["backtrace"], expected["backtrace"])
+
+ assert sorted(actual.keys()) == sorted(expected_keys)
+
+ check_list_match(lambda a, e: matches(a["path"], e["path"]), obj["sources"],
+ expected["sources"], check=check_source,
+ check_exception=lambda a, e: "Source file: %s" % a["path"],
+ missing_exception=lambda e: "Source file: %s" % e["path"],
+ extra_exception=lambda a: "Source file: %s" % a["path"])
+
+ if expected["backtrace"] is not None:
+ expected_keys.append("backtrace")
+ check_backtrace(obj, obj["backtrace"], expected["backtrace"])
+
+ if expected["folder"] is not None:
+ expected_keys.append("folder")
+ assert is_dict(obj["folder"])
+ assert sorted(obj["folder"].keys()) == ["name"]
+ assert is_string(obj["folder"]["name"], expected["folder"])
+
+ if expected["nameOnDisk"] is not None:
+ expected_keys.append("nameOnDisk")
+ assert matches(obj["nameOnDisk"], expected["nameOnDisk"])
+
+ if expected["artifacts"] is not None:
+ expected_keys.append("artifacts")
+
+ def check_artifact(actual, expected):
+ assert is_dict(actual)
+ assert sorted(actual.keys()) == ["path"]
+
+ check_list_match(lambda a, e: matches(a["path"], e["path"]),
+ obj["artifacts"], expected["artifacts"],
+ check=check_artifact,
+ check_exception=lambda a, e: "Artifact: %s" % a["path"],
+ missing_exception=lambda e: "Artifact: %s" % e["path"],
+ extra_exception=lambda a: "Artifact: %s" % a["path"])
+
+ if expected["isGeneratorProvided"] is not None:
+ expected_keys.append("isGeneratorProvided")
+ assert is_bool(obj["isGeneratorProvided"], expected["isGeneratorProvided"])
+
+ if expected["install"] is not None:
+ expected_keys.append("install")
+ assert is_dict(obj["install"])
+ assert sorted(obj["install"].keys()) == ["destinations", "prefix"]
+
+ assert is_dict(obj["install"]["prefix"])
+ assert sorted(obj["install"]["prefix"].keys()) == ["path"]
+ assert matches(obj["install"]["prefix"]["path"], expected["install"]["prefix"])
+
+ def check_install_destination(actual, expected):
+ assert is_dict(actual)
+ expected_keys = ["path"]
+
+ if expected["backtrace"] is not None:
+ expected_keys.append("backtrace")
+ check_backtrace(obj, actual["backtrace"], expected["backtrace"])
+
+ assert sorted(actual.keys()) == sorted(expected_keys)
+
+ check_list_match(lambda a, e: matches(a["path"], e["path"]),
+ obj["install"]["destinations"], expected["install"]["destinations"],
+ check=check_install_destination,
+ check_exception=lambda a, e: "Install path: %s" % a["path"],
+ missing_exception=lambda e: "Install path: %s" % e["path"],
+ extra_exception=lambda a: "Install path: %s" % a["path"])
+
+ if expected["link"] is not None:
+ expected_keys.append("link")
+ assert is_dict(obj["link"])
+ link_keys = ["language"]
+
+ assert is_string(obj["link"]["language"], expected["link"]["language"])
+
+ # FIXME: Properly test commandFragments
+ if "commandFragments" in obj["link"]:
+ link_keys.append("commandFragments")
+ assert is_list(obj["link"]["commandFragments"])
+ for f in obj["link"]["commandFragments"]:
+ assert is_dict(f)
+ assert sorted(f.keys()) == ["fragment", "role"]
+ assert is_string(f["fragment"])
+ assert is_string(f["role"])
+ assert f["role"] in ("flags", "libraries", "libraryPath", "frameworkPath")
+
+ if expected["link"]["lto"] is not None:
+ link_keys.append("lto")
+ assert is_bool(obj["link"]["lto"], expected["link"]["lto"])
+
+ # FIXME: Properly test sysroot
+ if "sysroot" in obj["link"]:
+ link_keys.append("sysroot")
+ assert is_string(obj["link"]["sysroot"])
+
+ assert sorted(obj["link"].keys()) == sorted(link_keys)
+
+ if expected["archive"] is not None:
+ expected_keys.append("archive")
+ assert is_dict(obj["archive"])
+ archive_keys = []
+
+ # FIXME: Properly test commandFragments
+ if "commandFragments" in obj["archive"]:
+ archive_keys.append("commandFragments")
+ assert is_list(obj["archive"]["commandFragments"])
+ for f in obj["archive"]["commandFragments"]:
+ assert is_dict(f)
+ assert sorted(f.keys()) == ["fragment", "role"]
+ assert is_string(f["fragment"])
+ assert is_string(f["role"])
+ assert f["role"] in ("flags")
+
+ if expected["archive"]["lto"] is not None:
+ archive_keys.append("lto")
+ assert is_bool(obj["archive"]["lto"], expected["archive"]["lto"])
+
+ assert sorted(obj["archive"].keys()) == sorted(archive_keys)
+
+ if expected["dependencies"] is not None:
+ expected_keys.append("dependencies")
+
+ def check_dependency(actual, expected):
+ assert is_dict(actual)
+ expected_keys = ["id"]
+
+ if expected["backtrace"] is not None:
+ expected_keys.append("backtrace")
+ check_backtrace(obj, actual["backtrace"], expected["backtrace"])
+
+ assert sorted(actual.keys()) == sorted(expected_keys)
+
+ check_list_match(lambda a, e: matches(a["id"], e["id"]),
+ obj["dependencies"], expected["dependencies"],
+ check=check_dependency,
+ check_exception=lambda a, e: "Dependency ID: %s" % a["id"],
+ missing_exception=lambda e: "Dependency ID: %s" % e["id"],
+ extra_exception=lambda a: "Dependency ID: %s" % a["id"])
+
+ if expected["sourceGroups"] is not None:
+ expected_keys.append("sourceGroups")
+
+ def check_source_group(actual, expected):
+ assert is_dict(actual)
+ assert sorted(actual.keys()) == ["name", "sourceIndexes"]
+
+ check_list_match(lambda a, e: matches(obj["sources"][a]["path"], e),
+ actual["sourceIndexes"], expected["sourcePaths"],
+ missing_exception=lambda e: "Source path: %s" % e,
+ extra_exception=lambda a: "Source path: %s" % obj["sources"][a]["path"])
+
+ check_list_match(lambda a, e: is_string(a["name"], e["name"]),
+ obj["sourceGroups"], expected["sourceGroups"],
+ check=check_source_group,
+ check_exception=lambda a, e: "Source group: %s" % a["name"],
+ missing_exception=lambda e: "Source group: %s" % e["name"],
+ extra_exception=lambda a: "Source group: %s" % a["name"])
+
+ if expected["compileGroups"] is not None:
+ expected_keys.append("compileGroups")
+
+ def check_compile_group(actual, expected):
+ assert is_dict(actual)
+ expected_keys = ["sourceIndexes", "language"]
+
+ check_list_match(lambda a, e: matches(obj["sources"][a]["path"], e),
+ actual["sourceIndexes"], expected["sourcePaths"],
+ missing_exception=lambda e: "Source path: %s" % e,
+ extra_exception=lambda a: "Source path: %s" % obj["sources"][a]["path"])
+
+ # FIXME: Properly test compileCommandFragments
+ if "compileCommandFragments" in actual:
+ expected_keys.append("compileCommandFragments")
+ assert is_list(actual["compileCommandFragments"])
+ for f in actual["compileCommandFragments"]:
+ assert is_dict(f)
+ assert sorted(f.keys()) == ["fragment"]
+ assert is_string(f["fragment"])
+
+ if expected["includes"] is not None:
+ expected_keys.append("includes")
+
+ def check_include(actual, expected):
+ assert is_dict(actual)
+ expected_keys = ["path"]
+
+ if expected["isSystem"] is not None:
+ expected_keys.append("isSystem")
+ assert is_bool(actual["isSystem"], expected["isSystem"])
+
+ if expected["backtrace"] is not None:
+ expected_keys.append("backtrace")
+ check_backtrace(obj, actual["backtrace"], expected["backtrace"])
+
+ assert sorted(actual.keys()) == sorted(expected_keys)
+
+ check_list_match(lambda a, e: matches(a["path"], e["path"]),
+ actual["includes"], expected["includes"],
+ check=check_include,
+ check_exception=lambda a, e: "Include path: %s" % a["path"],
+ missing_exception=lambda e: "Include path: %s" % e["path"],
+ extra_exception=lambda a: "Include path: %s" % a["path"])
+
+ if expected["defines"] is not None:
+ expected_keys.append("defines")
+
+ def check_define(actual, expected):
+ assert is_dict(actual)
+ expected_keys = ["define"]
+
+ if expected["backtrace"] is not None:
+ expected_keys.append("backtrace")
+ check_backtrace(obj, actual["backtrace"], expected["backtrace"])
+
+ assert sorted(actual.keys()) == sorted(expected_keys)
+
+ check_list_match(lambda a, e: is_string(a["define"], e["define"]),
+ actual["defines"], expected["defines"],
+ check=check_define,
+ check_exception=lambda a, e: "Define: %s" % a["define"],
+ missing_exception=lambda e: "Define: %s" % e["define"],
+ extra_exception=lambda a: "Define: %s" % a["define"])
+
+ # FIXME: Properly test sysroot
+ if "sysroot" in actual:
+ expected_keys.append("sysroot")
+ assert is_string(actual["sysroot"])
+
+ assert sorted(actual.keys()) == sorted(expected_keys)
+
+ check_list_match(lambda a, e: is_string(a["language"], e["language"]),
+ obj["compileGroups"], expected["compileGroups"],
+ check=check_compile_group,
+ check_exception=lambda a, e: "Compile group: %s" % a["language"],
+ missing_exception=lambda e: "Compile group: %s" % e["language"],
+ extra_exception=lambda a: "Compile group: %s" % a["language"])
+
+ assert sorted(obj.keys()) == sorted(expected_keys)
+
+ return _check
+
+def check_project(c):
+ def _check(actual, expected):
+ assert is_dict(actual)
+ expected_keys = ["name", "directoryIndexes"]
+
+ check_list_match(lambda a, e: matches(c["directories"][a]["source"], e),
+ actual["directoryIndexes"], expected["directorySources"],
+ missing_exception=lambda e: "Directory source: %s" % e,
+ extra_exception=lambda a: "Directory source: %s" % c["directories"][a]["source"])
+
+ if expected["parentName"] is not None:
+ expected_keys.append("parentIndex")
+ assert is_int(actual["parentIndex"])
+ assert is_string(c["projects"][actual["parentIndex"]]["name"], expected["parentName"])
+
+ if expected["childNames"] is not None:
+ expected_keys.append("childIndexes")
+ check_list_match(lambda a, e: is_string(c["projects"][a]["name"], e),
+ actual["childIndexes"], expected["childNames"],
+ missing_exception=lambda e: "Child name: %s" % e,
+ extra_exception=lambda a: "Child name: %s" % c["projects"][a]["name"])
+
+ if expected["targetIds"] is not None:
+ expected_keys.append("targetIndexes")
+ check_list_match(lambda a, e: matches(c["targets"][a]["id"], e),
+ actual["targetIndexes"], expected["targetIds"],
+ missing_exception=lambda e: "Target ID: %s" % e,
+ extra_exception=lambda a: "Target ID: %s" % c["targets"][a]["id"])
+
+ assert sorted(actual.keys()) == sorted(expected_keys)
+
+ return _check
+
+def gen_check_directories(c, g):
+ expected = [
+ {
+ "source": "^\\.$",
+ "build": "^\\.$",
+ "parentSource": None,
+ "childSources": [
+ "^alias$",
+ "^custom$",
+ "^cxx$",
+ "^imported$",
+ "^object$",
+ "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ "^dir$",
+ ],
+ "targetIds": [
+ "^ALL_BUILD::@6890427a1f51a3e7e1df$",
+ "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "^c_exe::@6890427a1f51a3e7e1df$",
+ "^c_lib::@6890427a1f51a3e7e1df$",
+ "^c_shared_exe::@6890427a1f51a3e7e1df$",
+ "^c_shared_lib::@6890427a1f51a3e7e1df$",
+ "^c_static_exe::@6890427a1f51a3e7e1df$",
+ "^c_static_lib::@6890427a1f51a3e7e1df$",
+ "^interface_exe::@6890427a1f51a3e7e1df$",
+ ],
+ "projectName": "codemodel-v2",
+ "minimumCMakeVersion": "3.12",
+ "hasInstallRule": True,
+ },
+ {
+ "source": "^alias$",
+ "build": "^alias$",
+ "parentSource": "^\\.$",
+ "childSources": None,
+ "targetIds": [
+ "^ALL_BUILD::@53632cba2752272bb008$",
+ "^ZERO_CHECK::@53632cba2752272bb008$",
+ "^c_alias_exe::@53632cba2752272bb008$",
+ "^cxx_alias_exe::@53632cba2752272bb008$",
+ ],
+ "projectName": "Alias",
+ "minimumCMakeVersion": "3.12",
+ "hasInstallRule": None,
+ },
+ {
+ "source": "^custom$",
+ "build": "^custom$",
+ "parentSource": "^\\.$",
+ "childSources": None,
+ "targetIds": [
+ "^ALL_BUILD::@c11385ffed57b860da63$",
+ "^ZERO_CHECK::@c11385ffed57b860da63$",
+ "^custom_exe::@c11385ffed57b860da63$",
+ "^custom_tgt::@c11385ffed57b860da63$",
+ ],
+ "projectName": "Custom",
+ "minimumCMakeVersion": "3.12",
+ "hasInstallRule": None,
+ },
+ {
+ "source": "^cxx$",
+ "build": "^cxx$",
+ "parentSource": "^\\.$",
+ "childSources": None,
+ "targetIds": [
+ "^ALL_BUILD::@a56b12a3f5c0529fb296$",
+ "^ZERO_CHECK::@a56b12a3f5c0529fb296$",
+ "^cxx_exe::@a56b12a3f5c0529fb296$",
+ "^cxx_lib::@a56b12a3f5c0529fb296$",
+ "^cxx_shared_exe::@a56b12a3f5c0529fb296$",
+ "^cxx_shared_lib::@a56b12a3f5c0529fb296$",
+ "^cxx_static_exe::@a56b12a3f5c0529fb296$",
+ "^cxx_static_lib::@a56b12a3f5c0529fb296$",
+ ],
+ "projectName": "Cxx",
+ "minimumCMakeVersion": "3.12",
+ "hasInstallRule": None,
+ },
+ {
+ "source": "^imported$",
+ "build": "^imported$",
+ "parentSource": "^\\.$",
+ "childSources": None,
+ "targetIds": [
+ "^ALL_BUILD::@ba7eb709d0b48779c6c8$",
+ "^ZERO_CHECK::@ba7eb709d0b48779c6c8$",
+ "^link_imported_exe::@ba7eb709d0b48779c6c8$",
+ "^link_imported_interface_exe::@ba7eb709d0b48779c6c8$",
+ "^link_imported_object_exe::@ba7eb709d0b48779c6c8$",
+ "^link_imported_shared_exe::@ba7eb709d0b48779c6c8$",
+ "^link_imported_static_exe::@ba7eb709d0b48779c6c8$",
+ ],
+ "projectName": "Imported",
+ "minimumCMakeVersion": "3.12",
+ "hasInstallRule": None,
+ },
+ {
+ "source": "^object$",
+ "build": "^object$",
+ "parentSource": "^\\.$",
+ "childSources": None,
+ "targetIds": [
+ "^ALL_BUILD::@5ed5358f70faf8d8af7a$",
+ "^ZERO_CHECK::@5ed5358f70faf8d8af7a$",
+ "^c_object_exe::@5ed5358f70faf8d8af7a$",
+ "^c_object_lib::@5ed5358f70faf8d8af7a$",
+ "^cxx_object_exe::@5ed5358f70faf8d8af7a$",
+ "^cxx_object_lib::@5ed5358f70faf8d8af7a$",
+ ],
+ "projectName": "Object",
+ "minimumCMakeVersion": "3.13",
+ "hasInstallRule": True,
+ },
+ {
+ "source": "^dir$",
+ "build": "^dir$",
+ "parentSource": "^\\.$",
+ "childSources": [
+ "^dir/dir$",
+ ],
+ "targetIds": None,
+ "projectName": "codemodel-v2",
+ "minimumCMakeVersion": "3.12",
+ "hasInstallRule": None,
+ },
+ {
+ "source": "^dir/dir$",
+ "build": "^dir/dir$",
+ "parentSource": "^dir$",
+ "childSources": None,
+ "targetIds": None,
+ "projectName": "codemodel-v2",
+ "minimumCMakeVersion": "3.12",
+ "hasInstallRule": None,
+ },
+ {
+ "source": "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ "build": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild$",
+ "parentSource": "^\\.$",
+ "childSources": None,
+ "targetIds": [
+ "^ALL_BUILD::@[0-9a-f]+$",
+ "^ZERO_CHECK::@[0-9a-f]+$",
+ "^generated_exe::@[0-9a-f]+$",
+ ],
+ "projectName": "External",
+ "minimumCMakeVersion": "3.12",
+ "hasInstallRule": None,
+ },
+ ]
+
+ if matches(g, "^Visual Studio "):
+ for e in expected:
+ if e["parentSource"] is not None:
+ e["targetIds"] = filter_list(lambda t: not matches(t, "^\\^ZERO_CHECK"), e["targetIds"])
+
+ elif g == "Xcode":
+ if ';' in os.environ.get("CMAKE_OSX_ARCHITECTURES", ""):
+ for e in expected:
+ e["targetIds"] = filter_list(lambda t: not matches(t, "^\\^(link_imported_object_exe)"), e["targetIds"])
+
+ else:
+ for e in expected:
+ e["targetIds"] = filter_list(lambda t: not matches(t, "^\\^(ALL_BUILD|ZERO_CHECK)"), e["targetIds"])
+
+ return expected
+
+def check_directories(c, g):
+ check_list_match(lambda a, e: matches(a["source"], e["source"]), c["directories"], gen_check_directories(c, g),
+ check=check_directory(c),
+ check_exception=lambda a, e: "Directory source: %s" % a["source"],
+ missing_exception=lambda e: "Directory source: %s" % e["source"],
+ extra_exception=lambda a: "Directory source: %s" % a["source"])
+
+def gen_check_targets(c, g, inSource):
+ expected = [
+ {
+ "name": "ALL_BUILD",
+ "id": "^ALL_BUILD::@6890427a1f51a3e7e1df$",
+ "directorySource": "^\\.$",
+ "projectName": "codemodel-v2",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/CMakeFiles/ALL_BUILD$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/CMakeFiles/ALL_BUILD\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/CMakeFiles/ALL_BUILD$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/CMakeFiles/ALL_BUILD\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^\\.$",
+ "source": "^\\.$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ {
+ "id": "^interface_exe::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_lib::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_exe::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_shared_lib::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_shared_exe::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_static_lib::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_static_exe::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_alias_exe::@53632cba2752272bb008$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_alias_exe::@53632cba2752272bb008$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_lib::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_exe::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_shared_lib::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_shared_exe::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_static_lib::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_static_exe::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_object_lib::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_object_exe::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_object_lib::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_object_exe::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ {
+ "id": "^link_imported_exe::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ {
+ "id": "^link_imported_shared_exe::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ {
+ "id": "^link_imported_static_exe::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ {
+ "id": "^link_imported_object_exe::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ {
+ "id": "^link_imported_interface_exe::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ {
+ "id": "^custom_exe::@c11385ffed57b860da63$",
+ "backtrace": None,
+ },
+ {
+ "id": "^generated_exe::@[0-9a-f]+$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ZERO_CHECK",
+ "id": "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "directorySource": "^\\.$",
+ "projectName": "codemodel-v2",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/CMakeFiles/ZERO_CHECK$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/CMakeFiles/ZERO_CHECK\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/CMakeFiles/ZERO_CHECK$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/CMakeFiles/ZERO_CHECK\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^\\.$",
+ "source": "^\\.$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": None,
+ },
+ {
+ "name": "interface_exe",
+ "id": "^interface_exe::@6890427a1f51a3e7e1df$",
+ "directorySource": "^\\.$",
+ "projectName": "codemodel-v2",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^include_test\\.cmake$",
+ "line": 3,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^include_test\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": [
+ {
+ "define": "interface_exe_EXPORTS",
+ "backtrace": None,
+ },
+ ],
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^include_test\\.cmake$",
+ "line": 3,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^include_test\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^my_interface_exe\\.myexe$",
+ "artifacts": [
+ {
+ "path": "^bin/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?my_interface_exe\\.myexe$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^lib/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib)?my_interface_exe\\.(dll\\.a|lib)$",
+ "_dllExtra": True,
+ },
+ {
+ "path": "^bin/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?my_interface_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^\\.$",
+ "source": "^\\.$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "c_lib",
+ "id": "^c_lib::@6890427a1f51a3e7e1df$",
+ "directorySource": "^\\.$",
+ "projectName": "codemodel-v2",
+ "type": "STATIC_LIBRARY",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 5,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 5,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^(lib)?c_lib\\.(a|lib)$",
+ "artifacts": [
+ {
+ "path": "^((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib)?c_lib\\.(a|lib)$",
+ "_dllExtra": False,
+ },
+ ],
+ "build": "^\\.$",
+ "source": "^\\.$",
+ "install": None,
+ "link": None,
+ "archive": {
+ "lto": None,
+ },
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "c_exe",
+ "id": "^c_exe::@6890427a1f51a3e7e1df$",
+ "directorySource": "^\\.$",
+ "projectName": "codemodel-v2",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 6,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 6,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^c_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^((Debug|Release|RelWithDebInfo|MinSizeRel)/)?c_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^((Debug|Release|RelWithDebInfo|MinSizeRel)/)?c_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^\\.$",
+ "source": "^\\.$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^c_lib::@6890427a1f51a3e7e1df$",
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 7,
+ "command": "target_link_libraries",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "id": "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "c_shared_lib",
+ "id": "^c_shared_lib::@6890427a1f51a3e7e1df$",
+ "directorySource": "^\\.$",
+ "projectName": "codemodel-v2",
+ "type": "SHARED_LIBRARY",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 9,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": [
+ {
+ "define": "c_shared_lib_EXPORTS",
+ "backtrace": None,
+ },
+ ],
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 9,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^(lib|cyg)?c_shared_lib\\.(so|dylib|dll)$",
+ "artifacts": [
+ {
+ "path": "^lib/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib|cyg)?c_shared_lib\\.(so|dylib|dll)$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib)?c_shared_lib\\.(dll\\.a|lib)$",
+ "_dllExtra": True,
+ },
+ {
+ "path": "^lib/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib|cyg)?c_shared_lib\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^\\.$",
+ "source": "^\\.$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": True,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "c_shared_exe",
+ "id": "^c_shared_exe::@6890427a1f51a3e7e1df$",
+ "directorySource": "^\\.$",
+ "projectName": "codemodel-v2",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 10,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 10,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^c_shared_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^((Debug|Release|RelWithDebInfo|MinSizeRel)/)?c_shared_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^((Debug|Release|RelWithDebInfo|MinSizeRel)/)?c_shared_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^\\.$",
+ "source": "^\\.$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": True,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^c_shared_lib::@6890427a1f51a3e7e1df$",
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 11,
+ "command": "target_link_libraries",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "id": "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "c_static_lib",
+ "id": "^c_static_lib::@6890427a1f51a3e7e1df$",
+ "directorySource": "^\\.$",
+ "projectName": "codemodel-v2",
+ "type": "STATIC_LIBRARY",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 13,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 13,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^(lib)?c_static_lib\\.(a|lib)$",
+ "artifacts": [
+ {
+ "path": "^((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib)?c_static_lib\\.(a|lib)$",
+ "_dllExtra": False,
+ },
+ ],
+ "build": "^\\.$",
+ "source": "^\\.$",
+ "install": None,
+ "link": None,
+ "archive": {
+ "lto": True,
+ },
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "c_static_exe",
+ "id": "^c_static_exe::@6890427a1f51a3e7e1df$",
+ "directorySource": "^\\.$",
+ "projectName": "codemodel-v2",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 14,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 14,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^c_static_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^((Debug|Release|RelWithDebInfo|MinSizeRel)/)?c_static_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^((Debug|Release|RelWithDebInfo|MinSizeRel)/)?c_static_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^\\.$",
+ "source": "^\\.$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^c_static_lib::@6890427a1f51a3e7e1df$",
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 15,
+ "command": "target_link_libraries",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "id": "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ALL_BUILD",
+ "id": "^ALL_BUILD::@a56b12a3f5c0529fb296$",
+ "directorySource": "^cxx$",
+ "projectName": "Cxx",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/cxx/CMakeFiles/ALL_BUILD$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/cxx/CMakeFiles/ALL_BUILD\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/cxx/CMakeFiles/ALL_BUILD$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/cxx/CMakeFiles/ALL_BUILD\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^cxx$",
+ "source": "^cxx$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_lib::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_exe::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_shared_lib::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_shared_exe::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_static_lib::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_static_exe::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ZERO_CHECK",
+ "id": "^ZERO_CHECK::@a56b12a3f5c0529fb296$",
+ "directorySource": "^cxx$",
+ "projectName": "Cxx",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/cxx/CMakeFiles/ZERO_CHECK$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/cxx/CMakeFiles/ZERO_CHECK\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/cxx/CMakeFiles/ZERO_CHECK$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/cxx/CMakeFiles/ZERO_CHECK\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^cxx$",
+ "source": "^cxx$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": None,
+ },
+ {
+ "name": "cxx_lib",
+ "id": "^cxx_lib::@a56b12a3f5c0529fb296$",
+ "directorySource": "^cxx$",
+ "projectName": "Cxx",
+ "type": "STATIC_LIBRARY",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.cxx$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "CXX",
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 4,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "CXX",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 4,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^(lib)?cxx_lib\\.(a|lib)$",
+ "artifacts": [
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib)?cxx_lib\\.(a|lib)$",
+ "_dllExtra": False,
+ },
+ ],
+ "build": "^cxx$",
+ "source": "^cxx$",
+ "install": None,
+ "link": None,
+ "archive": {
+ "lto": None,
+ },
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "cxx_exe",
+ "id": "^cxx_exe::@a56b12a3f5c0529fb296$",
+ "directorySource": "^cxx$",
+ "projectName": "Cxx",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.cxx$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "CXX",
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "CXX",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": "bin",
+ "nameOnDisk": "^cxx_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?cxx_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?cxx_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^cxx$",
+ "source": "^cxx$",
+ "install": {
+ "prefix": "^(/usr/local|[A-Za-z]:.*/codemodel-v2)$",
+ "destinations": [
+ {
+ "path": "bin",
+ "backtrace": [
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": 37,
+ "command": "install",
+ "hasParent": True,
+ },
+ {
+ "file": "^codemodel-v2\\.cmake$",
+ "line": None,
+ "command": None,
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": 3,
+ "command": "include",
+ "hasParent": True,
+ },
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ },
+ "link": {
+ "language": "CXX",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^cxx_lib::@a56b12a3f5c0529fb296$",
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 6,
+ "command": "target_link_libraries",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "id": "^ZERO_CHECK::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "cxx_shared_lib",
+ "id": "^cxx_shared_lib::@a56b12a3f5c0529fb296$",
+ "directorySource": "^cxx$",
+ "projectName": "Cxx",
+ "type": "SHARED_LIBRARY",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.cxx$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "CXX",
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 9,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "CXX",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ "includes": None,
+ "defines": [
+ {
+ "define": "cxx_shared_lib_EXPORTS",
+ "backtrace": None,
+ },
+ ],
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 9,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^(lib|cyg)?cxx_shared_lib\\.(so|dylib|dll)$",
+ "artifacts": [
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib|cyg)?cxx_shared_lib\\.(so|dylib|dll)$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib)?cxx_shared_lib\\.(dll\\.a|lib)$",
+ "_dllExtra": True,
+ },
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib|cyg)?cxx_shared_lib\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^cxx$",
+ "source": "^cxx$",
+ "install": None,
+ "link": {
+ "language": "CXX",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "cxx_shared_exe",
+ "id": "^cxx_shared_exe::@a56b12a3f5c0529fb296$",
+ "directorySource": "^cxx$",
+ "projectName": "Cxx",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.cxx$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "CXX",
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 10,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "CXX",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 10,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^cxx_shared_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?cxx_shared_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?cxx_shared_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^cxx$",
+ "source": "^cxx$",
+ "install": None,
+ "link": {
+ "language": "CXX",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^cxx_shared_lib::@a56b12a3f5c0529fb296$",
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 11,
+ "command": "target_link_libraries",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "id": "^ZERO_CHECK::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "cxx_static_lib",
+ "id": "^cxx_static_lib::@a56b12a3f5c0529fb296$",
+ "directorySource": "^cxx$",
+ "projectName": "Cxx",
+ "type": "STATIC_LIBRARY",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.cxx$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "CXX",
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 13,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "CXX",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 13,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^(lib)?cxx_static_lib\\.(a|lib)$",
+ "artifacts": [
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?(lib)?cxx_static_lib\\.(a|lib)$",
+ "_dllExtra": False,
+ },
+ ],
+ "build": "^cxx$",
+ "source": "^cxx$",
+ "install": None,
+ "link": None,
+ "archive": {
+ "lto": None,
+ },
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "cxx_static_exe",
+ "id": "^cxx_static_exe::@a56b12a3f5c0529fb296$",
+ "directorySource": "^cxx$",
+ "projectName": "Cxx",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.cxx$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "CXX",
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 14,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "CXX",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 14,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^cxx_static_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?cxx_static_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^cxx/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?cxx_static_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^cxx$",
+ "source": "^cxx$",
+ "install": None,
+ "link": {
+ "language": "CXX",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^cxx_static_lib::@a56b12a3f5c0529fb296$",
+ "backtrace": [
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": 15,
+ "command": "target_link_libraries",
+ "hasParent": True,
+ },
+ {
+ "file": "^cxx/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "id": "^ZERO_CHECK::@a56b12a3f5c0529fb296$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ALL_BUILD",
+ "id": "^ALL_BUILD::@53632cba2752272bb008$",
+ "directorySource": "^alias$",
+ "projectName": "Alias",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/alias/CMakeFiles/ALL_BUILD$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/alias/CMakeFiles/ALL_BUILD\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/alias/CMakeFiles/ALL_BUILD$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/alias/CMakeFiles/ALL_BUILD\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^alias$",
+ "source": "^alias$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@53632cba2752272bb008$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_alias_exe::@53632cba2752272bb008$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_alias_exe::@53632cba2752272bb008$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ZERO_CHECK",
+ "id": "^ZERO_CHECK::@53632cba2752272bb008$",
+ "directorySource": "^alias$",
+ "projectName": "Alias",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/alias/CMakeFiles/ZERO_CHECK$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/alias/CMakeFiles/ZERO_CHECK\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/alias/CMakeFiles/ZERO_CHECK$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/alias/CMakeFiles/ZERO_CHECK\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^alias$",
+ "source": "^alias$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": None,
+ },
+ {
+ "name": "c_alias_exe",
+ "id": "^c_alias_exe::@53632cba2752272bb008$",
+ "directorySource": "^alias$",
+ "projectName": "Alias",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^c_alias_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^alias/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?c_alias_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^alias/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?c_alias_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^alias$",
+ "source": "^alias$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^c_lib::@6890427a1f51a3e7e1df$",
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": 6,
+ "command": "target_link_libraries",
+ "hasParent": True,
+ },
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "id": "^ZERO_CHECK::@53632cba2752272bb008$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "cxx_alias_exe",
+ "id": "^cxx_alias_exe::@53632cba2752272bb008$",
+ "directorySource": "^alias$",
+ "projectName": "Alias",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.cxx$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "CXX",
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": 9,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "CXX",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": 9,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^cxx_alias_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^alias/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?cxx_alias_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^alias/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?cxx_alias_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^alias$",
+ "source": "^alias$",
+ "install": None,
+ "link": {
+ "language": "CXX",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^cxx_lib::@a56b12a3f5c0529fb296$",
+ "backtrace": [
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": 10,
+ "command": "target_link_libraries",
+ "hasParent": True,
+ },
+ {
+ "file": "^alias/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "id": "^ZERO_CHECK::@53632cba2752272bb008$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ALL_BUILD",
+ "id": "^ALL_BUILD::@5ed5358f70faf8d8af7a$",
+ "directorySource": "^object$",
+ "projectName": "Object",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/CMakeFiles/ALL_BUILD$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/CMakeFiles/ALL_BUILD\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/CMakeFiles/ALL_BUILD$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/CMakeFiles/ALL_BUILD\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^object$",
+ "source": "^object$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_object_lib::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ {
+ "id": "^c_object_exe::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_object_lib::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ {
+ "id": "^cxx_object_exe::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ZERO_CHECK",
+ "id": "^ZERO_CHECK::@5ed5358f70faf8d8af7a$",
+ "directorySource": "^object$",
+ "projectName": "Object",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/CMakeFiles/ZERO_CHECK$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/CMakeFiles/ZERO_CHECK\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/CMakeFiles/ZERO_CHECK$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/CMakeFiles/ZERO_CHECK\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^object$",
+ "source": "^object$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": None,
+ },
+ {
+ "name": "c_object_lib",
+ "id": "^c_object_lib::@5ed5358f70faf8d8af7a$",
+ "directorySource": "^object$",
+ "projectName": "Object",
+ "type": "OBJECT_LIBRARY",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": [
+ {
+ "path": "^object/.*/empty(\\.c)?\\.o(bj)?$",
+ "_dllExtra": False,
+ },
+ ],
+ "build": "^object$",
+ "source": "^object$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "c_object_exe",
+ "id": "^c_object_exe::@5ed5358f70faf8d8af7a$",
+ "directorySource": "^object$",
+ "projectName": "Object",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 6,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/.*/empty(\\.c)?\\.o(bj)?$",
+ "isGenerated": True,
+ "sourceGroupName": "Object Libraries",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 7,
+ "command": "target_link_libraries",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ {
+ "name": "Object Libraries",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/.*/empty(\\.c)?\\.o(bj)?$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 6,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^c_object_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^object/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?c_object_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^object/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?c_object_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^object$",
+ "source": "^object$",
+ "install": {
+ "prefix": "^(/usr/local|[A-Za-z]:.*/codemodel-v2)$",
+ "destinations": [
+ {
+ "path": "bin",
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 13,
+ "command": "install",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ },
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^c_object_lib::@5ed5358f70faf8d8af7a$",
+ # FIXME: Add a backtrace here when it becomes available.
+ # You'll know when it's available, because this test will
+ # fail.
+ "backtrace": None,
+ },
+ {
+ "id": "^ZERO_CHECK::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "cxx_object_lib",
+ "id": "^cxx_object_lib::@5ed5358f70faf8d8af7a$",
+ "directorySource": "^object$",
+ "projectName": "Object",
+ "type": "OBJECT_LIBRARY",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.cxx$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "CXX",
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 9,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "CXX",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 9,
+ "command": "add_library",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": [
+ {
+ "path": "^object/.*/empty(\\.cxx)?\\.o(bj)?$",
+ "_dllExtra": False,
+ },
+ ],
+ "build": "^object$",
+ "source": "^object$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "cxx_object_exe",
+ "id": "^cxx_object_exe::@5ed5358f70faf8d8af7a$",
+ "directorySource": "^object$",
+ "projectName": "Object",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.cxx$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "CXX",
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 10,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/.*/empty(\\.cxx)?\\.o(bj)?$",
+ "isGenerated": True,
+ "sourceGroupName": "Object Libraries",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 11,
+ "command": "target_link_libraries",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ },
+ {
+ "name": "Object Libraries",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/object/.*/empty(\\.cxx)?\\.o(bj)?$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "CXX",
+ "sourcePaths": [
+ "^empty\\.cxx$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 10,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^cxx_object_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^object/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?cxx_object_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^object/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?cxx_object_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^object$",
+ "source": "^object$",
+ "install": {
+ "prefix": "^(/usr/local|[A-Za-z]:.*/codemodel-v2)$",
+ "destinations": [
+ {
+ "path": "bin",
+ "backtrace": [
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": 13,
+ "command": "install",
+ "hasParent": True,
+ },
+ {
+ "file": "^object/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ },
+ "link": {
+ "language": "CXX",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^cxx_object_lib::@5ed5358f70faf8d8af7a$",
+ # FIXME: Add a backtrace here when it becomes available.
+ # You'll know when it's available, because this test will
+ # fail.
+ "backtrace": None,
+ },
+ {
+ "id": "^ZERO_CHECK::@5ed5358f70faf8d8af7a$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ALL_BUILD",
+ "id": "^ALL_BUILD::@ba7eb709d0b48779c6c8$",
+ "directorySource": "^imported$",
+ "projectName": "Imported",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/imported/CMakeFiles/ALL_BUILD$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/imported/CMakeFiles/ALL_BUILD\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/imported/CMakeFiles/ALL_BUILD$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/imported/CMakeFiles/ALL_BUILD\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^imported$",
+ "source": "^imported$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ {
+ "id": "^link_imported_exe::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ {
+ "id": "^link_imported_shared_exe::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ {
+ "id": "^link_imported_static_exe::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ {
+ "id": "^link_imported_object_exe::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ {
+ "id": "^link_imported_interface_exe::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ZERO_CHECK",
+ "id": "^ZERO_CHECK::@ba7eb709d0b48779c6c8$",
+ "directorySource": "^imported$",
+ "projectName": "Imported",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/imported/CMakeFiles/ZERO_CHECK$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/imported/CMakeFiles/ZERO_CHECK\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/imported/CMakeFiles/ZERO_CHECK$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/imported/CMakeFiles/ZERO_CHECK\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^imported$",
+ "source": "^imported$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": None,
+ },
+ {
+ "name": "link_imported_exe",
+ "id": "^link_imported_exe::@ba7eb709d0b48779c6c8$",
+ "directorySource": "^imported$",
+ "projectName": "Imported",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^link_imported_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^imported/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?link_imported_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^imported/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?link_imported_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^imported$",
+ "source": "^imported$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "link_imported_shared_exe",
+ "id": "^link_imported_shared_exe::@ba7eb709d0b48779c6c8$",
+ "directorySource": "^imported$",
+ "projectName": "Imported",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": 9,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": 9,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^link_imported_shared_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^imported/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?link_imported_shared_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^imported/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?link_imported_shared_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^imported$",
+ "source": "^imported$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "link_imported_static_exe",
+ "id": "^link_imported_static_exe::@ba7eb709d0b48779c6c8$",
+ "directorySource": "^imported$",
+ "projectName": "Imported",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": 13,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": 13,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^link_imported_static_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^imported/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?link_imported_static_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^imported/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?link_imported_static_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^imported$",
+ "source": "^imported$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "link_imported_object_exe",
+ "id": "^link_imported_object_exe::@ba7eb709d0b48779c6c8$",
+ "directorySource": "^imported$",
+ "projectName": "Imported",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": 18,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": 18,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^link_imported_object_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^imported/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?link_imported_object_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^imported/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?link_imported_object_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^imported$",
+ "source": "^imported$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "link_imported_interface_exe",
+ "id": "^link_imported_interface_exe::@ba7eb709d0b48779c6c8$",
+ "directorySource": "^imported$",
+ "projectName": "Imported",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": 23,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": 23,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^imported/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^link_imported_interface_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^imported/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?link_imported_interface_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^imported/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?link_imported_interface_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^imported$",
+ "source": "^imported$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@ba7eb709d0b48779c6c8$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ALL_BUILD",
+ "id": "^ALL_BUILD::@c11385ffed57b860da63$",
+ "directorySource": "^custom$",
+ "projectName": "Custom",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/custom/CMakeFiles/ALL_BUILD$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/custom/CMakeFiles/ALL_BUILD\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/custom/CMakeFiles/ALL_BUILD$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/custom/CMakeFiles/ALL_BUILD\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^custom$",
+ "source": "^custom$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@c11385ffed57b860da63$",
+ "backtrace": None,
+ },
+ {
+ "id": "^custom_exe::@c11385ffed57b860da63$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ZERO_CHECK",
+ "id": "^ZERO_CHECK::@c11385ffed57b860da63$",
+ "directorySource": "^custom$",
+ "projectName": "Custom",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/custom/CMakeFiles/ZERO_CHECK$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/custom/CMakeFiles/ZERO_CHECK\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/custom/CMakeFiles/ZERO_CHECK$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/custom/CMakeFiles/ZERO_CHECK\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^custom$",
+ "source": "^custom$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": None,
+ },
+ {
+ "name": "custom_tgt",
+ "id": "^custom_tgt::@c11385ffed57b860da63$",
+ "directorySource": "^custom$",
+ "projectName": "Custom",
+ "type": "UTILITY",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/custom/CMakeFiles/custom_tgt$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": 3,
+ "command": "add_custom_target",
+ "hasParent": True,
+ },
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/(custom/)?CMakeFiles/([0-9a-f]+/)?custom_tgt\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/custom/CMakeFiles/custom_tgt$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/(custom/)?CMakeFiles/([0-9a-f]+/)?custom_tgt\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": 3,
+ "command": "add_custom_target",
+ "hasParent": True,
+ },
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^custom$",
+ "source": "^custom$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@c11385ffed57b860da63$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "custom_exe",
+ "id": "^custom_exe::@c11385ffed57b860da63$",
+ "directorySource": "^custom$",
+ "projectName": "Custom",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": 4,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^empty\\.c$",
+ ],
+ "includes": None,
+ "defines": None,
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": 4,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^custom_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^custom/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?custom_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^custom/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?custom_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^custom$",
+ "source": "^custom$",
+ "install": None,
+ "link": {
+ "language": "C",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^custom_tgt::@c11385ffed57b860da63$",
+ "backtrace": [
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_dependencies",
+ "hasParent": True,
+ },
+ {
+ "file": "^custom/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "id": "^ZERO_CHECK::@c11385ffed57b860da63$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ALL_BUILD",
+ "id": "^ALL_BUILD::@[0-9a-f]+$",
+ "directorySource": "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ "projectName": "External",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/CMakeFiles/ALL_BUILD$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/CMakeFiles/ALL_BUILD\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/CMakeFiles/ALL_BUILD$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/CMakeFiles/ALL_BUILD\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild$",
+ "source": "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@[0-9a-f]+$",
+ "backtrace": None,
+ },
+ {
+ "id": "^generated_exe::@[0-9a-f]+$",
+ "backtrace": None,
+ },
+ ],
+ },
+ {
+ "name": "ZERO_CHECK",
+ "id": "^ZERO_CHECK::@[0-9a-f]+$",
+ "directorySource": "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ "projectName": "External",
+ "type": "UTILITY",
+ "isGeneratorProvided": True,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/CMakeFiles/ZERO_CHECK$",
+ "isGenerated": True,
+ "sourceGroupName": "",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/CMakeFiles/ZERO_CHECK\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/CMakeFiles/ZERO_CHECK$",
+ ],
+ },
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/CMakeFiles/ZERO_CHECK\\.rule$",
+ ],
+ },
+ ],
+ "compileGroups": None,
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": None,
+ "artifacts": None,
+ "build": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild$",
+ "source": "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ "install": None,
+ "link": None,
+ "archive": None,
+ "dependencies": None,
+ },
+ {
+ "name": "generated_exe",
+ "id": "^generated_exe::@[0-9a-f]+$",
+ "directorySource": "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ "projectName": "External",
+ "type": "EXECUTABLE",
+ "isGeneratorProvided": None,
+ "sources": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPIExternalSource/empty\\.c$",
+ "isGenerated": None,
+ "sourceGroupName": "Source Files",
+ "compileGroupLanguage": "C",
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/generated\\.cxx$",
+ "isGenerated": True,
+ "sourceGroupName": "Generated Source Files",
+ "compileGroupLanguage": "CXX",
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": 6,
+ "command": "target_sources",
+ "hasParent": True,
+ },
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "sourceGroups": [
+ {
+ "name": "Source Files",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPIExternalSource/empty\\.c$",
+ ],
+ },
+ {
+ "name": "Generated Source Files",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/generated\\.cxx$",
+ ],
+ },
+ ],
+ "compileGroups": [
+ {
+ "language": "C",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPIExternalSource/empty\\.c$",
+ ],
+ "includes": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild$",
+ "isSystem": None,
+ "backtrace": None,
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ "isSystem": True,
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": 11,
+ "command": "target_include_directories",
+ "hasParent": True,
+ },
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "defines": [
+ {
+ "define": "EMPTY_C=1",
+ "backtrace": None,
+ },
+ {
+ "define": "SRC_DUMMY",
+ "backtrace": None,
+ },
+ {
+ "define": "GENERATED_EXE=1",
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": 12,
+ "command": "target_compile_definitions",
+ "hasParent": True,
+ },
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "define": "TGT_DUMMY",
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": 12,
+ "command": "target_compile_definitions",
+ "hasParent": True,
+ },
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ },
+ {
+ "language": "CXX",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/generated\\.cxx$",
+ ],
+ "includes": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ "isSystem": True,
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": 11,
+ "command": "target_include_directories",
+ "hasParent": True,
+ },
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ "defines": [
+ {
+ "define": "GENERATED_EXE=1",
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": 12,
+ "command": "target_compile_definitions",
+ "hasParent": True,
+ },
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ {
+ "define": "TGT_DUMMY",
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": 12,
+ "command": "target_compile_definitions",
+ "hasParent": True,
+ },
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ "backtrace": [
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": 5,
+ "command": "add_executable",
+ "hasParent": True,
+ },
+ {
+ "file": "^.*/Tests/RunCMake/FileAPIExternalSource/CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ "folder": None,
+ "nameOnDisk": "^generated_exe(\\.exe)?$",
+ "artifacts": [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?generated_exe(\\.exe)?$",
+ "_dllExtra": False,
+ },
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild/((Debug|Release|RelWithDebInfo|MinSizeRel)/)?generated_exe\\.pdb$",
+ "_dllExtra": True,
+ },
+ ],
+ "build": "^.*/Tests/RunCMake/FileAPI/FileAPIExternalBuild$",
+ "source": "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ "install": None,
+ "link": {
+ "language": "CXX",
+ "lto": None,
+ },
+ "archive": None,
+ "dependencies": [
+ {
+ "id": "^ZERO_CHECK::@[0-9a-f]+$",
+ "backtrace": None,
+ },
+ ],
+ },
+ ]
+
+ if not os.path.exists(os.path.join(reply_dir, "..", "..", "..", "..", "ipo_enabled.txt")):
+ for e in expected:
+ try:
+ e["link"]["lto"] = None
+ except TypeError: # "link" is not a dict, no problem.
+ pass
+ try:
+ e["archive"]["lto"] = None
+ except TypeError: # "archive" is not a dict, no problem.
+ pass
+
+ if inSource:
+ for e in expected:
+ if e["sources"] is not None:
+ for s in e["sources"]:
+ s["path"] = s["path"].replace("^.*/Tests/RunCMake/FileAPI/", "^", 1)
+ if e["sourceGroups"] is not None:
+ for g in e["sourceGroups"]:
+ g["sourcePaths"] = [p.replace("^.*/Tests/RunCMake/FileAPI/", "^", 1) for p in g["sourcePaths"]]
+ if e["compileGroups"] is not None:
+ for g in e["compileGroups"]:
+ g["sourcePaths"] = [p.replace("^.*/Tests/RunCMake/FileAPI/", "^", 1) for p in g["sourcePaths"]]
+
+ if matches(g, "^Visual Studio "):
+ expected = filter_list(lambda e: e["name"] not in ("ZERO_CHECK") or e["id"] == "^ZERO_CHECK::@6890427a1f51a3e7e1df$", expected)
+ for e in expected:
+ if e["type"] == "UTILITY":
+ if e["id"] == "^ZERO_CHECK::@6890427a1f51a3e7e1df$":
+ e["sources"] = [
+ {
+ "path": "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/CMakeFiles/([0-9a-f]+/)?generate\\.stamp\\.rule$",
+ "isGenerated": True,
+ "sourceGroupName": "CMake Rules",
+ "compileGroupLanguage": None,
+ "backtrace": [
+ {
+ "file": "^CMakeLists\\.txt$",
+ "line": None,
+ "command": None,
+ "hasParent": False,
+ },
+ ],
+ },
+ ]
+ e["sourceGroups"] = [
+ {
+ "name": "CMake Rules",
+ "sourcePaths": [
+ "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build/CMakeFiles/([0-9a-f]+/)?generate\\.stamp\\.rule$",
+ ],
+ },
+ ]
+ elif e["name"] in ("ALL_BUILD"):
+ e["sources"] = []
+ e["sourceGroups"] = None
+ if e["dependencies"] is not None:
+ for d in e["dependencies"]:
+ if matches(d["id"], "^\\^ZERO_CHECK::@"):
+ d["id"] = "^ZERO_CHECK::@6890427a1f51a3e7e1df$"
+
+ elif g == "Xcode":
+ if ';' in os.environ.get("CMAKE_OSX_ARCHITECTURES", ""):
+ expected = filter_list(lambda e: e["name"] not in ("link_imported_object_exe"), expected)
+ for e in expected:
+ e["dependencies"] = filter_list(lambda d: not matches(d["id"], "^\\^link_imported_object_exe::@"), e["dependencies"])
+ if e["name"] in ("c_object_lib", "cxx_object_lib"):
+ e["artifacts"] = None
+
+ else:
+ for e in expected:
+ e["dependencies"] = filter_list(lambda d: not matches(d["id"], "^\\^ZERO_CHECK::@"), e["dependencies"])
+
+ expected = filter_list(lambda t: t["name"] not in ("ALL_BUILD", "ZERO_CHECK"), expected)
+
+ if sys.platform not in ("win32", "cygwin", "msys"):
+ for e in expected:
+ e["artifacts"] = filter_list(lambda a: not a["_dllExtra"], e["artifacts"])
+
+ return expected
+
+def check_targets(c, g, inSource):
+ check_list_match(lambda a, e: matches(a["id"], e["id"]),
+ c["targets"], gen_check_targets(c, g, inSource),
+ check=check_target(c),
+ check_exception=lambda a, e: "Target ID: %s" % a["id"],
+ missing_exception=lambda e: "Target ID: %s" % e["id"],
+ extra_exception=lambda a: "Target ID: %s" % a["id"])
+
+def gen_check_projects(c, g):
+ expected = [
+ {
+ "name": "codemodel-v2",
+ "parentName": None,
+ "childNames": [
+ "Alias",
+ "Custom",
+ "Cxx",
+ "Imported",
+ "Object",
+ "External",
+ ],
+ "directorySources": [
+ "^\\.$",
+ "^dir$",
+ "^dir/dir$",
+ ],
+ "targetIds": [
+ "^ALL_BUILD::@6890427a1f51a3e7e1df$",
+ "^ZERO_CHECK::@6890427a1f51a3e7e1df$",
+ "^interface_exe::@6890427a1f51a3e7e1df$",
+ "^c_lib::@6890427a1f51a3e7e1df$",
+ "^c_exe::@6890427a1f51a3e7e1df$",
+ "^c_shared_lib::@6890427a1f51a3e7e1df$",
+ "^c_shared_exe::@6890427a1f51a3e7e1df$",
+ "^c_static_lib::@6890427a1f51a3e7e1df$",
+ "^c_static_exe::@6890427a1f51a3e7e1df$",
+ ],
+ },
+ {
+ "name": "Cxx",
+ "parentName": "codemodel-v2",
+ "childNames": None,
+ "directorySources": [
+ "^cxx$",
+ ],
+ "targetIds": [
+ "^ALL_BUILD::@a56b12a3f5c0529fb296$",
+ "^ZERO_CHECK::@a56b12a3f5c0529fb296$",
+ "^cxx_lib::@a56b12a3f5c0529fb296$",
+ "^cxx_exe::@a56b12a3f5c0529fb296$",
+ "^cxx_shared_lib::@a56b12a3f5c0529fb296$",
+ "^cxx_shared_exe::@a56b12a3f5c0529fb296$",
+ "^cxx_static_lib::@a56b12a3f5c0529fb296$",
+ "^cxx_static_exe::@a56b12a3f5c0529fb296$",
+ ],
+ },
+ {
+ "name": "Alias",
+ "parentName": "codemodel-v2",
+ "childNames": None,
+ "directorySources": [
+ "^alias$",
+ ],
+ "targetIds": [
+ "^ALL_BUILD::@53632cba2752272bb008$",
+ "^ZERO_CHECK::@53632cba2752272bb008$",
+ "^c_alias_exe::@53632cba2752272bb008$",
+ "^cxx_alias_exe::@53632cba2752272bb008$",
+ ],
+ },
+ {
+ "name": "Object",
+ "parentName": "codemodel-v2",
+ "childNames": None,
+ "directorySources": [
+ "^object$",
+ ],
+ "targetIds": [
+ "^ALL_BUILD::@5ed5358f70faf8d8af7a$",
+ "^ZERO_CHECK::@5ed5358f70faf8d8af7a$",
+ "^c_object_lib::@5ed5358f70faf8d8af7a$",
+ "^c_object_exe::@5ed5358f70faf8d8af7a$",
+ "^cxx_object_lib::@5ed5358f70faf8d8af7a$",
+ "^cxx_object_exe::@5ed5358f70faf8d8af7a$",
+ ],
+ },
+ {
+ "name": "Imported",
+ "parentName": "codemodel-v2",
+ "childNames": None,
+ "directorySources": [
+ "^imported$",
+ ],
+ "targetIds": [
+ "^ALL_BUILD::@ba7eb709d0b48779c6c8$",
+ "^ZERO_CHECK::@ba7eb709d0b48779c6c8$",
+ "^link_imported_exe::@ba7eb709d0b48779c6c8$",
+ "^link_imported_shared_exe::@ba7eb709d0b48779c6c8$",
+ "^link_imported_static_exe::@ba7eb709d0b48779c6c8$",
+ "^link_imported_object_exe::@ba7eb709d0b48779c6c8$",
+ "^link_imported_interface_exe::@ba7eb709d0b48779c6c8$",
+ ],
+ },
+ {
+ "name": "Custom",
+ "parentName": "codemodel-v2",
+ "childNames": None,
+ "directorySources": [
+ "^custom$",
+ ],
+ "targetIds": [
+ "^ALL_BUILD::@c11385ffed57b860da63$",
+ "^ZERO_CHECK::@c11385ffed57b860da63$",
+ "^custom_tgt::@c11385ffed57b860da63$",
+ "^custom_exe::@c11385ffed57b860da63$",
+ ],
+ },
+ {
+ "name": "External",
+ "parentName": "codemodel-v2",
+ "childNames": None,
+ "directorySources": [
+ "^.*/Tests/RunCMake/FileAPIExternalSource$",
+ ],
+ "targetIds": [
+ "^ALL_BUILD::@[0-9a-f]+$",
+ "^ZERO_CHECK::@[0-9a-f]+$",
+ "^generated_exe::@[0-9a-f]+$",
+ ],
+ },
+ ]
+
+ if matches(g, "^Visual Studio "):
+ for e in expected:
+ if e["parentName"] is not None:
+ e["targetIds"] = filter_list(lambda t: not matches(t, "^\\^ZERO_CHECK"), e["targetIds"])
+
+ elif g == "Xcode":
+ if ';' in os.environ.get("CMAKE_OSX_ARCHITECTURES", ""):
+ for e in expected:
+ e["targetIds"] = filter_list(lambda t: not matches(t, "^\\^(link_imported_object_exe)"), e["targetIds"])
+
+ else:
+ for e in expected:
+ e["targetIds"] = filter_list(lambda t: not matches(t, "^\\^(ALL_BUILD|ZERO_CHECK)"), e["targetIds"])
+
+ return expected
+
+def check_projects(c, g):
+ check_list_match(lambda a, e: is_string(a["name"], e["name"]), c["projects"], gen_check_projects(c, g),
+ check=check_project(c),
+ check_exception=lambda a, e: "Project name: %s" % a["name"],
+ missing_exception=lambda e: "Project name: %s" % e["name"],
+ extra_exception=lambda a: "Project name: %s" % a["name"])
+
+def check_object_codemodel_configuration(c, g, inSource):
+ assert sorted(c.keys()) == ["directories", "name", "projects", "targets"]
+ assert is_string(c["name"])
+ check_directories(c, g)
+ check_targets(c, g, inSource)
+ check_projects(c, g)
+
+def check_object_codemodel(g):
+ def _check(o):
+ assert sorted(o.keys()) == ["configurations", "kind", "paths", "version"]
+ # The "kind" and "version" members are handled by check_index_object.
+ assert is_dict(o["paths"])
+ assert sorted(o["paths"].keys()) == ["build", "source"]
+ assert matches(o["paths"]["build"], "^.*/Tests/RunCMake/FileAPI/codemodel-v2-build$")
+ assert matches(o["paths"]["source"], "^.*/Tests/RunCMake/FileAPI$")
+
+ inSource = os.path.dirname(o["paths"]["build"]) == o["paths"]["source"]
+
+ if matches(g, "^(Visual Studio |Xcode$)"):
+ assert sorted([c["name"] for c in o["configurations"]]) == ["Debug", "MinSizeRel", "RelWithDebInfo", "Release"]
+ else:
+ assert len(o["configurations"]) == 1
+ assert o["configurations"][0]["name"] in ("", "Debug", "Release", "RelWithDebInfo", "MinSizeRel")
+
+ for c in o["configurations"]:
+ check_object_codemodel_configuration(c, g, inSource)
+ return _check
+
+assert is_dict(index)
+assert sorted(index.keys()) == ["cmake", "objects", "reply"]
+check_objects(index["objects"], index["cmake"]["generator"]["name"])
diff --git a/Tests/RunCMake/FileAPI/codemodel-v2.cmake b/Tests/RunCMake/FileAPI/codemodel-v2.cmake
new file mode 100644
index 000000000..c98a84c26
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/codemodel-v2.cmake
@@ -0,0 +1,37 @@
+enable_language(C)
+
+include("${CMAKE_CURRENT_LIST_DIR}/include_test.cmake")
+
+add_library(c_lib empty.c)
+add_executable(c_exe empty.c)
+target_link_libraries(c_exe PRIVATE c_lib)
+
+add_library(c_shared_lib SHARED empty.c)
+add_executable(c_shared_exe empty.c)
+target_link_libraries(c_shared_exe PRIVATE c_shared_lib)
+
+add_library(c_static_lib STATIC empty.c)
+add_executable(c_static_exe empty.c)
+target_link_libraries(c_static_exe PRIVATE c_static_lib)
+
+add_subdirectory(cxx)
+add_subdirectory(alias)
+add_subdirectory(object)
+add_subdirectory(imported)
+add_subdirectory(custom)
+add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../FileAPIExternalSource" "${CMAKE_CURRENT_BINARY_DIR}/../FileAPIExternalBuild")
+add_subdirectory(dir)
+
+set_property(TARGET c_shared_lib PROPERTY LIBRARY_OUTPUT_DIRECTORY lib)
+set_property(TARGET c_shared_lib PROPERTY RUNTIME_OUTPUT_DIRECTORY lib)
+
+include(CheckIPOSupported)
+check_ipo_supported(RESULT _ipo LANGUAGES C)
+if(_ipo)
+ set_property(TARGET c_shared_lib PROPERTY INTERPROCEDURAL_OPTIMIZATION ON)
+ set_property(TARGET c_shared_exe PROPERTY INTERPROCEDURAL_OPTIMIZATION ON)
+ set_property(TARGET c_static_lib PROPERTY INTERPROCEDURAL_OPTIMIZATION ON)
+ file(WRITE "${CMAKE_BINARY_DIR}/ipo_enabled.txt" "")
+endif()
+
+install(TARGETS cxx_exe)
diff --git a/Tests/RunCMake/FileAPI/custom/CMakeLists.txt b/Tests/RunCMake/FileAPI/custom/CMakeLists.txt
new file mode 100644
index 000000000..1cdf5c20a
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/custom/CMakeLists.txt
@@ -0,0 +1,5 @@
+project(Custom)
+
+add_custom_target(custom_tgt COMMAND ${CMAKE_COMMAND} -E echo "Building custom_tgt")
+add_executable(custom_exe ../empty.c)
+add_dependencies(custom_exe custom_tgt)
diff --git a/Tests/RunCMake/FileAPI/cxx/CMakeLists.txt b/Tests/RunCMake/FileAPI/cxx/CMakeLists.txt
new file mode 100644
index 000000000..29b61b84f
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/cxx/CMakeLists.txt
@@ -0,0 +1,15 @@
+project(Cxx)
+enable_language(CXX)
+
+add_library(cxx_lib ../empty.cxx)
+add_executable(cxx_exe ../empty.cxx)
+target_link_libraries(cxx_exe PRIVATE cxx_lib)
+set_property(TARGET cxx_exe PROPERTY FOLDER bin)
+
+add_library(cxx_shared_lib SHARED ../empty.cxx)
+add_executable(cxx_shared_exe ../empty.cxx)
+target_link_libraries(cxx_shared_exe PRIVATE cxx_shared_lib)
+
+add_library(cxx_static_lib STATIC ../empty.cxx)
+add_executable(cxx_static_exe ../empty.cxx)
+target_link_libraries(cxx_static_exe PRIVATE cxx_static_lib)
diff --git a/Tests/RunCMake/FileAPI/dir/CMakeLists.txt b/Tests/RunCMake/FileAPI/dir/CMakeLists.txt
new file mode 100644
index 000000000..780445d6b
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/dir/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(dir)
diff --git a/Tests/RunCMake/FileAPI/dir/dir/CMakeLists.txt b/Tests/RunCMake/FileAPI/dir/dir/CMakeLists.txt
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/dir/dir/CMakeLists.txt
diff --git a/Tests/RunCMake/FileAPI/dir/dirtest.cmake b/Tests/RunCMake/FileAPI/dir/dirtest.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/dir/dirtest.cmake
diff --git a/Tests/RunCMake/FileAPI/empty.c b/Tests/RunCMake/FileAPI/empty.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/empty.c
diff --git a/Tests/RunCMake/FileAPI/empty.cxx b/Tests/RunCMake/FileAPI/empty.cxx
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/empty.cxx
diff --git a/Tests/RunCMake/FileAPI/imported/CMakeLists.txt b/Tests/RunCMake/FileAPI/imported/CMakeLists.txt
new file mode 100644
index 000000000..d36d88ba8
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/imported/CMakeLists.txt
@@ -0,0 +1,24 @@
+project(Imported)
+
+add_library(imported_lib UNKNOWN IMPORTED)
+add_executable(imported_exe IMPORTED)
+add_executable(link_imported_exe ../empty.c)
+target_link_libraries(link_imported_exe PRIVATE imported_lib)
+
+add_library(imported_shared_lib SHARED IMPORTED)
+add_executable(link_imported_shared_exe ../empty.c)
+target_link_libraries(link_imported_shared_exe PRIVATE imported_shared_lib)
+
+add_library(imported_static_lib STATIC IMPORTED)
+add_executable(link_imported_static_exe ../empty.c)
+target_link_libraries(link_imported_static_exe PRIVATE imported_static_lib)
+
+if(NOT CMAKE_GENERATOR STREQUAL "Xcode" OR NOT CMAKE_OSX_ARCHITECTURES MATCHES "[;$]")
+ add_library(imported_object_lib OBJECT IMPORTED)
+ add_executable(link_imported_object_exe ../empty.c)
+ target_link_libraries(link_imported_object_exe PRIVATE imported_object_lib)
+endif()
+
+add_library(imported_interface_lib INTERFACE IMPORTED)
+add_executable(link_imported_interface_exe ../empty.c)
+target_link_libraries(link_imported_interface_exe PRIVATE imported_interface_lib)
diff --git a/Tests/RunCMake/FileAPI/include_test.cmake b/Tests/RunCMake/FileAPI/include_test.cmake
new file mode 100644
index 000000000..c74d26431
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/include_test.cmake
@@ -0,0 +1,9 @@
+add_library(interface_lib INTERFACE)
+target_compile_definitions(interface_lib INTERFACE COMPILED_WITH_INTERFACE_LIB)
+add_executable(interface_exe empty.c)
+target_link_libraries(interface_exe PRIVATE inteface_lib)
+set_property(TARGET interface_exe PROPERTY ENABLE_EXPORTS ON)
+set_property(TARGET interface_exe PROPERTY RUNTIME_OUTPUT_DIRECTORY bin)
+set_property(TARGET interface_exe PROPERTY ARCHIVE_OUTPUT_DIRECTORY lib)
+set_property(TARGET interface_exe PROPERTY OUTPUT_NAME my_interface_exe)
+set_property(TARGET interface_exe PROPERTY SUFFIX .myexe)
diff --git a/Tests/RunCMake/FileAPI/object/CMakeLists.txt b/Tests/RunCMake/FileAPI/object/CMakeLists.txt
new file mode 100644
index 000000000..9773b8148
--- /dev/null
+++ b/Tests/RunCMake/FileAPI/object/CMakeLists.txt
@@ -0,0 +1,13 @@
+cmake_minimum_required(VERSION 3.13)
+project(Object)
+enable_language(CXX)
+
+add_library(c_object_lib OBJECT ../empty.c)
+add_executable(c_object_exe ../empty.c)
+target_link_libraries(c_object_exe PRIVATE c_object_lib)
+
+add_library(cxx_object_lib OBJECT ../empty.cxx)
+add_executable(cxx_object_exe ../empty.cxx)
+target_link_libraries(cxx_object_exe PRIVATE cxx_object_lib)
+
+install(TARGETS c_object_exe cxx_object_exe DESTINATION bin)
diff --git a/Tests/RunCMake/FileAPIDummyFile.cmake b/Tests/RunCMake/FileAPIDummyFile.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPIDummyFile.cmake
diff --git a/Tests/RunCMake/FileAPIExternalSource/CMakeLists.txt b/Tests/RunCMake/FileAPIExternalSource/CMakeLists.txt
new file mode 100644
index 000000000..f5670a727
--- /dev/null
+++ b/Tests/RunCMake/FileAPIExternalSource/CMakeLists.txt
@@ -0,0 +1,12 @@
+project(External)
+enable_language(CXX)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/generated.cxx" "")
+add_executable(generated_exe empty.c)
+target_sources(generated_exe PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated.cxx")
+source_group("Generated Source Files" FILES "${CMAKE_CURRENT_BINARY_DIR}/generated.cxx")
+set_property(SOURCE "${CMAKE_CURRENT_BINARY_DIR}/generated.cxx" PROPERTY GENERATED ON)
+set_property(SOURCE empty.c PROPERTY COMPILE_DEFINITIONS EMPTY_C=1 SRC_DUMMY)
+set_property(SOURCE empty.c PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_BINARY_DIR}")
+target_include_directories(generated_exe SYSTEM PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
+target_compile_definitions(generated_exe PRIVATE GENERATED_EXE=1 -DTGT_DUMMY)
diff --git a/Tests/RunCMake/FileAPIExternalSource/empty.c b/Tests/RunCMake/FileAPIExternalSource/empty.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FileAPIExternalSource/empty.c
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/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/CMP0093-NEW-stdout.txt b/Tests/RunCMake/FindBoost/CMP0093-NEW-stdout.txt
new file mode 100644
index 000000000..62a6d39cb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMP0093-NEW-stdout.txt
@@ -0,0 +1 @@
+-- Boost_VERSION=1.70.0
diff --git a/Tests/RunCMake/FindBoost/CMP0093-NEW.cmake b/Tests/RunCMake/FindBoost/CMP0093-NEW.cmake
new file mode 100644
index 000000000..64f44d25b
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMP0093-NEW.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0093 NEW)
+include(ModuleMode.cmake)
diff --git a/Tests/RunCMake/FindBoost/CMP0093-OLD-stdout.txt b/Tests/RunCMake/FindBoost/CMP0093-OLD-stdout.txt
new file mode 100644
index 000000000..9e51e35c8
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMP0093-OLD-stdout.txt
@@ -0,0 +1 @@
+-- Boost_VERSION=107000
diff --git a/Tests/RunCMake/FindBoost/CMP0093-OLD.cmake b/Tests/RunCMake/FindBoost/CMP0093-OLD.cmake
new file mode 100644
index 000000000..69a3a9542
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMP0093-OLD.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0093 OLD)
+include(ModuleMode.cmake)
diff --git a/Tests/RunCMake/FindBoost/CMP0093-UNSET-stdout.txt b/Tests/RunCMake/FindBoost/CMP0093-UNSET-stdout.txt
new file mode 100644
index 000000000..9e51e35c8
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMP0093-UNSET-stdout.txt
@@ -0,0 +1 @@
+-- Boost_VERSION=107000
diff --git a/Tests/RunCMake/FindBoost/CMP0093-UNSET.cmake b/Tests/RunCMake/FindBoost/CMP0093-UNSET.cmake
new file mode 100644
index 000000000..974094a0e
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMP0093-UNSET.cmake
@@ -0,0 +1 @@
+include(ModuleMode.cmake)
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..0a67488a8
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage-stdout.txt
@@ -0,0 +1,2 @@
+-- Found Boost: [^
+]* \(found suitable version "1\.12345", minimum required is "1\.12345"\) found 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..36a9abd5c
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage/BoostConfig.cmake
@@ -0,0 +1,4 @@
+set(Boost_DATE_TIME_FOUND 1)
+add_library(Boost::boost INTERFACE IMPORTED)
+add_library(Boost::headers INTERFACE IMPORTED)
+add_library(Boost::date_time UNKNOWN IMPORTED)
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/CMakePackageFixtures/Boost-1.70.0/BoostConfig.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/Boost-1.70.0/BoostConfig.cmake
new file mode 100644
index 000000000..539267d92
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/Boost-1.70.0/BoostConfig.cmake
@@ -0,0 +1,140 @@
+# Copyright 2019 Peter Dimov
+# Distributed under the Boost Software License, Version 1.0.
+# (See accompanying file LICENSE_1_0.txt or copy at http://boost.org/LICENSE_1_0.txt)
+
+# This CMake configuration file, installed as part of the Boost build
+# and installation procedure done by `b2 install`, provides support
+# for find_package(Boost).
+#
+# It's roughly, but not perfectly, compatible with the behavior
+# of find_package(Boost) as provided by FindBoost.cmake.
+#
+# A typical use might be
+#
+# find_package(Boost 1.70 REQUIRED COMPONENTS filesystem regex PATHS C:/Boost)
+#
+# On success, the above invocation would define the targets Boost::headers,
+# Boost::filesystem and Boost::regex. Boost::headers represents all
+# header-only libraries. An alias, Boost::boost, for Boost::headers is
+# provided for compatibility.
+#
+# Since Boost libraries can coexist in many variants - 32/64 bit,
+# static/dynamic runtime, debug/release, the following variables can be used
+# to control which variant is chosen:
+#
+# Boost_USE_DEBUG_LIBS: When OFF, disables debug libraries.
+# Boost_USE_RELEASE_LIBS: When OFF, disables release libraries.
+# Boost_USE_STATIC_LIBS: When ON, uses static Boost libraries; when OFF,
+# uses shared Boost libraries; when not set, the
+# default is to use shared when BUILD_SHARED_LIBS is
+# ON, static otherwise.
+# Boost_USE_STATIC_RUNTIME: When ON, uses Boost libraries linked against the
+# static runtime. The default is shared runtime.
+# Boost_USE_DEBUG_RUNTIME: When ON, uses Boost libraries linked against the
+# debug runtime. When OFF, against the release
+# runtime. The default is to use either.
+# Boost_COMPILER: The compiler that has been used to build Boost,
+# such as vc141, gcc7, clang37. The default is
+# determined from CMAKE_CXX_COMPILER_ID.
+
+message(STATUS "Found Boost ${Boost_VERSION} at ${Boost_DIR}")
+
+# Output requested configuration (f.ex. "REQUIRED COMPONENTS filesystem")
+
+if(Boost_FIND_QUIETLY)
+ set(_BOOST_CONFIG "${_BOOST_CONFIG} QUIET")
+endif()
+
+if(Boost_FIND_REQUIRED)
+ set(_BOOST_CONFIG "${_BOOST_CONFIG} REQUIRED")
+endif()
+
+foreach(__boost_comp IN LISTS Boost_FIND_COMPONENTS)
+ if(${Boost_FIND_REQUIRED_${__boost_comp}})
+ list(APPEND _BOOST_COMPONENTS ${__boost_comp})
+ else()
+ list(APPEND _BOOST_OPTIONAL_COMPONENTS ${__boost_comp})
+ endif()
+endforeach()
+
+if(_BOOST_COMPONENTS)
+ set(_BOOST_CONFIG "${_BOOST_CONFIG} COMPONENTS ${_BOOST_COMPONENTS}")
+endif()
+
+if(_BOOST_OPTIONAL_COMPONENTS)
+ set(_BOOST_CONFIG "${_BOOST_CONFIG} OPTIONAL_COMPONENTS ${_BOOST_OPTIONAL_COMPONENTS}")
+endif()
+
+if(_BOOST_CONFIG)
+ message(STATUS " Requested configuration:${_BOOST_CONFIG}")
+endif()
+
+unset(_BOOST_CONFIG)
+unset(_BOOST_COMPONENTS)
+unset(_BOOST_OPTIONAL_COMPONENTS)
+
+# find_dependency doesn't forward arguments until 3.9, so we have to roll our own
+
+macro(boost_find_dependency dep req)
+
+ set(_BOOST_QUIET)
+ if(Boost_FIND_QUIETLY)
+ set(_BOOST_QUIET QUIET)
+ endif()
+
+ set(_BOOST_REQUIRED)
+ if(${req} AND Boost_FIND_REQUIRED)
+ set(_BOOST_REQUIRED REQUIRED)
+ endif()
+
+ get_filename_component(_BOOST_CMAKEDIR "${CMAKE_CURRENT_LIST_DIR}/../" ABSOLUTE)
+
+ if(Boost_DEBUG)
+ message(STATUS "BoostConfig: find_package(boost_${dep} ${Boost_VERSION} EXACT CONFIG ${_BOOST_REQUIRED} ${_BOOST_QUIET} HINTS ${_BOOST_CMAKEDIR})")
+ endif()
+ find_package(boost_${dep} ${Boost_VERSION} EXACT CONFIG ${_BOOST_REQUIRED} ${_BOOST_QUIET} HINTS ${_BOOST_CMAKEDIR})
+
+ string(TOUPPER ${dep} _BOOST_DEP)
+ set(Boost_${_BOOST_DEP}_FOUND ${boost_${dep}_FOUND})
+
+ unset(_BOOST_REQUIRED)
+ unset(_BOOST_QUIET)
+ unset(_BOOST_CMAKEDIR)
+ unset(_BOOST_DEP)
+
+endmacro()
+
+# Find boost_headers
+
+boost_find_dependency(headers 1)
+
+if(NOT boost_headers_FOUND)
+
+ set(Boost_FOUND 0)
+ set(Boost_NOT_FOUND_MESSAGE "A required dependency, boost_headers, has not been found.")
+
+ return()
+
+endif()
+
+# Find components
+
+foreach(__boost_comp IN LISTS Boost_FIND_COMPONENTS)
+
+ boost_find_dependency(${__boost_comp} ${Boost_FIND_REQUIRED_${__boost_comp}})
+
+endforeach()
+
+# Compatibility targets
+
+if(NOT TARGET Boost::boost)
+
+ add_library(Boost::boost INTERFACE IMPORTED)
+ set_property(TARGET Boost::boost APPEND PROPERTY INTERFACE_LINK_LIBRARIES Boost::headers)
+
+ # All Boost:: targets already disable autolink
+ add_library(Boost::diagnostic_definitions INTERFACE IMPORTED)
+ add_library(Boost::disable_autolinking INTERFACE IMPORTED)
+ add_library(Boost::dynamic_linking INTERFACE IMPORTED)
+
+endif()
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/Boost-1.70.0/BoostConfigVersion.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/Boost-1.70.0/BoostConfigVersion.cmake
new file mode 100644
index 000000000..114bba078
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/Boost-1.70.0/BoostConfigVersion.cmake
@@ -0,0 +1,12 @@
+# Generated by Boost 1.70.0
+
+set(PACKAGE_VERSION 1.70.0)
+
+if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
+else()
+ set(PACKAGE_VERSION_COMPATIBLE TRUE)
+ if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
+ set(PACKAGE_VERSION_EXACT TRUE)
+ endif()
+endif()
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/BoostDetectToolset-1.70.0.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/BoostDetectToolset-1.70.0.cmake
new file mode 100644
index 000000000..2f1ac0199
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/BoostDetectToolset-1.70.0.cmake
@@ -0,0 +1 @@
+set(BOOST_DETECTED_TOOLSET "gcc7")
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/boost_chrono-config-version.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/boost_chrono-config-version.cmake
new file mode 100644
index 000000000..114bba078
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/boost_chrono-config-version.cmake
@@ -0,0 +1,12 @@
+# Generated by Boost 1.70.0
+
+set(PACKAGE_VERSION 1.70.0)
+
+if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
+else()
+ set(PACKAGE_VERSION_COMPATIBLE TRUE)
+ if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
+ set(PACKAGE_VERSION_EXACT TRUE)
+ endif()
+endif()
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/boost_chrono-config.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/boost_chrono-config.cmake
new file mode 100644
index 000000000..5d798b52a
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/boost_chrono-config.cmake
@@ -0,0 +1,98 @@
+# Generated by Boost 1.70.0
+
+if(TARGET Boost::chrono)
+ return()
+endif()
+
+message(STATUS "Found boost_chrono ${boost_chrono_VERSION} at ${boost_chrono_DIR}")
+
+# Compute the include and library directories relative to this file.
+get_filename_component(_BOOST_CMAKEDIR "${CMAKE_CURRENT_LIST_DIR}/../" ABSOLUTE)
+get_filename_component(_BOOST_INCLUDEDIR "${_BOOST_CMAKEDIR}/../../include/" ABSOLUTE)
+get_filename_component(_BOOST_LIBDIR "${_BOOST_CMAKEDIR}/../" ABSOLUTE)
+
+# Create imported target Boost::chrono
+add_library(Boost::chrono UNKNOWN IMPORTED)
+
+set_target_properties(Boost::chrono PROPERTIES
+ INTERFACE_INCLUDE_DIRECTORIES "${_BOOST_INCLUDEDIR}"
+ INTERFACE_COMPILE_DEFINITIONS "BOOST_ALL_NO_LIB"
+)
+
+include(${CMAKE_CURRENT_LIST_DIR}/../BoostDetectToolset-1.70.0.cmake)
+
+if(Boost_DEBUG)
+ message(STATUS "Scanning ${CMAKE_CURRENT_LIST_DIR}/libboost_chrono-variant*.cmake")
+endif()
+
+file(GLOB __boost_variants "${CMAKE_CURRENT_LIST_DIR}/libboost_chrono-variant*.cmake")
+
+macro(_BOOST_SKIPPED fname reason)
+ if(Boost_DEBUG)
+ message(STATUS " ... skipped ${fname} (${reason})")
+ endif()
+ list(APPEND __boost_skipped "${fname} (${reason})")
+endmacro()
+
+foreach(f IN LISTS __boost_variants)
+ if(Boost_DEBUG)
+ message(STATUS " Including ${f}")
+ endif()
+ include(${f})
+endforeach()
+
+unset(_BOOST_LIBDIR)
+unset(_BOOST_INCLUDEDIR)
+unset(_BOOST_CMAKEDIR)
+
+get_target_property(__boost_configs Boost::chrono IMPORTED_CONFIGURATIONS)
+
+if(__boost_variants AND NOT __boost_configs)
+ message(STATUS "No suitable boost_chrono variant has been identified!")
+ if(NOT Boost_DEBUG)
+ foreach(s IN LISTS __boost_skipped)
+ message(STATUS " ${s}")
+ endforeach()
+ endif()
+ set(boost_chrono_FOUND 0)
+ set(boost_chrono_NOT_FOUND_MESSAGE "No suitable build variant has been found.")
+ unset(__boost_skipped)
+ unset(__boost_configs)
+ unset(__boost_variants)
+ unset(_BOOST_CHRONO_DEPS)
+ return()
+endif()
+
+unset(__boost_skipped)
+unset(__boost_configs)
+unset(__boost_variants)
+
+if(_BOOST_CHRONO_DEPS)
+ list(REMOVE_DUPLICATES _BOOST_CHRONO_DEPS)
+ message(STATUS "Adding boost_chrono dependencies: ${_BOOST_CHRONO_DEPS}")
+endif()
+
+foreach(dep_boost_chrono IN LISTS _BOOST_CHRONO_DEPS)
+ set(_BOOST_QUIET)
+ if(boost_chrono_FIND_QUIETLY)
+ set(_BOOST_QUIET QUIET)
+ endif()
+ set(_BOOST_REQUIRED)
+ if(boost_chrono_FIND_REQUIRED)
+ set(_BOOST_REQUIRED REQUIRED)
+ endif()
+ get_filename_component(_BOOST_CMAKEDIR "${CMAKE_CURRENT_LIST_DIR}/../" ABSOLUTE)
+ find_package(boost_${dep_boost_chrono} 1.70.0 EXACT CONFIG ${_BOOST_REQUIRED} ${_BOOST_QUIET} HINTS ${_BOOST_CMAKEDIR})
+ set_property(TARGET Boost::chrono APPEND PROPERTY INTERFACE_LINK_LIBRARIES Boost::${dep_boost_chrono})
+ unset(_BOOST_QUIET)
+ unset(_BOOST_REQUIRED)
+ unset(_BOOST_CMAKEDIR)
+ if(NOT boost_${dep_boost_chrono}_FOUND)
+ set(boost_chrono_FOUND 0)
+ set(boost_chrono_NOT_FOUND_MESSAGE "A required dependency, boost_${dep_boost_chrono}, has not been found.")
+ unset(_BOOST_CHRONO_DEPS)
+ return()
+ endif()
+endforeach()
+
+unset(_BOOST_CHRONO_DEPS)
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/libboost_chrono-variant-shared.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/libboost_chrono-variant-shared.cmake
new file mode 100644
index 000000000..7f07aed47
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/libboost_chrono-variant-shared.cmake
@@ -0,0 +1,62 @@
+# Generated by Boost 1.70.0
+
+# address-model=64
+
+if(CMAKE_SIZEOF_VOID_P EQUAL 4)
+ _BOOST_SKIPPED("libboost_chrono.so.1.70.0" "64 bit, need 32")
+ return()
+endif()
+
+# layout=system
+
+# toolset=gcc8
+
+# link=shared
+
+if(NOT "${Boost_USE_STATIC_LIBS}" STREQUAL "" AND Boost_USE_STATIC_LIBS)
+ _BOOST_SKIPPED("libboost_chrono.so.1.70.0" "shared, Boost_USE_STATIC_LIBS=${Boost_USE_STATIC_LIBS}")
+ return()
+endif()
+
+if(NOT BUILD_SHARED_LIBS)
+ _BOOST_SKIPPED("libboost_chrono.so.1.70.0" "shared, BUILD_SHARED_LIBS not ON, set Boost_USE_STATIC_LIBS=OFF to override")
+ return()
+endif()
+
+# runtime-link=shared
+
+if(Boost_USE_STATIC_RUNTIME)
+ _BOOST_SKIPPED("libboost_chrono.so.1.70.0" "shared runtime, Boost_USE_STATIC_RUNTIME=${Boost_USE_STATIC_RUNTIME}")
+ return()
+endif()
+
+# runtime-debugging=off
+
+if(Boost_USE_DEBUG_RUNTIME)
+ _BOOST_SKIPPED("libboost_chrono.so.1.70.0" "release runtime, Boost_USE_DEBUG_RUNTIME=${Boost_USE_DEBUG_RUNTIME}")
+ return()
+endif()
+
+# threading=multi
+
+# variant=release
+
+if(NOT "${Boost_USE_RELEASE_LIBS}" STREQUAL "" AND NOT Boost_USE_RELEASE_LIBS)
+ _BOOST_SKIPPED("libboost_chrono.so.1.70.0" "release, Boost_USE_RELEASE_LIBS=${Boost_USE_RELEASE_LIBS}")
+ return()
+endif()
+
+message(STATUS " libboost_chrono.so.1.70.0")
+
+# Target file name: libboost_chrono.so.1.70.0
+set_property(TARGET Boost::chrono APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
+set_target_properties(Boost::chrono PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE CXX
+ IMPORTED_LOCATION_RELEASE "${_BOOST_LIBDIR}/libboost_chrono.so.1.70.0"
+ )
+
+set_target_properties(Boost::chrono PROPERTIES
+ INTERFACE_COMPILE_DEFINITIONS "BOOST_CHRONO_DYN_LINK"
+ )
+
+list(APPEND _BOOST_CHRONO_DEPS headers)
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/libboost_chrono-variant-static.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/libboost_chrono-variant-static.cmake
new file mode 100644
index 000000000..d7477b4d7
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_chrono-1.70.0/libboost_chrono-variant-static.cmake
@@ -0,0 +1,58 @@
+# Generated by Boost 1.70.0
+
+# address-model=64
+
+if(CMAKE_SIZEOF_VOID_P EQUAL 4)
+ _BOOST_SKIPPED("libboost_chrono.a" "64 bit, need 32")
+ return()
+endif()
+
+# layout=system
+
+# toolset=gcc8
+
+# link=static
+
+if(NOT "${Boost_USE_STATIC_LIBS}" STREQUAL "" AND NOT Boost_USE_STATIC_LIBS)
+ _BOOST_SKIPPED("libboost_chrono.a" "static, Boost_USE_STATIC_LIBS=${Boost_USE_STATIC_LIBS}")
+ return()
+endif()
+
+if(BUILD_SHARED_LIBS)
+ _BOOST_SKIPPED("libboost_chrono.a" "static, BUILD_SHARED_LIBS=${BUILD_SHARED_LIBS}, set Boost_USE_STATIC_LIBS=ON to override")
+ return()
+endif()
+
+# runtime-link=shared
+
+if(Boost_USE_STATIC_RUNTIME)
+ _BOOST_SKIPPED("libboost_chrono.a" "shared runtime, Boost_USE_STATIC_RUNTIME=${Boost_USE_STATIC_RUNTIME}")
+ return()
+endif()
+
+# runtime-debugging=off
+
+if(Boost_USE_DEBUG_RUNTIME)
+ _BOOST_SKIPPED("libboost_chrono.a" "release runtime, Boost_USE_DEBUG_RUNTIME=${Boost_USE_DEBUG_RUNTIME}")
+ return()
+endif()
+
+# threading=multi
+
+# variant=release
+
+if(NOT "${Boost_USE_RELEASE_LIBS}" STREQUAL "" AND NOT Boost_USE_RELEASE_LIBS)
+ _BOOST_SKIPPED("libboost_chrono.a" "release, Boost_USE_RELEASE_LIBS=${Boost_USE_RELEASE_LIBS}")
+ return()
+endif()
+
+message(STATUS " libboost_chrono.a")
+
+# Target file name: libboost_chrono.a
+set_property(TARGET Boost::chrono APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
+set_target_properties(Boost::chrono PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE CXX
+ IMPORTED_LOCATION_RELEASE "${_BOOST_LIBDIR}/libboost_chrono.a"
+ )
+
+list(APPEND _BOOST_CHRONO_DEPS headers)
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_headers-1.70.0/boost_headers-config-version.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_headers-1.70.0/boost_headers-config-version.cmake
new file mode 100644
index 000000000..114bba078
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_headers-1.70.0/boost_headers-config-version.cmake
@@ -0,0 +1,12 @@
+# Generated by Boost 1.70.0
+
+set(PACKAGE_VERSION 1.70.0)
+
+if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
+else()
+ set(PACKAGE_VERSION_COMPATIBLE TRUE)
+ if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
+ set(PACKAGE_VERSION_EXACT TRUE)
+ endif()
+endif()
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_headers-1.70.0/boost_headers-config.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_headers-1.70.0/boost_headers-config.cmake
new file mode 100644
index 000000000..0305ecd5c
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_headers-1.70.0/boost_headers-config.cmake
@@ -0,0 +1,20 @@
+# Generated by Boost 1.70.0
+
+if(TARGET Boost::headers)
+ return()
+endif()
+
+message(STATUS "Found boost_headers ${boost_headers_VERSION} at ${boost_headers_DIR}")
+
+# Compute the include and library directories relative to this file.
+get_filename_component(_BOOST_CMAKEDIR "${CMAKE_CURRENT_LIST_DIR}/../" ABSOLUTE)
+get_filename_component(_BOOST_INCLUDEDIR "${_BOOST_CMAKEDIR}/../../include/" ABSOLUTE)
+get_filename_component(_BOOST_LIBDIR "${_BOOST_CMAKEDIR}/../" ABSOLUTE)
+
+# Create imported target Boost::headers
+add_library(Boost::headers INTERFACE IMPORTED)
+
+set_target_properties(Boost::headers PROPERTIES
+ INTERFACE_INCLUDE_DIRECTORIES "${_BOOST_INCLUDEDIR}"
+ INTERFACE_COMPILE_DEFINITIONS "BOOST_ALL_NO_LIB"
+)
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/boost_system-config-version.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/boost_system-config-version.cmake
new file mode 100644
index 000000000..114bba078
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/boost_system-config-version.cmake
@@ -0,0 +1,12 @@
+# Generated by Boost 1.70.0
+
+set(PACKAGE_VERSION 1.70.0)
+
+if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
+else()
+ set(PACKAGE_VERSION_COMPATIBLE TRUE)
+ if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
+ set(PACKAGE_VERSION_EXACT TRUE)
+ endif()
+endif()
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/boost_system-config.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/boost_system-config.cmake
new file mode 100644
index 000000000..40b10d0c6
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/boost_system-config.cmake
@@ -0,0 +1,98 @@
+# Generated by Boost 1.70.0
+
+if(TARGET Boost::system)
+ return()
+endif()
+
+message(STATUS "Found boost_system ${boost_system_VERSION} at ${boost_system_DIR}")
+
+# Compute the include and library directories relative to this file.
+get_filename_component(_BOOST_CMAKEDIR "${CMAKE_CURRENT_LIST_DIR}/../" ABSOLUTE)
+get_filename_component(_BOOST_INCLUDEDIR "${_BOOST_CMAKEDIR}/../../include/" ABSOLUTE)
+get_filename_component(_BOOST_LIBDIR "${_BOOST_CMAKEDIR}/../" ABSOLUTE)
+
+# Create imported target Boost::system
+add_library(Boost::system UNKNOWN IMPORTED)
+
+set_target_properties(Boost::system PROPERTIES
+ INTERFACE_INCLUDE_DIRECTORIES "${_BOOST_INCLUDEDIR}"
+ INTERFACE_COMPILE_DEFINITIONS "BOOST_ALL_NO_LIB"
+)
+
+include(${CMAKE_CURRENT_LIST_DIR}/../BoostDetectToolset-1.70.0.cmake)
+
+if(Boost_DEBUG)
+ message(STATUS "Scanning ${CMAKE_CURRENT_LIST_DIR}/libboost_system-variant*.cmake")
+endif()
+
+file(GLOB __boost_variants "${CMAKE_CURRENT_LIST_DIR}/libboost_system-variant*.cmake")
+
+macro(_BOOST_SKIPPED fname reason)
+ if(Boost_DEBUG)
+ message(STATUS " ... skipped ${fname} (${reason})")
+ endif()
+ list(APPEND __boost_skipped "${fname} (${reason})")
+endmacro()
+
+foreach(f IN LISTS __boost_variants)
+ if(Boost_DEBUG)
+ message(STATUS " Including ${f}")
+ endif()
+ include(${f})
+endforeach()
+
+unset(_BOOST_LIBDIR)
+unset(_BOOST_INCLUDEDIR)
+unset(_BOOST_CMAKEDIR)
+
+get_target_property(__boost_configs Boost::system IMPORTED_CONFIGURATIONS)
+
+if(__boost_variants AND NOT __boost_configs)
+ message(STATUS "No suitable boost_system variant has been identified!")
+ if(NOT Boost_DEBUG)
+ foreach(s IN LISTS __boost_skipped)
+ message(STATUS " ${s}")
+ endforeach()
+ endif()
+ set(boost_system_FOUND 0)
+ set(boost_system_NOT_FOUND_MESSAGE "No suitable build variant has been found.")
+ unset(__boost_skipped)
+ unset(__boost_configs)
+ unset(__boost_variants)
+ unset(_BOOST_SYSTEM_DEPS)
+ return()
+endif()
+
+unset(__boost_skipped)
+unset(__boost_configs)
+unset(__boost_variants)
+
+if(_BOOST_SYSTEM_DEPS)
+ list(REMOVE_DUPLICATES _BOOST_SYSTEM_DEPS)
+ message(STATUS "Adding boost_system dependencies: ${_BOOST_SYSTEM_DEPS}")
+endif()
+
+foreach(dep_boost_system IN LISTS _BOOST_SYSTEM_DEPS)
+ set(_BOOST_QUIET)
+ if(boost_system_FIND_QUIETLY)
+ set(_BOOST_QUIET QUIET)
+ endif()
+ set(_BOOST_REQUIRED)
+ if(boost_system_FIND_REQUIRED)
+ set(_BOOST_REQUIRED REQUIRED)
+ endif()
+ get_filename_component(_BOOST_CMAKEDIR "${CMAKE_CURRENT_LIST_DIR}/../" ABSOLUTE)
+ find_package(boost_${dep_boost_system} 1.70.0 EXACT CONFIG ${_BOOST_REQUIRED} ${_BOOST_QUIET} HINTS ${_BOOST_CMAKEDIR})
+ set_property(TARGET Boost::system APPEND PROPERTY INTERFACE_LINK_LIBRARIES Boost::${dep_boost_system})
+ unset(_BOOST_QUIET)
+ unset(_BOOST_REQUIRED)
+ unset(_BOOST_CMAKEDIR)
+ if(NOT boost_${dep_boost_system}_FOUND)
+ set(boost_system_FOUND 0)
+ set(boost_system_NOT_FOUND_MESSAGE "A required dependency, boost_${dep_boost_system}, has not been found.")
+ unset(_BOOST_SYSTEM_DEPS)
+ return()
+ endif()
+endforeach()
+
+unset(_BOOST_SYSTEM_DEPS)
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/libboost_system-variant-shared.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/libboost_system-variant-shared.cmake
new file mode 100644
index 000000000..751db32c3
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/libboost_system-variant-shared.cmake
@@ -0,0 +1,62 @@
+# Generated by Boost 1.70.0
+
+# address-model=64
+
+if(CMAKE_SIZEOF_VOID_P EQUAL 4)
+ _BOOST_SKIPPED("libboost_system.so.1.70.0" "64 bit, need 32")
+ return()
+endif()
+
+# layout=system
+
+# toolset=gcc8
+
+# link=shared
+
+if(NOT "${Boost_USE_STATIC_LIBS}" STREQUAL "" AND Boost_USE_STATIC_LIBS)
+ _BOOST_SKIPPED("libboost_system.so.1.70.0" "shared, Boost_USE_STATIC_LIBS=${Boost_USE_STATIC_LIBS}")
+ return()
+endif()
+
+if(NOT BUILD_SHARED_LIBS)
+ _BOOST_SKIPPED("libboost_system.so.1.70.0" "shared, BUILD_SHARED_LIBS not ON, set Boost_USE_STATIC_LIBS=OFF to override")
+ return()
+endif()
+
+# runtime-link=shared
+
+if(Boost_USE_STATIC_RUNTIME)
+ _BOOST_SKIPPED("libboost_system.so.1.70.0" "shared runtime, Boost_USE_STATIC_RUNTIME=${Boost_USE_STATIC_RUNTIME}")
+ return()
+endif()
+
+# runtime-debugging=off
+
+if(Boost_USE_DEBUG_RUNTIME)
+ _BOOST_SKIPPED("libboost_system.so.1.70.0" "release runtime, Boost_USE_DEBUG_RUNTIME=${Boost_USE_DEBUG_RUNTIME}")
+ return()
+endif()
+
+# threading=multi
+
+# variant=release
+
+if(NOT "${Boost_USE_RELEASE_LIBS}" STREQUAL "" AND NOT Boost_USE_RELEASE_LIBS)
+ _BOOST_SKIPPED("libboost_system.so.1.70.0" "release, Boost_USE_RELEASE_LIBS=${Boost_USE_RELEASE_LIBS}")
+ return()
+endif()
+
+message(STATUS " libboost_system.so.1.70.0")
+
+# Target file name: libboost_system.so.1.70.0
+set_property(TARGET Boost::system APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
+set_target_properties(Boost::system PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE CXX
+ IMPORTED_LOCATION_RELEASE "${_BOOST_LIBDIR}/libboost_system.so.1.70.0"
+ )
+
+set_target_properties(Boost::system PROPERTIES
+ INTERFACE_COMPILE_DEFINITIONS "BOOST_SYSTEM_DYN_LINK"
+ )
+
+list(APPEND _BOOST_SYSTEM_DEPS headers)
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/libboost_system-variant-static.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/libboost_system-variant-static.cmake
new file mode 100644
index 000000000..b10e0b9e3
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_system-1.70.0/libboost_system-variant-static.cmake
@@ -0,0 +1,58 @@
+# Generated by Boost 1.70.0
+
+# address-model=64
+
+if(CMAKE_SIZEOF_VOID_P EQUAL 4)
+ _BOOST_SKIPPED("libboost_system.a" "64 bit, need 32")
+ return()
+endif()
+
+# layout=system
+
+# toolset=gcc8
+
+# link=static
+
+if(NOT "${Boost_USE_STATIC_LIBS}" STREQUAL "" AND NOT Boost_USE_STATIC_LIBS)
+ _BOOST_SKIPPED("libboost_system.a" "static, Boost_USE_STATIC_LIBS=${Boost_USE_STATIC_LIBS}")
+ return()
+endif()
+
+if(BUILD_SHARED_LIBS)
+ _BOOST_SKIPPED("libboost_system.a" "static, BUILD_SHARED_LIBS=${BUILD_SHARED_LIBS}, set Boost_USE_STATIC_LIBS=ON to override")
+ return()
+endif()
+
+# runtime-link=shared
+
+if(Boost_USE_STATIC_RUNTIME)
+ _BOOST_SKIPPED("libboost_system.a" "shared runtime, Boost_USE_STATIC_RUNTIME=${Boost_USE_STATIC_RUNTIME}")
+ return()
+endif()
+
+# runtime-debugging=off
+
+if(Boost_USE_DEBUG_RUNTIME)
+ _BOOST_SKIPPED("libboost_system.a" "release runtime, Boost_USE_DEBUG_RUNTIME=${Boost_USE_DEBUG_RUNTIME}")
+ return()
+endif()
+
+# threading=multi
+
+# variant=release
+
+if(NOT "${Boost_USE_RELEASE_LIBS}" STREQUAL "" AND NOT Boost_USE_RELEASE_LIBS)
+ _BOOST_SKIPPED("libboost_system.a" "release, Boost_USE_RELEASE_LIBS=${Boost_USE_RELEASE_LIBS}")
+ return()
+endif()
+
+message(STATUS " libboost_system.a")
+
+# Target file name: libboost_system.a
+set_property(TARGET Boost::system APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
+set_target_properties(Boost::system PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE CXX
+ IMPORTED_LOCATION_RELEASE "${_BOOST_LIBDIR}/libboost_system.a"
+ )
+
+list(APPEND _BOOST_SYSTEM_DEPS headers)
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/boost_timer-config-version.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/boost_timer-config-version.cmake
new file mode 100644
index 000000000..114bba078
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/boost_timer-config-version.cmake
@@ -0,0 +1,12 @@
+# Generated by Boost 1.70.0
+
+set(PACKAGE_VERSION 1.70.0)
+
+if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
+else()
+ set(PACKAGE_VERSION_COMPATIBLE TRUE)
+ if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
+ set(PACKAGE_VERSION_EXACT TRUE)
+ endif()
+endif()
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/boost_timer-config.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/boost_timer-config.cmake
new file mode 100644
index 000000000..b0d0e5403
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/boost_timer-config.cmake
@@ -0,0 +1,98 @@
+# Generated by Boost 1.70.0
+
+if(TARGET Boost::timer)
+ return()
+endif()
+
+message(STATUS "Found boost_timer ${boost_timer_VERSION} at ${boost_timer_DIR}")
+
+# Compute the include and library directories relative to this file.
+get_filename_component(_BOOST_CMAKEDIR "${CMAKE_CURRENT_LIST_DIR}/../" ABSOLUTE)
+get_filename_component(_BOOST_INCLUDEDIR "${_BOOST_CMAKEDIR}/../../include/" ABSOLUTE)
+get_filename_component(_BOOST_LIBDIR "${_BOOST_CMAKEDIR}/../" ABSOLUTE)
+
+# Create imported target Boost::timer
+add_library(Boost::timer UNKNOWN IMPORTED)
+
+set_target_properties(Boost::timer PROPERTIES
+ INTERFACE_INCLUDE_DIRECTORIES "${_BOOST_INCLUDEDIR}"
+ INTERFACE_COMPILE_DEFINITIONS "BOOST_ALL_NO_LIB"
+)
+
+include(${CMAKE_CURRENT_LIST_DIR}/../BoostDetectToolset-1.70.0.cmake)
+
+if(Boost_DEBUG)
+ message(STATUS "Scanning ${CMAKE_CURRENT_LIST_DIR}/libboost_timer-variant*.cmake")
+endif()
+
+file(GLOB __boost_variants "${CMAKE_CURRENT_LIST_DIR}/libboost_timer-variant*.cmake")
+
+macro(_BOOST_SKIPPED fname reason)
+ if(Boost_DEBUG)
+ message(STATUS " ... skipped ${fname} (${reason})")
+ endif()
+ list(APPEND __boost_skipped "${fname} (${reason})")
+endmacro()
+
+foreach(f IN LISTS __boost_variants)
+ if(Boost_DEBUG)
+ message(STATUS " Including ${f}")
+ endif()
+ include(${f})
+endforeach()
+
+unset(_BOOST_LIBDIR)
+unset(_BOOST_INCLUDEDIR)
+unset(_BOOST_CMAKEDIR)
+
+get_target_property(__boost_configs Boost::timer IMPORTED_CONFIGURATIONS)
+
+if(__boost_variants AND NOT __boost_configs)
+ message(STATUS "No suitable boost_timer variant has been identified!")
+ if(NOT Boost_DEBUG)
+ foreach(s IN LISTS __boost_skipped)
+ message(STATUS " ${s}")
+ endforeach()
+ endif()
+ set(boost_timer_FOUND 0)
+ set(boost_timer_NOT_FOUND_MESSAGE "No suitable build variant has been found.")
+ unset(__boost_skipped)
+ unset(__boost_configs)
+ unset(__boost_variants)
+ unset(_BOOST_TIMER_DEPS)
+ return()
+endif()
+
+unset(__boost_skipped)
+unset(__boost_configs)
+unset(__boost_variants)
+
+if(_BOOST_TIMER_DEPS)
+ list(REMOVE_DUPLICATES _BOOST_TIMER_DEPS)
+ message(STATUS "Adding boost_timer dependencies: ${_BOOST_TIMER_DEPS}")
+endif()
+
+foreach(dep_boost_timer IN LISTS _BOOST_TIMER_DEPS)
+ set(_BOOST_QUIET)
+ if(boost_timer_FIND_QUIETLY)
+ set(_BOOST_QUIET QUIET)
+ endif()
+ set(_BOOST_REQUIRED)
+ if(boost_timer_FIND_REQUIRED)
+ set(_BOOST_REQUIRED REQUIRED)
+ endif()
+ get_filename_component(_BOOST_CMAKEDIR "${CMAKE_CURRENT_LIST_DIR}/../" ABSOLUTE)
+ find_package(boost_${dep_boost_timer} 1.70.0 EXACT CONFIG ${_BOOST_REQUIRED} ${_BOOST_QUIET} HINTS ${_BOOST_CMAKEDIR})
+ set_property(TARGET Boost::timer APPEND PROPERTY INTERFACE_LINK_LIBRARIES Boost::${dep_boost_timer})
+ unset(_BOOST_QUIET)
+ unset(_BOOST_REQUIRED)
+ unset(_BOOST_CMAKEDIR)
+ if(NOT boost_${dep_boost_timer}_FOUND)
+ set(boost_timer_FOUND 0)
+ set(boost_timer_NOT_FOUND_MESSAGE "A required dependency, boost_${dep_boost_timer}, has not been found.")
+ unset(_BOOST_TIMER_DEPS)
+ return()
+ endif()
+endforeach()
+
+unset(_BOOST_TIMER_DEPS)
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/libboost_timer-variant-shared.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/libboost_timer-variant-shared.cmake
new file mode 100644
index 000000000..b35b59d64
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/libboost_timer-variant-shared.cmake
@@ -0,0 +1,62 @@
+# Generated by Boost 1.70.0
+
+# address-model=64
+
+if(CMAKE_SIZEOF_VOID_P EQUAL 4)
+ _BOOST_SKIPPED("libboost_timer.so.1.70.0" "64 bit, need 32")
+ return()
+endif()
+
+# layout=system
+
+# toolset=gcc8
+
+# link=shared
+
+if(NOT "${Boost_USE_STATIC_LIBS}" STREQUAL "" AND Boost_USE_STATIC_LIBS)
+ _BOOST_SKIPPED("libboost_timer.so.1.70.0" "shared, Boost_USE_STATIC_LIBS=${Boost_USE_STATIC_LIBS}")
+ return()
+endif()
+
+if(NOT BUILD_SHARED_LIBS)
+ _BOOST_SKIPPED("libboost_timer.so.1.70.0" "shared, BUILD_SHARED_LIBS not ON, set Boost_USE_STATIC_LIBS=OFF to override")
+ return()
+endif()
+
+# runtime-link=shared
+
+if(Boost_USE_STATIC_RUNTIME)
+ _BOOST_SKIPPED("libboost_timer.so.1.70.0" "shared runtime, Boost_USE_STATIC_RUNTIME=${Boost_USE_STATIC_RUNTIME}")
+ return()
+endif()
+
+# runtime-debugging=off
+
+if(Boost_USE_DEBUG_RUNTIME)
+ _BOOST_SKIPPED("libboost_timer.so.1.70.0" "release runtime, Boost_USE_DEBUG_RUNTIME=${Boost_USE_DEBUG_RUNTIME}")
+ return()
+endif()
+
+# threading=multi
+
+# variant=release
+
+if(NOT "${Boost_USE_RELEASE_LIBS}" STREQUAL "" AND NOT Boost_USE_RELEASE_LIBS)
+ _BOOST_SKIPPED("libboost_timer.so.1.70.0" "release, Boost_USE_RELEASE_LIBS=${Boost_USE_RELEASE_LIBS}")
+ return()
+endif()
+
+message(STATUS " libboost_timer.so.1.70.0")
+
+# Target file name: libboost_timer.so.1.70.0
+set_property(TARGET Boost::timer APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
+set_target_properties(Boost::timer PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE CXX
+ IMPORTED_LOCATION_RELEASE "${_BOOST_LIBDIR}/libboost_timer.so.1.70.0"
+ )
+
+set_target_properties(Boost::timer PROPERTIES
+ INTERFACE_COMPILE_DEFINITIONS "BOOST_TIMER_DYN_LINK"
+ )
+
+list(APPEND _BOOST_TIMER_DEPS chrono headers)
diff --git a/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/libboost_timer-variant-static.cmake b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/libboost_timer-variant-static.cmake
new file mode 100644
index 000000000..37fa9c0a5
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackageFixtures/boost_timer-1.70.0/libboost_timer-variant-static.cmake
@@ -0,0 +1,58 @@
+# Generated by Boost 1.70.0
+
+# address-model=64
+
+if(CMAKE_SIZEOF_VOID_P EQUAL 4)
+ _BOOST_SKIPPED("libboost_timer.a" "64 bit, need 32")
+ return()
+endif()
+
+# layout=system
+
+# toolset=gcc8
+
+# link=static
+
+if(NOT "${Boost_USE_STATIC_LIBS}" STREQUAL "" AND NOT Boost_USE_STATIC_LIBS)
+ _BOOST_SKIPPED("libboost_timer.a" "static, Boost_USE_STATIC_LIBS=${Boost_USE_STATIC_LIBS}")
+ return()
+endif()
+
+if(BUILD_SHARED_LIBS)
+ _BOOST_SKIPPED("libboost_timer.a" "static, BUILD_SHARED_LIBS=${BUILD_SHARED_LIBS}, set Boost_USE_STATIC_LIBS=ON to override")
+ return()
+endif()
+
+# runtime-link=shared
+
+if(Boost_USE_STATIC_RUNTIME)
+ _BOOST_SKIPPED("libboost_timer.a" "shared runtime, Boost_USE_STATIC_RUNTIME=${Boost_USE_STATIC_RUNTIME}")
+ return()
+endif()
+
+# runtime-debugging=off
+
+if(Boost_USE_DEBUG_RUNTIME)
+ _BOOST_SKIPPED("libboost_timer.a" "release runtime, Boost_USE_DEBUG_RUNTIME=${Boost_USE_DEBUG_RUNTIME}")
+ return()
+endif()
+
+# threading=multi
+
+# variant=release
+
+if(NOT "${Boost_USE_RELEASE_LIBS}" STREQUAL "" AND NOT Boost_USE_RELEASE_LIBS)
+ _BOOST_SKIPPED("libboost_timer.a" "release, Boost_USE_RELEASE_LIBS=${Boost_USE_RELEASE_LIBS}")
+ return()
+endif()
+
+message(STATUS " libboost_timer.a")
+
+# Target file name: libboost_timer.a
+set_property(TARGET Boost::timer APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
+set_target_properties(Boost::timer PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE CXX
+ IMPORTED_LOCATION_RELEASE "${_BOOST_LIBDIR}/libboost_timer.a"
+ )
+
+list(APPEND _BOOST_TIMER_DEPS chrono headers)
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/BoostConfig.cmake b/Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/BoostConfig.cmake
new file mode 100644
index 000000000..cf13b4ac3
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/BoostConfig.cmake
@@ -0,0 +1,26 @@
+# No boost::boost target and all targets start with lowercase letters
+# Similar to https://github.com/boost-cmake/boost-cmake
+
+add_library(boost::headers INTERFACE IMPORTED)
+target_include_directories(boost::headers INTERFACE "${CMAKE_CURRENT_LIST_DIR}/include")
+
+set(Boost_date_time_FOUND 1)
+add_library(boost::date_time UNKNOWN IMPORTED)
+set_target_properties(boost::date_time PROPERTIES
+ IMPORTED_CONFIGURATIONS RELEASE
+ IMPORTED_LOCATION_RELEASE "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_date_time.a"
+ )
+set(Boost_python37_FOUND 1)
+add_library(boost::python UNKNOWN IMPORTED)
+set_target_properties(boost::python PROPERTIES
+ IMPORTED_CONFIGURATIONS "RELEASE;DEBUG"
+ IMPORTED_LOCATION_RELEASE "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_python_release.a"
+ IMPORTED_LOCATION_DEBUG "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_python.a"
+ )
+set(Boost_mpi_python2_FOUND 1)
+add_library(boost::mpi_python UNKNOWN IMPORTED)
+set_target_properties(boost::mpi_python PROPERTIES
+ IMPORTED_CONFIGURATIONS "RELEASE;DEBUG"
+ IMPORTED_LOCATION_RELEASE "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_mpi_python.a"
+ IMPORTED_LOCATION_DEBUG "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_mpi_python.a"
+ )
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/BoostConfigVersion.cmake b/Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/BoostConfigVersion.cmake
new file mode 100644
index 000000000..b4b606000
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/BoostConfigVersion.cmake
@@ -0,0 +1,7 @@
+set(PACKAGE_VERSION 1.70.42)
+if(PACKAGE_FIND_VERSION_MAJOR EQUAL 1)
+ set(PACKAGE_VERSION_COMPATIBLE 1)
+ if(PACKAGE_FIND_VERSION_MINOR EQUAL 70 AND PACKAGE_FIND_VERSION_PATCH EQUAL 42)
+ set(PACKAGE_VERSION_EXACT 1)
+ endif()
+endif()
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/include/boost/version.hpp b/Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/include/boost/version.hpp
new file mode 100644
index 000000000..fe8e72c6d
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_LowerCaseTargetPrefix/include/boost/version.hpp
@@ -0,0 +1,34 @@
+// Boost version.hpp configuration header file
+// ------------------------------//
+
+// (C) Copyright John maddock 1999. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/config for documentation
+
+#ifndef BOOST_VERSION_HPP
+#define BOOST_VERSION_HPP
+
+//
+// Caution: this is the only Boost header that is guaranteed
+// to change with every Boost release. Including this header
+// will cause a recompile every time a new Boost version is
+// used.
+//
+// BOOST_VERSION % 100 is the patch level
+// BOOST_VERSION / 100 % 1000 is the minor version
+// BOOST_VERSION / 100000 is the major version
+
+#define BOOST_VERSION 1070042
+
+//
+// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
+// but as a *string* in the form "x_y[_z]" where x is the major version
+// number, y is the minor version number, and z is the patch level if not 0.
+// This is used by <config/auto_link.hpp> to select which library version to
+// link to.
+
+#define BOOST_LIB_VERSION "1_70_42"
+
+#endif
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/BoostConfig.cmake b/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/BoostConfig.cmake
new file mode 100644
index 000000000..97d4c797b
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/BoostConfig.cmake
@@ -0,0 +1,7 @@
+# Don't have targets
+set(Boost_INCLUDE_DIRS "${CMAKE_CURRENT_LIST_DIR}/include")
+
+set(Boost_DATE_TIME_FOUND 1)
+set(Boost_DATE_TIME_LIBRARY "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_date_time.a")
+
+set(Boost_LIBRARIES ${Boost_DATE_TIME_LIBRARY})
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/BoostConfigVersion.cmake b/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/BoostConfigVersion.cmake
new file mode 100644
index 000000000..b4b606000
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/BoostConfigVersion.cmake
@@ -0,0 +1,7 @@
+set(PACKAGE_VERSION 1.70.42)
+if(PACKAGE_FIND_VERSION_MAJOR EQUAL 1)
+ set(PACKAGE_VERSION_COMPATIBLE 1)
+ if(PACKAGE_FIND_VERSION_MINOR EQUAL 70 AND PACKAGE_FIND_VERSION_PATCH EQUAL 42)
+ set(PACKAGE_VERSION_EXACT 1)
+ endif()
+endif()
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/include/boost/version.hpp b/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/include/boost/version.hpp
new file mode 100644
index 000000000..fe8e72c6d
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/include/boost/version.hpp
@@ -0,0 +1,34 @@
+// Boost version.hpp configuration header file
+// ------------------------------//
+
+// (C) Copyright John maddock 1999. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/config for documentation
+
+#ifndef BOOST_VERSION_HPP
+#define BOOST_VERSION_HPP
+
+//
+// Caution: this is the only Boost header that is guaranteed
+// to change with every Boost release. Including this header
+// will cause a recompile every time a new Boost version is
+// used.
+//
+// BOOST_VERSION % 100 is the patch level
+// BOOST_VERSION / 100 % 1000 is the minor version
+// BOOST_VERSION / 100000 is the major version
+
+#define BOOST_VERSION 1070042
+
+//
+// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
+// but as a *string* in the form "x_y[_z]" where x is the major version
+// number, y is the minor version number, and z is the patch level if not 0.
+// This is used by <config/auto_link.hpp> to select which library version to
+// link to.
+
+#define BOOST_LIB_VERSION "1_70_42"
+
+#endif
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_New/BoostConfig.cmake b/Tests/RunCMake/FindBoost/CMakePackage_New/BoostConfig.cmake
new file mode 100644
index 000000000..115151476
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_New/BoostConfig.cmake
@@ -0,0 +1,29 @@
+add_library(Boost::boost INTERFACE IMPORTED)
+add_library(Boost::headers INTERFACE IMPORTED)
+target_include_directories(Boost::headers INTERFACE "${CMAKE_CURRENT_LIST_DIR}/include")
+
+set(Boost_date_time_FOUND 1)
+add_library(Boost::date_time UNKNOWN IMPORTED)
+set_target_properties(Boost::date_time PROPERTIES
+ IMPORTED_CONFIGURATIONS RELEASE
+ IMPORTED_LOCATION_RELEASE "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_date_time.a"
+ )
+
+set(Boost_python37_FOUND 1)
+add_library(Boost::python UNKNOWN IMPORTED)
+set_target_properties(Boost::python PROPERTIES
+ IMPORTED_CONFIGURATIONS "RELEASE;DEBUG"
+ IMPORTED_LOCATION_RELEASE "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_python_release.a"
+ IMPORTED_LOCATION_DEBUG "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_python.a"
+ )
+# Versioned target alias for compatibility (added by upstream BoostConfig).
+add_library(Boost::python37 INTERFACE IMPORTED)
+set_property(TARGET Boost::python37 APPEND PROPERTY INTERFACE_LINK_LIBRARIES Boost::python)
+
+set(Boost_mpi_python2_FOUND 1)
+add_library(Boost::mpi_python UNKNOWN IMPORTED)
+set_target_properties(Boost::mpi_python PROPERTIES
+ IMPORTED_CONFIGURATIONS "RELEASE;DEBUG"
+ IMPORTED_LOCATION_RELEASE "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_mpi_python.a"
+ IMPORTED_LOCATION_DEBUG "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_mpi_python.a"
+ )
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_New/BoostConfigVersion.cmake b/Tests/RunCMake/FindBoost/CMakePackage_New/BoostConfigVersion.cmake
new file mode 100644
index 000000000..b4b606000
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_New/BoostConfigVersion.cmake
@@ -0,0 +1,7 @@
+set(PACKAGE_VERSION 1.70.42)
+if(PACKAGE_FIND_VERSION_MAJOR EQUAL 1)
+ set(PACKAGE_VERSION_COMPATIBLE 1)
+ if(PACKAGE_FIND_VERSION_MINOR EQUAL 70 AND PACKAGE_FIND_VERSION_PATCH EQUAL 42)
+ set(PACKAGE_VERSION_EXACT 1)
+ endif()
+endif()
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_New/include/boost/version.hpp b/Tests/RunCMake/FindBoost/CMakePackage_New/include/boost/version.hpp
new file mode 100644
index 000000000..fe8e72c6d
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_New/include/boost/version.hpp
@@ -0,0 +1,34 @@
+// Boost version.hpp configuration header file
+// ------------------------------//
+
+// (C) Copyright John maddock 1999. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/config for documentation
+
+#ifndef BOOST_VERSION_HPP
+#define BOOST_VERSION_HPP
+
+//
+// Caution: this is the only Boost header that is guaranteed
+// to change with every Boost release. Including this header
+// will cause a recompile every time a new Boost version is
+// used.
+//
+// BOOST_VERSION % 100 is the patch level
+// BOOST_VERSION / 100 % 1000 is the minor version
+// BOOST_VERSION / 100000 is the major version
+
+#define BOOST_VERSION 1070042
+
+//
+// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
+// but as a *string* in the form "x_y[_z]" where x is the major version
+// number, y is the minor version number, and z is the patch level if not 0.
+// This is used by <config/auto_link.hpp> to select which library version to
+// link to.
+
+#define BOOST_LIB_VERSION "1_70_42"
+
+#endif
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_date_time.a b/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_date_time.a
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_date_time.a
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_mpi_python.a b/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_mpi_python.a
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_mpi_python.a
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_python.a b/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_python.a
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_python.a
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_python_release.a b/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_python_release.a
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_New/lib/libboost_python_release.a
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/BoostConfig.cmake b/Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/BoostConfig.cmake
new file mode 100644
index 000000000..ba2269adb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/BoostConfig.cmake
@@ -0,0 +1,25 @@
+# UPPER_CASE FOUND vars and no header targets
+
+set(Boost_DATE_TIME_FOUND 1)
+add_library(Boost::date_time UNKNOWN IMPORTED)
+set_target_properties(Boost::date_time PROPERTIES
+ IMPORTED_CONFIGURATIONS RELEASE
+ IMPORTED_LOCATION_RELEASE "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_date_time.a"
+ INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_LIST_DIR}/include"
+ )
+set(Boost_PYTHON37_FOUND 1)
+add_library(Boost::python UNKNOWN IMPORTED)
+set_target_properties(Boost::python PROPERTIES
+ IMPORTED_CONFIGURATIONS "RELEASE;DEBUG"
+ IMPORTED_LOCATION_RELEASE "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_python_release.a"
+ IMPORTED_LOCATION_DEBUG "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_python.a"
+ INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_LIST_DIR}/include"
+ )
+set(Boost_MPI_PYTHON2_FOUND 1)
+add_library(Boost::mpi_python UNKNOWN IMPORTED)
+set_target_properties(Boost::mpi_python PROPERTIES
+ IMPORTED_CONFIGURATIONS "RELEASE;DEBUG"
+ IMPORTED_LOCATION_RELEASE "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_mpi_python.a"
+ IMPORTED_LOCATION_DEBUG "${CMAKE_CURRENT_LIST_DIR}/lib/libboost_mpi_python.a"
+ INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_LIST_DIR}/include"
+ )
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/BoostConfigVersion.cmake b/Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/BoostConfigVersion.cmake
new file mode 100644
index 000000000..b4b606000
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/BoostConfigVersion.cmake
@@ -0,0 +1,7 @@
+set(PACKAGE_VERSION 1.70.42)
+if(PACKAGE_FIND_VERSION_MAJOR EQUAL 1)
+ set(PACKAGE_VERSION_COMPATIBLE 1)
+ if(PACKAGE_FIND_VERSION_MINOR EQUAL 70 AND PACKAGE_FIND_VERSION_PATCH EQUAL 42)
+ set(PACKAGE_VERSION_EXACT 1)
+ endif()
+endif()
diff --git a/Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/include/boost/version.hpp b/Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/include/boost/version.hpp
new file mode 100644
index 000000000..fe8e72c6d
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage_NoHeaderTarget/include/boost/version.hpp
@@ -0,0 +1,34 @@
+// Boost version.hpp configuration header file
+// ------------------------------//
+
+// (C) Copyright John maddock 1999. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/config for documentation
+
+#ifndef BOOST_VERSION_HPP
+#define BOOST_VERSION_HPP
+
+//
+// Caution: this is the only Boost header that is guaranteed
+// to change with every Boost release. Including this header
+// will cause a recompile every time a new Boost version is
+// used.
+//
+// BOOST_VERSION % 100 is the patch level
+// BOOST_VERSION / 100 % 1000 is the minor version
+// BOOST_VERSION / 100000 is the major version
+
+#define BOOST_VERSION 1070042
+
+//
+// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
+// but as a *string* in the form "x_y[_z]" where x is the major version
+// number, y is the minor version number, and z is the patch level if not 0.
+// This is used by <config/auto_link.hpp> to select which library version to
+// link to.
+
+#define BOOST_LIB_VERSION "1_70_42"
+
+#endif
diff --git a/Tests/RunCMake/FindBoost/CommonNotFound-stderr.txt b/Tests/RunCMake/FindBoost/CommonNotFound-stderr.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CommonNotFound-stderr.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/FindBoost/CommonNotFound-stdout.txt b/Tests/RunCMake/FindBoost/CommonNotFound-stdout.txt
new file mode 100644
index 000000000..644469e5f
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CommonNotFound-stdout.txt
@@ -0,0 +1 @@
+-- Could NOT find Boost
diff --git a/Tests/RunCMake/FindBoost/CommonNotFound.cmake b/Tests/RunCMake/FindBoost/CommonNotFound.cmake
new file mode 100644
index 000000000..864a54913
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CommonNotFound.cmake
@@ -0,0 +1,2 @@
+# Make sure to use the module mode signature here to not bypass FindBoost
+find_package(Boost 1.80 COMPONENTS timer foobar)
diff --git a/Tests/RunCMake/FindBoost/CommonResults-stdout.txt b/Tests/RunCMake/FindBoost/CommonResults-stdout.txt
new file mode 100644
index 000000000..a560843e0
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CommonResults-stdout.txt
@@ -0,0 +1,13 @@
+-- Found Boost: [^
+]* \(found suitable version "1\.70\.0", minimum required is "1\.60"\) found components: .*timer.*
+-- Boost_FOUND
+-- Boost_VERSION=(107000|1\.70\.0)
+-- Boost_VERSION_MAJOR=1
+-- Boost_VERSION_MINOR=70
+-- Boost_VERSION_PATCH=0
+-- Boost_VERSION_COUNT=3
+-- Boost::headers
+-- Boost::boost
+-- Boost::chrono
+-- Boost::timer
+(-- Boost::system)?
diff --git a/Tests/RunCMake/FindBoost/CommonResults.cmake b/Tests/RunCMake/FindBoost/CommonResults.cmake
new file mode 100644
index 000000000..6876800a5
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CommonResults.cmake
@@ -0,0 +1,25 @@
+# Make sure to use the module mode signature here to not bypass FindBoost
+find_package(Boost 1.60 COMPONENTS timer MODULE)
+if(Boost_FOUND)
+ message(STATUS "Boost_FOUND")
+endif()
+message(STATUS "Boost_VERSION=${Boost_VERSION}")
+message(STATUS "Boost_VERSION_MAJOR=${Boost_VERSION_MAJOR}")
+message(STATUS "Boost_VERSION_MINOR=${Boost_VERSION_MINOR}")
+message(STATUS "Boost_VERSION_PATCH=${Boost_VERSION_PATCH}")
+message(STATUS "Boost_VERSION_COUNT=${Boost_VERSION_COUNT}")
+if(TARGET Boost::headers)
+ message(STATUS "Boost::headers")
+endif()
+if(TARGET Boost::boost)
+ message(STATUS "Boost::boost")
+endif()
+if(TARGET Boost::chrono)
+ message(STATUS "Boost::chrono")
+endif()
+if(TARGET Boost::timer)
+ message(STATUS "Boost::timer")
+endif()
+if(TARGET Boost::system)
+ message(STATUS "Boost::system")
+endif()
diff --git a/Tests/RunCMake/FindBoost/ConfigMode.cmake b/Tests/RunCMake/FindBoost/ConfigMode.cmake
new file mode 100644
index 000000000..5600658a4
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/ConfigMode.cmake
@@ -0,0 +1,2 @@
+set(Boost_DIR ${CMAKE_CURRENT_SOURCE_DIR}/CMakePackageFixtures/Boost-1.70.0)
+include(${CMAKE_CURRENT_SOURCE_DIR}/CommonResults.cmake)
diff --git a/Tests/RunCMake/FindBoost/ConfigModeNotFound.cmake b/Tests/RunCMake/FindBoost/ConfigModeNotFound.cmake
new file mode 100644
index 000000000..7e90a3cfc
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/ConfigModeNotFound.cmake
@@ -0,0 +1,2 @@
+set(Boost_DIR ${CMAKE_CURRENT_SOURCE_DIR}/CMakePackageFixtures/Boost-1.70.0)
+include(${CMAKE_CURRENT_SOURCE_DIR}/CommonNotFound.cmake)
diff --git a/Tests/RunCMake/FindBoost/LegacyVars-LowercaseTargetPrefix-stdout.txt b/Tests/RunCMake/FindBoost/LegacyVars-LowercaseTargetPrefix-stdout.txt
new file mode 100644
index 000000000..a781dce30
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/LegacyVars-LowercaseTargetPrefix-stdout.txt
@@ -0,0 +1,34 @@
+-- Found Boost: [^
+]* \(found suitable version "1\.70\.42", minimum required is "1\.70"\) found components: date_time python37 mpi_python2 *
+-- Boost_FOUND: TRUE
+-- Boost_INCLUDE_DIRS: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/include
+-- Boost_LIBRARY_DIRS: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib
+-- Boost_LIBRARIES: boost::date_time;boost::python;boost::mpi_python
+-- Boost_DATE_TIME_FOUND: 1
+-- Boost_DATE_TIME_LIBRARY: boost::date_time
+-- Boost_PYTHON37_FOUND: 1
+-- Boost_PYTHON37_LIBRARY: boost::python
+-- Boost_MPI_PYTHON2_FOUND: 1
+-- Boost_MPI_PYTHON2_LIBRARY: boost::mpi_python
+-- Boost_VERSION_MACRO: 1070042
+-- Boost_VERSION_STRING: 1.70.42
+-- Boost_VERSION: 1.70.42
+-- Boost_LIB_VERSION: 1_70_42
+-- Boost_MAJOR_VERSION: 1
+-- Boost_MINOR_VERSION: 70
+-- Boost_SUBMINOR_VERSION: 42
+-- Boost_INCLUDE_DIR: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/include
+-- Boost_DATE_TIME_LIBRARY_DEBUG: *
+-- Boost_DATE_TIME_LIBRARY_RELEASE: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib/libboost_date_time.a
+-- Boost_PYTHON37_LIBRARY_DEBUG: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib/libboost_python.a
+-- Boost_PYTHON37_LIBRARY_RELEASE: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib/libboost_python_release.a
+-- Boost_MPI_PYTHON2_LIBRARY_DEBUG: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib/libboost_mpi_python.a
+-- Boost_MPI_PYTHON2_LIBRARY_RELEASE: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib/libboost_mpi_python.a
diff --git a/Tests/RunCMake/FindBoost/LegacyVars-LowercaseTargetPrefix.cmake b/Tests/RunCMake/FindBoost/LegacyVars-LowercaseTargetPrefix.cmake
new file mode 100644
index 000000000..a398c2d8c
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/LegacyVars-LowercaseTargetPrefix.cmake
@@ -0,0 +1,6 @@
+# Use a (made up) modern style BoostConfig that defines all targets
+# as boost::<component> with appropriate properties set
+# No legacy variables defined in the BoostConfig
+set(Boost_DIR ${CMAKE_CURRENT_SOURCE_DIR}/CMakePackage_LowerCaseTargetPrefix)
+
+include(${CMAKE_CURRENT_SOURCE_DIR}/LegacyVars.cmake)
diff --git a/Tests/RunCMake/FindBoost/LegacyVars-NoHeaderTarget.cmake b/Tests/RunCMake/FindBoost/LegacyVars-NoHeaderTarget.cmake
new file mode 100644
index 000000000..edb6dda97
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/LegacyVars-NoHeaderTarget.cmake
@@ -0,0 +1,6 @@
+# Use a (made up?) BoostConfig that defines all targets
+# as Boost::<component> with appropriate properties set
+# But no Boost::headers or Boost::boost target is defined
+set(Boost_DIR ${CMAKE_CURRENT_SOURCE_DIR}/CMakePackage_NoHeaderTarget)
+
+include(${CMAKE_CURRENT_SOURCE_DIR}/LegacyVars.cmake)
diff --git a/Tests/RunCMake/FindBoost/LegacyVars-TargetsDefined-stdout.txt b/Tests/RunCMake/FindBoost/LegacyVars-TargetsDefined-stdout.txt
new file mode 100644
index 000000000..a4e9c6af1
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/LegacyVars-TargetsDefined-stdout.txt
@@ -0,0 +1,34 @@
+-- Found Boost: [^
+]* \(found suitable version "1\.70\.42", minimum required is "1\.70"\) found components: date_time python37 mpi_python2 *
+-- Boost_FOUND: TRUE
+-- Boost_INCLUDE_DIRS: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/include
+-- Boost_LIBRARY_DIRS: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib
+-- Boost_LIBRARIES: Boost::date_time;Boost::python;Boost::mpi_python
+-- Boost_DATE_TIME_FOUND: 1
+-- Boost_DATE_TIME_LIBRARY: Boost::date_time
+-- Boost_PYTHON37_FOUND: 1
+-- Boost_PYTHON37_LIBRARY: Boost::python
+-- Boost_MPI_PYTHON2_FOUND: 1
+-- Boost_MPI_PYTHON2_LIBRARY: Boost::mpi_python
+-- Boost_VERSION_MACRO: 1070042
+-- Boost_VERSION_STRING: 1.70.42
+-- Boost_VERSION: 1.70.42
+-- Boost_LIB_VERSION: 1_70_42
+-- Boost_MAJOR_VERSION: 1
+-- Boost_MINOR_VERSION: 70
+-- Boost_SUBMINOR_VERSION: 42
+-- Boost_INCLUDE_DIR: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/include
+-- Boost_DATE_TIME_LIBRARY_DEBUG: *
+-- Boost_DATE_TIME_LIBRARY_RELEASE: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib/libboost_date_time.a
+-- Boost_PYTHON37_LIBRARY_DEBUG: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib/libboost_python.a
+-- Boost_PYTHON37_LIBRARY_RELEASE: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib/libboost_python_release.a
+-- Boost_MPI_PYTHON2_LIBRARY_DEBUG: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib/libboost_mpi_python.a
+-- Boost_MPI_PYTHON2_LIBRARY_RELEASE: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage[^/]*/lib/libboost_mpi_python.a
diff --git a/Tests/RunCMake/FindBoost/LegacyVars-TargetsDefined.cmake b/Tests/RunCMake/FindBoost/LegacyVars-TargetsDefined.cmake
new file mode 100644
index 000000000..19ad49f8f
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/LegacyVars-TargetsDefined.cmake
@@ -0,0 +1,6 @@
+# Use a modern style BoostConfig that defines all targets
+# as Boost::<component> with appropriate properties set
+# No legacy variables defined in the BoostConfig
+set(Boost_DIR ${CMAKE_CURRENT_SOURCE_DIR}/CMakePackage_New)
+
+include(${CMAKE_CURRENT_SOURCE_DIR}/LegacyVars.cmake)
diff --git a/Tests/RunCMake/FindBoost/LegacyVars.cmake b/Tests/RunCMake/FindBoost/LegacyVars.cmake
new file mode 100644
index 000000000..d0d5ee01c
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/LegacyVars.cmake
@@ -0,0 +1,28 @@
+find_package(Boost 1.70 COMPONENTS date_time python37 mpi_python2)
+
+foreach(var Boost_FOUND Boost_INCLUDE_DIRS Boost_LIBRARY_DIRS Boost_LIBRARIES
+ Boost_DATE_TIME_FOUND Boost_DATE_TIME_LIBRARY
+ Boost_PYTHON37_FOUND Boost_PYTHON37_LIBRARY
+ Boost_MPI_PYTHON2_FOUND Boost_MPI_PYTHON2_LIBRARY
+ Boost_VERSION_MACRO Boost_VERSION_STRING Boost_VERSION Boost_LIB_VERSION
+ Boost_MAJOR_VERSION Boost_MINOR_VERSION Boost_SUBMINOR_VERSION
+)
+ message(STATUS "${var}: ${${var}}")
+endforeach()
+
+foreach(cachevar Boost_INCLUDE_DIR
+ Boost_DATE_TIME_LIBRARY_DEBUG Boost_DATE_TIME_LIBRARY_RELEASE
+ Boost_PYTHON37_LIBRARY_DEBUG Boost_PYTHON37_LIBRARY_RELEASE
+ Boost_MPI_PYTHON2_LIBRARY_DEBUG Boost_MPI_PYTHON2_LIBRARY_RELEASE
+)
+ unset(${cachevar})
+ message(STATUS "${cachevar}: ${${cachevar}}")
+endforeach()
+
+foreach(lib Boost::headers Boost::date_time Boost::python Boost::mpi_python
+ Boost::boost Boost::diagnostic_definitions Boost::disable_autolinking Boost::dynamic_linking
+)
+ if(NOT TARGET ${lib})
+ message(FATAL_ERROR "Missing target ${lib}")
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/FindBoost/MissingTarget-stdout.txt b/Tests/RunCMake/FindBoost/MissingTarget-stdout.txt
new file mode 100644
index 000000000..8e9d684c8
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MissingTarget-stdout.txt
@@ -0,0 +1,22 @@
+-- Found Boost: [^
+]* \(found suitable version "1\.70\.42", minimum required is "1\.70"\) found components: date_time *
+-- Boost_FOUND: TRUE
+-- Boost_INCLUDE_DIRS: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/include
+-- Boost_LIBRARY_DIRS: *
+-- Boost_LIBRARIES: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/lib/libboost_date_time.a
+-- Boost_DATE_TIME_FOUND: 1
+-- Boost_DATE_TIME_LIBRARY: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/lib/libboost_date_time.a
+-- Boost_VERSION_MACRO: 1070042
+-- Boost_VERSION_STRING: 1.70.42
+-- Boost_VERSION: 1.70.42
+-- Boost_LIB_VERSION: 1_70_42
+-- Boost_MAJOR_VERSION: 1
+-- Boost_MINOR_VERSION: 70
+-- Boost_SUBMINOR_VERSION: 42
+-- Boost_INCLUDE_DIR: [^
+]*/Tests/RunCMake/FindBoost/CMakePackage_MissingTarget/include
+-- Boost_DATE_TIME_LIBRARY_DEBUG: *
+-- Boost_DATE_TIME_LIBRARY_RELEASE: *
diff --git a/Tests/RunCMake/FindBoost/MissingTarget.cmake b/Tests/RunCMake/FindBoost/MissingTarget.cmake
new file mode 100644
index 000000000..581e0065f
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MissingTarget.cmake
@@ -0,0 +1,25 @@
+set(Boost_DIR ${CMAKE_CURRENT_SOURCE_DIR}/CMakePackage_MissingTarget)
+find_package(Boost 1.70 COMPONENTS date_time)
+
+foreach(var Boost_FOUND Boost_INCLUDE_DIRS Boost_LIBRARY_DIRS Boost_LIBRARIES
+ Boost_DATE_TIME_FOUND Boost_DATE_TIME_LIBRARY
+ Boost_VERSION_MACRO Boost_VERSION_STRING Boost_VERSION Boost_LIB_VERSION
+ Boost_MAJOR_VERSION Boost_MINOR_VERSION Boost_SUBMINOR_VERSION
+)
+ message(STATUS "${var}: ${${var}}")
+endforeach()
+
+foreach(cachevar Boost_INCLUDE_DIR
+ Boost_DATE_TIME_LIBRARY_DEBUG Boost_DATE_TIME_LIBRARY_RELEASE
+)
+ unset(${cachevar})
+ message(STATUS "${cachevar}: ${${cachevar}}")
+endforeach()
+
+foreach(lib Boost::headers
+ Boost::boost Boost::diagnostic_definitions Boost::disable_autolinking Boost::dynamic_linking
+)
+ if(NOT TARGET ${lib})
+ message(FATAL_ERROR "Missing target ${lib}")
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/chrono.hpp b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/chrono.hpp
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/chrono.hpp
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/config.hpp b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/config.hpp
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/config.hpp
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/system/config.hpp b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/system/config.hpp
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/system/config.hpp
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/timer.hpp b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/timer.hpp
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/timer.hpp
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/version.hpp b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/version.hpp
new file mode 100644
index 000000000..3ca02b32a
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/include/boost/version.hpp
@@ -0,0 +1,34 @@
+// Boost version.hpp configuration header file
+// ------------------------------//
+
+// (C) Copyright John maddock 1999. Distributed under the Boost
+// Software License, Version 1.0. (See accompanying file
+// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
+
+// See http://www.boost.org/libs/config for documentation
+
+#ifndef BOOST_VERSION_HPP
+#define BOOST_VERSION_HPP
+
+//
+// Caution: this is the only Boost header that is guaranteed
+// to change with every Boost release. Including this header
+// will cause a recompile every time a new Boost version is
+// used.
+//
+// BOOST_VERSION % 100 is the patch level
+// BOOST_VERSION / 100 % 1000 is the minor version
+// BOOST_VERSION / 100000 is the major version
+
+#define BOOST_VERSION 107000
+
+//
+// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
+// but as a *string* in the form "x_y[_z]" where x is the major version
+// number, y is the minor version number, and z is the patch level if not 0.
+// This is used by <config/auto_link.hpp> to select which library version to
+// link to.
+
+#define BOOST_LIB_VERSION "1_70"
+
+#endif
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_chrono-mt-1_70.lib b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_chrono-mt-1_70.lib
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_chrono-mt-1_70.lib
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_system-mt-1_70.lib b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_system-mt-1_70.lib
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_system-mt-1_70.lib
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_timer-mt-1_70.lib b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_timer-mt-1_70.lib
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/boost_timer-mt-1_70.lib
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono-mt-1_70.lib b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono-mt-1_70.lib
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono-mt-1_70.lib
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono.a b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono.a
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono.a
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono.so.1.70.0 b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono.so.1.70.0
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_chrono.so.1.70.0
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system-mt-1_70.lib b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system-mt-1_70.lib
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system-mt-1_70.lib
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system.a b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system.a
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system.a
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system.so.1.70.0 b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system.so.1.70.0
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_system.so.1.70.0
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer-mt-1_70.lib b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer-mt-1_70.lib
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer-mt-1_70.lib
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer.a b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer.a
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer.a
diff --git a/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer.so.1.70.0 b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer.so.1.70.0
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/MockInstalls/1.70.0/lib/libboost_timer.so.1.70.0
diff --git a/Tests/RunCMake/FindBoost/ModuleMode.cmake b/Tests/RunCMake/FindBoost/ModuleMode.cmake
new file mode 100644
index 000000000..823fc53d4
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/ModuleMode.cmake
@@ -0,0 +1,4 @@
+set(BOOST_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/MockInstalls/1.70.0)
+set(Boost_NO_BOOST_CMAKE ON)
+set(Boost_NO_SYSTEM_PATHS ON)
+include(${CMAKE_CURRENT_SOURCE_DIR}/CommonResults.cmake)
diff --git a/Tests/RunCMake/FindBoost/ModuleModeNotFound.cmake b/Tests/RunCMake/FindBoost/ModuleModeNotFound.cmake
new file mode 100644
index 000000000..aaffbf2a1
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/ModuleModeNotFound.cmake
@@ -0,0 +1,4 @@
+set(BOOST_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/MockInstalls/1.70.0)
+set(Boost_NO_BOOST_CMAKE ON)
+set(Boost_NO_SYSTEM_PATHS ON)
+include(${CMAKE_CURRENT_SOURCE_DIR}/CommonNotFound.cmake)
diff --git a/Tests/RunCMake/FindBoost/NoCXX-stderr.txt b/Tests/RunCMake/FindBoost/NoCXX-stderr.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/NoCXX-stderr.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/FindBoost/NoCXX.cmake b/Tests/RunCMake/FindBoost/NoCXX.cmake
new file mode 100644
index 000000000..04b9cac61
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/NoCXX.cmake
@@ -0,0 +1 @@
+find_package(Boost)
diff --git a/Tests/RunCMake/FindBoost/RunCMakeTest.cmake b/Tests/RunCMake/FindBoost/RunCMakeTest.cmake
new file mode 100644
index 000000000..851a996db
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/RunCMakeTest.cmake
@@ -0,0 +1,28 @@
+include(RunCMake)
+unset(ENV{Boost_ROOT})
+
+run_cmake(CMakePackage)
+run_cmake(NoCXX)
+
+run_cmake(LegacyVars-TargetsDefined) # "Good" BoostConfig
+run_cmake(LegacyVars-LowercaseTargetPrefix)
+set(RunCMake-stdout-file LegacyVars-TargetsDefined-stdout.txt)
+run_cmake(LegacyVars-NoHeaderTarget)
+
+unset(RunCMake-stdout-file)
+run_cmake(MissingTarget)
+
+set(RunCMake-stdout-file CommonResults-stdout.txt)
+run_cmake(ConfigMode)
+run_cmake(ModuleMode)
+unset(RunCMake-stdout-file)
+set(RunCMake-stdout-file CommonNotFound-stdout.txt)
+set(RunCMake-stderr-file CommonNotFound-stderr.txt)
+run_cmake(ConfigModeNotFound)
+run_cmake(ModuleModeNotFound)
+unset(RunCMake-stdout-file)
+unset(RunCMake-stderr-file)
+
+run_cmake(CMP0093-NEW)
+run_cmake(CMP0093-OLD)
+run_cmake(CMP0093-UNSET)
diff --git a/Tests/RunCMake/FindLua/CMakeLists.txt b/Tests/RunCMake/FindLua/CMakeLists.txt
new file mode 100644
index 000000000..a2c4d9812
--- /dev/null
+++ b/Tests/RunCMake/FindLua/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.4)
+project(${RunCMake_TEST} C)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/FindLua/FindLuaTest.cmake b/Tests/RunCMake/FindLua/FindLuaTest.cmake
new file mode 100644
index 000000000..610d544de
--- /dev/null
+++ b/Tests/RunCMake/FindLua/FindLuaTest.cmake
@@ -0,0 +1,87 @@
+unset(VERSION)
+
+# Ignore all default paths for this test to avoid finding system Lua
+set(CMAKE_INCLUDE_PATH )
+set(CMAKE_PREFIX_PATH )
+set(CMAKE_FRAMEWORK_PATH )
+
+set(ENV{CMAKE_INCLUDE_PATH} )
+set(ENV{CMAKE_PREFIX_PATH} )
+set(ENV{CMAKE_FRAMEWORK_PATH} )
+
+set(ENV{PATH} )
+set(ENV{INCLUDE} )
+
+set(CMAKE_SYSTEM_INCLUDE_PATH )
+set(CMAKE_SYSTEM_PREFIX_PATH )
+set(CMAKE_SYSTEM_FRAMEWORK_PATH )
+
+function(require_found path version)
+ find_package(Lua ${VERSION} QUIET)
+ if(NOT "${LUA_INCLUDE_DIR}" STREQUAL "${path}")
+ message(FATAL_ERROR "LUA_INCLUDE_PATH != path: '${LUA_INCLUDE_DIR}' != '${path}'")
+ endif()
+ if(NOT LUA_VERSION_STRING MATCHES "^${version}\.[0-9]$")
+ message(FATAL_ERROR "Wrong versionfound in '${LUA_INCLUDE_DIR}': ${LUA_VERSION_STRING} != ${version}")
+ endif()
+endfunction()
+
+# Use functions for scoping and better error messages
+function(require_find path version)
+ unset(LUA_INCLUDE_DIR CACHE)
+ require_found(${lua_path} ${version})
+endfunction()
+
+function(test_prefix_path path lua_path version)
+ set(CMAKE_PREFIX_PATH ${path})
+ require_find(lua_path ${version})
+endfunction()
+
+function(test_include_path path lua_path version)
+ set(CMAKE_INCLUDE_PATH ${path})
+ require_find(lua_path ${version})
+endfunction()
+
+function(test_env_path path lua_path version)
+ set(ENV{LUA_DIR} ${path})
+ require_find(lua_path ${version})
+ unset(ENV{LUA_DIR})
+endfunction()
+
+function(test_path prefix_path lua_path version)
+ # Shortcut: Make paths relative to current list dir
+ set(prefix_path ${CMAKE_CURRENT_LIST_DIR}/${prefix_path})
+ set(lua_path ${CMAKE_CURRENT_LIST_DIR}/${lua_path})
+
+ test_prefix_path(${prefix_path} ${lua_path} ${version})
+ test_include_path(${prefix_path}/include ${lua_path} ${version})
+ test_env_path(${prefix_path} ${lua_path} ${version})
+endfunction()
+
+# Simple test
+test_path(prefix1 prefix1/include 5.3)
+# Find highest version
+test_path(prefix2 prefix2/include/lua5.3 5.3)
+foreach(ver 5.3 5.2 5.1)
+ # At least X or X.0 -> Highest
+ set(VERSION "${ver}")
+ test_path(prefix2 prefix2/include/lua5.3 5.3)
+ set(VERSION "${ver}.0")
+ test_path(prefix2 prefix2/include/lua5.3 5.3)
+ # Exactly X/X.0
+ set(VERSION "${ver}" EXACT)
+ test_path(prefix2 prefix2/include/lua${ver} ${ver})
+ set(VERSION "${ver}.0" EXACT)
+ test_path(prefix2 prefix2/include/lua${ver} ${ver})
+endforeach()
+
+# Find unknown version
+set(VERSION "5.9")
+test_path(prefix2 prefix2/include/lua5.9 5.9)
+set(VERSION "5.9" EXACT)
+test_path(prefix2 prefix2/include/lua5.9 5.9)
+
+# Set LUA_INCLUDE_DIR (non-cache) to unsuitable version
+set(LUA_INCLUDE_DIR ${CMAKE_CURRENT_LIST_DIR}/prefix2/include/lua5.2)
+set(VERSION "5.1" EXACT)
+test_path(prefix2 prefix2/include/lua5.1 5.1)
diff --git a/Tests/RunCMake/FindLua/RunCMakeTest.cmake b/Tests/RunCMake/FindLua/RunCMakeTest.cmake
new file mode 100644
index 000000000..3f180333a
--- /dev/null
+++ b/Tests/RunCMake/FindLua/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(FindLuaTest)
diff --git a/Tests/RunCMake/FindLua/prefix1/include/lua.h b/Tests/RunCMake/FindLua/prefix1/include/lua.h
new file mode 100644
index 000000000..d33434a5e
--- /dev/null
+++ b/Tests/RunCMake/FindLua/prefix1/include/lua.h
@@ -0,0 +1,8 @@
+
+#define LUA_VERSION_MAJOR "5"
+#define LUA_VERSION_MINOR "3"
+#define LUA_VERSION_NUM 503
+#define LUA_VERSION_RELEASE "4"
+
+#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
+#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
diff --git a/Tests/RunCMake/FindLua/prefix2/include/lua5.1/lua.h b/Tests/RunCMake/FindLua/prefix2/include/lua5.1/lua.h
new file mode 100644
index 000000000..661e62c73
--- /dev/null
+++ b/Tests/RunCMake/FindLua/prefix2/include/lua5.1/lua.h
@@ -0,0 +1,8 @@
+
+#define LUA_VERSION_MAJOR "5"
+#define LUA_VERSION_MINOR "1"
+#define LUA_VERSION_NUM 501
+#define LUA_VERSION_RELEASE "4"
+
+#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
+#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
diff --git a/Tests/RunCMake/FindLua/prefix2/include/lua5.2/lua.h b/Tests/RunCMake/FindLua/prefix2/include/lua5.2/lua.h
new file mode 100644
index 000000000..d53f326cc
--- /dev/null
+++ b/Tests/RunCMake/FindLua/prefix2/include/lua5.2/lua.h
@@ -0,0 +1,8 @@
+
+#define LUA_VERSION_MAJOR "5"
+#define LUA_VERSION_MINOR "2"
+#define LUA_VERSION_NUM 502
+#define LUA_VERSION_RELEASE "4"
+
+#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
+#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
diff --git a/Tests/RunCMake/FindLua/prefix2/include/lua5.3/lua.h b/Tests/RunCMake/FindLua/prefix2/include/lua5.3/lua.h
new file mode 100644
index 000000000..d33434a5e
--- /dev/null
+++ b/Tests/RunCMake/FindLua/prefix2/include/lua5.3/lua.h
@@ -0,0 +1,8 @@
+
+#define LUA_VERSION_MAJOR "5"
+#define LUA_VERSION_MINOR "3"
+#define LUA_VERSION_NUM 503
+#define LUA_VERSION_RELEASE "4"
+
+#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
+#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
diff --git a/Tests/RunCMake/FindLua/prefix2/include/lua5.9/lua.h b/Tests/RunCMake/FindLua/prefix2/include/lua5.9/lua.h
new file mode 100644
index 000000000..730f7cc21
--- /dev/null
+++ b/Tests/RunCMake/FindLua/prefix2/include/lua5.9/lua.h
@@ -0,0 +1,8 @@
+
+#define LUA_VERSION_MAJOR "5"
+#define LUA_VERSION_MINOR "9"
+#define LUA_VERSION_NUM 509
+#define LUA_VERSION_RELEASE "4"
+
+#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
+#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
diff --git a/Tests/RunCMake/FindOpenGL/CMP0072-NEW-stdout.txt b/Tests/RunCMake/FindOpenGL/CMP0072-NEW-stdout.txt
new file mode 100644
index 000000000..f5ee220b2
--- /dev/null
+++ b/Tests/RunCMake/FindOpenGL/CMP0072-NEW-stdout.txt
@@ -0,0 +1,3 @@
+-- OpenGL_GL_PREFERENCE='GLVND'
+-- OPENGL_gl_LIBRARY=''
+-- OPENGL_LIBRARIES='OpenGL;GLX;GLU'
diff --git a/Tests/RunCMake/FindOpenGL/CMP0072-NEW.cmake b/Tests/RunCMake/FindOpenGL/CMP0072-NEW.cmake
new file mode 100644
index 000000000..6cbbeec75
--- /dev/null
+++ b/Tests/RunCMake/FindOpenGL/CMP0072-NEW.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0072 NEW)
+include(CMP0072-common.cmake)
diff --git a/Tests/RunCMake/FindOpenGL/CMP0072-OLD-stdout.txt b/Tests/RunCMake/FindOpenGL/CMP0072-OLD-stdout.txt
new file mode 100644
index 000000000..22df1b12d
--- /dev/null
+++ b/Tests/RunCMake/FindOpenGL/CMP0072-OLD-stdout.txt
@@ -0,0 +1,3 @@
+-- OpenGL_GL_PREFERENCE='LEGACY'
+-- OPENGL_gl_LIBRARY='GL'
+-- OPENGL_LIBRARIES='GL;GLU'
diff --git a/Tests/RunCMake/FindOpenGL/CMP0072-OLD.cmake b/Tests/RunCMake/FindOpenGL/CMP0072-OLD.cmake
new file mode 100644
index 000000000..6d570043a
--- /dev/null
+++ b/Tests/RunCMake/FindOpenGL/CMP0072-OLD.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0072 OLD)
+include(CMP0072-common.cmake)
diff --git a/Tests/RunCMake/FindOpenGL/CMP0072-WARN-stderr.txt b/Tests/RunCMake/FindOpenGL/CMP0072-WARN-stderr.txt
new file mode 100644
index 000000000..f26f217b0
--- /dev/null
+++ b/Tests/RunCMake/FindOpenGL/CMP0072-WARN-stderr.txt
@@ -0,0 +1,21 @@
+^CMake Warning \(dev\) at .*/Modules/FindOpenGL.cmake:[0-9]+ \(message\):
+ Policy CMP0072 is not set: FindOpenGL prefers GLVND by default when
+ available. Run "cmake --help-policy CMP0072" for policy details. Use the
+ cmake_policy command to set the policy and suppress this warning.
+
+ FindOpenGL found both a legacy GL library:
+
+ OPENGL_gl_LIBRARY: GL
+
+ and GLVND libraries for OpenGL and GLX:
+
+ OPENGL_opengl_LIBRARY: OpenGL
+ OPENGL_glx_LIBRARY: GLX
+
+ OpenGL_GL_PREFERENCE has not been set to "GLVND" or "LEGACY", so for
+ compatibility with CMake 3.10 and below the legacy GL library will be used.
+Call Stack \(most recent call first\):
+ CMP0072-common.cmake:[0-9]+ \(find_package\)
+ CMP0072-WARN.cmake:[0-9]+ \(include\)
+ CMakeLists.txt:[0-9]+ \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/FindOpenGL/CMP0072-WARN-stdout.txt b/Tests/RunCMake/FindOpenGL/CMP0072-WARN-stdout.txt
new file mode 100644
index 000000000..22df1b12d
--- /dev/null
+++ b/Tests/RunCMake/FindOpenGL/CMP0072-WARN-stdout.txt
@@ -0,0 +1,3 @@
+-- OpenGL_GL_PREFERENCE='LEGACY'
+-- OPENGL_gl_LIBRARY='GL'
+-- OPENGL_LIBRARIES='GL;GLU'
diff --git a/Tests/RunCMake/FindOpenGL/CMP0072-WARN.cmake b/Tests/RunCMake/FindOpenGL/CMP0072-WARN.cmake
new file mode 100644
index 000000000..459c4583b
--- /dev/null
+++ b/Tests/RunCMake/FindOpenGL/CMP0072-WARN.cmake
@@ -0,0 +1 @@
+include(CMP0072-common.cmake)
diff --git a/Tests/RunCMake/FindOpenGL/CMP0072-common.cmake b/Tests/RunCMake/FindOpenGL/CMP0072-common.cmake
new file mode 100644
index 000000000..3fe80309b
--- /dev/null
+++ b/Tests/RunCMake/FindOpenGL/CMP0072-common.cmake
@@ -0,0 +1,13 @@
+set(CYGWIN 0)
+set(WIN32 0)
+set(APPLE 0)
+set(OPENGL_INCLUDE_DIR GL/include)
+set(OPENGL_GLX_INCLUDE_DIR GLX/include)
+set(OPENGL_gl_LIBRARY GL)
+set(OPENGL_opengl_LIBRARY OpenGL)
+set(OPENGL_glx_LIBRARY GLX)
+set(OPENGL_glu_LIBRARY GLU)
+find_package(OpenGL)
+message(STATUS "OpenGL_GL_PREFERENCE='${OpenGL_GL_PREFERENCE}'")
+message(STATUS "OPENGL_gl_LIBRARY='${OPENGL_gl_LIBRARY}'")
+message(STATUS "OPENGL_LIBRARIES='${OPENGL_LIBRARIES}'")
diff --git a/Tests/RunCMake/FindOpenGL/CMakeLists.txt b/Tests/RunCMake/FindOpenGL/CMakeLists.txt
new file mode 100644
index 000000000..bf2ef1506
--- /dev/null
+++ b/Tests/RunCMake/FindOpenGL/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/FindOpenGL/RunCMakeTest.cmake b/Tests/RunCMake/FindOpenGL/RunCMakeTest.cmake
new file mode 100644
index 000000000..fcc130f55
--- /dev/null
+++ b/Tests/RunCMake/FindOpenGL/RunCMakeTest.cmake
@@ -0,0 +1,5 @@
+include(RunCMake)
+
+run_cmake(CMP0072-WARN)
+run_cmake(CMP0072-OLD)
+run_cmake(CMP0072-NEW)
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_GET_VARIABLE_PKGCONFIG_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_GET_VARIABLE_PKGCONFIG_PATH.cmake
new file mode 100644
index 000000000..f5f5c8cea
--- /dev/null
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_GET_VARIABLE_PKGCONFIG_PATH.cmake
@@ -0,0 +1,21 @@
+# Prepare environment and variables
+set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH FALSE)
+if(WIN32)
+ set(ENV{CMAKE_PREFIX_PATH} "C:\\baz")
+ set(ENV{PKG_CONFIG_PATH} "${CMAKE_CURRENT_SOURCE_DIR}\\pc-bletch\\lib\\pkgconfig;X:\\this\\directory\\should\\not\\exist\\in\\the\\filesystem")
+else()
+ set(ENV{CMAKE_PREFIX_PATH} "/baz")
+ set(ENV{PKG_CONFIG_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/pc-bletch/lib/pkgconfig:/this/directory/should/not/exist/in/the/filesystem")
+endif()
+
+find_package(PkgConfig REQUIRED)
+pkg_check_modules(BLETCH QUIET bletch)
+
+if (NOT BLETCH_FOUND)
+ message(FATAL_ERROR "Failed to find embedded package bletch via PKG_CONFIG_PATH")
+endif ()
+
+pkg_get_variable(bletchvar bletch jackpot)
+if (NOT bletchvar STREQUAL "bletch-lives")
+ message(FATAL_ERROR "Failed to fetch variable jackpot from embedded package bletch via PKG_CONFIG_PATH")
+endif ()
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_GET_VARIABLE_PREFIX_PATH.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_GET_VARIABLE_PREFIX_PATH.cmake
new file mode 100644
index 000000000..cfc0760df
--- /dev/null
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_GET_VARIABLE_PREFIX_PATH.cmake
@@ -0,0 +1,21 @@
+# Prepare environment and variables
+set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH TRUE)
+if(WIN32)
+ set(ENV{CMAKE_PREFIX_PATH} "${CMAKE_CURRENT_SOURCE_DIR}\\pc-bletch;X:\\this\\directory\\should\\not\\exist\\in\\the\\filesystem")
+ set(ENV{PKG_CONFIG_PATH} "C:\\baz")
+else()
+ set(ENV{CMAKE_PREFIX_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/pc-bletch:/this/directory/should/not/exist/in/the/filesystem")
+ set(ENV{PKG_CONFIG_PATH} "/baz")
+endif()
+
+find_package(PkgConfig REQUIRED)
+pkg_check_modules(BLETCH QUIET bletch)
+
+if (NOT BLETCH_FOUND)
+ message(FATAL_ERROR "Failed to find embedded package bletch via CMAKE_PREFIX_PATH")
+endif ()
+
+pkg_get_variable(bletchvar bletch jackpot)
+if (NOT bletchvar STREQUAL "bletch-lives")
+ message(FATAL_ERROR "Failed to fetch variable jackpot from embedded package bletch via CMAKE_PREFIX_PATH")
+endif ()
diff --git a/Tests/RunCMake/FindPkgConfig/FindPkgConfig_VERSION_OPERATORS.cmake b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_VERSION_OPERATORS.cmake
new file mode 100644
index 000000000..2a505c6a5
--- /dev/null
+++ b/Tests/RunCMake/FindPkgConfig/FindPkgConfig_VERSION_OPERATORS.cmake
@@ -0,0 +1,83 @@
+cmake_minimum_required(VERSION 3.12)
+
+project(FindPkgConfig_IMPORTED_TARGET C)
+
+find_package(PkgConfig REQUIRED)
+
+message(STATUS "source: ${CMAKE_CURRENT_SOURCE_DIR} bin ${CMAKE_CURRENT_BINARY_DIR}")
+
+# Setup for the remaining package tests below
+set(PKG_CONFIG_USE_CMAKE_PREFIX_PATH)
+set(fakePkgDir ${CMAKE_CURRENT_BINARY_DIR}/pc-fakepackage)
+file(WRITE ${fakePkgDir}/lib/libcmakeinternalfakepackage.a "")
+file(WRITE ${fakePkgDir}/lib/cmakeinternalfakepackage.lib "")
+file(WRITE ${fakePkgDir}/lib/pkgconfig/cmakeinternalfakepackage.pc
+"Name: CMakeInternalFakePackage
+Description: Dummy package for FindPkgConfig VERSION_OPERATORS test
+Version: 8.9
+Libs: -lcmakeinternalfakepackage
+")
+
+# Always find the .pc file in the calls further below so that we can test that
+# the import target find_library() calls handle the NO...PATH options correctly
+set(ENV{PKG_CONFIG_PATH} ${fakePkgDir}/lib/pkgconfig)
+
+pkg_check_modules(FakePackageGE REQUIRED QUIET "cmakeinternalfakepackage >= 8")
+if (NOT FakePackageGE_FOUND)
+ message(FATAL_ERROR "fake package >= 8 not found")
+endif()
+
+pkg_check_modules(FakePackageGE_FAIL QUIET "cmakeinternalfakepackage >= 8.10")
+if (FakePackageGE_FAIL_FOUND)
+ message(FATAL_ERROR "fake package >= 8.10 found")
+endif()
+
+pkg_check_modules(FakePackageLE REQUIRED QUIET "cmakeinternalfakepackage<=9")
+if (NOT FakePackageLE_FOUND)
+ message(FATAL_ERROR "fake package <= 9 not found")
+endif()
+
+pkg_check_modules(FakePackageLE_FAIL QUIET "cmakeinternalfakepackage <= 8.1")
+if (FakePackageLE_FAIL_FOUND)
+ message(FATAL_ERROR "fake package <= 8.1 found")
+endif()
+
+pkg_check_modules(FakePackageGT REQUIRED QUIET "cmakeinternalfakepackage > 8")
+if (NOT FakePackageGT_FOUND)
+ message(FATAL_ERROR "fake package > 8 not found")
+endif()
+
+pkg_check_modules(FakePackageGT_FAIL QUIET "cmakeinternalfakepackage > 8.9")
+if (FakePackageGT_FAIL_FOUND)
+ message(FATAL_ERROR "fake package > 8.9 found")
+endif()
+
+pkg_check_modules(FakePackageLT REQUIRED QUIET "cmakeinternalfakepackage<9")
+if (NOT FakePackageLT_FOUND)
+ message(FATAL_ERROR "fake package < 9 not found")
+endif()
+
+pkg_check_modules(FakePackageLT_FAIL QUIET "cmakeinternalfakepackage < 8.9")
+if (FakePackageLT_FAIL_FOUND)
+ message(FATAL_ERROR "fake package < 8.9 found")
+endif()
+
+pkg_check_modules(FakePackageEQ REQUIRED QUIET "cmakeinternalfakepackage=8.9")
+if (NOT FakePackageEQ_FOUND)
+ message(FATAL_ERROR "fake package = 8.9 not found")
+endif()
+
+pkg_check_modules(FakePackageEQ_FAIL QUIET "cmakeinternalfakepackage = 8.8")
+if (FakePackageEQ_FAIL_FOUND)
+ message(FATAL_ERROR "fake package = 8.8 found")
+endif()
+
+pkg_check_modules(FakePackageEQ_INV QUIET "cmakeinternalfakepackage == 8.9")
+if (FakePackageEQ_FAIL_FOUND)
+ message(FATAL_ERROR "fake package == 8.9 found")
+endif()
+
+pkg_check_modules(FakePackageLLT_INV QUIET "cmakeinternalfakepackage <<= 9")
+if (FakePackageLLT_FAIL_FOUND)
+ message(FATAL_ERROR "fake package <<= 9 found")
+endif()
diff --git a/Tests/RunCMake/FindPkgConfig/pc-bletch/lib/pkgconfig/bletch.pc b/Tests/RunCMake/FindPkgConfig/pc-bletch/lib/pkgconfig/bletch.pc
new file mode 100644
index 000000000..04d2c1b00
--- /dev/null
+++ b/Tests/RunCMake/FindPkgConfig/pc-bletch/lib/pkgconfig/bletch.pc
@@ -0,0 +1,12 @@
+prefix=/opt/bletch
+exec_prefix=${prefix}
+libdir=${exec_prefix}/lib
+includedir=${prefix}/include
+
+jackpot=bletch-lives
+
+Name: Bletch
+Description: Dummy packaget to test variable support
+Version: 1.0
+Libs: -L${libdir} -lbletch
+Cflags: -Dbletch_version=1
diff --git a/Tests/RunCMake/FindPkgConfig/target_subdir/CMakeLists.txt b/Tests/RunCMake/FindPkgConfig/target_subdir/CMakeLists.txt
new file mode 100644
index 000000000..2171ef6d8
--- /dev/null
+++ b/Tests/RunCMake/FindPkgConfig/target_subdir/CMakeLists.txt
@@ -0,0 +1,5 @@
+# a target with visibility only in this directory
+pkg_check_modules(FakePackage1_dir REQUIRED QUIET IMPORTED_TARGET cmakeinternalfakepackage1)
+
+# the same with global visibility
+pkg_check_modules(FakePackage1_global REQUIRED QUIET IMPORTED_TARGET GLOBAL cmakeinternalfakepackage1)
diff --git a/Tests/RunCMake/Framework/InstallBeforeFramework-stderr.txt b/Tests/RunCMake/Framework/InstallBeforeFramework-stderr.txt
new file mode 100644
index 000000000..a3a7c6cbb
--- /dev/null
+++ b/Tests/RunCMake/Framework/InstallBeforeFramework-stderr.txt
@@ -0,0 +1,7 @@
+^CMake Warning \(dev\) at InstallBeforeFramework.cmake:4 \(install\):
+ Target 'foo' was changed to a FRAMEWORK sometime after install\(\). This may
+ result in the wrong install DESTINATION. Set the FRAMEWORK property
+ earlier.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/Framework/InstallBeforeFramework.cmake b/Tests/RunCMake/Framework/InstallBeforeFramework.cmake
new file mode 100644
index 000000000..3791dace7
--- /dev/null
+++ b/Tests/RunCMake/Framework/InstallBeforeFramework.cmake
@@ -0,0 +1,5 @@
+enable_language(C)
+
+add_library(foo SHARED foo.c)
+install(TARGETS foo LIBRARY DESTINATION lib)
+set_property(TARGET foo PROPERTY FRAMEWORK TRUE)
diff --git a/Tests/RunCMake/GNUInstallDirs/Opt-FreeBSD-stderr.txt b/Tests/RunCMake/GNUInstallDirs/Opt-FreeBSD-stderr.txt
new file mode 100644
index 000000000..feb747b18
--- /dev/null
+++ b/Tests/RunCMake/GNUInstallDirs/Opt-FreeBSD-stderr.txt
@@ -0,0 +1,30 @@
+^CMAKE_INSTALL_BINDIR='bin'
+CMAKE_INSTALL_DATADIR='share'
+CMAKE_INSTALL_DATAROOTDIR='share'
+CMAKE_INSTALL_DOCDIR='share/doc/Opt'
+CMAKE_INSTALL_INCLUDEDIR='include'
+CMAKE_INSTALL_INFODIR='share/info'
+CMAKE_INSTALL_LIBDIR='(lib|lib64)'
+CMAKE_INSTALL_LIBEXECDIR='libexec'
+CMAKE_INSTALL_LOCALEDIR='share/locale'
+CMAKE_INSTALL_LOCALSTATEDIR='var'
+CMAKE_INSTALL_RUNSTATEDIR='var/run'
+CMAKE_INSTALL_MANDIR='man'
+CMAKE_INSTALL_SBINDIR='sbin'
+CMAKE_INSTALL_SHAREDSTATEDIR='com'
+CMAKE_INSTALL_SYSCONFDIR='etc'
+CMAKE_INSTALL_FULL_BINDIR='/opt/Opt/bin'
+CMAKE_INSTALL_FULL_DATADIR='/opt/Opt/share'
+CMAKE_INSTALL_FULL_DATAROOTDIR='/opt/Opt/share'
+CMAKE_INSTALL_FULL_DOCDIR='/opt/Opt/share/doc/Opt'
+CMAKE_INSTALL_FULL_INCLUDEDIR='/opt/Opt/include'
+CMAKE_INSTALL_FULL_INFODIR='/opt/Opt/share/info'
+CMAKE_INSTALL_FULL_LIBDIR='/opt/Opt/(lib|lib64)'
+CMAKE_INSTALL_FULL_LIBEXECDIR='/opt/Opt/libexec'
+CMAKE_INSTALL_FULL_LOCALEDIR='/opt/Opt/share/locale'
+CMAKE_INSTALL_FULL_LOCALSTATEDIR='/var/opt/Opt'
+CMAKE_INSTALL_FULL_RUNSTATEDIR='/var/run/opt/Opt'
+CMAKE_INSTALL_FULL_MANDIR='/opt/Opt/man'
+CMAKE_INSTALL_FULL_SBINDIR='/opt/Opt/sbin'
+CMAKE_INSTALL_FULL_SHAREDSTATEDIR='/opt/Opt/com'
+CMAKE_INSTALL_FULL_SYSCONFDIR='/etc/opt/Opt'$
diff --git a/Tests/RunCMake/GNUInstallDirs/Root-FreeBSD-stderr.txt b/Tests/RunCMake/GNUInstallDirs/Root-FreeBSD-stderr.txt
new file mode 100644
index 000000000..4284a15b1
--- /dev/null
+++ b/Tests/RunCMake/GNUInstallDirs/Root-FreeBSD-stderr.txt
@@ -0,0 +1,30 @@
+^CMAKE_INSTALL_BINDIR='usr/bin'
+CMAKE_INSTALL_DATADIR='usr/share'
+CMAKE_INSTALL_DATAROOTDIR='usr/share'
+CMAKE_INSTALL_DOCDIR='usr/share/doc/Root'
+CMAKE_INSTALL_INCLUDEDIR='usr/include'
+CMAKE_INSTALL_INFODIR='usr/share/info'
+CMAKE_INSTALL_LIBDIR='usr/(lib|lib64)'
+CMAKE_INSTALL_LIBEXECDIR='usr/libexec'
+CMAKE_INSTALL_LOCALEDIR='usr/share/locale'
+CMAKE_INSTALL_LOCALSTATEDIR='var'
+CMAKE_INSTALL_RUNSTATEDIR='var/run'
+CMAKE_INSTALL_MANDIR='usr/man'
+CMAKE_INSTALL_SBINDIR='usr/sbin'
+CMAKE_INSTALL_SHAREDSTATEDIR='usr/com'
+CMAKE_INSTALL_SYSCONFDIR='etc'
+CMAKE_INSTALL_FULL_BINDIR='/usr/bin'
+CMAKE_INSTALL_FULL_DATADIR='/usr/share'
+CMAKE_INSTALL_FULL_DATAROOTDIR='/usr/share'
+CMAKE_INSTALL_FULL_DOCDIR='/usr/share/doc/Root'
+CMAKE_INSTALL_FULL_INCLUDEDIR='/usr/include'
+CMAKE_INSTALL_FULL_INFODIR='/usr/share/info'
+CMAKE_INSTALL_FULL_LIBDIR='/usr/(lib|lib64)'
+CMAKE_INSTALL_FULL_LIBEXECDIR='/usr/libexec'
+CMAKE_INSTALL_FULL_LOCALEDIR='/usr/share/locale'
+CMAKE_INSTALL_FULL_LOCALSTATEDIR='/var'
+CMAKE_INSTALL_FULL_RUNSTATEDIR='/var/run'
+CMAKE_INSTALL_FULL_MANDIR='/usr/man'
+CMAKE_INSTALL_FULL_SBINDIR='/usr/sbin'
+CMAKE_INSTALL_FULL_SHAREDSTATEDIR='/usr/com'
+CMAKE_INSTALL_FULL_SYSCONFDIR='/etc'$
diff --git a/Tests/RunCMake/GNUInstallDirs/Usr-FreeBSD-stderr.txt b/Tests/RunCMake/GNUInstallDirs/Usr-FreeBSD-stderr.txt
new file mode 100644
index 000000000..9efc1103e
--- /dev/null
+++ b/Tests/RunCMake/GNUInstallDirs/Usr-FreeBSD-stderr.txt
@@ -0,0 +1,30 @@
+^CMAKE_INSTALL_BINDIR='bin'
+CMAKE_INSTALL_DATADIR='share'
+CMAKE_INSTALL_DATAROOTDIR='share'
+CMAKE_INSTALL_DOCDIR='share/doc/Usr'
+CMAKE_INSTALL_INCLUDEDIR='include'
+CMAKE_INSTALL_INFODIR='share/info'
+CMAKE_INSTALL_LIBDIR='(lib|lib64|lib/arch)'
+CMAKE_INSTALL_LIBEXECDIR='libexec'
+CMAKE_INSTALL_LOCALEDIR='share/locale'
+CMAKE_INSTALL_LOCALSTATEDIR='var'
+CMAKE_INSTALL_RUNSTATEDIR='var/run'
+CMAKE_INSTALL_MANDIR='man'
+CMAKE_INSTALL_SBINDIR='sbin'
+CMAKE_INSTALL_SHAREDSTATEDIR='com'
+CMAKE_INSTALL_SYSCONFDIR='etc'
+CMAKE_INSTALL_FULL_BINDIR='/usr/bin'
+CMAKE_INSTALL_FULL_DATADIR='/usr/share'
+CMAKE_INSTALL_FULL_DATAROOTDIR='/usr/share'
+CMAKE_INSTALL_FULL_DOCDIR='/usr/share/doc/Usr'
+CMAKE_INSTALL_FULL_INCLUDEDIR='/usr/include'
+CMAKE_INSTALL_FULL_INFODIR='/usr/share/info'
+CMAKE_INSTALL_FULL_LIBDIR='/usr/(lib|lib64|lib/arch)'
+CMAKE_INSTALL_FULL_LIBEXECDIR='/usr/libexec'
+CMAKE_INSTALL_FULL_LOCALEDIR='/usr/share/locale'
+CMAKE_INSTALL_FULL_LOCALSTATEDIR='/var'
+CMAKE_INSTALL_FULL_RUNSTATEDIR='/var/run'
+CMAKE_INSTALL_FULL_MANDIR='/usr/man'
+CMAKE_INSTALL_FULL_SBINDIR='/usr/sbin'
+CMAKE_INSTALL_FULL_SHAREDSTATEDIR='/usr/com'
+CMAKE_INSTALL_FULL_SYSCONFDIR='/etc'$
diff --git a/Tests/RunCMake/GNUInstallDirs/UsrLocal-FreeBSD-stderr.txt b/Tests/RunCMake/GNUInstallDirs/UsrLocal-FreeBSD-stderr.txt
new file mode 100644
index 000000000..505bf08ef
--- /dev/null
+++ b/Tests/RunCMake/GNUInstallDirs/UsrLocal-FreeBSD-stderr.txt
@@ -0,0 +1,30 @@
+^CMAKE_INSTALL_BINDIR='bin'
+CMAKE_INSTALL_DATADIR='share'
+CMAKE_INSTALL_DATAROOTDIR='share'
+CMAKE_INSTALL_DOCDIR='share/doc/UsrLocal'
+CMAKE_INSTALL_INCLUDEDIR='include'
+CMAKE_INSTALL_INFODIR='share/info'
+CMAKE_INSTALL_LIBDIR='(lib|lib64)'
+CMAKE_INSTALL_LIBEXECDIR='libexec'
+CMAKE_INSTALL_LOCALEDIR='share/locale'
+CMAKE_INSTALL_LOCALSTATEDIR='var'
+CMAKE_INSTALL_RUNSTATEDIR='var/run'
+CMAKE_INSTALL_MANDIR='man'
+CMAKE_INSTALL_SBINDIR='sbin'
+CMAKE_INSTALL_SHAREDSTATEDIR='com'
+CMAKE_INSTALL_SYSCONFDIR='etc'
+CMAKE_INSTALL_FULL_BINDIR='/usr/local/bin'
+CMAKE_INSTALL_FULL_DATADIR='/usr/local/share'
+CMAKE_INSTALL_FULL_DATAROOTDIR='/usr/local/share'
+CMAKE_INSTALL_FULL_DOCDIR='/usr/local/share/doc/UsrLocal'
+CMAKE_INSTALL_FULL_INCLUDEDIR='/usr/local/include'
+CMAKE_INSTALL_FULL_INFODIR='/usr/local/share/info'
+CMAKE_INSTALL_FULL_LIBDIR='/usr/local/(lib|lib64)'
+CMAKE_INSTALL_FULL_LIBEXECDIR='/usr/local/libexec'
+CMAKE_INSTALL_FULL_LOCALEDIR='/usr/local/share/locale'
+CMAKE_INSTALL_FULL_LOCALSTATEDIR='/usr/local/var'
+CMAKE_INSTALL_FULL_RUNSTATEDIR='/usr/local/var/run'
+CMAKE_INSTALL_FULL_MANDIR='/usr/local/man'
+CMAKE_INSTALL_FULL_SBINDIR='/usr/local/sbin'
+CMAKE_INSTALL_FULL_SHAREDSTATEDIR='/usr/local/com'
+CMAKE_INSTALL_FULL_SYSCONFDIR='/usr/local/etc'$
diff --git a/Tests/RunCMake/GenerateExportHeader/includeguard/CMakeLists.txt b/Tests/RunCMake/GenerateExportHeader/includeguard/CMakeLists.txt
new file mode 100644
index 000000000..514d27b67
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/includeguard/CMakeLists.txt
@@ -0,0 +1,19 @@
+set(libincludeguard_SRC libincludeguard.cpp)
+
+add_library(includeguard_macro ${libincludeguard_SRC})
+generate_export_header(includeguard_macro)
+
+set(EXPORT_HEADER includeguard_macro_export.h)
+set(DEF_SYMBOL INCLUDEGUARD_MACRO_EXPORT_H)
+set(NDEF_SYMBOL CUSTOM_GUARD)
+configure_file(main.cpp.in main_macro.cpp)
+add_executable(test_includeguard_macro ${CMAKE_CURRENT_BINARY_DIR}/main_macro.cpp)
+
+add_library(includeguard_custom ${libincludeguard_SRC})
+generate_export_header(includeguard_custom INCLUDE_GUARD_NAME CUSTOM_GUARD)
+
+set(EXPORT_HEADER includeguard_custom_export.h)
+set(DEF_SYMBOL CUSTOM_GUARD)
+set(NDEF_SYMBOL INCLUDEGUARD_CUSTOM_EXPORT_H)
+configure_file(main.cpp.in main_custom.cpp)
+add_executable(test_includeguard_custom ${CMAKE_CURRENT_BINARY_DIR}/main_custom.cpp)
diff --git a/Tests/RunCMake/GenerateExportHeader/includeguard/libincludeguard.cpp b/Tests/RunCMake/GenerateExportHeader/includeguard/libincludeguard.cpp
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/includeguard/libincludeguard.cpp
diff --git a/Tests/RunCMake/GenerateExportHeader/includeguard/main.cpp.in b/Tests/RunCMake/GenerateExportHeader/includeguard/main.cpp.in
new file mode 100644
index 000000000..51bd5d95d
--- /dev/null
+++ b/Tests/RunCMake/GenerateExportHeader/includeguard/main.cpp.in
@@ -0,0 +1,10 @@
+#include "@EXPORT_HEADER@"
+
+int main()
+{
+#if defined(@DEF_SYMBOL@) && !defined(@NDEF_SYMBOL@)
+ return 0;
+#else
+ return 1;
+#endif
+}
diff --git a/Tests/RunCMake/GeneratorExpression/CMP0085-NEW-check.cmake b/Tests/RunCMake/GeneratorExpression/CMP0085-NEW-check.cmake
new file mode 100644
index 000000000..520bf3dcd
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/CMP0085-NEW-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/CMP0085-NEW-generated.txt" content)
+
+set(expected "101011")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/CMP0085-NEW.cmake b/Tests/RunCMake/GeneratorExpression/CMP0085-NEW.cmake
new file mode 100644
index 000000000..ee85c0d36
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/CMP0085-NEW.cmake
@@ -0,0 +1,4 @@
+cmake_policy(SET CMP0070 NEW)
+file(GENERATE OUTPUT CMP0085-NEW-generated.txt CONTENT
+ "$<IN_LIST:,>$<IN_LIST:,a>$<IN_LIST:,;a>$<IN_LIST:a,>$<IN_LIST:a,a>$<IN_LIST:a,;a>"
+ )
diff --git a/Tests/RunCMake/GeneratorExpression/CMP0085-OLD-check.cmake b/Tests/RunCMake/GeneratorExpression/CMP0085-OLD-check.cmake
new file mode 100644
index 000000000..c387db77c
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/CMP0085-OLD-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/CMP0085-OLD-generated.txt" content)
+
+set(expected "000011")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/CMP0085-OLD.cmake b/Tests/RunCMake/GeneratorExpression/CMP0085-OLD.cmake
new file mode 100644
index 000000000..31b6a51b4
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/CMP0085-OLD.cmake
@@ -0,0 +1,4 @@
+cmake_policy(SET CMP0070 NEW)
+file(GENERATE OUTPUT CMP0085-OLD-generated.txt CONTENT
+ "$<IN_LIST:,>$<IN_LIST:,a>$<IN_LIST:,;a>$<IN_LIST:a,>$<IN_LIST:a,a>$<IN_LIST:a,;a>"
+ )
diff --git a/Tests/RunCMake/GeneratorExpression/CMP0085-WARN-check.cmake b/Tests/RunCMake/GeneratorExpression/CMP0085-WARN-check.cmake
new file mode 100644
index 000000000..f7bcf0ff1
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/CMP0085-WARN-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/CMP0085-WARN-generated.txt" content)
+
+set(expected "000011")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/CMP0085-WARN-stderr.txt b/Tests/RunCMake/GeneratorExpression/CMP0085-WARN-stderr.txt
new file mode 100644
index 000000000..81bd45028
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/CMP0085-WARN-stderr.txt
@@ -0,0 +1,33 @@
+CMake Warning \(dev\) at CMP0085-WARN\.cmake:[0-9]+ \(file\):
+ Policy CMP0085 is not set: \$<IN_LIST:\.\.\.> handles empty list items\. Run
+ "cmake --help-policy CMP0085" for policy details\. Use the cmake_policy
+ command to set the policy and suppress this warning\.
+
+ Search Item:
+
+ ""
+
+ List:
+
+ ""
+
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+This warning is for project developers\. Use -Wno-dev to suppress it\.
+
+CMake Warning \(dev\) at CMP0085-WARN\.cmake:[0-9]+ \(file\):
+ Policy CMP0085 is not set: \$<IN_LIST:\.\.\.> handles empty list items\. Run
+ "cmake --help-policy CMP0085" for policy details\. Use the cmake_policy
+ command to set the policy and suppress this warning\.
+
+ Search Item:
+
+ ""
+
+ List:
+
+ ";a"
+
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+This warning is for project developers\. Use -Wno-dev to suppress it\.
diff --git a/Tests/RunCMake/GeneratorExpression/CMP0085-WARN.cmake b/Tests/RunCMake/GeneratorExpression/CMP0085-WARN.cmake
new file mode 100644
index 000000000..59c782653
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/CMP0085-WARN.cmake
@@ -0,0 +1,4 @@
+cmake_policy(SET CMP0070 NEW)
+file(GENERATE OUTPUT CMP0085-WARN-generated.txt CONTENT
+ "$<IN_LIST:,>$<IN_LIST:,a>$<IN_LIST:,;a>$<IN_LIST:a,>$<IN_LIST:a,a>$<IN_LIST:a,;a>"
+ )
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command-result.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command-stderr.txt
new file mode 100644
index 000000000..2ee96ed14
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at COMPILE_LANG_AND_ID-add_custom_command.cmake:2 \(add_custom_command\):
+ Error evaluating generator expression:
+
+ \$<COMPILE_LANG_AND_ID>
+
+ \$<COMPILE_LANG_AND_ID> expression requires at least two parameters.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command.cmake b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command.cmake
new file mode 100644
index 000000000..9bd5e8e7e
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_command.cmake
@@ -0,0 +1,4 @@
+add_custom_target(drive)
+add_custom_command(TARGET drive PRE_BUILD
+ COMMAND ${CMAKE_COMMAND} -E echo $<COMPILE_LANG_AND_ID>
+)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target-result.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target-stderr.txt
new file mode 100644
index 000000000..589e64b4e
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target-stderr.txt
@@ -0,0 +1,11 @@
+CMake Error at COMPILE_LANG_AND_ID-add_custom_target.cmake:2 \(add_custom_target\):
+ Error evaluating generator expression:
+
+ \$<COMPILE_LANG_AND_ID:LANG,ID>
+
+ \$<COMPILE_LANG_AND_ID:lang,id> may only be used with binary targets to
+ specify include directories, compile definitions, and compile options. It
+ may not be used with the add_custom_command, add_custom_target, or
+ file\(GENERATE\) commands.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target.cmake b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target.cmake
new file mode 100644
index 000000000..398db1978
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_custom_target.cmake
@@ -0,0 +1,4 @@
+
+add_custom_target(drive
+ COMMAND ${CMAKE_COMMAND} -E echo $<COMPILE_LANG_AND_ID:LANG,ID>
+)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable-result.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable-stderr.txt
new file mode 100644
index 000000000..3b3f38d37
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable-stderr.txt
@@ -0,0 +1,11 @@
+CMake Error at COMPILE_LANG_AND_ID-add_executable.cmake:1 \(add_executable\):
+ Error evaluating generator expression:
+
+ \$<COMPILE_LANG_AND_ID:C,MSVC>
+
+ \$<COMPILE_LANG_AND_ID:lang,id> may only be used with binary targets to
+ specify include directories, compile definitions, and compile options. It
+ may not be used with the add_custom_command, add_custom_target, or
+ file\(GENERATE\) commands.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable.cmake b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable.cmake
new file mode 100644
index 000000000..2245f5046
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_executable.cmake
@@ -0,0 +1,5 @@
+add_executable(empty main.c
+ $<$<COMPILE_LANG_AND_ID:C,MSVC>:empty.c>
+ $<$<COMPILE_LANG_AND_ID:C,GNU>:empty2.c>
+ $<$<COMPILE_LANG_AND_ID:C,Clang>:empty3.c>
+ )
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library-result.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library-stderr.txt
new file mode 100644
index 000000000..4cbf000ea
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library-stderr.txt
@@ -0,0 +1,11 @@
+CMake Error at COMPILE_LANG_AND_ID-add_library.cmake:2 \(add_library\):
+ Error evaluating generator expression:
+
+ \$<COMPILE_LANG_AND_ID:C,MSVC>
+
+ \$<COMPILE_LANG_AND_ID:lang,id> may only be used with binary targets to
+ specify include directories, compile definitions, and compile options. It
+ may not be used with the add_custom_command, add_custom_target, or
+ file\(GENERATE\) commands.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library.cmake b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library.cmake
new file mode 100644
index 000000000..044962a53
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_library.cmake
@@ -0,0 +1,2 @@
+
+add_library(empty empty.$<COMPILE_LANG_AND_ID:C,MSVC>)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test-result.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test-stderr.txt
new file mode 100644
index 000000000..26a5940f3
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test-stderr.txt
@@ -0,0 +1,11 @@
+CMake Error at COMPILE_LANG_AND_ID-add_test.cmake:5 \(add_test\):
+ Error evaluating generator expression:
+
+ \$<COMPILE_LANG_AND_ID:CXX,GNU>
+
+ \$<COMPILE_LANG_AND_ID:lang,id> may only be used with binary targets to
+ specify include directories, compile definitions, and compile options. It
+ may not be used with the add_custom_command, add_custom_target, or
+ file\(GENERATE\) commands.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test.cmake b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test.cmake
new file mode 100644
index 000000000..b5b6c2b82
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-add_test.cmake
@@ -0,0 +1,5 @@
+
+include(CTest)
+enable_testing()
+
+add_test(NAME dummy COMMAND ${CMAKE_COMMAND} -E echo $<COMPILE_LANG_AND_ID:CXX,GNU>)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install-result.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install-stderr.txt
new file mode 100644
index 000000000..0c4ecd091
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install-stderr.txt
@@ -0,0 +1,9 @@
+CMake Error:
+ Error evaluating generator expression:
+
+ \$<COMPILE_LANG_AND_ID:C,MSVC>
+
+ \$<COMPILE_LANG_AND_ID:lang,id> may only be used with binary targets to
+ specify include directories, compile definitions, and compile options. It
+ may not be used with the add_custom_command, add_custom_target, or
+ file\(GENERATE\) commands.
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install.cmake b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install.cmake
new file mode 100644
index 000000000..c13eda6ec
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-install.cmake
@@ -0,0 +1,5 @@
+
+install(FILES
+ empty.$<COMPILE_LANG_AND_ID:C,MSVC>
+ DESTINATION src
+)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources-result.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources-stderr.txt
new file mode 100644
index 000000000..3ecbdc360
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at COMPILE_LANG_AND_ID-target_sources.cmake:2 \(target_sources\):
+ Error evaluating generator expression:
+
+ \$<COMPILE_LANG_AND_ID>
+
+ \$<COMPILE_LANG_AND_ID> expression requires at least two parameters.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources.cmake b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources.cmake
new file mode 100644
index 000000000..a2c9b03f5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-target_sources.cmake
@@ -0,0 +1,2 @@
+add_library(empty)
+target_sources(empty PRIVATE empty.$<COMPILE_LANG_AND_ID>)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-unknown-lang.cmake b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-unknown-lang.cmake
new file mode 100644
index 000000000..b9e840b41
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANG_AND_ID-unknown-lang.cmake
@@ -0,0 +1,4 @@
+
+enable_language(C)
+add_executable(empty empty.c)
+target_compile_options(empty PRIVATE $<$<COMPILE_LANG_AND_ID:CXX,GNU>:$<TARGET_EXISTS:too,many,parameters>>)
diff --git a/Tests/RunCMake/GeneratorExpression/FILTER-Exclude-check.cmake b/Tests/RunCMake/GeneratorExpression/FILTER-Exclude-check.cmake
new file mode 100644
index 000000000..605ae4d19
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/FILTER-Exclude-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/FILTER-generated.txt" content)
+
+set(expected "DO_NOT_FILTER_THIS;thisisanitem")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/FILTER-Exclude.cmake b/Tests/RunCMake/GeneratorExpression/FILTER-Exclude.cmake
new file mode 100644
index 000000000..b879be220
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/FILTER-Exclude.cmake
@@ -0,0 +1,4 @@
+cmake_policy(VERSION 3.11)
+
+set(mylist FILTER_THIS_BIT DO_NOT_FILTER_THIS thisisanitem FILTER_THIS_THING)
+file(GENERATE OUTPUT "FILTER-generated.txt" CONTENT "$<FILTER:${mylist},EXCLUDE,^FILTER_THIS_.+>")
diff --git a/Tests/RunCMake/GeneratorExpression/FILTER-Include-check.cmake b/Tests/RunCMake/GeneratorExpression/FILTER-Include-check.cmake
new file mode 100644
index 000000000..9d48d982a
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/FILTER-Include-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/FILTER-generated.txt" content)
+
+set(expected "FILTER_THIS_BIT;FILTER_THIS_THING")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/FILTER-Include.cmake b/Tests/RunCMake/GeneratorExpression/FILTER-Include.cmake
new file mode 100644
index 000000000..5e0260ad7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/FILTER-Include.cmake
@@ -0,0 +1,4 @@
+cmake_policy(VERSION 3.11)
+
+set(mylist FILTER_THIS_BIT DO_NOT_FILTER_THIS thisisanitem FILTER_THIS_THING)
+file(GENERATE OUTPUT "FILTER-generated.txt" CONTENT "$<FILTER:${mylist},INCLUDE,^FILTER_THIS_.+>")
diff --git a/Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator-result.txt b/Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator-stderr.txt b/Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator-stderr.txt
new file mode 100644
index 000000000..dd1092556
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at FILTER-InvalidOperator.cmake:3 \(file\):
+ Error evaluating generator expression:
+
+ \$<FILTER:,RM,>
+
+ \$<FILTER:...> second parameter must be either INCLUDE or EXCLUDE
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator.cmake b/Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator.cmake
new file mode 100644
index 000000000..26f3917dc
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/FILTER-InvalidOperator.cmake
@@ -0,0 +1,3 @@
+cmake_policy(VERSION 3.11)
+
+file(GENERATE OUTPUT "FILTER-generated.txt" CONTENT "$<FILTER:,RM,>")
diff --git a/Tests/RunCMake/GeneratorExpression/FILTER-empty-check.cmake b/Tests/RunCMake/GeneratorExpression/FILTER-empty-check.cmake
new file mode 100644
index 000000000..2844484c5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/FILTER-empty-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/FILTER-generated.txt" content)
+
+set(expected "")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/FILTER-empty.cmake b/Tests/RunCMake/GeneratorExpression/FILTER-empty.cmake
new file mode 100644
index 000000000..e0fc671d0
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/FILTER-empty.cmake
@@ -0,0 +1,3 @@
+cmake_policy(VERSION 3.11)
+
+file(GENERATE OUTPUT "FILTER-generated.txt" CONTENT "$<FILTER:,INCLUDE,>")
diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-check.cmake b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-check.cmake
new file mode 100644
index 000000000..df7674051
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/GENEX_EVAL-generated.txt" content)
+
+set(expected "BEFORE_PROPERTY1_AFTER")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-result.txt b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-stderr.txt b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-stderr.txt
new file mode 100644
index 000000000..012dff658
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1-stderr.txt
@@ -0,0 +1,26 @@
+^CMake Error at GENEX_EVAL-recursion1.cmake:7 \(add_custom_target\):
+ Error evaluating generator expression:
+
+ \$<GENEX_EVAL:\$<TARGET_PROPERTY:CUSTOM_PROPERTY>>
+
+ Dependency loop found.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+
+
+CMake Error at GENEX_EVAL-recursion1.cmake:7 \(add_custom_target\):
+ Loop step 1
+
+ \$<GENEX_EVAL:\$<TARGET_PROPERTY:CUSTOM_PROPERTY>>
+
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+
+
+CMake Error at GENEX_EVAL-recursion1.cmake:7 \(add_custom_target\):
+ Loop step 2
+
+ \$<TARGET_GENEX_EVAL:recursion,\$<TARGET_PROPERTY:recursion,CUSTOM_PROPERTY>>
+
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1.cmake b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1.cmake
new file mode 100644
index 000000000..6596a81ab
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion1.cmake
@@ -0,0 +1,9 @@
+
+enable_language(C)
+
+add_library (recursion SHARED empty.c)
+set_property (TARGET recursion PROPERTY CUSTOM_PROPERTY "$<GENEX_EVAL:$<TARGET_PROPERTY:CUSTOM_PROPERTY>>")
+
+add_custom_target (drive
+ COMMAND echo "$<TARGET_GENEX_EVAL:recursion,$<TARGET_PROPERTY:recursion,CUSTOM_PROPERTY>>"
+ DEPENDS recursion)
diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-result.txt b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-stderr.txt b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-stderr.txt
new file mode 100644
index 000000000..ed6840057
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2-stderr.txt
@@ -0,0 +1,26 @@
+^CMake Error at GENEX_EVAL-recursion2.cmake:8 \(add_custom_target\):
+ Error evaluating generator expression:
+
+ \$<GENEX_EVAL:\$<TARGET_PROPERTY:CUSTOM_PROPERTY2>>
+
+ Dependency loop found.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+
+
+CMake Error at GENEX_EVAL-recursion2.cmake:8 \(add_custom_target\):
+ Loop step 1
+
+ \$<GENEX_EVAL:\$<TARGET_PROPERTY:CUSTOM_PROPERTY1>>
+
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+
+
+CMake Error at GENEX_EVAL-recursion2.cmake:8 \(add_custom_target\):
+ Loop step 2
+
+ \$<GENEX_EVAL:\$<TARGET_PROPERTY:CUSTOM_PROPERTY2>>
+
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2.cmake b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2.cmake
new file mode 100644
index 000000000..773749f2c
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL-recursion2.cmake
@@ -0,0 +1,10 @@
+
+enable_language(C)
+
+add_library(recursion SHARED empty.c)
+set_property (TARGET recursion PROPERTY CUSTOM_PROPERTY1 "$<GENEX_EVAL:$<TARGET_PROPERTY:CUSTOM_PROPERTY2>>")
+set_property (TARGET recursion PROPERTY CUSTOM_PROPERTY2 "$<GENEX_EVAL:$<TARGET_PROPERTY:CUSTOM_PROPERTY1>>")
+
+add_custom_target (drive
+ COMMAND echo "$<TARGET_GENEX_EVAL:recursion,$<TARGET_PROPERTY:recursion,CUSTOM_PROPERTY1>>"
+ DEPENDS recursion)
diff --git a/Tests/RunCMake/GeneratorExpression/GENEX_EVAL.cmake b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL.cmake
new file mode 100644
index 000000000..153cd176f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/GENEX_EVAL.cmake
@@ -0,0 +1,12 @@
+
+cmake_policy(VERSION 3.11)
+
+enable_language(C)
+
+add_library (example SHARED empty.c)
+set_property (TARGET example PROPERTY CUSTOM_PROPERTY1 "PROPERTY1")
+set_property (TARGET example PROPERTY CUSTOM_PROPERTY2 "$<TARGET_PROPERTY:CUSTOM_PROPERTY1>")
+set_property (TARGET example PROPERTY CUSTOM_PROPERTY3 "$<GENEX_EVAL:BEFORE_$<TARGET_PROPERTY:CUSTOM_PROPERTY2>_AFTER>")
+set_property (TARGET example PROPERTY CUSTOM_PROPERTY4 "$<GENEX_EVAL:$<TARGET_PROPERTY:CUSTOM_PROPERTY3>>")
+
+file(GENERATE OUTPUT "GENEX_EVAL-generated.txt" CONTENT "$<TARGET_GENEX_EVAL:example,$<TARGET_PROPERTY:example,CUSTOM_PROPERTY4>>")
diff --git a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-result.txt b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt
new file mode 100644
index 000000000..3b2a814a7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at ImportedTarget-TARGET_PDB_FILE_BASE_NAME.cmake:2 \(add_custom_target\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PDB_FILE_BASE_NAME:empty>
+
+ TARGET_PDB_FILE_BASE_NAME not allowed for IMPORTED targets.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME.cmake b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME.cmake
new file mode 100644
index 000000000..489d8e620
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/ImportedTarget-TARGET_PDB_FILE_BASE_NAME.cmake
@@ -0,0 +1,2 @@
+add_library(empty UNKNOWN IMPORTED)
+add_custom_target(custom COMMAND echo $<TARGET_PDB_FILE_BASE_NAME:empty>)
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-result.txt b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-stderr.txt b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-stderr.txt
new file mode 100644
index 000000000..b061ce3de
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at NonValidCompiler-TARGET_PDB_FILE_BASE_NAME.cmake:6 \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PDB_FILE_BASE_NAME:empty>
+
+ TARGET_PDB_FILE_BASE_NAME is not supported by the target linker.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME.cmake b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME.cmake
new file mode 100644
index 000000000..811c3f70f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidCompiler-TARGET_PDB_FILE_BASE_NAME.cmake
@@ -0,0 +1,9 @@
+
+enable_language(C)
+
+add_library(empty STATIC empty.c)
+
+file(GENERATE
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+ CONTENT "[$<TARGET_PDB_FILE_BASE_NAME:empty>]"
+)
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID-result.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID-stderr.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID-stderr.txt
new file mode 100644
index 000000000..fc1324807
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID-stderr.txt
@@ -0,0 +1,9 @@
+CMake Error at NonValidTarget-Fortran_COMPILER_ID.cmake:1 \(add_custom_command\):
+ Error evaluating generator expression:
+
+ \$<Fortran_COMPILER_ID>
+
+ \$<Fortran_COMPILER_ID> may only be used with binary targets. It may not be
+ used with add_custom_command or add_custom_target.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID.cmake b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID.cmake
new file mode 100644
index 000000000..88a0bfb99
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_ID.cmake
@@ -0,0 +1,4 @@
+add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c"
+ COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_SOURCE_DIR}/empty.c" "${CMAKE_CURRENT_BINARY_DIR}/copied_file$<Fortran_COMPILER_ID>.c"
+)
+add_custom_target(drive DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c")
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION-result.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION-stderr.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION-stderr.txt
new file mode 100644
index 000000000..f8a41205c
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION-stderr.txt
@@ -0,0 +1,9 @@
+CMake Error at NonValidTarget-Fortran_COMPILER_VERSION.cmake:1 \(add_custom_command\):
+ Error evaluating generator expression:
+
+ \$<Fortran_COMPILER_VERSION>
+
+ \$<Fortran_COMPILER_VERSION> may only be used with binary targets. It may
+ not be used with add_custom_command or add_custom_target.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION.cmake b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION.cmake
new file mode 100644
index 000000000..34a4884d4
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-Fortran_COMPILER_VERSION.cmake
@@ -0,0 +1,4 @@
+add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c"
+ COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_SOURCE_DIR}/empty.c" "${CMAKE_CURRENT_BINARY_DIR}/copied_file$<Fortran_COMPILER_VERSION>.c"
+)
+add_custom_target(drive DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c")
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-result.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt
new file mode 100644
index 000000000..c7d245c54
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME-stderr.txt
@@ -0,0 +1,9 @@
+CMake Error at NonValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake:6 \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PDB_FILE_BASE_NAME:empty>
+
+ TARGET_PDB_FILE_BASE_NAME is allowed only for targets with linker created
+ artifacts.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake
new file mode 100644
index 000000000..811c3f70f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/NonValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake
@@ -0,0 +1,9 @@
+
+enable_language(C)
+
+add_library(empty STATIC empty.c)
+
+file(GENERATE
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+ CONTENT "[$<TARGET_PDB_FILE_BASE_NAME:empty>]"
+)
diff --git a/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-1-check.cmake b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-1-check.cmake
new file mode 100644
index 000000000..e127711eb
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-1-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/REMOVE_DUPLICATES-generated.txt" content)
+
+set(expected "1")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-1.cmake b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-1.cmake
new file mode 100644
index 000000000..53934afb0
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-1.cmake
@@ -0,0 +1,3 @@
+cmake_policy(VERSION 3.11)
+
+file(GENERATE OUTPUT "REMOVE_DUPLICATES-generated.txt" CONTENT "$<REMOVE_DUPLICATES:1>")
diff --git a/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-2-check.cmake b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-2-check.cmake
new file mode 100644
index 000000000..e127711eb
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-2-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/REMOVE_DUPLICATES-generated.txt" content)
+
+set(expected "1")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-2.cmake b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-2.cmake
new file mode 100644
index 000000000..a8aca6e35
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-2.cmake
@@ -0,0 +1,3 @@
+cmake_policy(VERSION 3.11)
+
+file(GENERATE OUTPUT "REMOVE_DUPLICATES-generated.txt" CONTENT "$<REMOVE_DUPLICATES:1$<SEMICOLON>1>")
diff --git a/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-3-check.cmake b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-3-check.cmake
new file mode 100644
index 000000000..e3055ce94
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-3-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/REMOVE_DUPLICATES-generated.txt" content)
+
+set(expected "2;1")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-3.cmake b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-3.cmake
new file mode 100644
index 000000000..ee2dd3ea5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-3.cmake
@@ -0,0 +1,3 @@
+cmake_policy(VERSION 3.11)
+
+file(GENERATE OUTPUT "REMOVE_DUPLICATES-generated.txt" CONTENT "$<REMOVE_DUPLICATES:2$<SEMICOLON>1>")
diff --git a/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-4-check.cmake b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-4-check.cmake
new file mode 100644
index 000000000..e3055ce94
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-4-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/REMOVE_DUPLICATES-generated.txt" content)
+
+set(expected "2;1")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-4.cmake b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-4.cmake
new file mode 100644
index 000000000..557bc28c1
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-4.cmake
@@ -0,0 +1,3 @@
+cmake_policy(VERSION 3.11)
+
+file(GENERATE OUTPUT "REMOVE_DUPLICATES-generated.txt" CONTENT "$<REMOVE_DUPLICATES:2$<SEMICOLON>1$<SEMICOLON>2>")
diff --git a/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-empty-check.cmake b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-empty-check.cmake
new file mode 100644
index 000000000..f779d489b
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-empty-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/REMOVE_DUPLICATES-generated.txt" content)
+
+set(expected "")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-empty.cmake b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-empty.cmake
new file mode 100644
index 000000000..3b9d674ff
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/REMOVE_DUPLICATES-empty.cmake
@@ -0,0 +1,3 @@
+cmake_policy(VERSION 3.11)
+
+file(GENERATE OUTPUT "REMOVE_DUPLICATES-generated.txt" CONTENT "$<REMOVE_DUPLICATES:>")
diff --git a/Tests/RunCMake/GeneratorExpression/ResultValidator.cmake b/Tests/RunCMake/GeneratorExpression/ResultValidator.cmake
new file mode 100644
index 000000000..722ae0527
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/ResultValidator.cmake
@@ -0,0 +1,6 @@
+
+function (CHECK_VALUE test_msg value expected)
+ if (NOT value STREQUAL expected)
+ string (APPEND RunCMake_TEST_FAILED "${test_msg}: actual result:\n [[${value}]]\nbut expected:\n [[${expected}]]\n")
+ endif()
+endfunction()
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-check.cmake
new file mode 100644
index 000000000..c4c3a513b
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/TARGET_EXISTS-generated.txt" content)
+
+set(expected "1")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-stderr.txt
new file mode 100644
index 000000000..1df6e28f5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at TARGET_EXISTS-empty-arg.cmake:2 \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_EXISTS:>
+
+ \$<TARGET_EXISTS:tgt> expression requires a non-empty valid target name.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg.cmake
new file mode 100644
index 000000000..e387abccb
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-empty-arg.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0070 NEW)
+file(GENERATE OUTPUT TARGET_EXISTS-generated.txt CONTENT "$<TARGET_EXISTS:${empty}>")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-stderr.txt
new file mode 100644
index 000000000..69e613052
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at TARGET_EXISTS-no-arg.cmake:2 \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_EXISTS>
+
+ \$<TARGET_EXISTS> expression requires exactly one parameter.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg.cmake
new file mode 100644
index 000000000..0a5ce323f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-no-arg.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0070 NEW)
+file(GENERATE OUTPUT TARGET_EXISTS-generated.txt CONTENT "$<TARGET_EXISTS>")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target-check.cmake
new file mode 100644
index 000000000..35ba26746
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/TARGET_EXISTS-not-a-target-generated.txt" content)
+
+set(expected "0")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target.cmake
new file mode 100644
index 000000000..d8a8d3e45
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS-not-a-target.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0070 NEW)
+file(GENERATE OUTPUT TARGET_EXISTS-not-a-target-generated.txt CONTENT "$<TARGET_EXISTS:just-random-string>")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS.cmake
new file mode 100644
index 000000000..9a83b34ca
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_EXISTS.cmake
@@ -0,0 +1,3 @@
+cmake_policy(SET CMP0070 NEW)
+add_custom_target(foo)
+file(GENERATE OUTPUT TARGET_EXISTS-generated.txt CONTENT "$<TARGET_EXISTS:foo>")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-check.cmake
new file mode 100644
index 000000000..793edb1de
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-check.cmake
@@ -0,0 +1,2 @@
+
+include ("${RunCMake_TEST_BINARY_DIR}/TARGET_FILE_BASE_NAME-generated.cmake")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target-check.cmake
new file mode 100644
index 000000000..793edb1de
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target-check.cmake
@@ -0,0 +1,2 @@
+
+include ("${RunCMake_TEST_BINARY_DIR}/TARGET_FILE_BASE_NAME-generated.cmake")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target.cmake
new file mode 100644
index 000000000..40f7c66f2
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-imported-target.cmake
@@ -0,0 +1,106 @@
+
+cmake_minimum_required(VERSION 3.14)
+
+enable_language (C)
+
+set (GENERATE_CONTENT [[
+macro (CHECK_VALUE test_msg value expected)
+ if (NOT "${value}" STREQUAL "${expected}")
+ string (APPEND RunCMake_TEST_FAILED "${test_msg}: actual result:\n [${value}]\nbut expected:\n [${expected}]\n")
+ endif()
+endmacro()
+]])
+
+add_executable(exec1 IMPORTED)
+add_library (shared1 SHARED IMPORTED)
+add_library (static1 STATIC IMPORTED)
+
+string (APPEND GENERATE_CONTENT [[
+
+check_value ("TARGET_FILE_BASE_NAME executable default" "$<TARGET_FILE_BASE_NAME:exec1>" "exec1")
+check_value ("TARGET_FILE_BASE_NAME shared default" "$<TARGET_FILE_BASE_NAME:shared1>" "shared1")
+check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker default" "$<TARGET_LINKER_FILE_BASE_NAME:shared1>" "shared1")
+check_value ("TARGET_FILE_BASE_NAME static default" "$<TARGET_FILE_BASE_NAME:static1>" "static1")
+check_value ("TARGET_LINKER_FILE_BASE_NAME static linker default" "$<TARGET_LINKER_FILE_BASE_NAME:static1>" "static1")
+]])
+
+
+add_executable (exec2 IMPORTED)
+set_property (TARGET exec2 PROPERTY OUTPUT_NAME exec2_custom)
+add_library (shared2 SHARED IMPORTED)
+set_property (TARGET shared2 PROPERTY OUTPUT_NAME shared2_custom)
+add_library (static2 STATIC IMPORTED)
+set_property (TARGET static2 PROPERTY OUTPUT_NAME static2_custom)
+
+string (APPEND GENERATE_CONTENT [[
+
+check_value ("TARGET_FILE_BASE_NAME executable custom" "$<TARGET_FILE_BASE_NAME:exec2>" "exec2_custom")
+check_value ("TARGET_FILE_BASE_NAME shared custom" "$<TARGET_FILE_BASE_NAME:shared2>" "shared2_custom")
+check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker custom" "$<TARGET_LINKER_FILE_BASE_NAME:shared2>" "shared2_custom")
+check_value ("TARGET_FILE_BASE_NAME static custom" "$<TARGET_FILE_BASE_NAME:static2>" "static2_custom")
+check_value ("TARGET_LINKER_FILE_BASE_NAME static linker custom" "$<TARGET_LINKER_FILE_BASE_NAME:static2>" "static2_custom")
+]])
+
+
+add_executable (exec3 IMPORTED)
+set_property (TARGET exec3 PROPERTY RUNTIME_OUTPUT_NAME exec3_runtime)
+set_property (TARGET exec3 PROPERTY LIBRARY_OUTPUT_NAME exec3_library)
+set_property (TARGET exec3 PROPERTY ARCHIVE_OUTPUT_NAME exec3_archive)
+add_library (shared3 SHARED IMPORTED)
+set_property (TARGET shared3 PROPERTY RUNTIME_OUTPUT_NAME shared3_runtime)
+set_property (TARGET shared3 PROPERTY LIBRARY_OUTPUT_NAME shared3_library)
+set_property (TARGET shared3 PROPERTY ARCHIVE_OUTPUT_NAME shared3_archive)
+add_library (static3 STATIC IMPORTED)
+set_property (TARGET static3 PROPERTY RUNTIME_OUTPUT_NAME static3_runtime)
+set_property (TARGET static3 PROPERTY LIBRARY_OUTPUT_NAME static3_library)
+set_property (TARGET static3 PROPERTY ARCHIVE_OUTPUT_NAME static3_archive)
+
+string (APPEND GENERATE_CONTENT [[
+
+check_value ("TARGET_FILE_BASE_NAME executable all properties" "$<TARGET_FILE_BASE_NAME:exec3>" "exec3_runtime")
+check_value ("TARGET_FILE_BASE_NAME shared all properties" "$<TARGET_FILE_BASE_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_runtime,shared3_library>")
+check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker all properties" "$<TARGET_LINKER_FILE_BASE_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_archive,shared3_library>")
+check_value ("TARGET_FILE_BASE_NAME static all properties" "$<TARGET_FILE_BASE_NAME:static3>" "static3_archive")
+check_value ("TARGET_LINKER_FILE_BASE_NAME static linker all properties" "$<TARGET_LINKER_FILE_BASE_NAME:static3>" "static3_archive")
+]])
+
+
+unset(GENERATE_CONDITION)
+get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
+if(_isMultiConfig)
+ list(GET CMAKE_CONFIGURATION_TYPES 0 FIRST_CONFIG)
+ set(GENERATE_CONDITION CONDITION $<CONFIG:${FIRST_CONFIG}>)
+else()
+ set (FIRST_CONFIG ${CMAKE_BUILD_TYPE})
+endif()
+string (TOUPPER "${FIRST_CONFIG}" FIRST_CONFIG)
+
+
+add_executable (exec4 IMPORTED)
+set_property (TARGET exec4 PROPERTY RUNTIME_OUTPUT_NAME exec4_runtime)
+set_property (TARGET exec4 PROPERTY LIBRARY_OUTPUT_NAME exec4_library)
+set_property (TARGET exec4 PROPERTY ARCHIVE_OUTPUT_NAME exec4_archive)
+set_property (TARGET exec4 PROPERTY ${FIRST_CONFIG}_POSTFIX _postfix)
+add_library (shared4 SHARED IMPORTED)
+set_property (TARGET shared4 PROPERTY RUNTIME_OUTPUT_NAME shared4_runtime)
+set_property (TARGET shared4 PROPERTY LIBRARY_OUTPUT_NAME shared4_library)
+set_property (TARGET shared4 PROPERTY ARCHIVE_OUTPUT_NAME shared4_archive)
+set_property (TARGET shared4 PROPERTY ${FIRST_CONFIG}_POSTFIX _postfix)
+add_library (static4 STATIC IMPORTED)
+set_property (TARGET static4 PROPERTY RUNTIME_OUTPUT_NAME static4_runtime)
+set_property (TARGET static4 PROPERTY LIBRARY_OUTPUT_NAME static4_library)
+set_property (TARGET static4 PROPERTY ARCHIVE_OUTPUT_NAME static4_archive)
+set_property (TARGET static4 PROPERTY ${FIRST_CONFIG}_POSTFIX _postfix)
+
+string (APPEND GENERATE_CONTENT [[
+
+check_value ("TARGET_FILE_BASE_NAME executable all properties + postfix" "$<TARGET_FILE_BASE_NAME:exec4>" "exec4_runtime_postfix")
+check_value ("TARGET_FILE_BASE_NAME shared all properties + postfix" "$<TARGET_FILE_BASE_NAME:shared4>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared4_runtime,shared4_library>_postfix")
+check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker all properties + postfix" "$<TARGET_LINKER_FILE_BASE_NAME:shared4>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared4_archive,shared4_library>_postfix")
+check_value ("TARGET_FILE_BASE_NAME static all properties + postfix" "$<TARGET_FILE_BASE_NAME:static4>" "static4_archive_postfix")
+check_value ("TARGET_LINKER_FILE_BASE_NAME static linker all properties + postfix" "$<TARGET_LINKER_FILE_BASE_NAME:static4>" "static4_archive_postfix")
+]])
+
+
+file (GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/TARGET_FILE_BASE_NAME-generated.cmake"
+ CONTENT "${GENERATE_CONTENT}" ${GENERATE_CONDITION})
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-stderr.txt
new file mode 100644
index 000000000..ecb9e5d03
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at TARGET_FILE_BASE_NAME-non-valid-target.cmake:[0-9]+ \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_FILE_BASE_NAME:empty>
+
+ Target "empty" is not an executable or library\.
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target.cmake
new file mode 100644
index 000000000..8622b7dc9
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME-non-valid-target.cmake
@@ -0,0 +1,7 @@
+
+add_custom_target(empty)
+
+file(GENERATE
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+ CONTENT "[$<TARGET_FILE_BASE_NAME:empty>]"
+)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME.cmake
new file mode 100644
index 000000000..f88d7109a
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_BASE_NAME.cmake
@@ -0,0 +1,135 @@
+
+cmake_minimum_required(VERSION 3.14)
+
+enable_language (C)
+
+set (GENERATE_CONTENT [[
+macro (CHECK_VALUE test_msg value expected)
+ if (NOT "${value}" STREQUAL "${expected}")
+ string (APPEND RunCMake_TEST_FAILED "${test_msg}: actual result:\n [${value}]\nbut expected:\n [${expected}]\n")
+ endif()
+endmacro()
+]])
+
+add_executable (exec1 empty.c)
+add_library (shared1 SHARED empty.c)
+add_library (static1 STATIC empty.c)
+
+string (APPEND GENERATE_CONTENT [[
+
+check_value ("TARGET_FILE_BASE_NAME executable default" "$<TARGET_FILE_BASE_NAME:exec1>" "exec1")
+check_value ("TARGET_FILE_BASE_NAME shared default" "$<TARGET_FILE_BASE_NAME:shared1>" "shared1")
+check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker default" "$<TARGET_LINKER_FILE_BASE_NAME:shared1>" "shared1")
+check_value ("TARGET_FILE_BASE_NAME static default" "$<TARGET_FILE_BASE_NAME:static1>" "static1")
+check_value ("TARGET_LINKER_FILE_BASE_NAME static linker default" "$<TARGET_LINKER_FILE_BASE_NAME:static1>" "static1")
+]])
+if (CMAKE_C_LINKER_SUPPORTS_PDB)
+ string(APPEND GENERATE_CONTENT [[
+check_value ("TARGET_PDB_FILE_BASE_NAME executable PDB default" "$<TARGET_PDB_FILE_BASE_NAME:exec1>" "exec1")
+check_value ("TARGET_PDB_FILE_BASE_NAME shared PDB default" "$<TARGET_PDB_FILE_BASE_NAME:shared1>" "shared1")
+]])
+endif()
+
+
+add_executable (exec2 empty.c)
+set_property (TARGET exec2 PROPERTY OUTPUT_NAME exec2_custom)
+add_library (shared2 SHARED empty.c)
+set_property (TARGET shared2 PROPERTY OUTPUT_NAME shared2_custom)
+add_library (static2 STATIC empty.c)
+set_property (TARGET static2 PROPERTY OUTPUT_NAME static2_custom)
+
+string (APPEND GENERATE_CONTENT [[
+
+check_value ("TARGET_FILE_BASE_NAME executable custom" "$<TARGET_FILE_BASE_NAME:exec2>" "exec2_custom")
+check_value ("TARGET_FILE_BASE_NAME shared custom" "$<TARGET_FILE_BASE_NAME:shared2>" "shared2_custom")
+check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker custom" "$<TARGET_LINKER_FILE_BASE_NAME:shared2>" "shared2_custom")
+check_value ("TARGET_FILE_BASE_NAME static custom" "$<TARGET_FILE_BASE_NAME:static2>" "static2_custom")
+check_value ("TARGET_LINKER_FILE_BASE_NAME static linker custom" "$<TARGET_LINKER_FILE_BASE_NAME:static2>" "static2_custom")
+]])
+if (CMAKE_C_LINKER_SUPPORTS_PDB)
+ string (APPEND GENERATE_CONTENT [[
+check_value ("TARGET_PDB_FILE_BASE_NAME executable PDB custom" "$<TARGET_PDB_FILE_BASE_NAME:exec2>" "exec2_custom")
+check_value ("TARGET_PDB_FILE_BASE_NAME shared PDB custom" "$<TARGET_PDB_FILE_BASE_NAME:shared2>" "shared2_custom")
+ ]])
+endif()
+
+add_executable (exec3 empty.c)
+set_property (TARGET exec3 PROPERTY RUNTIME_OUTPUT_NAME exec3_runtime)
+set_property (TARGET exec3 PROPERTY LIBRARY_OUTPUT_NAME exec3_library)
+set_property (TARGET exec3 PROPERTY ARCHIVE_OUTPUT_NAME exec3_archive)
+set_property (TARGET exec3 PROPERTY PDB_NAME exec3_pdb)
+add_library (shared3 SHARED empty.c)
+set_property (TARGET shared3 PROPERTY RUNTIME_OUTPUT_NAME shared3_runtime)
+set_property (TARGET shared3 PROPERTY LIBRARY_OUTPUT_NAME shared3_library)
+set_property (TARGET shared3 PROPERTY ARCHIVE_OUTPUT_NAME shared3_archive)
+set_property (TARGET shared3 PROPERTY PDB_NAME shared3_pdb)
+add_library (static3 STATIC empty.c)
+set_property (TARGET static3 PROPERTY RUNTIME_OUTPUT_NAME static3_runtime)
+set_property (TARGET static3 PROPERTY LIBRARY_OUTPUT_NAME static3_library)
+set_property (TARGET static3 PROPERTY ARCHIVE_OUTPUT_NAME static3_archive)
+set_property (TARGET static3 PROPERTY PDB_NAME static3_pdb)
+
+string (APPEND GENERATE_CONTENT [[
+
+check_value ("TARGET_FILE_BASE_NAME executable all properties" "$<TARGET_FILE_BASE_NAME:exec3>" "exec3_runtime")
+check_value ("TARGET_FILE_BASE_NAME shared all properties" "$<TARGET_FILE_BASE_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_runtime,shared3_library>")
+check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker all properties" "$<TARGET_LINKER_FILE_BASE_NAME:shared3>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared3_archive,shared3_library>")
+check_value ("TARGET_FILE_BASE_NAME static all properties" "$<TARGET_FILE_BASE_NAME:static3>" "static3_archive")
+check_value ("TARGET_LINKER_FILE_BASE_NAME static linker all properties" "$<TARGET_LINKER_FILE_BASE_NAME:static3>" "static3_archive")
+]])
+if (CMAKE_C_LINKER_SUPPORTS_PDB)
+ string (APPEND GENERATE_CONTENT [[
+check_value ("TARGET_PDB_FILE_BASE_NAME executable PDB all properties" "$<TARGET_PDB_FILE_BASE_NAME:exec3>" "exec3_pdb")
+check_value ("TARGET_PDB_FILE_BASE_NAME shared PDB all properties" "$<TARGET_PDB_FILE_BASE_NAME:shared3>" "shared3_pdb")
+]])
+endif()
+
+
+unset(GENERATE_CONDITION)
+get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
+if(_isMultiConfig)
+ list(GET CMAKE_CONFIGURATION_TYPES 0 FIRST_CONFIG)
+ set(GENERATE_CONDITION CONDITION $<CONFIG:${FIRST_CONFIG}>)
+else()
+ set (FIRST_CONFIG ${CMAKE_BUILD_TYPE})
+endif()
+string (TOUPPER "${FIRST_CONFIG}" FIRST_CONFIG)
+
+
+add_executable (exec4 empty.c)
+set_property (TARGET exec4 PROPERTY RUNTIME_OUTPUT_NAME exec4_runtime)
+set_property (TARGET exec4 PROPERTY LIBRARY_OUTPUT_NAME exec4_library)
+set_property (TARGET exec4 PROPERTY ARCHIVE_OUTPUT_NAME exec4_archive)
+set_property (TARGET exec4 PROPERTY PDB_NAME exec4_pdb)
+set_property (TARGET exec4 PROPERTY ${FIRST_CONFIG}_POSTFIX _postfix)
+add_library (shared4 SHARED empty.c)
+set_property (TARGET shared4 PROPERTY RUNTIME_OUTPUT_NAME shared4_runtime)
+set_property (TARGET shared4 PROPERTY LIBRARY_OUTPUT_NAME shared4_library)
+set_property (TARGET shared4 PROPERTY ARCHIVE_OUTPUT_NAME shared4_archive)
+set_property (TARGET shared4 PROPERTY PDB_NAME shared4_pdb)
+set_property (TARGET shared4 PROPERTY ${FIRST_CONFIG}_POSTFIX _postfix)
+add_library (static4 STATIC empty.c)
+set_property (TARGET static4 PROPERTY RUNTIME_OUTPUT_NAME static4_runtime)
+set_property (TARGET static4 PROPERTY LIBRARY_OUTPUT_NAME static4_library)
+set_property (TARGET static4 PROPERTY ARCHIVE_OUTPUT_NAME static4_archive)
+set_property (TARGET static4 PROPERTY PDB_NAME static4_pdb)
+set_property (TARGET static4 PROPERTY ${FIRST_CONFIG}_POSTFIX _postfix)
+
+string (APPEND GENERATE_CONTENT [[
+
+check_value ("TARGET_FILE_BASE_NAME executable all properties + postfix" "$<TARGET_FILE_BASE_NAME:exec4>" "exec4_runtime_postfix")
+check_value ("TARGET_FILE_BASE_NAME shared all properties + postfix" "$<TARGET_FILE_BASE_NAME:shared4>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared4_runtime,shared4_library>_postfix")
+check_value ("TARGET_LINKER_FILE_BASE_NAME shared linker all properties + postfix" "$<TARGET_LINKER_FILE_BASE_NAME:shared4>" "$<IF:$<IN_LIST:$<PLATFORM_ID>,Windows$<SEMICOLON>CYGWIN>,shared4_archive,shared4_library>_postfix")
+check_value ("TARGET_FILE_BASE_NAME static all properties + postfix" "$<TARGET_FILE_BASE_NAME:static4>" "static4_archive_postfix")
+check_value ("TARGET_LINKER_FILE_BASE_NAME static linker all properties + postfix" "$<TARGET_LINKER_FILE_BASE_NAME:static4>" "static4_archive_postfix")
+]])
+if (CMAKE_C_LINKER_SUPPORTS_PDB)
+ string (APPEND GENERATE_CONTENT [[
+check_value ("TARGET_PDB_FILE_BASE_NAME executable PDB all properties + postfix" "$<TARGET_PDB_FILE_BASE_NAME:exec4>" "exec4_pdb_postfix")
+check_value ("TARGET_PDB_FILE_BASE_NAME shared PDB all properties + postfix" "$<TARGET_PDB_FILE_BASE_NAME:shared4>" "shared4_pdb_postfix")
+]])
+endif()
+
+
+file (GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/TARGET_FILE_BASE_NAME-generated.cmake"
+ CONTENT "${GENERATE_CONTENT}" ${GENERATE_CONDITION})
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-check.cmake
new file mode 100644
index 000000000..676ad4bc8
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-check.cmake
@@ -0,0 +1,2 @@
+
+include ("${RunCMake_TEST_BINARY_DIR}/TARGET_FILE_PREFIX-generated.cmake")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-imported-target-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-imported-target-check.cmake
new file mode 100644
index 000000000..676ad4bc8
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-imported-target-check.cmake
@@ -0,0 +1,2 @@
+
+include ("${RunCMake_TEST_BINARY_DIR}/TARGET_FILE_PREFIX-generated.cmake")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-imported-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-imported-target.cmake
new file mode 100644
index 000000000..34e500ac4
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-imported-target.cmake
@@ -0,0 +1,49 @@
+
+cmake_minimum_required(VERSION 3.14)
+
+enable_language (C)
+
+set (win_platforms Windows CYGWIN)
+
+set (GENERATE_CONTENT [[
+macro (CHECK_VALUE test_msg value expected)
+ if (NOT "${value}" STREQUAL "${expected}")
+ string (APPEND RunCMake_TEST_FAILED "${test_msg}: actual result:\n [${value}]\nbut expected:\n [${expected}]\n")
+ endif()
+endmacro()
+]])
+
+add_executable(exec1 IMPORTED)
+add_library (shared1 SHARED IMPORTED)
+add_library (static1 STATIC IMPORTED)
+
+string (APPEND GENERATE_CONTENT
+"\ncheck_value (\"TARGET_FILE_PREFIX executable default\" \"$<TARGET_FILE_PREFIX:exec1>\" \"\")
+check_value (\"TARGET_FILE_PREFIX shared default\" \"$<TARGET_FILE_PREFIX:shared1>\" \"${CMAKE_SHARED_LIBRARY_PREFIX}\")
+check_value (\"TARGET_LINKER_FILE_PREFIX shared linker default\" \"$<TARGET_LINKER_FILE_PREFIX:shared1>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,${CMAKE_IMPORT_LIBRARY_PREFIX},${CMAKE_SHARED_LIBRARY_PREFIX}>\")
+check_value (\"TARGET_FILE_PREFIX static default\" \"$<TARGET_FILE_PREFIX:static1>\" \"${CMAKE_STATIC_LIBRARY_PREFIX}\")
+check_value (\"TARGET_LINKER_FILE_PREFIX static linker default\" \"$<TARGET_LINKER_FILE_PREFIX:static1>\" \"${CMAKE_STATIC_LIBRARY_PREFIX}\")\n")
+
+
+add_executable (exec2 IMPORTED)
+set_property (TARGET exec2 PROPERTY PREFIX exec2_prefix)
+set_property (TARGET exec2 PROPERTY ENABLE_EXPORTS TRUE)
+set_property (TARGET exec2 PROPERTY IMPORT_PREFIX exec2_import_prefix)
+add_library (shared2 SHARED IMPORTED)
+set_property (TARGET shared2 PROPERTY PREFIX shared2_prefix)
+set_property (TARGET shared2 PROPERTY IMPORT_PREFIX shared2_import_prefix)
+add_library (static2 STATIC IMPORTED)
+set_property (TARGET static2 PROPERTY PREFIX static2_prefix)
+set_property (TARGET static2 PROPERTY IMPORT_PREFIX static2_import_prefix)
+
+string (APPEND GENERATE_CONTENT
+"\ncheck_value (\"TARGET_FILE_PREFIX executable custom\" \"$<TARGET_FILE_PREFIX:exec2>\" \"exec2_prefix\")
+check_value (\"TARGET_LINKER_FILE_PREFIX executable linker custom\" \"$<TARGET_LINKER_FILE_PREFIX:exec2>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,exec2_import_prefix,exec2_prefix>\")
+check_value (\"TARGET_FILE_PREFIX shared custom\" \"$<TARGET_FILE_PREFIX:shared2>\" \"shared2_prefix\")
+check_value (\"TARGET_LINKER_FILE_PREFIX shared linker custom\" \"$<TARGET_LINKER_FILE_PREFIX:shared2>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,shared2_import_prefix,shared2_prefix>\")
+check_value (\"TARGET_FILE_PREFIX static custom\" \"$<TARGET_FILE_PREFIX:static2>\" \"static2_prefix\")
+check_value (\"TARGET_LINKER_FILE_PREFIX static linker custom\" \"$<TARGET_LINKER_FILE_PREFIX:static2>\" \"static2_prefix\")\n")
+
+
+file (GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/TARGET_FILE_PREFIX-generated.cmake"
+ CONTENT "${GENERATE_CONTENT}")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target-stderr.txt
new file mode 100644
index 000000000..81362ef04
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at TARGET_FILE_PREFIX-non-valid-target.cmake:[0-9]+ \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_FILE_PREFIX:empty>
+
+ Target "empty" is not an executable or library\.
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target.cmake
new file mode 100644
index 000000000..d1095fa53
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX-non-valid-target.cmake
@@ -0,0 +1,7 @@
+
+add_custom_target(empty)
+
+file(GENERATE
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+ CONTENT "[$<TARGET_FILE_PREFIX:empty>]"
+)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX.cmake
new file mode 100644
index 000000000..6bb1e44d6
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_PREFIX.cmake
@@ -0,0 +1,49 @@
+
+cmake_minimum_required(VERSION 3.14)
+
+enable_language (C)
+
+set (win_platforms Windows CYGWIN)
+
+set (GENERATE_CONTENT [[
+macro (CHECK_VALUE test_msg value expected)
+ if (NOT "${value}" STREQUAL "${expected}")
+ string (APPEND RunCMake_TEST_FAILED "${test_msg}: actual result:\n [${value}]\nbut expected:\n [${expected}]\n")
+ endif()
+endmacro()
+]])
+
+add_executable (exec1 empty.c)
+add_library (shared1 SHARED empty.c)
+add_library (static1 STATIC empty.c)
+
+string (APPEND GENERATE_CONTENT
+"\ncheck_value (\"TARGET_FILE_PREFIX executable default\" \"$<TARGET_FILE_PREFIX:exec1>\" \"\")
+check_value (\"TARGET_FILE_PREFIX shared default\" \"$<TARGET_FILE_PREFIX:shared1>\" \"${CMAKE_SHARED_LIBRARY_PREFIX}\")
+check_value (\"TARGET_LINKER_FILE_PREFIX shared linker default\" \"$<TARGET_LINKER_FILE_PREFIX:shared1>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,${CMAKE_IMPORT_LIBRARY_PREFIX},${CMAKE_SHARED_LIBRARY_PREFIX}>\")
+check_value (\"TARGET_FILE_PREFIX static default\" \"$<TARGET_FILE_PREFIX:static1>\" \"${CMAKE_STATIC_LIBRARY_PREFIX}\")
+check_value (\"TARGET_LINKER_FILE_PREFIX static linker default\" \"$<TARGET_LINKER_FILE_PREFIX:static1>\" \"${CMAKE_STATIC_LIBRARY_PREFIX}\")\n")
+
+
+add_executable (exec2 empty.c)
+set_property (TARGET exec2 PROPERTY PREFIX exec2_prefix)
+set_property (TARGET exec2 PROPERTY ENABLE_EXPORTS TRUE)
+set_property (TARGET exec2 PROPERTY IMPORT_PREFIX exec2_import_prefix)
+add_library (shared2 SHARED empty.c)
+set_property (TARGET shared2 PROPERTY PREFIX shared2_prefix)
+set_property (TARGET shared2 PROPERTY IMPORT_PREFIX shared2_import_prefix)
+add_library (static2 STATIC empty.c)
+set_property (TARGET static2 PROPERTY PREFIX static2_prefix)
+set_property (TARGET static2 PROPERTY IMPORT_PREFIX static2_import_prefix)
+
+string (APPEND GENERATE_CONTENT
+"\ncheck_value (\"TARGET_FILE_PREFIX executable custom\" \"$<TARGET_FILE_PREFIX:exec2>\" \"exec2_prefix\")
+check_value (\"TARGET_LINKER_FILE_PREFIX executable linker custom\" \"$<TARGET_LINKER_FILE_PREFIX:exec2>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,exec2_import_prefix,exec2_prefix>\")
+check_value (\"TARGET_FILE_PREFIX shared custom\" \"$<TARGET_FILE_PREFIX:shared2>\" \"shared2_prefix\")
+check_value (\"TARGET_LINKER_FILE_PREFIX shared linker custom\" \"$<TARGET_LINKER_FILE_PREFIX:shared2>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,shared2_import_prefix,shared2_prefix>\")
+check_value (\"TARGET_FILE_PREFIX static custom\" \"$<TARGET_FILE_PREFIX:static2>\" \"static2_prefix\")
+check_value (\"TARGET_LINKER_FILE_PREFIX static linker custom\" \"$<TARGET_LINKER_FILE_PREFIX:static2>\" \"static2_prefix\")\n")
+
+
+file (GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/TARGET_FILE_PREFIX-generated.cmake"
+ CONTENT "${GENERATE_CONTENT}")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-check.cmake
new file mode 100644
index 000000000..f159370d7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-check.cmake
@@ -0,0 +1,2 @@
+
+include ("${RunCMake_TEST_BINARY_DIR}/TARGET_FILE_SUFFIX-generated.cmake")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-imported-target-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-imported-target-check.cmake
new file mode 100644
index 000000000..f159370d7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-imported-target-check.cmake
@@ -0,0 +1,2 @@
+
+include ("${RunCMake_TEST_BINARY_DIR}/TARGET_FILE_SUFFIX-generated.cmake")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-imported-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-imported-target.cmake
new file mode 100644
index 000000000..e1b7654ce
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-imported-target.cmake
@@ -0,0 +1,49 @@
+
+cmake_minimum_required(VERSION 3.14)
+
+enable_language (C)
+
+set (win_platforms Windows CYGWIN)
+
+set (GENERATE_CONTENT [[
+macro (CHECK_VALUE test_msg value expected)
+ if (NOT "${value}" STREQUAL "${expected}")
+ string (APPEND RunCMake_TEST_FAILED "${test_msg}: actual result:\n [${value}]\nbut expected:\n [${expected}]\n")
+ endif()
+endmacro()
+]])
+
+add_executable (exec1 IMPORTED)
+add_library (shared1 SHARED IMPORTED)
+add_library (static1 STATIC IMPORTED)
+
+string (APPEND GENERATE_CONTENT
+"\ncheck_value (\"TARGET_FILE_SUFFIX executable default\" \"$<TARGET_FILE_SUFFIX:exec1>\" \"${CMAKE_EXECUTABLE_SUFFIX}\")
+check_value (\"TARGET_FILE_SUFFIX shared default\" \"$<TARGET_FILE_SUFFIX:shared1>\" \"${CMAKE_SHARED_LIBRARY_SUFFIX}\")
+check_value (\"TARGET_LINKER_FILE_SUFFIX shared linker default\" \"$<TARGET_LINKER_FILE_SUFFIX:shared1>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,${CMAKE_IMPORT_LIBRARY_SUFFIX},${CMAKE_SHARED_LIBRARY_SUFFIX}>\")
+check_value (\"TARGET_FILE_SUFFIX static default\" \"$<TARGET_FILE_SUFFIX:static1>\" \"${CMAKE_STATIC_LIBRARY_SUFFIX}\")
+check_value (\"TARGET_LINKER_FILE_SUFFIX static linker default\" \"$<TARGET_LINKER_FILE_SUFFIX:static1>\" \"${CMAKE_STATIC_LIBRARY_SUFFIX}\")\n")
+
+
+add_executable (exec2 IMPORTED)
+set_property (TARGET exec2 PROPERTY SUFFIX exec2_suffix)
+set_property (TARGET exec2 PROPERTY ENABLE_EXPORTS TRUE)
+set_property (TARGET exec2 PROPERTY IMPORT_SUFFIX exec2_import_suffix)
+add_library (shared2 SHARED IMPORTED)
+set_property (TARGET shared2 PROPERTY SUFFIX shared2_suffix)
+set_property (TARGET shared2 PROPERTY IMPORT_SUFFIX shared2_import_suffix)
+add_library (static2 STATIC IMPORTED)
+set_property (TARGET static2 PROPERTY SUFFIX static2_suffix)
+set_property (TARGET static2 PROPERTY IMPORT_SUFFIX static2_import_suffix)
+
+string (APPEND GENERATE_CONTENT
+"\ncheck_value (\"TARGET_FILE_SUFFIX executable custom\" \"$<TARGET_FILE_SUFFIX:exec2>\" \"exec2_suffix\")
+check_value (\"TARGET_LINKER_FILE_SUFFIX executable linker custom\" \"$<TARGET_LINKER_FILE_SUFFIX:exec2>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,exec2_import_suffix,exec2_suffix>\")
+check_value (\"TARGET_FILE_SUFFIX shared custom\" \"$<TARGET_FILE_SUFFIX:shared2>\" \"shared2_suffix\")
+check_value (\"TARGET_LINKER_FILE_SUFFIX shared linker custom\" \"$<TARGET_LINKER_FILE_SUFFIX:shared2>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,shared2_import_suffix,shared2_suffix>\")
+check_value (\"TARGET_FILE_SUFFIX static custom\" \"$<TARGET_FILE_SUFFIX:static2>\" \"static2_suffix\")
+check_value (\"TARGET_LINKER_FILE_SUFFIX static linker custom\" \"$<TARGET_LINKER_FILE_SUFFIX:static2>\" \"static2_suffix\")\n")
+
+
+file (GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/TARGET_FILE_SUFFIX-generated.cmake"
+ CONTENT "${GENERATE_CONTENT}")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target-stderr.txt
new file mode 100644
index 000000000..9ea09d163
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at TARGET_FILE_SUFFIX-non-valid-target.cmake:[0-9]+ \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_FILE_SUFFIX:empty>
+
+ Target "empty" is not an executable or library\.
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target.cmake
new file mode 100644
index 000000000..f7089f947
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX-non-valid-target.cmake
@@ -0,0 +1,7 @@
+
+add_custom_target(empty)
+
+file(GENERATE
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+ CONTENT "[$<TARGET_FILE_SUFFIX:empty>]"
+)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX.cmake
new file mode 100644
index 000000000..78afecdaa
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_FILE_SUFFIX.cmake
@@ -0,0 +1,49 @@
+
+cmake_minimum_required(VERSION 3.14)
+
+enable_language (C)
+
+set (win_platforms Windows CYGWIN)
+
+set (GENERATE_CONTENT [[
+macro (CHECK_VALUE test_msg value expected)
+ if (NOT "${value}" STREQUAL "${expected}")
+ string (APPEND RunCMake_TEST_FAILED "${test_msg}: actual result:\n [${value}]\nbut expected:\n [${expected}]\n")
+ endif()
+endmacro()
+]])
+
+add_executable (exec1 empty.c)
+add_library (shared1 SHARED empty.c)
+add_library (static1 STATIC empty.c)
+
+string (APPEND GENERATE_CONTENT
+"\ncheck_value (\"TARGET_FILE_SUFFIX executable default\" \"$<TARGET_FILE_SUFFIX:exec1>\" \"${CMAKE_EXECUTABLE_SUFFIX}\")
+check_value (\"TARGET_FILE_SUFFIX shared default\" \"$<TARGET_FILE_SUFFIX:shared1>\" \"${CMAKE_SHARED_LIBRARY_SUFFIX}\")
+check_value (\"TARGET_LINKER_FILE_SUFFIX shared linker default\" \"$<TARGET_LINKER_FILE_SUFFIX:shared1>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,${CMAKE_IMPORT_LIBRARY_SUFFIX},${CMAKE_SHARED_LIBRARY_SUFFIX}>\")
+check_value (\"TARGET_FILE_SUFFIX static default\" \"$<TARGET_FILE_SUFFIX:static1>\" \"${CMAKE_STATIC_LIBRARY_SUFFIX}\")
+check_value (\"TARGET_LINKER_FILE_SUFFIX static linker default\" \"$<TARGET_LINKER_FILE_SUFFIX:static1>\" \"${CMAKE_STATIC_LIBRARY_SUFFIX}\")\n")
+
+
+add_executable (exec2 empty.c)
+set_property (TARGET exec2 PROPERTY SUFFIX exec2_suffix)
+set_property (TARGET exec2 PROPERTY ENABLE_EXPORTS TRUE)
+set_property (TARGET exec2 PROPERTY IMPORT_SUFFIX exec2_import_suffix)
+add_library (shared2 SHARED empty.c)
+set_property (TARGET shared2 PROPERTY SUFFIX shared2_suffix)
+set_property (TARGET shared2 PROPERTY IMPORT_SUFFIX shared2_import_suffix)
+add_library (static2 STATIC empty.c)
+set_property (TARGET static2 PROPERTY SUFFIX static2_suffix)
+set_property (TARGET static2 PROPERTY IMPORT_SUFFIX static2_import_suffix)
+
+string (APPEND GENERATE_CONTENT
+"\ncheck_value (\"TARGET_FILE_SUFFIX executable custom\" \"$<TARGET_FILE_SUFFIX:exec2>\" \"exec2_suffix\")
+check_value (\"TARGET_LINKER_FILE_SUFFIX executable linker custom\" \"$<TARGET_LINKER_FILE_SUFFIX:exec2>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,exec2_import_suffix,exec2_suffix>\")
+check_value (\"TARGET_FILE_SUFFIX shared custom\" \"$<TARGET_FILE_SUFFIX:shared2>\" \"shared2_suffix\")
+check_value (\"TARGET_LINKER_FILE_SUFFIX shared linker custom\" \"$<TARGET_LINKER_FILE_SUFFIX:shared2>\" \"$<IF:$<IN_LIST:$<PLATFORM_ID>,${win_platforms}>,shared2_import_suffix,shared2_suffix>\")
+check_value (\"TARGET_FILE_SUFFIX static custom\" \"$<TARGET_FILE_SUFFIX:static2>\" \"static2_suffix\")
+check_value (\"TARGET_LINKER_FILE_SUFFIX static linker custom\" \"$<TARGET_LINKER_FILE_SUFFIX:static2>\" \"static2_suffix\")\n")
+
+
+file (GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/TARGET_FILE_SUFFIX-generated.cmake"
+ CONTENT "${GENERATE_CONTENT}")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-check.cmake
new file mode 100644
index 000000000..124a583e2
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/TARGET_GENEX_EVAL-generated.txt" content)
+
+set(expected "BEFORE_PROPERTY1_AFTER")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-stderr.txt
new file mode 100644
index 000000000..9b0844f9f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg-stderr.txt
@@ -0,0 +1,9 @@
+^CMake Error at TARGET_GENEX_EVAL-no-arg.cmake:4 \(add_custom_command\):
+ Error evaluating generator expression:
+
+ \$<TARGET_GENEX_EVAL:>
+
+ \$<TARGET_GENEX_EVAL> expression requires 2 comma separated parameters, but
+ got 1 instead.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg.cmake
new file mode 100644
index 000000000..2dc13ea5e
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-arg.cmake
@@ -0,0 +1,7 @@
+
+cmake_policy(VERSION 3.11)
+
+add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c"
+ COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_SOURCE_DIR}/empty.c" "${CMAKE_CURRENT_BINARY_DIR}/copied_file$<TARGET_GENEX_EVAL:>.c"
+)
+add_custom_target(drive DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-stderr.txt
new file mode 100644
index 000000000..647fd85c6
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target-stderr.txt
@@ -0,0 +1,9 @@
+^CMake Error at TARGET_GENEX_EVAL-no-target.cmake:2 \(add_custom_command\):
+ Error evaluating generator expression:
+
+ \$<TARGET_GENEX_EVAL:,>
+
+ \$<TARGET_GENEX_EVAL:tgt, ...> expression requires a non-empty valid target
+ name.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target.cmake
new file mode 100644
index 000000000..df4f0eac6
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-no-target.cmake
@@ -0,0 +1,5 @@
+
+add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c"
+ COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_SOURCE_DIR}/empty.c" "${CMAKE_CURRENT_BINARY_DIR}/copied_file$<TARGET_GENEX_EVAL:,>.c"
+)
+add_custom_target(drive DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-stderr.txt
new file mode 100644
index 000000000..cc44d4b9c
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target-stderr.txt
@@ -0,0 +1,8 @@
+^CMake Error at TARGET_GENEX_EVAL-non-valid-target.cmake:2 \(add_custom_command\):
+ Error evaluating generator expression:
+
+ \$<TARGET_GENEX_EVAL:bad-target,>
+
+ \$<TARGET_GENEX_EVAL:tgt, ...> target "bad-target" not found.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target.cmake
new file mode 100644
index 000000000..8db737593
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-non-valid-target.cmake
@@ -0,0 +1,5 @@
+
+add_custom_command(OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c"
+ COMMAND "${CMAKE_COMMAND}" -E copy "${CMAKE_CURRENT_SOURCE_DIR}/empty.c" "${CMAKE_CURRENT_BINARY_DIR}/copied_file$<TARGET_GENEX_EVAL:bad-target,>.c"
+)
+add_custom_target(drive DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/copied_file.c")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-stderr.txt
new file mode 100644
index 000000000..bba22340c
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1-stderr.txt
@@ -0,0 +1,9 @@
+^CMake Error at TARGET_GENEX_EVAL-recursion1.cmake:7 \(add_custom_target\):
+ Error evaluating generator expression:
+
+ \$<TARGET_GENEX_EVAL:recursion,\$<TARGET_PROPERTY:CUSTOM_PROPERTY>>
+
+ Self reference on target "recursion".
+
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1.cmake
new file mode 100644
index 000000000..b75d21175
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion1.cmake
@@ -0,0 +1,9 @@
+
+enable_language(C)
+
+add_library (recursion SHARED empty.c)
+set_property (TARGET recursion PROPERTY CUSTOM_PROPERTY "$<TARGET_GENEX_EVAL:recursion,$<TARGET_PROPERTY:CUSTOM_PROPERTY>>")
+
+add_custom_target (drive
+ COMMAND echo "$<TARGET_GENEX_EVAL:recursion,$<TARGET_PROPERTY:recursion,CUSTOM_PROPERTY>>"
+ DEPENDS recursion)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-stderr.txt
new file mode 100644
index 000000000..73f6b77e9
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2-stderr.txt
@@ -0,0 +1,26 @@
+^CMake Error at TARGET_GENEX_EVAL-recursion2.cmake:10 \(add_custom_target\):
+ Error evaluating generator expression:
+
+ \$<TARGET_GENEX_EVAL:recursion1,\$<TARGET_PROPERTY:recursion1,CUSTOM_PROPERTY1>>
+
+ Dependency loop found.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+
+
+CMake Error at TARGET_GENEX_EVAL-recursion2.cmake:10 \(add_custom_target\):
+ Loop step 1
+
+ \$<TARGET_GENEX_EVAL:recursion2,\$<TARGET_PROPERTY:recursion2,CUSTOM_PROPERTY2>>
+
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+
+
+CMake Error at TARGET_GENEX_EVAL-recursion2.cmake:10 \(add_custom_target\):
+ Loop step 2
+
+ \$<TARGET_GENEX_EVAL:recursion1,\$<TARGET_PROPERTY:recursion1,CUSTOM_PROPERTY1>>
+
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2.cmake
new file mode 100644
index 000000000..a28dfc34d
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL-recursion2.cmake
@@ -0,0 +1,12 @@
+
+enable_language(C)
+
+add_library (recursion1 SHARED empty.c)
+set_property (TARGET recursion1 PROPERTY CUSTOM_PROPERTY1 "$<TARGET_GENEX_EVAL:recursion2,$<TARGET_PROPERTY:recursion2,CUSTOM_PROPERTY2>>")
+
+add_library (recursion2 SHARED empty.c)
+set_property (TARGET recursion2 PROPERTY CUSTOM_PROPERTY2 "$<TARGET_GENEX_EVAL:recursion1,$<TARGET_PROPERTY:recursion1,CUSTOM_PROPERTY1>>")
+
+add_custom_target (drive
+ COMMAND echo "$<TARGET_GENEX_EVAL:recursion1,$<TARGET_PROPERTY:recursion1,CUSTOM_PROPERTY1>>"
+ DEPENDS recursion)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL.cmake
new file mode 100644
index 000000000..68b371257
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_GENEX_EVAL.cmake
@@ -0,0 +1,10 @@
+
+cmake_policy(VERSION 3.11)
+
+enable_language(C)
+
+add_library (example SHARED empty.c)
+set_property (TARGET example PROPERTY CUSTOM_PROPERTY1 "PROPERTY1")
+set_property (TARGET example PROPERTY CUSTOM_PROPERTY2 "BEFORE_$<TARGET_PROPERTY:CUSTOM_PROPERTY1>_AFTER")
+
+file(GENERATE OUTPUT "TARGET_GENEX_EVAL-generated.txt" CONTENT "$<TARGET_GENEX_EVAL:example,$<TARGET_PROPERTY:example,CUSTOM_PROPERTY2>>")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-stderr.txt
new file mode 100644
index 000000000..1ae2f2c86
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at TARGET_LINKER_FILE_BASE_NAME-non-valid-target.cmake:[0-9]+ \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_LINKER_FILE_BASE_NAME:empty>
+
+ Target "empty" is not an executable or library\.
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target.cmake
new file mode 100644
index 000000000..776fb4bbb
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_BASE_NAME-non-valid-target.cmake
@@ -0,0 +1,7 @@
+
+add_custom_target(empty)
+
+file(GENERATE
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+ CONTENT "[$<TARGET_LINKER_FILE_BASE_NAME:empty>]"
+)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target-stderr.txt
new file mode 100644
index 000000000..7a36cefbc
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at TARGET_LINKER_FILE_PREFIX-non-valid-target.cmake:[0-9]+ \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_LINKER_FILE_PREFIX:empty>
+
+ Target "empty" is not an executable or library\.
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target.cmake
new file mode 100644
index 000000000..8dad4dad4
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_PREFIX-non-valid-target.cmake
@@ -0,0 +1,7 @@
+
+add_custom_target(empty)
+
+file(GENERATE
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+ CONTENT "[$<TARGET_LINKER_FILE_PREFIX:empty>]"
+)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target-stderr.txt
new file mode 100644
index 000000000..cc5217a14
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target-stderr.txt
@@ -0,0 +1,6 @@
+CMake Error at TARGET_LINKER_FILE_SUFFIX-non-valid-target.cmake:[0-9]+ \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_LINKER_FILE_SUFFIX:empty>
+
+ Target "empty" is not an executable or library\.
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target.cmake
new file mode 100644
index 000000000..82c2f3a04
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_LINKER_FILE_SUFFIX-non-valid-target.cmake
@@ -0,0 +1,7 @@
+
+add_custom_target(empty)
+
+file(GENERATE
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+ CONTENT "[$<TARGET_LINKER_FILE_SUFFIX:empty>]"
+)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-check.cmake
new file mode 100644
index 000000000..2f5743093
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-check.cmake
@@ -0,0 +1,6 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/TARGET_NAME_IF_EXISTS-generated.txt" content)
+
+set(expected "foo")
+if(NOT content STREQUAL expected)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected:\n [[${expected}]]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-stderr.txt
new file mode 100644
index 000000000..5ee13b727
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg-stderr.txt
@@ -0,0 +1,9 @@
+CMake Error at TARGET_NAME_IF_EXISTS-empty-arg.cmake:2 \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_NAME_IF_EXISTS:>
+
+ \$<TARGET_NAME_IF_EXISTS:tgt> expression requires a non-empty valid target
+ name.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg.cmake
new file mode 100644
index 000000000..f5034f429
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-empty-arg.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0070 NEW)
+file(GENERATE OUTPUT TARGET_NAME_IF_EXISTS-generated.txt CONTENT "$<TARGET_NAME_IF_EXISTS:${empty}>")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-result.txt b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-stderr.txt b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-stderr.txt
new file mode 100644
index 000000000..4122425ab
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at TARGET_NAME_IF_EXISTS-no-arg.cmake:2 \(file\):
+ Error evaluating generator expression:
+
+ \$<TARGET_NAME_IF_EXISTS>
+
+ \$<TARGET_NAME_IF_EXISTS> expression requires exactly one parameter.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg.cmake
new file mode 100644
index 000000000..32930948a
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-no-arg.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0070 NEW)
+file(GENERATE OUTPUT TARGET_NAME_IF_EXISTS-generated.txt CONTENT "$<TARGET_NAME_IF_EXISTS>")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target-check.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target-check.cmake
new file mode 100644
index 000000000..2085c167e
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target-check.cmake
@@ -0,0 +1,5 @@
+file(READ "${RunCMake_TEST_BINARY_DIR}/TARGET_NAME_IF_EXISTS-not-a-target-generated.txt" content)
+
+if(content)
+ set(RunCMake_TEST_FAILED "actual content:\n [[${content}]]\nbut expected an empty string")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target.cmake
new file mode 100644
index 000000000..a054e6cc7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS-not-a-target.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0070 NEW)
+file(GENERATE OUTPUT TARGET_NAME_IF_EXISTS-not-a-target-generated.txt CONTENT "$<TARGET_NAME_IF_EXISTS:just-random-string>")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS.cmake
new file mode 100644
index 000000000..0ce3b1d7f
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_NAME_IF_EXISTS.cmake
@@ -0,0 +1,3 @@
+cmake_policy(SET CMP0070 NEW)
+add_custom_target(foo)
+file(GENERATE OUTPUT TARGET_NAME_IF_EXISTS-generated.txt CONTENT "$<TARGET_NAME_IF_EXISTS:foo>")
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-INCLUDE_DIRECTORIES.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-INCLUDE_DIRECTORIES.cmake
new file mode 100644
index 000000000..cb6f4d867
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-INCLUDE_DIRECTORIES.cmake
@@ -0,0 +1,18 @@
+cmake_minimum_required(VERSION 3.14)
+enable_language(C)
+
+add_library(foo1 STATIC empty.c)
+target_include_directories(foo1 PUBLIC include)
+target_link_libraries(foo1 PRIVATE foo2 foo3 foo4)
+
+add_library(foo2 STATIC empty.c)
+target_include_directories(foo2 PUBLIC $<TARGET_PROPERTY:foo1,INCLUDE_DIRECTORIES>)
+
+add_library(foo3 STATIC empty.c)
+target_include_directories(foo3 PUBLIC $<TARGET_PROPERTY:foo2,INCLUDE_DIRECTORIES>)
+
+add_library(foo4 STATIC empty.c)
+target_include_directories(foo4 PUBLIC $<TARGET_PROPERTY:foo3,INCLUDE_DIRECTORIES>)
+
+# Evaluate a genex that looks up INCLUDE_DIRECTORIES on multiple targets.
+file(GENERATE OUTPUT out.txt CONTENT "$<TARGET_PROPERTY:foo4,INCLUDE_DIRECTORIES>")
diff --git a/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME-check.cmake b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME-check.cmake
new file mode 100644
index 000000000..996d2d4e6
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME-check.cmake
@@ -0,0 +1,7 @@
+file(STRINGS ${RunCMake_TEST_BINARY_DIR}/test.txt TEST_TXT ENCODING UTF-8)
+
+list(GET TEST_TXT 0 PDB_FILE_BASE_NAME)
+
+if(NOT PDB_FILE_BASE_NAME MATCHES "empty")
+ set(RunCMake_TEST_FAILED "unexpected PDB_FILE_BASE_NAME [${PDB_FILE_BASE_NAME}]")
+endif()
diff --git a/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake
new file mode 100644
index 000000000..cc53bdf0a
--- /dev/null
+++ b/Tests/RunCMake/GeneratorExpression/ValidTarget-TARGET_PDB_FILE_BASE_NAME.cmake
@@ -0,0 +1,16 @@
+
+enable_language(C)
+
+add_library(empty SHARED empty.c)
+
+get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
+if(_isMultiConfig)
+ list(GET CMAKE_CONFIGURATION_TYPES 0 FIRST_CONFIG)
+ set(GENERATE_CONDITION CONDITION $<CONFIG:${FIRST_CONFIG}>)
+endif()
+
+file(GENERATE
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/test.txt"
+ CONTENT "$<TARGET_PDB_FILE_BASE_NAME:empty>"
+ ${GENERATE_CONDITION}
+)
diff --git a/Tests/RunCMake/GeneratorInstance/BadInstance-result.txt b/Tests/RunCMake/GeneratorInstance/BadInstance-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/BadInstance-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorInstance/BadInstance-stderr.txt b/Tests/RunCMake/GeneratorInstance/BadInstance-stderr.txt
new file mode 100644
index 000000000..5d01c4f9a
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/BadInstance-stderr.txt
@@ -0,0 +1,10 @@
+CMake Error at CMakeLists.txt:[0-9]+ \(project\):
+ Generator
+
+ .*
+
+ does not support instance specification, but instance
+
+ Bad Instance
+
+ was specified.$
diff --git a/Tests/RunCMake/GeneratorInstance/BadInstance-toolchain.cmake b/Tests/RunCMake/GeneratorInstance/BadInstance-toolchain.cmake
new file mode 100644
index 000000000..1d99259d5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/BadInstance-toolchain.cmake
@@ -0,0 +1 @@
+set(CMAKE_GENERATOR_INSTANCE "Bad Instance")
diff --git a/Tests/RunCMake/GeneratorInstance/BadInstance.cmake b/Tests/RunCMake/GeneratorInstance/BadInstance.cmake
new file mode 100644
index 000000000..2fc38e5c5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/BadInstance.cmake
@@ -0,0 +1 @@
+message(FATAL_ERROR "This should not be reached!")
diff --git a/Tests/RunCMake/GeneratorInstance/BadInstanceToolchain-result.txt b/Tests/RunCMake/GeneratorInstance/BadInstanceToolchain-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/BadInstanceToolchain-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorInstance/BadInstanceToolchain-stderr.txt b/Tests/RunCMake/GeneratorInstance/BadInstanceToolchain-stderr.txt
new file mode 100644
index 000000000..5d01c4f9a
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/BadInstanceToolchain-stderr.txt
@@ -0,0 +1,10 @@
+CMake Error at CMakeLists.txt:[0-9]+ \(project\):
+ Generator
+
+ .*
+
+ does not support instance specification, but instance
+
+ Bad Instance
+
+ was specified.$
diff --git a/Tests/RunCMake/GeneratorInstance/BadInstanceToolchain.cmake b/Tests/RunCMake/GeneratorInstance/BadInstanceToolchain.cmake
new file mode 100644
index 000000000..2fc38e5c5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/BadInstanceToolchain.cmake
@@ -0,0 +1 @@
+message(FATAL_ERROR "This should not be reached!")
diff --git a/Tests/RunCMake/GeneratorInstance/CMakeLists.txt b/Tests/RunCMake/GeneratorInstance/CMakeLists.txt
new file mode 100644
index 000000000..d3137f614
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/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/GeneratorInstance/DefaultInstance.cmake b/Tests/RunCMake/GeneratorInstance/DefaultInstance.cmake
new file mode 100644
index 000000000..7750c2e14
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/DefaultInstance.cmake
@@ -0,0 +1,13 @@
+if("x${CMAKE_GENERATOR_INSTANCE}" STREQUAL "x")
+ message(FATAL_ERROR "CMAKE_GENERATOR_INSTANCE is empty but should have a value.")
+elseif("x${CMAKE_GENERATOR_INSTANCE}" MATCHES [[\\]])
+ message(FATAL_ERROR
+ "CMAKE_GENERATOR_INSTANCE is\n"
+ " ${CMAKE_GENERATOR_INSTANCE}\n"
+ "which contains a backslash.")
+elseif(NOT IS_DIRECTORY "${CMAKE_GENERATOR_INSTANCE}")
+ message(FATAL_ERROR
+ "CMAKE_GENERATOR_INSTANCE is\n"
+ " ${CMAKE_GENERATOR_INSTANCE}\n"
+ "which is not an existing directory.")
+endif()
diff --git a/Tests/RunCMake/GeneratorInstance/MissingInstance-result.txt b/Tests/RunCMake/GeneratorInstance/MissingInstance-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/MissingInstance-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorInstance/MissingInstance-stderr.txt b/Tests/RunCMake/GeneratorInstance/MissingInstance-stderr.txt
new file mode 100644
index 000000000..623bf2ef8
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/MissingInstance-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at CMakeLists.txt:[0-9]+ \(project\):
+ Generator
+
+ .*
+
+ could not find specified instance of .*:
+
+ .*/Tests/RunCMake/GeneratorInstance/instance_does_not_exist$
diff --git a/Tests/RunCMake/GeneratorInstance/MissingInstance-toolchain.cmake b/Tests/RunCMake/GeneratorInstance/MissingInstance-toolchain.cmake
new file mode 100644
index 000000000..f803f14d0
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/MissingInstance-toolchain.cmake
@@ -0,0 +1 @@
+set(CMAKE_GENERATOR_INSTANCE "${CMAKE_CURRENT_LIST_DIR}/instance_does_not_exist")
diff --git a/Tests/RunCMake/GeneratorInstance/MissingInstance.cmake b/Tests/RunCMake/GeneratorInstance/MissingInstance.cmake
new file mode 100644
index 000000000..2fc38e5c5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/MissingInstance.cmake
@@ -0,0 +1 @@
+message(FATAL_ERROR "This should not be reached!")
diff --git a/Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain-result.txt b/Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain-stderr.txt b/Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain-stderr.txt
new file mode 100644
index 000000000..623bf2ef8
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain-stderr.txt
@@ -0,0 +1,8 @@
+CMake Error at CMakeLists.txt:[0-9]+ \(project\):
+ Generator
+
+ .*
+
+ could not find specified instance of .*:
+
+ .*/Tests/RunCMake/GeneratorInstance/instance_does_not_exist$
diff --git a/Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain.cmake b/Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain.cmake
new file mode 100644
index 000000000..2fc38e5c5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/MissingInstanceToolchain.cmake
@@ -0,0 +1 @@
+message(FATAL_ERROR "This should not be reached!")
diff --git a/Tests/RunCMake/GeneratorInstance/NoInstance-result.txt b/Tests/RunCMake/GeneratorInstance/NoInstance-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/NoInstance-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorInstance/NoInstance-stderr.txt b/Tests/RunCMake/GeneratorInstance/NoInstance-stderr.txt
new file mode 100644
index 000000000..e7b52fd5d
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/NoInstance-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at NoInstance.cmake:2 \(message\):
+ CMAKE_GENERATOR_INSTANCE is empty as expected.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorInstance/NoInstance.cmake b/Tests/RunCMake/GeneratorInstance/NoInstance.cmake
new file mode 100644
index 000000000..2e6782e38
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/NoInstance.cmake
@@ -0,0 +1,7 @@
+if("x${CMAKE_GENERATOR_INSTANCE}" STREQUAL "x")
+ message(FATAL_ERROR "CMAKE_GENERATOR_INSTANCE is empty as expected.")
+else()
+ message(FATAL_ERROR
+ "CMAKE_GENERATOR_INSTANCE is \"${CMAKE_GENERATOR_INSTANCE}\" "
+ "but should be empty!")
+endif()
diff --git a/Tests/RunCMake/GeneratorInstance/RunCMakeTest.cmake b/Tests/RunCMake/GeneratorInstance/RunCMakeTest.cmake
new file mode 100644
index 000000000..e7f9ccbc4
--- /dev/null
+++ b/Tests/RunCMake/GeneratorInstance/RunCMakeTest.cmake
@@ -0,0 +1,22 @@
+include(RunCMake)
+
+if("${RunCMake_GENERATOR}" MATCHES "^Visual Studio 1[56789]")
+ set(RunCMake_GENERATOR_INSTANCE "")
+ run_cmake(DefaultInstance)
+
+ set(RunCMake_GENERATOR_INSTANCE "${RunCMake_SOURCE_DIR}/instance_does_not_exist")
+ run_cmake(MissingInstance)
+ set(RunCMake_TEST_OPTIONS -DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/MissingInstance-toolchain.cmake)
+ run_cmake(MissingInstanceToolchain)
+ unset(RunCMake_TEST_OPTIONS)
+else()
+ set(RunCMake_GENERATOR_INSTANCE "")
+ run_cmake(NoInstance)
+
+ set(RunCMake_GENERATOR_INSTANCE "Bad Instance")
+ run_cmake(BadInstance)
+
+ set(RunCMake_TEST_OPTIONS -DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/BadInstance-toolchain.cmake)
+ run_cmake(BadInstanceToolchain)
+ unset(RunCMake_TEST_OPTIONS)
+endif()
diff --git a/Tests/RunCMake/GeneratorToolset/BadToolsetVersion-result.txt b/Tests/RunCMake/GeneratorToolset/BadToolsetVersion-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/BadToolsetVersion-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorToolset/BadToolsetVersion-stderr.txt b/Tests/RunCMake/GeneratorToolset/BadToolsetVersion-stderr.txt
new file mode 100644
index 000000000..c976f59ca
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/BadToolsetVersion-stderr.txt
@@ -0,0 +1,10 @@
+CMake Error at CMakeLists.txt:[0-9]+ \(project\):
+ Generator
+
+ .*
+
+ given toolset and version specification
+
+ Test Toolset,version=Bad Toolset Version
+
+ contains an invalid version specification.
diff --git a/Tests/RunCMake/GeneratorToolset/BadToolsetVersion.cmake b/Tests/RunCMake/GeneratorToolset/BadToolsetVersion.cmake
new file mode 100644
index 000000000..2fc38e5c5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/BadToolsetVersion.cmake
@@ -0,0 +1 @@
+message(FATAL_ERROR "This should not be reached!")
diff --git a/Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice-result.txt b/Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice-stderr.txt b/Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice-stderr.txt
new file mode 100644
index 000000000..b780dad92
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice-stderr.txt
@@ -0,0 +1,10 @@
+CMake Error at CMakeLists.txt:[0-9]+ \(project\):
+ Generator
+
+ .*
+
+ given toolset specification
+
+ Test Toolset,version=Test Toolset Version,version=Test Toolset Version
+
+ that contains duplicate field key 'version'\.$
diff --git a/Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice.cmake b/Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice.cmake
new file mode 100644
index 000000000..2fc38e5c5
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/BadToolsetVersionTwice.cmake
@@ -0,0 +1 @@
+message(FATAL_ERROR "This should not be reached!")
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x64-stdout.txt b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x64-stdout.txt
new file mode 100644
index 000000000..8271bd487
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x64-stdout.txt
@@ -0,0 +1,2 @@
+-- CMAKE_VS_PLATFORM_TOOLSET='v[0-9]+'
+-- CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE='x64'
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x64.cmake b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x64.cmake
new file mode 100644
index 000000000..26926f9db
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x64.cmake
@@ -0,0 +1,2 @@
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET='${CMAKE_VS_PLATFORM_TOOLSET}'")
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE='${CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE}'")
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x86-stdout.txt b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x86-stdout.txt
new file mode 100644
index 000000000..c7293dc42
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x86-stdout.txt
@@ -0,0 +1,2 @@
+-- CMAKE_VS_PLATFORM_TOOLSET='v[0-9]+'
+-- CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE='x86'
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x86.cmake b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x86.cmake
new file mode 100644
index 000000000..26926f9db
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetHostArchOnly_x86.cmake
@@ -0,0 +1,2 @@
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET='${CMAKE_VS_PLATFORM_TOOLSET}'")
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE='${CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE}'")
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetVersionBoth-stdout.txt b/Tests/RunCMake/GeneratorToolset/TestToolsetVersionBoth-stdout.txt
new file mode 100644
index 000000000..9b91fdec3
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetVersionBoth-stdout.txt
@@ -0,0 +1,2 @@
+-- CMAKE_VS_PLATFORM_TOOLSET='Test Toolset'
+-- CMAKE_VS_PLATFORM_TOOLSET_VERSION='Test Toolset Version'
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetVersionBoth.cmake b/Tests/RunCMake/GeneratorToolset/TestToolsetVersionBoth.cmake
new file mode 100644
index 000000000..fbc75bec8
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetVersionBoth.cmake
@@ -0,0 +1,2 @@
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET='${CMAKE_VS_PLATFORM_TOOLSET}'")
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET_VERSION='${CMAKE_VS_PLATFORM_TOOLSET_VERSION}'")
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetVersionOnly-stdout.txt b/Tests/RunCMake/GeneratorToolset/TestToolsetVersionOnly-stdout.txt
new file mode 100644
index 000000000..25c41635b
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetVersionOnly-stdout.txt
@@ -0,0 +1,2 @@
+-- CMAKE_VS_PLATFORM_TOOLSET='v[0-9]+'
+-- CMAKE_VS_PLATFORM_TOOLSET_VERSION='Test Toolset Version'
diff --git a/Tests/RunCMake/GeneratorToolset/TestToolsetVersionOnly.cmake b/Tests/RunCMake/GeneratorToolset/TestToolsetVersionOnly.cmake
new file mode 100644
index 000000000..fbc75bec8
--- /dev/null
+++ b/Tests/RunCMake/GeneratorToolset/TestToolsetVersionOnly.cmake
@@ -0,0 +1,2 @@
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET='${CMAKE_VS_PLATFORM_TOOLSET}'")
+message(STATUS "CMAKE_VS_PLATFORM_TOOLSET_VERSION='${CMAKE_VS_PLATFORM_TOOLSET_VERSION}'")
diff --git a/Tests/RunCMake/GetPrerequisites/ExecutableScripts-stdout.txt b/Tests/RunCMake/GetPrerequisites/ExecutableScripts-stdout.txt
new file mode 100644
index 000000000..5a353d8c8
--- /dev/null
+++ b/Tests/RunCMake/GetPrerequisites/ExecutableScripts-stdout.txt
@@ -0,0 +1,3 @@
+-- GetPrequisites\(.*script.sh\) : ignoring script file
+-- GetPrequisites\(.*script.bat\) : ignoring script file
+-- GetPrequisites\(.*script\) : ignoring script file
diff --git a/Tests/RunCMake/GetPrerequisites/ExecutableScripts.cmake b/Tests/RunCMake/GetPrerequisites/ExecutableScripts.cmake
new file mode 100644
index 000000000..d1bc9b1d4
--- /dev/null
+++ b/Tests/RunCMake/GetPrerequisites/ExecutableScripts.cmake
@@ -0,0 +1,19 @@
+include(GetPrerequisites)
+
+function(check_script script)
+ set(prereqs "")
+ get_prerequisites(${script} prereqs 1 1 "" "")
+ if(NOT "${prereqs}" STREQUAL "")
+ message(FATAL_ERROR "Prerequisites for ${script} not empty")
+ endif()
+endfunction()
+
+# Should not throw any errors
+# Regular executable
+get_prerequisites(${CMAKE_COMMAND} cmake_prereqs 1 1 "" "")
+# Shell script
+check_script(${CMAKE_CURRENT_LIST_DIR}/script.sh)
+# Batch script
+check_script(${CMAKE_CURRENT_LIST_DIR}/script.bat)
+# Shell script without extension
+check_script(${CMAKE_CURRENT_LIST_DIR}/script)
diff --git a/Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake b/Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake
new file mode 100644
index 000000000..a635e385e
--- /dev/null
+++ b/Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake
@@ -0,0 +1,4 @@
+include(RunCMake)
+
+run_cmake_command(TargetMissing ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/TargetMissing.cmake)
+run_cmake_command(ExecutableScripts ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/ExecutableScripts.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/GetPrerequisites/script b/Tests/RunCMake/GetPrerequisites/script
new file mode 100755
index 000000000..23bf47c06
--- /dev/null
+++ b/Tests/RunCMake/GetPrerequisites/script
@@ -0,0 +1,3 @@
+#!/bin/bash
+
+echo "Hello World"
diff --git a/Tests/RunCMake/GetPrerequisites/script.bat b/Tests/RunCMake/GetPrerequisites/script.bat
new file mode 100755
index 000000000..338ae039b
--- /dev/null
+++ b/Tests/RunCMake/GetPrerequisites/script.bat
@@ -0,0 +1,3 @@
+@echo off
+
+echo "Hello world"
diff --git a/Tests/RunCMake/GetPrerequisites/script.sh b/Tests/RunCMake/GetPrerequisites/script.sh
new file mode 100755
index 000000000..23bf47c06
--- /dev/null
+++ b/Tests/RunCMake/GetPrerequisites/script.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+
+echo "Hello World"
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-discovery-timeout-result.txt b/Tests/RunCMake/GoogleTest/GoogleTest-discovery-timeout-result.txt
new file mode 100644
index 000000000..d197c913c
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-discovery-timeout-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-discovery-timeout-stdout.txt b/Tests/RunCMake/GoogleTest/GoogleTest-discovery-timeout-stdout.txt
new file mode 100644
index 000000000..3a6572c3e
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-discovery-timeout-stdout.txt
@@ -0,0 +1,7 @@
+( *|[0-9]+>)CMake Error at .*GoogleTestAddTests.cmake:[0-9]+ \(message\):
+( *|[0-9]+>) Error running test executable.
+?( *|[0-9]+>)
+( *|[0-9]+>) Path: '.*discovery_timeout_test(\.exe)?'
+( *|[0-9]+>) Result: Process terminated due to timeout
+( *|[0-9]+>) Output:
+( *|[0-9]+>) +
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-result.txt b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-result.txt
new file mode 100644
index 000000000..d197c913c
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-stderr.txt b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-stderr.txt
new file mode 100644
index 000000000..ba4235def
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-stderr.txt
@@ -0,0 +1 @@
+Errors while running CTest
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-stdout.txt b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-stdout.txt
new file mode 100644
index 000000000..0dda49d7c
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout1-stdout.txt
@@ -0,0 +1,10 @@
+Test project .*GoogleTest-build
+[ \t]*Start [0-9]+: property_timeout.case_no_discovery
+[^\n]+property_timeout.case_no_discovery +\.+\*\*\*Timeout +[0-9.]+ sec
++
+0% tests passed, 1 tests failed out of 1
++
+Total Test time \(real\) = +[0-9.]+ sec
++
+The following tests FAILED:
+[^\n]*property_timeout.case_no_discovery \(Timeout\)
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-result.txt b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-result.txt
new file mode 100644
index 000000000..d197c913c
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-stderr.txt b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-stderr.txt
new file mode 100644
index 000000000..ba4235def
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-stderr.txt
@@ -0,0 +1 @@
+Errors while running CTest
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-stdout.txt b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-stdout.txt
new file mode 100644
index 000000000..72cea558e
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-property-timeout2-stdout.txt
@@ -0,0 +1,10 @@
+Test project .*GoogleTest-build
+[ \t]*Start [0-9]+: property_timeout.case_with_discovery
+[^\n]+property_timeout.case_with_discovery +\.+\*\*\*Timeout +[0-9.]+ sec
++
+0% tests passed, 1 tests failed out of 1
++
+Total Test time \(real\) = +[0-9.]+ sec
++
+The following tests FAILED:
+[^\n]*property_timeout.case_with_discovery \(Timeout\)
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-test-missing-result.txt b/Tests/RunCMake/GoogleTest/GoogleTest-test-missing-result.txt
new file mode 100644
index 000000000..d197c913c
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-test-missing-result.txt
@@ -0,0 +1 @@
+[^0]
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-test-missing-stderr.txt b/Tests/RunCMake/GoogleTest/GoogleTest-test-missing-stderr.txt
new file mode 100644
index 000000000..a4cc97192
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-test-missing-stderr.txt
@@ -0,0 +1,2 @@
+Unable to find executable: no_tests_defined_NOT_BUILT
+Errors while running CTest
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-test1-stdout.txt b/Tests/RunCMake/GoogleTest/GoogleTest-test1-stdout.txt
new file mode 100644
index 000000000..5f7753dba
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-test1-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-test2-stdout.txt b/Tests/RunCMake/GoogleTest/GoogleTest-test2-stdout.txt
new file mode 100644
index 000000000..960c0b9cf
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-test2-stdout.txt
@@ -0,0 +1,25 @@
+Test project .*
+ Start 9: TEST:basic\.case_foo!2
+1/8 Test #9: TEST:basic\.case_foo!2 \.+ +Passed +[0-9.]+ sec
+ Start 10: TEST:basic\.case_bar!2
+2/8 Test #10: TEST:basic\.case_bar!2 \.+ +Passed +[0-9.]+ sec
+ Start 11: TEST:basic\.disabled_case!2
+3/8 Test #11: TEST:basic\.disabled_case!2 \.+\*+Not Run \(Disabled\) +[0-9.]+ sec
+ Start 12: TEST:disabled\.case!2
+4/8 Test #12: TEST:disabled\.case!2 \.+\*+Not Run \(Disabled\) +[0-9.]+ sec
+ Start 13: TEST:typed/short\.case!2
+5/8 Test #13: TEST:typed/short\.case!2 \.+ +Passed +[0-9.]+ sec
+ Start 14: TEST:typed/float\.case!2
+6/8 Test #14: TEST:typed/float\.case!2 \.+ +Passed +[0-9.]+ sec
+ Start 15: TEST:value/test\.case/1!2
+7/8 Test #15: TEST:value/test\.case/1!2 \.+ +Passed +[0-9.]+ sec
+ Start 16: TEST:value/test\.case/"foo"!2
+8/8 Test #16: TEST:value/test\.case/"foo"!2 \.+ +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:
+.*11 - TEST:basic\.disabled_case!2 \(Disabled\)
+.*12 - TEST:disabled\.case!2 \(Disabled\)
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest.cmake b/Tests/RunCMake/GoogleTest/GoogleTest.cmake
new file mode 100644
index 000000000..31808c670
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest.cmake
@@ -0,0 +1,59 @@
+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 TEST1
+)
+
+gtest_discover_tests(
+ fake_gtest
+ TEST_PREFIX TEST:
+ TEST_SUFFIX !2
+ EXTRA_ARGS how now "\"brown\" cow"
+ PROPERTIES LABELS TEST2
+)
+
+add_executable(no_tests_defined no_tests_defined.cpp)
+
+gtest_discover_tests(
+ no_tests_defined
+)
+
+# Note change in behavior of TIMEOUT keyword in 3.10.3
+# where it was renamed to DISCOVERY_TIMEOUT to prevent it
+# from shadowing the TIMEOUT test property. Verify the
+# 3.10.3 and later behavior, old behavior added in 3.10.1
+# is not supported.
+add_executable(property_timeout_test timeout_test.cpp)
+target_compile_definitions(property_timeout_test PRIVATE sleepSec=10)
+
+gtest_discover_tests(
+ property_timeout_test
+ TEST_PREFIX property_
+ TEST_SUFFIX _no_discovery
+ PROPERTIES TIMEOUT 2
+)
+gtest_discover_tests(
+ property_timeout_test
+ TEST_PREFIX property_
+ TEST_SUFFIX _with_discovery
+ DISCOVERY_TIMEOUT 20
+ PROPERTIES TIMEOUT 2
+)
+
+add_executable(discovery_timeout_test timeout_test.cpp)
+target_compile_definitions(discovery_timeout_test PRIVATE discoverySleepSec=10)
+gtest_discover_tests(
+ discovery_timeout_test
+ TEST_PREFIX discovery_
+ DISCOVERY_TIMEOUT 2
+)
diff --git a/Tests/RunCMake/GoogleTest/RunCMakeTest.cmake b/Tests/RunCMake/GoogleTest/RunCMakeTest.cmake
new file mode 100644
index 000000000..0fa4e2aa2
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/RunCMakeTest.cmake
@@ -0,0 +1,74 @@
+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(NOT RunCMake_GENERATOR_IS_MULTI_CONFIG)
+ 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
+ --target fake_gtest
+ )
+
+ run_cmake_command(GoogleTest-property-timeout-exe
+ ${CMAKE_COMMAND}
+ --build .
+ --config Debug
+ --target property_timeout_test
+ )
+
+ set(RunCMake_TEST_OUTPUT_MERGE 1)
+ run_cmake_command(GoogleTest-discovery-timeout
+ ${CMAKE_COMMAND}
+ --build .
+ --config Debug
+ --target discovery_timeout_test
+ )
+ set(RunCMake_TEST_OUTPUT_MERGE 0)
+
+ run_cmake_command(GoogleTest-test1
+ ${CMAKE_CTEST_COMMAND}
+ -C Debug
+ -L TEST1
+ --no-label-summary
+ )
+
+ run_cmake_command(GoogleTest-test2
+ ${CMAKE_CTEST_COMMAND}
+ -C Debug
+ -L TEST2
+ --no-label-summary
+ )
+
+ run_cmake_command(GoogleTest-test-missing
+ ${CMAKE_CTEST_COMMAND}
+ -C Debug
+ -R no_tests_defined
+ --no-label-summary
+ )
+
+ run_cmake_command(GoogleTest-property-timeout1
+ ${CMAKE_CTEST_COMMAND}
+ -C Debug
+ -R property_timeout\\.case_no_discovery
+ --no-label-summary
+ )
+
+ run_cmake_command(GoogleTest-property-timeout2
+ ${CMAKE_CTEST_COMMAND}
+ -C Debug
+ -R property_timeout\\.case_with_discovery
+ --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/GoogleTest/no_tests_defined.cpp b/Tests/RunCMake/GoogleTest/no_tests_defined.cpp
new file mode 100644
index 000000000..f8b643afb
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/no_tests_defined.cpp
@@ -0,0 +1,4 @@
+int main()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/GoogleTest/timeout_test.cpp b/Tests/RunCMake/GoogleTest/timeout_test.cpp
new file mode 100644
index 000000000..b8ad055e8
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/timeout_test.cpp
@@ -0,0 +1,39 @@
+#if defined(_WIN32)
+# include <windows.h>
+#else
+# include <unistd.h>
+#endif
+
+#include <iostream>
+#include <string>
+
+void sleepFor(unsigned seconds)
+{
+#if defined(_WIN32)
+ Sleep(seconds * 1000);
+#else
+ sleep(seconds);
+#endif
+}
+
+int main(int argc, char** argv)
+{
+ // Note: GoogleTest.cmake doesn't actually depend on Google Test as such;
+ // it only requires that we produce 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 << "timeout." << std::endl;
+ std::cout << " case" << std::endl;
+#ifdef discoverySleepSec
+ sleepFor(discoverySleepSec);
+#endif
+ return 0;
+ }
+
+#ifdef sleepSec
+ sleepFor(sleepSec);
+#endif
+
+ return 0;
+}
diff --git a/Tests/RunCMake/IfacePaths/BinInInstallPrefix-CMP0052-OLD-stderr.txt b/Tests/RunCMake/IfacePaths/BinInInstallPrefix-CMP0052-OLD-stderr.txt
new file mode 100644
index 000000000..37747a1e4
--- /dev/null
+++ b/Tests/RunCMake/IfacePaths/BinInInstallPrefix-CMP0052-OLD-stderr.txt
@@ -0,0 +1,8 @@
+^CMake Deprecation Warning at CMakeLists.txt:1 \(cmake_minimum_required\):
+ The OLD behavior for policy CMP0052 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.$
diff --git a/Tests/RunCMake/IfacePaths/SrcInInstallPrefix-CMP0052-OLD-stderr.txt b/Tests/RunCMake/IfacePaths/SrcInInstallPrefix-CMP0052-OLD-stderr.txt
new file mode 100644
index 000000000..37747a1e4
--- /dev/null
+++ b/Tests/RunCMake/IfacePaths/SrcInInstallPrefix-CMP0052-OLD-stderr.txt
@@ -0,0 +1,8 @@
+^CMake Deprecation Warning at CMakeLists.txt:1 \(cmake_minimum_required\):
+ The OLD behavior for policy CMP0052 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.$
diff --git a/Tests/RunCMake/Languages/ExternalCUDA.cmake b/Tests/RunCMake/Languages/ExternalCUDA.cmake
new file mode 100644
index 000000000..3afa93e55
--- /dev/null
+++ b/Tests/RunCMake/Languages/ExternalCUDA.cmake
@@ -0,0 +1,8 @@
+enable_language(C)
+
+add_library(ext_cuda IMPORTED STATIC)
+set_property(TARGET ext_cuda PROPERTY IMPORTED_LOCATION "/does_not_exist")
+set_property(TARGET ext_cuda PROPERTY IMPORTED_LINK_INTERFACE_LANGUAGES "CUDA")
+
+add_executable(main empty.c)
+target_link_libraries(main ext_cuda)
diff --git a/Tests/RunCMake/Languages/empty.c b/Tests/RunCMake/Languages/empty.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/Languages/empty.c
diff --git a/Tests/RunCMake/LinkStatic/LinkOptionsLib.c b/Tests/RunCMake/LinkStatic/LinkOptionsLib.c
new file mode 100644
index 000000000..9bbd24cd8
--- /dev/null
+++ b/Tests/RunCMake/LinkStatic/LinkOptionsLib.c
@@ -0,0 +1,7 @@
+#if defined(_WIN32)
+__declspec(dllexport)
+#endif
+ int flags_lib(void)
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-basic-check.cmake b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-basic-check.cmake
new file mode 100644
index 000000000..858ce06f7
--- /dev/null
+++ b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-basic-check.cmake
@@ -0,0 +1,4 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG'.")
+endif()
diff --git a/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-basic-result.txt b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-basic-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-basic-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-genex-check.cmake b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-genex-check.cmake
new file mode 100644
index 000000000..a686de945
--- /dev/null
+++ b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-genex-check.cmake
@@ -0,0 +1,7 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG_RELEASE")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG_RELEASE'.")
+endif()
+if (actual_stdout MATCHES "SHELL:")
+ string (APPEND RunCMake_TEST_FAILED "\nFound unexpected prefix 'SHELL:'.")
+endif()
diff --git a/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-genex-result.txt b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-genex-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-genex-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-shared-check.cmake b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-shared-check.cmake
new file mode 100644
index 000000000..8c1e96e61
--- /dev/null
+++ b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-shared-check.cmake
@@ -0,0 +1,4 @@
+
+if (actual_stdout MATCHES "BADFLAG")
+ string (APPEND RunCMake_TEST_FAILED "\nFound unexpected flag 'BADFLAG'.")
+endif()
diff --git a/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-shared-result.txt b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-shared-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS-shared-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS.cmake b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS.cmake
new file mode 100644
index 000000000..587af1d96
--- /dev/null
+++ b/Tests/RunCMake/LinkStatic/STATIC_LIBRARY_OPTIONS.cmake
@@ -0,0 +1,21 @@
+
+enable_language(C)
+
+set(obj "${CMAKE_C_OUTPUT_EXTENSION}")
+if(BORLAND)
+ set(pre -)
+endif()
+
+add_library(StaticLinkOptions STATIC LinkOptionsLib.c)
+set_property(TARGET StaticLinkOptions PROPERTY STATIC_LIBRARY_OPTIONS ${pre}BADFLAG${obj})
+
+# static library with generator expression
+add_library(StaticLinkOptions_genex STATIC LinkOptionsLib.c)
+set_property(TARGET StaticLinkOptions_genex PROPERTY STATIC_LIBRARY_OPTIONS
+ $<$<CONFIG:Release>:${pre}BADFLAG_RELEASE${obj}>
+ "SHELL:" # produces no options
+ )
+
+# shared library do not use property STATIC_LIBRARY_OPTIONS
+add_library(SharedLinkOptions SHARED LinkOptionsLib.c)
+set_property(TARGET SharedLinkOptions PROPERTY STATIC_LIBRARY_OPTIONS ${pre}BADFLAG${obj})
diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-result.txt b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-stderr.txt b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-stderr.txt
new file mode 100644
index 000000000..9afa461de
--- /dev/null
+++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error in CMakeLists.txt:
+ MSVC_RUNTIME_LIBRARY value 'BogusValue' not known for this C compiler.
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW.cmake b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW.cmake
new file mode 100644
index 000000000..c3ea2fddb
--- /dev/null
+++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-NEW.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0091 NEW)
+include(CMP0091-common.cmake)
diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-OLD.cmake b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-OLD.cmake
new file mode 100644
index 000000000..734cc9f68
--- /dev/null
+++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-OLD.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0091 OLD)
+include(CMP0091-common.cmake)
diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-WARN.cmake b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-WARN.cmake
new file mode 100644
index 000000000..26f86a050
--- /dev/null
+++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-WARN.cmake
@@ -0,0 +1,2 @@
+
+include(CMP0091-common.cmake)
diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-common.cmake b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-common.cmake
new file mode 100644
index 000000000..7827d2a6c
--- /dev/null
+++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMP0091-common.cmake
@@ -0,0 +1,37 @@
+enable_language(C)
+
+cmake_policy(GET CMP0091 cmp0091)
+if(cmp0091 STREQUAL "NEW")
+ if(NOT CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT)
+ message(SEND_ERROR "CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT not set under NEW behavior")
+ endif()
+else()
+ if(CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT)
+ message(SEND_ERROR "CMAKE_MSVC_RUNTIME_LIBRARY_DEFAULT is set under OLD behavior")
+ endif()
+endif()
+
+if(CMAKE_C_COMPILER_ID STREQUAL "MSVC")
+ if(CMAKE_C_FLAGS_DEBUG MATCHES "[/-]MDd( |$)")
+ set(have_MDd 1)
+ else()
+ set(have_MDd 0)
+ endif()
+ if(CMAKE_C_FLAGS_RELEASE MATCHES "[/-]MD( |$)")
+ set(have_MD 1)
+ else()
+ set(have_MD 0)
+ endif()
+ if(cmp0091 STREQUAL "NEW")
+ if(have_MDd OR have_MD)
+ message(SEND_ERROR "Have a -MD* flag under NEW behavior.")
+ endif()
+ else()
+ if(NOT (have_MDd AND have_MD))
+ message(SEND_ERROR "Do not have -MD* flags under OLD behavior.")
+ endif()
+ endif()
+endif()
+
+set(CMAKE_MSVC_RUNTIME_LIBRARY BogusValue)
+add_library(foo empty.c)
diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/CMakeLists.txt b/Tests/RunCMake/MSVCRuntimeLibrary/CMakeLists.txt
new file mode 100644
index 000000000..3e470a29c
--- /dev/null
+++ b/Tests/RunCMake/MSVCRuntimeLibrary/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.14)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/RunCMakeTest.cmake b/Tests/RunCMake/MSVCRuntimeLibrary/RunCMakeTest.cmake
new file mode 100644
index 000000000..fad18dacc
--- /dev/null
+++ b/Tests/RunCMake/MSVCRuntimeLibrary/RunCMakeTest.cmake
@@ -0,0 +1,5 @@
+include(RunCMake)
+
+run_cmake(CMP0091-WARN)
+run_cmake(CMP0091-OLD)
+run_cmake(CMP0091-NEW)
diff --git a/Tests/RunCMake/MSVCRuntimeLibrary/empty.c b/Tests/RunCMake/MSVCRuntimeLibrary/empty.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/MSVCRuntimeLibrary/empty.c
diff --git a/Tests/RunCMake/MSVCWarningFlags/CMP0092-NEW.cmake b/Tests/RunCMake/MSVCWarningFlags/CMP0092-NEW.cmake
new file mode 100644
index 000000000..15c52d217
--- /dev/null
+++ b/Tests/RunCMake/MSVCWarningFlags/CMP0092-NEW.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0092 NEW)
+include(CMP0092-common.cmake)
diff --git a/Tests/RunCMake/MSVCWarningFlags/CMP0092-OLD.cmake b/Tests/RunCMake/MSVCWarningFlags/CMP0092-OLD.cmake
new file mode 100644
index 000000000..ea7544564
--- /dev/null
+++ b/Tests/RunCMake/MSVCWarningFlags/CMP0092-OLD.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0092 OLD)
+include(CMP0092-common.cmake)
diff --git a/Tests/RunCMake/MSVCWarningFlags/CMP0092-WARN.cmake b/Tests/RunCMake/MSVCWarningFlags/CMP0092-WARN.cmake
new file mode 100644
index 000000000..45e183f4a
--- /dev/null
+++ b/Tests/RunCMake/MSVCWarningFlags/CMP0092-WARN.cmake
@@ -0,0 +1,2 @@
+
+include(CMP0092-common.cmake)
diff --git a/Tests/RunCMake/MSVCWarningFlags/CMP0092-common.cmake b/Tests/RunCMake/MSVCWarningFlags/CMP0092-common.cmake
new file mode 100644
index 000000000..87d7f67c6
--- /dev/null
+++ b/Tests/RunCMake/MSVCWarningFlags/CMP0092-common.cmake
@@ -0,0 +1,12 @@
+enable_language(C)
+
+cmake_policy(GET CMP0092 cmp0092)
+if(cmp0092 STREQUAL "NEW")
+ if("${CMAKE_C_FLAGS}" MATCHES "([/-]W[0-9])")
+ message(SEND_ERROR "CMAKE_C_FLAGS has '${CMAKE_MATCH_1}' under NEW behavior")
+ endif()
+else()
+ if(NOT " ${CMAKE_C_FLAGS} " MATCHES " /W3 ")
+ message(SEND_ERROR "CMAKE_C_FLAGS does not have '/W3' under OLD behavior")
+ endif()
+endif()
diff --git a/Tests/RunCMake/MSVCWarningFlags/CMakeLists.txt b/Tests/RunCMake/MSVCWarningFlags/CMakeLists.txt
new file mode 100644
index 000000000..3e470a29c
--- /dev/null
+++ b/Tests/RunCMake/MSVCWarningFlags/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.14)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/MSVCWarningFlags/RunCMakeTest.cmake b/Tests/RunCMake/MSVCWarningFlags/RunCMakeTest.cmake
new file mode 100644
index 000000000..7ce448dff
--- /dev/null
+++ b/Tests/RunCMake/MSVCWarningFlags/RunCMakeTest.cmake
@@ -0,0 +1,5 @@
+include(RunCMake)
+
+run_cmake(CMP0092-WARN)
+run_cmake(CMP0092-OLD)
+run_cmake(CMP0092-NEW)
diff --git a/Tests/RunCMake/Make/IncludeRegexSubdir-check.cmake b/Tests/RunCMake/Make/IncludeRegexSubdir-check.cmake
new file mode 100644
index 000000000..dbdf7bea9
--- /dev/null
+++ b/Tests/RunCMake/Make/IncludeRegexSubdir-check.cmake
@@ -0,0 +1,4 @@
+include("${RunCMake_TEST_BINARY_DIR}/IncludeRegexSubdir/CMakeFiles/CMakeDirectoryInformation.cmake" OPTIONAL)
+if(NOT CMAKE_C_INCLUDE_REGEX_SCAN STREQUAL "^custom_include_regex$")
+ set(RunCMake_TEST_FAILED "CMAKE_C_INCLUDE_REGEX_SCAN has unexpected value:\n \"${CMAKE_C_INCLUDE_REGEX_SCAN}\"")
+endif()
diff --git a/Tests/RunCMake/Make/IncludeRegexSubdir.cmake b/Tests/RunCMake/Make/IncludeRegexSubdir.cmake
new file mode 100644
index 000000000..a7a93a090
--- /dev/null
+++ b/Tests/RunCMake/Make/IncludeRegexSubdir.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+include_regular_expression("^custom_include_regex$")
+add_subdirectory(IncludeRegexSubdir)
diff --git a/Tests/RunCMake/Make/IncludeRegexSubdir/CMakeLists.txt b/Tests/RunCMake/Make/IncludeRegexSubdir/CMakeLists.txt
new file mode 100644
index 000000000..e712aea5d
--- /dev/null
+++ b/Tests/RunCMake/Make/IncludeRegexSubdir/CMakeLists.txt
@@ -0,0 +1 @@
+# We only need this directory to be processed. No targets needed.
diff --git a/Tests/RunCMake/Make/VerboseBuild-build-stdout.txt b/Tests/RunCMake/Make/VerboseBuild-build-stdout.txt
new file mode 100644
index 000000000..884bf953e
--- /dev/null
+++ b/Tests/RunCMake/Make/VerboseBuild-build-stdout.txt
@@ -0,0 +1 @@
+.*DEFINE_FOR_VERBOSE_DETECTION.*hello.dir.*
diff --git a/Tests/RunCMake/Make/VerboseBuild-build-watcom-stdout.txt b/Tests/RunCMake/Make/VerboseBuild-build-watcom-stdout.txt
new file mode 100644
index 000000000..9c558e357
--- /dev/null
+++ b/Tests/RunCMake/Make/VerboseBuild-build-watcom-stdout.txt
@@ -0,0 +1 @@
+.
diff --git a/Tests/RunCMake/Make/VerboseBuild-nowork-gnu-stdout.txt b/Tests/RunCMake/Make/VerboseBuild-nowork-gnu-stdout.txt
new file mode 100644
index 000000000..3e65cd95f
--- /dev/null
+++ b/Tests/RunCMake/Make/VerboseBuild-nowork-gnu-stdout.txt
@@ -0,0 +1 @@
+.*Nothing to be done for.*hello.*
diff --git a/Tests/RunCMake/Make/VerboseBuild.cmake b/Tests/RunCMake/Make/VerboseBuild.cmake
new file mode 100644
index 000000000..70a971d13
--- /dev/null
+++ b/Tests/RunCMake/Make/VerboseBuild.cmake
@@ -0,0 +1,8 @@
+enable_language(C)
+
+# Make sure compile command is not hidden in a temp file.
+string(REPLACE "${CMAKE_START_TEMP_FILE}" "" CMAKE_C_COMPILE_OBJECT "${CMAKE_C_COMPILE_OBJECT}")
+string(REPLACE "${CMAKE_END_TEMP_FILE}" "" CMAKE_C_COMPILE_OBJECT "${CMAKE_C_COMPILE_OBJECT}")
+
+add_executable(hello hello.c)
+target_compile_definitions(hello PRIVATE "DEFINE_FOR_VERBOSE_DETECTION")
diff --git a/Tests/RunCMake/Make/hello.c b/Tests/RunCMake/Make/hello.c
new file mode 100644
index 000000000..aac8b4e0f
--- /dev/null
+++ b/Tests/RunCMake/Make/hello.c
@@ -0,0 +1,7 @@
+#include <stdio.h>
+
+int main(void)
+{
+ printf("Hello world!\n");
+ return 0;
+}
diff --git a/Tests/RunCMake/MaxRecursionDepth/CMakeLists.txt b/Tests/RunCMake/MaxRecursionDepth/CMakeLists.txt
new file mode 100644
index 000000000..d2cd86d13
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/CMakeLists.txt
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.13)
+if(DEFINED CMAKE_GENERATOR)
+ project(${RunCMake_TEST} NONE)
+endif()
+include("${CMAKE_CURRENT_LIST_DIR}/${TEST_NAME}.cmake")
diff --git a/Tests/RunCMake/MaxRecursionDepth/CMakeLists.txt.in b/Tests/RunCMake/MaxRecursionDepth/CMakeLists.txt.in
new file mode 100644
index 000000000..fee3eda2f
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/CMakeLists.txt.in
@@ -0,0 +1,2 @@
+cmake_minimum_required(VERSION 3.12)
+project(MaxRecursionDepth NONE)
diff --git a/Tests/RunCMake/MaxRecursionDepth/CTestCustom.cmake b/Tests/RunCMake/MaxRecursionDepth/CTestCustom.cmake
new file mode 100644
index 000000000..354bc7a4e
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/CTestCustom.cmake
@@ -0,0 +1,3 @@
+message("${x}")
+math(EXPR x "${x} + 1")
+ctest_read_custom_files("${CMAKE_CURRENT_LIST_DIR}")
diff --git a/Tests/RunCMake/MaxRecursionDepth/FindRecursivePackage.cmake b/Tests/RunCMake/MaxRecursionDepth/FindRecursivePackage.cmake
new file mode 100644
index 000000000..3cbb99e87
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/FindRecursivePackage.cmake
@@ -0,0 +1,3 @@
+message("${x}")
+math(EXPR x "${x} + 1")
+find_package(RecursivePackage)
diff --git a/Tests/RunCMake/MaxRecursionDepth/RunCMakeTest.cmake b/Tests/RunCMake/MaxRecursionDepth/RunCMakeTest.cmake
new file mode 100644
index 000000000..c5a859d87
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/RunCMakeTest.cmake
@@ -0,0 +1,49 @@
+include(RunCMake)
+include(RunCTest)
+
+function(run_cmake_recursive name)
+ set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=${name})
+ run_cmake(${name}-default)
+ unset(RunCMake_TEST_OPTIONS)
+ set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=${name} -DCMAKE_MAXIMUM_RECURSION_DEPTH=10)
+ run_cmake(${name}-var)
+ unset(RunCMake_TEST_OPTIONS)
+ set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=${name} -DCMAKE_MAXIMUM_RECURSION_DEPTH=a)
+ run_cmake(${name}-invalid-var)
+ unset(RunCMake_TEST_OPTIONS)
+
+ run_cmake_command(${name}-default-script ${CMAKE_COMMAND} "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=${name} -P "${CMAKE_CURRENT_LIST_DIR}/CMakeLists.txt")
+ run_cmake_command(${name}-var-script ${CMAKE_COMMAND} "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=${name} -DCMAKE_MAXIMUM_RECURSION_DEPTH=10 -P "${CMAKE_CURRENT_LIST_DIR}/CMakeLists.txt")
+ run_cmake_command(${name}-invalid-var-script ${CMAKE_COMMAND} "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=${name} -DCMAKE_MAXIMUM_RECURSION_DEPTH=a -P "${CMAKE_CURRENT_LIST_DIR}/CMakeLists.txt")
+endfunction()
+
+function(run_ctest_recursive name)
+ run_ctest(${name}-default "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=${name})
+ run_ctest(${name}-var "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=${name} -DCMAKE_MAXIMUM_RECURSION_DEPTH=10)
+ run_ctest(${name}-invalid-var "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=${name} -DCMAKE_MAXIMUM_RECURSION_DEPTH=a)
+endfunction()
+
+run_cmake_recursive(function)
+run_cmake_recursive(macro)
+run_cmake_recursive(include)
+run_cmake_recursive(find_package)
+run_cmake_recursive(variable_watch)
+
+# We run these tests separately and only with a small limit because they are
+# taxing and slow. The "implicit" and "invalid" cases are already thoroughly
+# covered by the other tests above.
+set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=add_subdirectory -DCMAKE_MAXIMUM_RECURSION_DEPTH=10)
+run_cmake(add_subdirectory-var)
+unset(RunCMake_TEST_OPTIONS)
+set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=try_compile -DCMAKE_MAXIMUM_RECURSION_DEPTH=10)
+run_cmake(try_compile-var)
+unset(RunCMake_TEST_OPTIONS)
+
+run_ctest_recursive(ctest_read_custom_files)
+
+# We run the ctest_run_script() test separately and only with an explicit limit
+# because ctest_run_script() is taxing and slow, and because the implicit
+# recursion limit is hit by CTestScriptMode.cmake before we can test it
+# properly. The "implicit" and "invalid" cases are already thoroughly covered
+# by the other tests above.
+run_ctest(ctest_run_script-var "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" -DTEST_NAME=ctest_run_script -DCMAKE_MAXIMUM_RECURSION_DEPTH=10)
diff --git a/Tests/RunCMake/MaxRecursionDepth/add_subdirectory-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/add_subdirectory-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/add_subdirectory-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/add_subdirectory-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/add_subdirectory-var-stderr.txt
new file mode 100644
index 000000000..23fb5c65b
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/add_subdirectory-var-stderr.txt
@@ -0,0 +1,10 @@
+^3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at add_subdirectory/CMakeLists\.txt:1 \(message\):
+ Maximum recursion depth of 10 exceeded$
diff --git a/Tests/RunCMake/MaxRecursionDepth/add_subdirectory.cmake b/Tests/RunCMake/MaxRecursionDepth/add_subdirectory.cmake
new file mode 100644
index 000000000..36c21f30a
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/add_subdirectory.cmake
@@ -0,0 +1,2 @@
+set(x 3)
+add_subdirectory(add_subdirectory)
diff --git a/Tests/RunCMake/MaxRecursionDepth/add_subdirectory/CMakeLists.txt b/Tests/RunCMake/MaxRecursionDepth/add_subdirectory/CMakeLists.txt
new file mode 100644
index 000000000..a8244affe
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/add_subdirectory/CMakeLists.txt
@@ -0,0 +1,3 @@
+message("${x}")
+math(EXPR x "${x} + 1")
+add_subdirectory(. dir)
diff --git a/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-default-result.txt b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-default-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-default-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-default-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-default-stderr.txt
new file mode 100644
index 000000000..7dbbb3e72
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-default-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:1 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-invalid-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-invalid-var-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-invalid-var-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-invalid-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-invalid-var-stderr.txt
new file mode 100644
index 000000000..7dbbb3e72
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-invalid-var-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:1 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-var-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-var-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-var-stderr.txt
new file mode 100644
index 000000000..bc89703a0
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-var-stderr.txt
@@ -0,0 +1,34 @@
+^2
+3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:1 \(message\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
+ .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake:3 \(ctest_read_custom_files\)
+ .*/Tests/RunCMake/MaxRecursionDepth/ctest_read_custom_files-var/test\.cmake:10 \(ctest_read_custom_files\)
+
+
+Problem reading custom configuration: .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake
+Problem reading custom configuration: .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake
+Problem reading custom configuration: .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake
+Problem reading custom configuration: .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake
+Problem reading custom configuration: .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake
+Problem reading custom configuration: .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake
+Problem reading custom configuration: .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake
+Problem reading custom configuration: .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake
+Problem reading custom configuration: .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake
+Problem reading custom configuration: .*/Tests/RunCMake/MaxRecursionDepth/CTestCustom\.cmake$
diff --git a/Tests/RunCMake/MaxRecursionDepth/ctest_run_script-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/ctest_run_script-var-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/ctest_run_script-var-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/MaxRecursionDepth/ctest_run_script-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/ctest_run_script-var-stderr.txt
new file mode 100644
index 000000000..b10b26d32
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/ctest_run_script-var-stderr.txt
@@ -0,0 +1,51 @@
+^2
+3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script_11\.cmake:1 \(cmake_minimum_required\):
+ Maximum recursion depth of 10 exceeded
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script_10\.cmake:13 \(message\):
+ Nested script failed
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script_9\.cmake:13 \(message\):
+ Nested script failed
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script_8\.cmake:13 \(message\):
+ Nested script failed
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script_7\.cmake:13 \(message\):
+ Nested script failed
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script_6\.cmake:13 \(message\):
+ Nested script failed
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script_5\.cmake:13 \(message\):
+ Nested script failed
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script_4\.cmake:13 \(message\):
+ Nested script failed
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script_3\.cmake:13 \(message\):
+ Nested script failed
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script_2\.cmake:13 \(message\):
+ Nested script failed
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/ctest_run_script-var/test\.cmake:19 \(message\):
+ Nested script failed$
diff --git a/Tests/RunCMake/MaxRecursionDepth/ctest_run_script.cmake.in b/Tests/RunCMake/MaxRecursionDepth/ctest_run_script.cmake.in
new file mode 100644
index 000000000..d4f28c456
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/ctest_run_script.cmake.in
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.12)
+set(CTEST_RUN_CURRENT_SCRIPT 0)
+
+message("@LEVEL_CURRENT@")
+
+set(CTEST_SOURCE_DIRECTORY "@CTEST_SOURCE_DIRECTORY@")
+set(CTEST_BINARY_DIRECTORY "@CTEST_BINARY_DIRECTORY@")
+set(CTEST_COMMAND "@CTEST_COMMAND@")
+
+ctest_run_script("${CMAKE_CURRENT_LIST_DIR}/ctest_run_script_@LEVEL_NEXT@.cmake" RETURN_VALUE val)
+
+if(NOT val EQUAL 0)
+ message(FATAL_ERROR "Nested script failed")
+endif()
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-default-result.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-default-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-default-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-default-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-default-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-default-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-default-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-default-script-stderr.txt
new file mode 100644
index 000000000..b8557ab64
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-default-script-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at .*/FindRecursivePackage\.cmake:1 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/FindRecursivePackage\.cmake:3 \(find_package\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-default-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-default-stderr.txt
new file mode 100644
index 000000000..5d31e295b
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-default-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at FindRecursivePackage\.cmake:1 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ FindRecursivePackage\.cmake:3 \(find_package\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-script-stderr.txt
new file mode 100644
index 000000000..b8557ab64
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-script-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at .*/FindRecursivePackage\.cmake:1 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/FindRecursivePackage\.cmake:3 \(find_package\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-stderr.txt
new file mode 100644
index 000000000..5d31e295b
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-invalid-var-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at FindRecursivePackage\.cmake:1 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ FindRecursivePackage\.cmake:3 \(find_package\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-var-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-var-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-var-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-var-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-var-script-stderr.txt
new file mode 100644
index 000000000..53145515a
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-var-script-stderr.txt
@@ -0,0 +1,21 @@
+^3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at .*/FindRecursivePackage\.cmake:1 \(message\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ .*/FindRecursivePackage\.cmake:3 \(find_package\)
+ .*/FindRecursivePackage\.cmake:3 \(find_package\)
+ .*/FindRecursivePackage\.cmake:3 \(find_package\)
+ .*/FindRecursivePackage\.cmake:3 \(find_package\)
+ .*/FindRecursivePackage\.cmake:3 \(find_package\)
+ .*/FindRecursivePackage\.cmake:3 \(find_package\)
+ .*/FindRecursivePackage\.cmake:3 \(find_package\)
+ .*/FindRecursivePackage\.cmake:3 \(find_package\)
+ .*/find_package\.cmake:2 \(find_package\)
+ .*/CMakeLists\.txt:5 \(include\)$
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/find_package-var-stderr.txt
new file mode 100644
index 000000000..b47a13a17
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package-var-stderr.txt
@@ -0,0 +1,21 @@
+^3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at FindRecursivePackage\.cmake:1 \(message\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ FindRecursivePackage\.cmake:3 \(find_package\)
+ FindRecursivePackage\.cmake:3 \(find_package\)
+ FindRecursivePackage\.cmake:3 \(find_package\)
+ FindRecursivePackage\.cmake:3 \(find_package\)
+ FindRecursivePackage\.cmake:3 \(find_package\)
+ FindRecursivePackage\.cmake:3 \(find_package\)
+ FindRecursivePackage\.cmake:3 \(find_package\)
+ FindRecursivePackage\.cmake:3 \(find_package\)
+ find_package\.cmake:2 \(find_package\)
+ CMakeLists\.txt:5 \(include\)$
diff --git a/Tests/RunCMake/MaxRecursionDepth/find_package.cmake b/Tests/RunCMake/MaxRecursionDepth/find_package.cmake
new file mode 100644
index 000000000..a235f7d41
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/find_package.cmake
@@ -0,0 +1,2 @@
+set(x 3)
+find_package(RecursivePackage)
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-default-result.txt b/Tests/RunCMake/MaxRecursionDepth/function-default-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-default-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-default-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/function-default-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-default-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-default-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/function-default-script-stderr.txt
new file mode 100644
index 000000000..92de1fb3c
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-default-script-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at .*/function\.cmake:2 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/function\.cmake:4 \(recursive\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-default-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/function-default-stderr.txt
new file mode 100644
index 000000000..5c25c4b12
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-default-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at function\.cmake:2 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ function\.cmake:4 \(recursive\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-script-stderr.txt
new file mode 100644
index 000000000..92de1fb3c
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-script-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at .*/function\.cmake:2 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/function\.cmake:4 \(recursive\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-stderr.txt
new file mode 100644
index 000000000..5c25c4b12
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-invalid-var-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at function\.cmake:2 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ function\.cmake:4 \(recursive\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/function-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-var-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/function-var-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-var-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-var-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/function-var-script-stderr.txt
new file mode 100644
index 000000000..61304b13f
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-var-script-stderr.txt
@@ -0,0 +1,21 @@
+^3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at .*/function\.cmake:2 \(message\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ .*/function\.cmake:4 \(recursive\)
+ .*/function\.cmake:4 \(recursive\)
+ .*/function\.cmake:4 \(recursive\)
+ .*/function\.cmake:4 \(recursive\)
+ .*/function\.cmake:4 \(recursive\)
+ .*/function\.cmake:4 \(recursive\)
+ .*/function\.cmake:4 \(recursive\)
+ .*/function\.cmake:4 \(recursive\)
+ .*/function\.cmake:7 \(recursive\)
+ .*/CMakeLists\.txt:5 \(include\)$
diff --git a/Tests/RunCMake/MaxRecursionDepth/function-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/function-var-stderr.txt
new file mode 100644
index 000000000..54e72aff4
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function-var-stderr.txt
@@ -0,0 +1,21 @@
+^3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at function\.cmake:2 \(message\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ function\.cmake:4 \(recursive\)
+ function\.cmake:4 \(recursive\)
+ function\.cmake:4 \(recursive\)
+ function\.cmake:4 \(recursive\)
+ function\.cmake:4 \(recursive\)
+ function\.cmake:4 \(recursive\)
+ function\.cmake:4 \(recursive\)
+ function\.cmake:4 \(recursive\)
+ function\.cmake:7 \(recursive\)
+ CMakeLists\.txt:5 \(include\)$
diff --git a/Tests/RunCMake/MaxRecursionDepth/function.cmake b/Tests/RunCMake/MaxRecursionDepth/function.cmake
new file mode 100644
index 000000000..581cb8917
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/function.cmake
@@ -0,0 +1,7 @@
+function(recursive x)
+ message("${x}")
+ math(EXPR y "${x} + 1")
+ recursive(${y})
+endfunction()
+
+recursive(3)
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-default-result.txt b/Tests/RunCMake/MaxRecursionDepth/include-default-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-default-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-default-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/include-default-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-default-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-default-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/include-default-script-stderr.txt
new file mode 100644
index 000000000..0510e7c37
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-default-script-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at .*/include_recursive\.cmake:1 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/include_recursive\.cmake:3 \(include\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-default-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/include-default-stderr.txt
new file mode 100644
index 000000000..b1494a8e1
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-default-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at include_recursive\.cmake:1 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ include_recursive\.cmake:3 \(include\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-script-stderr.txt
new file mode 100644
index 000000000..0510e7c37
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-script-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at .*/include_recursive\.cmake:1 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/include_recursive\.cmake:3 \(include\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-stderr.txt
new file mode 100644
index 000000000..b1494a8e1
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-invalid-var-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at include_recursive\.cmake:1 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ include_recursive\.cmake:3 \(include\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/include-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-var-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/include-var-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-var-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-var-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/include-var-script-stderr.txt
new file mode 100644
index 000000000..f55f50536
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-var-script-stderr.txt
@@ -0,0 +1,21 @@
+^3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at .*/include_recursive\.cmake:1 \(message\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ .*/include_recursive\.cmake:3 \(include\)
+ .*/include_recursive\.cmake:3 \(include\)
+ .*/include_recursive\.cmake:3 \(include\)
+ .*/include_recursive\.cmake:3 \(include\)
+ .*/include_recursive\.cmake:3 \(include\)
+ .*/include_recursive\.cmake:3 \(include\)
+ .*/include_recursive\.cmake:3 \(include\)
+ .*/include_recursive\.cmake:3 \(include\)
+ .*/include\.cmake:2 \(include\)
+ .*/CMakeLists\.txt:5 \(include\)$
diff --git a/Tests/RunCMake/MaxRecursionDepth/include-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/include-var-stderr.txt
new file mode 100644
index 000000000..ff3398504
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include-var-stderr.txt
@@ -0,0 +1,21 @@
+^3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at include_recursive\.cmake:1 \(message\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ include_recursive\.cmake:3 \(include\)
+ include_recursive\.cmake:3 \(include\)
+ include_recursive\.cmake:3 \(include\)
+ include_recursive\.cmake:3 \(include\)
+ include_recursive\.cmake:3 \(include\)
+ include_recursive\.cmake:3 \(include\)
+ include_recursive\.cmake:3 \(include\)
+ include_recursive\.cmake:3 \(include\)
+ include\.cmake:2 \(include\)
+ CMakeLists\.txt:5 \(include\)$
diff --git a/Tests/RunCMake/MaxRecursionDepth/include.cmake b/Tests/RunCMake/MaxRecursionDepth/include.cmake
new file mode 100644
index 000000000..5e86a40cb
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include.cmake
@@ -0,0 +1,2 @@
+set(x 3)
+include("${CMAKE_CURRENT_LIST_DIR}/include_recursive.cmake")
diff --git a/Tests/RunCMake/MaxRecursionDepth/include_recursive.cmake b/Tests/RunCMake/MaxRecursionDepth/include_recursive.cmake
new file mode 100644
index 000000000..b3f744e38
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/include_recursive.cmake
@@ -0,0 +1,3 @@
+message("${x}")
+math(EXPR x "${x} + 1")
+include("${CMAKE_CURRENT_LIST_FILE}")
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-default-result.txt b/Tests/RunCMake/MaxRecursionDepth/macro-default-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-default-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-default-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/macro-default-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-default-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-default-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/macro-default-script-stderr.txt
new file mode 100644
index 000000000..c67be57d2
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-default-script-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at .*/macro\.cmake:2 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/macro\.cmake:4 \(recursive\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-default-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/macro-default-stderr.txt
new file mode 100644
index 000000000..0b271627d
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-default-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at macro\.cmake:2 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ macro\.cmake:4 \(recursive\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-script-stderr.txt
new file mode 100644
index 000000000..c67be57d2
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-script-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at .*/macro\.cmake:2 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/macro\.cmake:4 \(recursive\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-stderr.txt
new file mode 100644
index 000000000..0b271627d
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-invalid-var-stderr.txt
@@ -0,0 +1,5 @@
+[0-9]+
+CMake Error at macro\.cmake:2 \(message\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ macro\.cmake:4 \(recursive\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/macro-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-var-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/macro-var-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-var-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-var-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/macro-var-script-stderr.txt
new file mode 100644
index 000000000..142e068a0
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-var-script-stderr.txt
@@ -0,0 +1,21 @@
+^3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at .*/macro\.cmake:2 \(message\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ .*/macro\.cmake:4 \(recursive\)
+ .*/macro\.cmake:4 \(recursive\)
+ .*/macro\.cmake:4 \(recursive\)
+ .*/macro\.cmake:4 \(recursive\)
+ .*/macro\.cmake:4 \(recursive\)
+ .*/macro\.cmake:4 \(recursive\)
+ .*/macro\.cmake:4 \(recursive\)
+ .*/macro\.cmake:4 \(recursive\)
+ .*/macro\.cmake:7 \(recursive\)
+ .*/CMakeLists\.txt:5 \(include\)$
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/macro-var-stderr.txt
new file mode 100644
index 000000000..71de55376
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro-var-stderr.txt
@@ -0,0 +1,21 @@
+^3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at macro\.cmake:2 \(message\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ macro\.cmake:4 \(recursive\)
+ macro\.cmake:4 \(recursive\)
+ macro\.cmake:4 \(recursive\)
+ macro\.cmake:4 \(recursive\)
+ macro\.cmake:4 \(recursive\)
+ macro\.cmake:4 \(recursive\)
+ macro\.cmake:4 \(recursive\)
+ macro\.cmake:4 \(recursive\)
+ macro\.cmake:7 \(recursive\)
+ CMakeLists\.txt:5 \(include\)$
diff --git a/Tests/RunCMake/MaxRecursionDepth/macro.cmake b/Tests/RunCMake/MaxRecursionDepth/macro.cmake
new file mode 100644
index 000000000..a7cbfc2ad
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/macro.cmake
@@ -0,0 +1,7 @@
+macro(recursive x)
+ message("${x}")
+ math(EXPR y "${x} + 1")
+ recursive(${y})
+endmacro()
+
+recursive(3)
diff --git a/Tests/RunCMake/MaxRecursionDepth/test.cmake.in b/Tests/RunCMake/MaxRecursionDepth/test.cmake.in
new file mode 100644
index 000000000..fd1fc10a5
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/test.cmake.in
@@ -0,0 +1,21 @@
+cmake_minimum_required(VERSION 3.12)
+set(CTEST_RUN_CURRENT_SCRIPT 0)
+
+set(CTEST_SOURCE_DIRECTORY "@RunCMake_SOURCE_DIR@")
+set(CTEST_BINARY_DIRECTORY "@RunCMake_BINARY_DIR@")
+set(CTEST_COMMAND "${CMAKE_CTEST_COMMAND}")
+
+if(TEST_NAME STREQUAL "ctest_read_custom_files")
+ set(x 2)
+ ctest_read_custom_files("@RunCMake_SOURCE_DIR@")
+elseif(TEST_NAME STREQUAL "ctest_run_script")
+ foreach(LEVEL_CURRENT RANGE 2 15)
+ math(EXPR LEVEL_NEXT "${LEVEL_CURRENT} + 1")
+ configure_file("@RunCMake_SOURCE_DIR@/ctest_run_script.cmake.in" "@RunCMake_BINARY_DIR@/ctest_run_script_${LEVEL_CURRENT}.cmake" @ONLY)
+ endforeach()
+
+ ctest_run_script("@RunCMake_BINARY_DIR@/ctest_run_script_2.cmake" RETURN_VALUE val)
+ if(NOT val EQUAL 0)
+ message(FATAL_ERROR "Nested script failed")
+ endif()
+endif()
diff --git a/Tests/RunCMake/MaxRecursionDepth/try_compile-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/try_compile-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/try_compile-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/try_compile-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/try_compile-var-stderr.txt
new file mode 100644
index 000000000..130db346b
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/try_compile-var-stderr.txt
@@ -0,0 +1,48 @@
+^3
+4
+5
+6
+7
+8
+9
+10
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists\.txt:1 \(cmake_minimum_required\):
+ Maximum recursion depth of 10 exceeded
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists\.txt:5 \(try_compile\):
+ Failed to configure test project build system\.
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists\.txt:5 \(try_compile\):
+ Failed to configure test project build system\.
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists\.txt:5 \(try_compile\):
+ Failed to configure test project build system\.
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists\.txt:5 \(try_compile\):
+ Failed to configure test project build system\.
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists\.txt:5 \(try_compile\):
+ Failed to configure test project build system\.
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists\.txt:5 \(try_compile\):
+ Failed to configure test project build system\.
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists\.txt:5 \(try_compile\):
+ Failed to configure test project build system\.
+
+
+CMake Error at .*/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists\.txt:5 \(try_compile\):
+ Failed to configure test project build system\.
+
+
+CMake Error at try_compile\.cmake:1 \(try_compile\):
+ Failed to configure test project build system\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:5 \(include\)$
diff --git a/Tests/RunCMake/MaxRecursionDepth/try_compile.cmake b/Tests/RunCMake/MaxRecursionDepth/try_compile.cmake
new file mode 100644
index 000000000..c40fb0612
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/try_compile.cmake
@@ -0,0 +1,6 @@
+try_compile(result
+ "${CMAKE_CURRENT_BINARY_DIR}/try_compile"
+ "${CMAKE_CURRENT_SOURCE_DIR}/try_compile"
+ try_compile
+ CMAKE_FLAGS -Dx:STRING=3
+ )
diff --git a/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists.txt b/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists.txt
new file mode 100644
index 000000000..227109061
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/try_compile/CMakeLists.txt
@@ -0,0 +1,13 @@
+cmake_minimum_required(VERSION 3.12)
+
+message("${x}")
+math(EXPR x "${x} + 1")
+try_compile(result
+ "${CMAKE_CURRENT_BINARY_DIR}/try_compile"
+ "${CMAKE_CURRENT_SOURCE_DIR}"
+ try_compile
+ CMAKE_FLAGS -Dx:STRING=${x}
+ )
+
+# We put this last to avoid prematurely triggering the recursion limit
+project(try_compile NONE)
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-result.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-script-stderr.txt
new file mode 100644
index 000000000..4dddc96c8
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-script-stderr.txt
@@ -0,0 +1,6 @@
+[0-9]+
+CMake Error at .*/variable_watch\.cmake:9999 \(update_x\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/variable_watch\.cmake:5 \(set\)
+ .*/variable_watch\.cmake:9999 \(update_x\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-stderr.txt
new file mode 100644
index 000000000..a8b4756da
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-default-stderr.txt
@@ -0,0 +1,6 @@
+[0-9]+
+CMake Error at variable_watch\.cmake:9999 \(update_x\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ variable_watch\.cmake:5 \(set\)
+ variable_watch\.cmake:9999 \(update_x\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-script-stderr.txt
new file mode 100644
index 000000000..4dddc96c8
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-script-stderr.txt
@@ -0,0 +1,6 @@
+[0-9]+
+CMake Error at .*/variable_watch\.cmake:9999 \(update_x\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ .*/variable_watch\.cmake:5 \(set\)
+ .*/variable_watch\.cmake:9999 \(update_x\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-stderr.txt
new file mode 100644
index 000000000..a8b4756da
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-invalid-var-stderr.txt
@@ -0,0 +1,6 @@
+[0-9]+
+CMake Error at variable_watch\.cmake:9999 \(update_x\):
+ Maximum recursion depth of [0-9]+ exceeded
+Call Stack \(most recent call first\):
+ variable_watch\.cmake:5 \(set\)
+ variable_watch\.cmake:9999 \(update_x\)
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-result.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-script-result.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-script-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-script-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-script-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-script-stderr.txt
new file mode 100644
index 000000000..00b2b3c11
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-script-stderr.txt
@@ -0,0 +1,22 @@
+^4
+6
+8
+10
+CMake Error at .*/variable_watch\.cmake:9999 \(update_x\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ .*/variable_watch\.cmake:5 \(set\)
+ .*/variable_watch\.cmake:9999 \(update_x\)
+ .*/variable_watch\.cmake:5 \(set\)
+ .*/variable_watch\.cmake:9999 \(update_x\)
+ .*/variable_watch\.cmake:5 \(set\)
+ .*/variable_watch\.cmake:9999 \(update_x\)
+ .*/variable_watch\.cmake:5 \(set\)
+ .*/variable_watch\.cmake:9999 \(update_x\)
+ .*/variable_watch\.cmake:9 \(set\)
+ .*/CMakeLists\.txt:5 \(include\)
+
+
+CMake Error: Error in cmake code at
+Unknown:0:
+A command failed during the invocation of callback "update_x"\.$
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-stderr.txt b/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-stderr.txt
new file mode 100644
index 000000000..8f27bf1c2
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch-var-stderr.txt
@@ -0,0 +1,22 @@
+^4
+6
+8
+10
+CMake Error at variable_watch\.cmake:9999 \(update_x\):
+ Maximum recursion depth of 10 exceeded
+Call Stack \(most recent call first\):
+ variable_watch\.cmake:5 \(set\)
+ variable_watch\.cmake:9999 \(update_x\)
+ variable_watch\.cmake:5 \(set\)
+ variable_watch\.cmake:9999 \(update_x\)
+ variable_watch\.cmake:5 \(set\)
+ variable_watch\.cmake:9999 \(update_x\)
+ variable_watch\.cmake:5 \(set\)
+ variable_watch\.cmake:9999 \(update_x\)
+ variable_watch\.cmake:9 \(set\)
+ CMakeLists\.txt:5 \(include\)
+
+
+CMake Error: Error in cmake code at
+Unknown:0:
+A command failed during the invocation of callback "update_x"\.$
diff --git a/Tests/RunCMake/MaxRecursionDepth/variable_watch.cmake b/Tests/RunCMake/MaxRecursionDepth/variable_watch.cmake
new file mode 100644
index 000000000..b3c7b8dfe
--- /dev/null
+++ b/Tests/RunCMake/MaxRecursionDepth/variable_watch.cmake
@@ -0,0 +1,9 @@
+function(update_x)
+ message("${x}")
+ math(EXPR y "${x} + 2")
+ variable_watch(x update_x)
+ set(x "${y}")
+endfunction()
+
+variable_watch(x update_x)
+set(x 4)
diff --git a/Tests/RunCMake/MetaCompileFeatures/C.cmake b/Tests/RunCMake/MetaCompileFeatures/C.cmake
new file mode 100644
index 000000000..3bb6181ab
--- /dev/null
+++ b/Tests/RunCMake/MetaCompileFeatures/C.cmake
@@ -0,0 +1,27 @@
+
+enable_language(C)
+
+function(check_language_feature_flags lang level)
+ if(CMAKE_${lang}${level}_STANDARD_COMPILE_OPTION)
+ #this property is an internal implementation detail of CMake
+ get_property(known_features GLOBAL PROPERTY CMAKE_${lang}${level}_KNOWN_FEATURES)
+ list(LENGTH known_features len)
+ if(len LESS 1)
+ message(FATAL_ERROR "unable to find known features of ${lang}${level}")
+ endif()
+
+ string(TOLOWER ${lang} lang_lower)
+ set(known_name ${lang_lower}${level}_known_features)
+ set(meta_name ${lang_lower}${level}_meta_feature)
+
+ add_library(${known_name} STATIC a.c)
+ target_compile_features(${known_name} PUBLIC ${known_features})
+ add_library(${meta_name} STATIC a.c)
+ target_compile_features(${meta_name} PUBLIC ${lang_lower}_std_${level})
+ endif()
+endfunction()
+
+
+check_language_feature_flags(C 90)
+check_language_feature_flags(C 99)
+check_language_feature_flags(C 11)
diff --git a/Tests/RunCMake/MetaCompileFeatures/CMakeLists.txt b/Tests/RunCMake/MetaCompileFeatures/CMakeLists.txt
new file mode 100644
index 000000000..3e470a29c
--- /dev/null
+++ b/Tests/RunCMake/MetaCompileFeatures/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.14)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/MetaCompileFeatures/CXX.cmake b/Tests/RunCMake/MetaCompileFeatures/CXX.cmake
new file mode 100644
index 000000000..ef3b9d4be
--- /dev/null
+++ b/Tests/RunCMake/MetaCompileFeatures/CXX.cmake
@@ -0,0 +1,27 @@
+
+enable_language(CXX)
+
+function(check_language_feature_flags lang level)
+ if(CMAKE_${lang}${level}_STANDARD_COMPILE_OPTION)
+ #this property is an internal implementation detail of CMake
+ get_property(known_features GLOBAL PROPERTY CMAKE_${lang}${level}_KNOWN_FEATURES)
+ list(LENGTH known_features len)
+ if(len LESS 1)
+ message(FATAL_ERROR "unable to find known features of ${lang}${level}")
+ endif()
+
+ string(TOLOWER ${lang} lang_lower)
+ set(known_name ${lang_lower}${level}_known_features)
+ set(meta_name ${lang_lower}${level}_meta_feature)
+
+ add_library(${known_name} STATIC a.cxx)
+ target_compile_features(${known_name} PUBLIC ${known_features})
+ add_library(${meta_name} STATIC a.cxx)
+ target_compile_features(${meta_name} PUBLIC ${lang_lower}_std_${level})
+ endif()
+endfunction()
+
+
+check_language_feature_flags(CXX 98)
+check_language_feature_flags(CXX 11)
+check_language_feature_flags(CXX 14)
diff --git a/Tests/RunCMake/MetaCompileFeatures/RunCMakeTest.cmake b/Tests/RunCMake/MetaCompileFeatures/RunCMakeTest.cmake
new file mode 100644
index 000000000..009cde4f1
--- /dev/null
+++ b/Tests/RunCMake/MetaCompileFeatures/RunCMakeTest.cmake
@@ -0,0 +1,4 @@
+include(RunCMake)
+
+run_cmake(C)
+run_cmake(CXX)
diff --git a/Tests/RunCMake/MetaCompileFeatures/a.c b/Tests/RunCMake/MetaCompileFeatures/a.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/MetaCompileFeatures/a.c
diff --git a/Tests/RunCMake/MetaCompileFeatures/a.cxx b/Tests/RunCMake/MetaCompileFeatures/a.cxx
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/MetaCompileFeatures/a.cxx
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/Ninja/CMP0058-OLD-by-stderr.txt b/Tests/RunCMake/Ninja/CMP0058-OLD-by-stderr.txt
new file mode 100644
index 000000000..9a606ee60
--- /dev/null
+++ b/Tests/RunCMake/Ninja/CMP0058-OLD-by-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0058-OLD-by.cmake:[0-9]+ \(cmake_policy\):
+ The OLD behavior for policy CMP0058 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/Ninja/CMP0058-OLD-no-stderr.txt b/Tests/RunCMake/Ninja/CMP0058-OLD-no-stderr.txt
new file mode 100644
index 000000000..ba6e5da4e
--- /dev/null
+++ b/Tests/RunCMake/Ninja/CMP0058-OLD-no-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0058-OLD-no.cmake:[0-9]+ \(cmake_policy\):
+ The OLD behavior for policy CMP0058 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/Ninja/CustomCommandJobPool-check.cmake b/Tests/RunCMake/Ninja/CustomCommandJobPool-check.cmake
new file mode 100644
index 000000000..7f7fa33bf
--- /dev/null
+++ b/Tests/RunCMake/Ninja/CustomCommandJobPool-check.cmake
@@ -0,0 +1,8 @@
+set(log "${RunCMake_BINARY_DIR}/CustomCommandJobPool-build/build.ninja")
+file(READ "${log}" build_file)
+if(NOT "${build_file}" MATCHES "pool = custom_command_pool")
+ set(RunCMake_TEST_FAILED "Log file:\n ${log}\ndoes not have expected line: pool = custom_command_pool")
+endif()
+if(NOT "${build_file}" MATCHES "pool = custom_target_pool")
+ set(RunCMake_TEST_FAILED "Log file:\n ${log}\ndoes not have expected line: pool = custom_target_pool")
+endif()
diff --git a/Tests/RunCMake/Ninja/CustomCommandJobPool.cmake b/Tests/RunCMake/Ninja/CustomCommandJobPool.cmake
new file mode 100644
index 000000000..1e36e65e2
--- /dev/null
+++ b/Tests/RunCMake/Ninja/CustomCommandJobPool.cmake
@@ -0,0 +1,17 @@
+add_custom_command(
+ OUTPUT hello.copy.c
+ COMMAND "${CMAKE_COMMAND}" -E copy
+ "${CMAKE_CURRENT_SOURCE_DIR}/hello.c"
+ hello.copy.c
+ WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
+ JOB_POOL "custom_command_pool"
+ )
+add_custom_target(copy ALL DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/hello.copy.c")
+
+add_custom_target(
+ hello.echo
+ COMMAND echo
+ JOB_POOL "custom_target_pool"
+)
+
+include(CheckNoPrefixSubDir.cmake)
diff --git a/Tests/RunCMake/Ninja/JobPoolUsesTerminal-result.txt b/Tests/RunCMake/Ninja/JobPoolUsesTerminal-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/Ninja/JobPoolUsesTerminal-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Ninja/JobPoolUsesTerminal-stderr.txt b/Tests/RunCMake/Ninja/JobPoolUsesTerminal-stderr.txt
new file mode 100644
index 000000000..45975caeb
--- /dev/null
+++ b/Tests/RunCMake/Ninja/JobPoolUsesTerminal-stderr.txt
@@ -0,0 +1,9 @@
+^CMake Error at JobPoolUsesTerminal.cmake:1 \(add_custom_command\):
+ add_custom_command JOB_POOL is shadowed by USES_TERMINAL.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+CMake Error at JobPoolUsesTerminal.cmake:2 \(add_custom_target\):
+ add_custom_target JOB_POOL is shadowed by USES_TERMINAL.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/Ninja/JobPoolUsesTerminal.cmake b/Tests/RunCMake/Ninja/JobPoolUsesTerminal.cmake
new file mode 100644
index 000000000..b7e440c60
--- /dev/null
+++ b/Tests/RunCMake/Ninja/JobPoolUsesTerminal.cmake
@@ -0,0 +1,2 @@
+add_custom_command(OUTPUT x COMMAND y USES_TERMINAL JOB_POOL z)
+add_custom_target(CustomTarget COMMAND y USES_TERMINAL JOB_POOL z)
diff --git a/Tests/RunCMake/Ninja/NoWorkToDo-nowork-stdout.txt b/Tests/RunCMake/Ninja/NoWorkToDo-nowork-stdout.txt
new file mode 100644
index 000000000..60a9228b0
--- /dev/null
+++ b/Tests/RunCMake/Ninja/NoWorkToDo-nowork-stdout.txt
@@ -0,0 +1 @@
+^ninja: no work to do
diff --git a/Tests/RunCMake/Ninja/NoWorkToDo.cmake b/Tests/RunCMake/Ninja/NoWorkToDo.cmake
new file mode 100644
index 000000000..a2fa0cb39
--- /dev/null
+++ b/Tests/RunCMake/Ninja/NoWorkToDo.cmake
@@ -0,0 +1,2 @@
+enable_language(C)
+add_executable(hello hello.c)
diff --git a/Tests/RunCMake/Ninja/PreventConfigureFileDupBuildRule.cmake b/Tests/RunCMake/Ninja/PreventConfigureFileDupBuildRule.cmake
new file mode 100644
index 000000000..505f75094
--- /dev/null
+++ b/Tests/RunCMake/Ninja/PreventConfigureFileDupBuildRule.cmake
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.12)
+project(Test LANGUAGES C)
+
+configure_file(PreventConfigureFileDupBuildRule.cmake PreventTargetAliasesDupBuildRule.cmake @ONLY)
+add_subdirectory(SubDirConfigureFileDup)
diff --git a/Tests/RunCMake/Ninja/PreventTargetAliasesDupBuildRule.cmake b/Tests/RunCMake/Ninja/PreventTargetAliasesDupBuildRule.cmake
new file mode 100644
index 000000000..da6f86a73
--- /dev/null
+++ b/Tests/RunCMake/Ninja/PreventTargetAliasesDupBuildRule.cmake
@@ -0,0 +1,41 @@
+cmake_minimum_required(VERSION 3.12)
+project(Test LANGUAGES C)
+
+# fake launcher executable
+set(input_launcher_executable ${CMAKE_CURRENT_BINARY_DIR}/fake_launcher_executable)
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/fake_launcher_executable "")
+
+# application and executable name
+set(application_target "HelloApp")
+set(application_name "Hello")
+set(executable_name "Hello")
+
+# target built in "<root>/bin"
+add_executable(${application_target} hello.c)
+set_target_properties(${application_target} PROPERTIES
+ OUTPUT_NAME ${executable_name}
+ RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin
+ )
+
+# configured launcher in "<root>"
+set(configured_launcher_executable "${CMAKE_CURRENT_BINARY_DIR}/${application_name}")
+
+# create command to copy the launcher
+add_custom_command(
+ DEPENDS
+ ${input_launcher_executable}
+ OUTPUT
+ ${configured_launcher_executable}
+ COMMAND
+ ${CMAKE_COMMAND} -E copy ${input_launcher_executable} ${configured_launcher_executable}
+ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+ COMMENT
+ "Configuring application launcher: ${application_name}"
+ )
+
+add_custom_target(Configure${application_name}Launcher ALL
+ DEPENDS
+ ${application_target}
+ ${input_launcher_executable}
+ ${configured_launcher_executable}
+ )
diff --git a/Tests/RunCMake/Ninja/RspFileC.cmake b/Tests/RunCMake/Ninja/RspFileC.cmake
new file mode 100644
index 000000000..4a4068237
--- /dev/null
+++ b/Tests/RunCMake/Ninja/RspFileC.cmake
@@ -0,0 +1,2 @@
+set(ENV{CMAKE_NINJA_FORCE_RESPONSE_FILE} 1)
+enable_language(C)
diff --git a/Tests/RunCMake/Ninja/RspFileCXX.cmake b/Tests/RunCMake/Ninja/RspFileCXX.cmake
new file mode 100644
index 000000000..9e61ffeff
--- /dev/null
+++ b/Tests/RunCMake/Ninja/RspFileCXX.cmake
@@ -0,0 +1,2 @@
+set(ENV{CMAKE_NINJA_FORCE_RESPONSE_FILE} 1)
+enable_language(CXX)
diff --git a/Tests/RunCMake/Ninja/RspFileFortran.cmake b/Tests/RunCMake/Ninja/RspFileFortran.cmake
new file mode 100644
index 000000000..8c18e3768
--- /dev/null
+++ b/Tests/RunCMake/Ninja/RspFileFortran.cmake
@@ -0,0 +1,2 @@
+set(ENV{CMAKE_NINJA_FORCE_RESPONSE_FILE} 1)
+enable_language(Fortran)
diff --git a/Tests/RunCMake/Ninja/SubDirConfigureFileDup/CMakeLists.txt b/Tests/RunCMake/Ninja/SubDirConfigureFileDup/CMakeLists.txt
new file mode 100644
index 000000000..433f77bf3
--- /dev/null
+++ b/Tests/RunCMake/Ninja/SubDirConfigureFileDup/CMakeLists.txt
@@ -0,0 +1 @@
+configure_file(../PreventConfigureFileDupBuildRule.cmake PreventTargetAliasesDupBuildRule.cmake @ONLY)
diff --git a/Tests/RunCMake/Ninja/VerboseBuild-build-stdout.txt b/Tests/RunCMake/Ninja/VerboseBuild-build-stdout.txt
new file mode 100644
index 000000000..884bf953e
--- /dev/null
+++ b/Tests/RunCMake/Ninja/VerboseBuild-build-stdout.txt
@@ -0,0 +1 @@
+.*DEFINE_FOR_VERBOSE_DETECTION.*hello.dir.*
diff --git a/Tests/RunCMake/Ninja/VerboseBuild-nowork-stdout.txt b/Tests/RunCMake/Ninja/VerboseBuild-nowork-stdout.txt
new file mode 100644
index 000000000..60a9228b0
--- /dev/null
+++ b/Tests/RunCMake/Ninja/VerboseBuild-nowork-stdout.txt
@@ -0,0 +1 @@
+^ninja: no work to do
diff --git a/Tests/RunCMake/Ninja/VerboseBuild.cmake b/Tests/RunCMake/Ninja/VerboseBuild.cmake
new file mode 100644
index 000000000..424e54eec
--- /dev/null
+++ b/Tests/RunCMake/Ninja/VerboseBuild.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+add_executable(hello hello.c)
+target_compile_definitions(hello PRIVATE "DEFINE_FOR_VERBOSE_DETECTION")
diff --git a/Tests/RunCMake/ObjectLibrary/CheckTargetObjects.cmake b/Tests/RunCMake/ObjectLibrary/CheckTargetObjects.cmake
new file mode 100644
index 000000000..0c85c72b0
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/CheckTargetObjects.cmake
@@ -0,0 +1,32 @@
+add_library(StaticLib STATIC a.c)
+
+add_custom_command(TARGET StaticLib POST_BUILD
+ VERBATIM
+ COMMAND ${CMAKE_COMMAND}
+ "-DTARGET_OBJECTS=$<TARGET_OBJECTS:StaticLib>"
+ -DEXPECTED_NUM_OBJECTFILES=2
+ -P "${CMAKE_CURRENT_SOURCE_DIR}/check_object_files.cmake"
+ )
+
+add_library(SharedLib SHARED a.c b.c)
+target_compile_definitions(SharedLib PRIVATE REQUIRED)
+
+add_custom_command(TARGET SharedLib POST_BUILD
+ VERBATIM
+ COMMAND ${CMAKE_COMMAND}
+ "-DTARGET_OBJECTS:STRING=$<TARGET_OBJECTS:SharedLib>"
+ -DEXPECTED_NUM_OBJECTFILES=2
+ -P "${CMAKE_CURRENT_SOURCE_DIR}/check_object_files.cmake"
+ )
+
+add_executable(ExecObjs a.c b.c exe.c)
+target_compile_definitions(ExecObjs PRIVATE REQUIRED)
+
+add_custom_target(check_exec_objs ALL
+ VERBATIM
+ COMMAND ${CMAKE_COMMAND}
+ "-DTARGET_OBJECTS=$<TARGET_OBJECTS:ExecObjs>"
+ -DEXPECTED_NUM_OBJECTFILES=3
+ -P "${CMAKE_CURRENT_SOURCE_DIR}/check_object_files.cmake"
+ DEPENDS ExecObjs
+ )
diff --git a/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-result.txt b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-stderr.txt b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-stderr.txt
new file mode 100644
index 000000000..f2f0f94d1
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1-stderr.txt
@@ -0,0 +1 @@
+CMake Error: install\(EXPORT "exp" ...\) includes target "UseA" which requires target "A" that is not in the export set.
diff --git a/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1.cmake b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1.cmake
new file mode 100644
index 000000000..9e2460987
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj1.cmake
@@ -0,0 +1,6 @@
+add_library(A OBJECT a.c)
+add_library(UseA STATIC)
+target_link_libraries(UseA PUBLIC A)
+
+install(TARGETS UseA EXPORT exp ARCHIVE DESTINATION lib)
+install(EXPORT exp DESTINATION lib/cmake/exp)
diff --git a/Tests/RunCMake/ObjectLibrary/InstallLinkedObj2.cmake b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj2.cmake
new file mode 100644
index 000000000..cdda96239
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/InstallLinkedObj2.cmake
@@ -0,0 +1,6 @@
+add_library(A OBJECT a.c)
+add_library(UseA STATIC)
+target_link_libraries(UseA PUBLIC A)
+
+install(TARGETS UseA A EXPORT exp ARCHIVE DESTINATION lib)
+install(EXPORT exp DESTINATION lib/cmake/exp)
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjLHSShared.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjLHSShared.cmake
new file mode 100644
index 000000000..4aa7bba6f
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjLHSShared.cmake
@@ -0,0 +1,7 @@
+project(LinkObjLHSShared C)
+
+add_library(OtherLib SHARED a.c)
+target_compile_definitions(OtherLib INTERFACE REQUIRED)
+
+add_library(AnObjLib OBJECT requires.c)
+target_link_libraries(AnObjLib OtherLib)
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjLHSStatic.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjLHSStatic.cmake
new file mode 100644
index 000000000..261bee781
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjLHSStatic.cmake
@@ -0,0 +1,7 @@
+project(LinkObjLHSStatic C)
+
+add_library(OtherLib STATIC a.c)
+target_compile_definitions(OtherLib INTERFACE REQUIRED)
+
+add_library(AnObjLib OBJECT requires.c)
+target_link_libraries(AnObjLib OtherLib)
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-result.txt b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-result.txt
new file mode 100644
index 000000000..e27f06b56
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-result.txt
@@ -0,0 +1 @@
+[1-9][0-9]*
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-stdout.txt b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-stdout.txt
new file mode 100644
index 000000000..4eeb0965c
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject-build-stdout.txt
@@ -0,0 +1 @@
+REQUIRED needs to be defined
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject.cmake
new file mode 100644
index 000000000..db571a3ca
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject.cmake
@@ -0,0 +1,12 @@
+cmake_policy(SET CMP0022 NEW)
+
+enable_language(C)
+
+add_library(AnObjLib OBJECT a.c)
+target_compile_definitions(AnObjLib INTERFACE REQUIRED)
+
+add_library(AnotherObjLib OBJECT b.c)
+target_link_libraries(AnotherObjLib PRIVATE AnObjLib)
+
+add_executable(exe exe.c)
+target_link_libraries(exe AnotherObjLib)
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2-build-result.txt b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2-build-result.txt
new file mode 100644
index 000000000..e27f06b56
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2-build-result.txt
@@ -0,0 +1 @@
+[1-9][0-9]*
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2.cmake
new file mode 100644
index 000000000..6bb8d5e7a
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSObject2.cmake
@@ -0,0 +1,12 @@
+cmake_policy(SET CMP0022 NEW)
+
+enable_language(C)
+
+add_library(AnObjLib OBJECT a.c)
+target_compile_definitions(AnObjLib INTERFACE REQUIRED)
+
+add_library(AnotherObjLib OBJECT b.c)
+target_link_libraries(AnotherObjLib PUBLIC AnObjLib)
+
+add_executable(exe exe.c)
+target_link_libraries(exe AnotherObjLib)
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared.cmake
new file mode 100644
index 000000000..b9030b318
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared.cmake
@@ -0,0 +1,13 @@
+enable_language(C)
+
+add_definitions(-DCOMPILE_FOR_SHARED_LIB)
+
+add_library(AnObjLib OBJECT a.c)
+target_compile_definitions(AnObjLib INTERFACE REQUIRED)
+set_target_properties(AnObjLib PROPERTIES POSITION_INDEPENDENT_CODE ON)
+
+add_library(A SHARED b.c $<TARGET_OBJECTS:AnObjLib>)
+target_link_libraries(A PUBLIC AnObjLib)
+
+add_executable(exe exe.c)
+target_link_libraries(exe A)
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared2.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared2.cmake
new file mode 100644
index 000000000..e2e5fa262
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSShared2.cmake
@@ -0,0 +1,14 @@
+enable_language(C)
+
+add_definitions(-DCOMPILE_FOR_SHARED_LIB)
+
+add_library(AnObjLib OBJECT a.c)
+target_compile_definitions(AnObjLib INTERFACE REQUIRED)
+set_target_properties(AnObjLib PROPERTIES POSITION_INDEPENDENT_CODE ON)
+
+add_library(A SHARED b.c)
+target_link_libraries(A PRIVATE AnObjLib)
+target_compile_definitions(A INTERFACE $<TARGET_PROPERTY:AnObjLib,INTERFACE_COMPILE_DEFINITIONS>)
+
+add_executable(exe exe.c)
+target_link_libraries(exe A)
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic.cmake
new file mode 100644
index 000000000..73fad063f
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic.cmake
@@ -0,0 +1,10 @@
+enable_language(C)
+
+add_library(AnObjLib OBJECT a.c)
+target_compile_definitions(AnObjLib INTERFACE REQUIRED)
+
+add_library(A STATIC b.c $<TARGET_OBJECTS:AnObjLib>)
+target_link_libraries(A PUBLIC AnObjLib)
+
+add_executable(exe exe.c)
+target_link_libraries(exe A)
diff --git a/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic2.cmake b/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic2.cmake
new file mode 100644
index 000000000..9e1ab6d94
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/LinkObjRHSStatic2.cmake
@@ -0,0 +1,11 @@
+enable_language(C)
+
+add_library(AnObjLib OBJECT a.c)
+target_compile_definitions(AnObjLib INTERFACE REQUIRED)
+
+add_library(A STATIC b.c)
+target_link_libraries(A PRIVATE AnObjLib)
+target_compile_definitions(A INTERFACE $<TARGET_PROPERTY:AnObjLib,INTERFACE_COMPILE_DEFINITIONS>)
+
+add_executable(exe exe.c)
+target_link_libraries(exe A)
diff --git a/Tests/RunCMake/ObjectLibrary/TransitiveDependencies.cmake b/Tests/RunCMake/ObjectLibrary/TransitiveDependencies.cmake
new file mode 100644
index 000000000..e41cf2ec9
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/TransitiveDependencies.cmake
@@ -0,0 +1,7 @@
+add_library(lib1 STATIC depends_obj0.c)
+add_library(lib2 OBJECT a.c)
+target_link_libraries(lib2 PRIVATE lib1)
+
+add_executable(test exe2.c)
+
+target_link_libraries(test PUBLIC lib2)
diff --git a/Tests/RunCMake/ObjectLibrary/check_object_files.cmake b/Tests/RunCMake/ObjectLibrary/check_object_files.cmake
new file mode 100644
index 000000000..3c34229ff
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/check_object_files.cmake
@@ -0,0 +1,17 @@
+
+if (NOT TARGET_OBJECTS)
+ message(SEND_ERROR "Object not passed as -DTARGET_OBJECTS")
+endif()
+
+foreach(objlib_file IN LISTS objects)
+ message(STATUS "objlib_file: =${objlib_file}=")
+
+ set(file_exists False)
+ if (EXISTS "${objlib_file}")
+ set(file_exists True)
+ endif()
+
+ if (NOT file_exists)
+ message(SEND_ERROR "File \"${objlib_file}\" does not exist!${tried}")
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/ObjectLibrary/exe.c b/Tests/RunCMake/ObjectLibrary/exe.c
new file mode 100644
index 000000000..2e08700c3
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/exe.c
@@ -0,0 +1,14 @@
+#if defined(_WIN32) && defined(COMPILE_FOR_SHARED_LIB)
+# define IMPORT __declspec(dllimport)
+#else
+# define IMPORT
+#endif
+
+extern IMPORT int b(void);
+int main()
+{
+ return b();
+}
+#ifndef REQUIRED
+# error "REQUIRED needs to be defined"
+#endif
diff --git a/Tests/RunCMake/ObjectLibrary/exe2.c b/Tests/RunCMake/ObjectLibrary/exe2.c
new file mode 100644
index 000000000..66e0caf95
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/exe2.c
@@ -0,0 +1,6 @@
+extern int myobj_foo(void);
+
+int main(void)
+{
+ return myobj_foo();
+}
diff --git a/Tests/RunCMake/ObjectLibrary/requires.c b/Tests/RunCMake/ObjectLibrary/requires.c
new file mode 100644
index 000000000..685632b3d
--- /dev/null
+++ b/Tests/RunCMake/ObjectLibrary/requires.c
@@ -0,0 +1,8 @@
+#ifdef REQUIRED
+int required()
+{
+ return 0;
+}
+#else
+# error "REQUIRED not defined"
+#endif
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/CMakeLists.txt b/Tests/RunCMake/ParseImplicitIncludeInfo/CMakeLists.txt
new file mode 100644
index 000000000..289710955
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.0)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/ParseImplicitIncludeInfo.cmake b/Tests/RunCMake/ParseImplicitIncludeInfo/ParseImplicitIncludeInfo.cmake
new file mode 100644
index 000000000..5880378c5
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/ParseImplicitIncludeInfo.cmake
@@ -0,0 +1,118 @@
+cmake_minimum_required(VERSION 3.14)
+project(Minimal NONE)
+
+#
+# list of targets to test. to add a target: put its files in the data
+# subdirectory and add it to this list... we run each target's
+# data/*.input file through the parser and check to see if it matches
+# the corresponding data/*.output file. note that the empty-* case
+# has special handling (it should not parse).
+#
+set(targets
+ aix-C-XL-13.1.3 aix-CXX-XL-13.1.3
+ aix-C-XLClang-16.1.0.1 aix-CXX-XLClang-16.1.0.1
+ craype-C-Cray-8.7 craype-CXX-Cray-8.7 craype-Fortran-Cray-8.7
+ craype-C-Cray-9.0-hlist-ad craype-CXX-Cray-9.0-hlist-ad craype-Fortran-Cray-9.0-hlist-ad
+ craype-C-GNU-7.3.0 craype-CXX-GNU-7.3.0 craype-Fortran-GNU-7.3.0
+ craype-C-Intel-18.0.2.20180210 craype-CXX-Intel-18.0.2.20180210
+ craype-Fortran-Intel-18.0.2.20180210
+ darwin-C-AppleClang-8.0.0.8000042 darwin-CXX-AppleClang-8.0.0.8000042
+ darwin_nostdinc-C-AppleClang-8.0.0.8000042
+ darwin_nostdinc-CXX-AppleClang-8.0.0.8000042
+ freebsd-C-Clang-3.3.0 freebsd-CXX-Clang-3.3.0 freebsd-Fortran-GNU-4.6.4
+ hand-C-empty hand-CXX-empty
+ hand-C-relative hand-CXX-relative
+ linux-C-GNU-7.3.0 linux-CXX-GNU-7.3.0 linux-Fortran-GNU-7.3.0
+ linux-C-Intel-18.0.0.20170811 linux-CXX-Intel-18.0.0.20170811
+ linux-C-PGI-18.10.1 linux-CXX-PGI-18.10.1
+ linux-Fortran-PGI-18.10.1 linux_pgf77-Fortran-PGI-18.10.1
+ linux_nostdinc-C-PGI-18.10.1 linux_nostdinc-CXX-PGI-18.10.1
+ linux_nostdinc-Fortran-PGI-18.10.1
+ linux-C-XL-12.1.0 linux-CXX-XL-12.1.0 linux-Fortran-XL-14.1.0
+ linux_nostdinc-C-XL-12.1.0 linux_nostdinc-CXX-XL-12.1.0
+ linux_nostdinc_i-C-XL-12.1.0 linux_nostdinc-CXX-XL-12.1.0
+ linux-C-XL-16.1.0.0 linux-CXX-XL-16.1.0.0
+ linux-CUDA-NVIDIA-9.2.148
+ mingw.org-C-GNU-4.9.3 mingw.org-CXX-GNU-4.9.3
+ netbsd-C-GNU-4.8.5 netbsd-CXX-GNU-4.8.5
+ netbsd_nostdinc-C-GNU-4.8.5 netbsd_nostdinc-CXX-GNU-4.8.5
+ openbsd-C-Clang-5.0.1 openbsd-CXX-Clang-5.0.1
+ sunos-C-SunPro-5.13.0 sunos-CXX-SunPro-5.13.0 sunos-Fortran-SunPro-8.8.0
+ )
+
+if(CMAKE_HOST_WIN32)
+ # The KWSys actual-case cache breaks case sensitivity on Windows.
+ list(FILTER targets EXCLUDE REGEX "-XL|-SunPro")
+else()
+ # Windows drive letters are not recognized as absolute on other platforms.
+ list(FILTER targets EXCLUDE REGEX "mingw")
+endif()
+
+include(${CMAKE_ROOT}/Modules/CMakeParseImplicitIncludeInfo.cmake)
+
+#
+# load_compiler_info: read infile, parsing out cmake compiler info
+# variables as we go. returns language, a list of variables we set
+# (so we can clear them later), and the remaining verbose output
+# from the compiler.
+#
+function(load_compiler_info infile lang_var outcmvars_var outstr_var)
+ unset(lang)
+ unset(outcmvars)
+ unset(outstr)
+ file(READ "${infile}" in)
+ string(REGEX REPLACE "\r?\n" ";" in_lines "${in}")
+ foreach(line IN LISTS in_lines)
+ # check for special CMAKE variable lines and parse them if found
+ if("${line}" MATCHES "^CMAKE_([_A-Za-z0-9]+)=(.*)$")
+ if("${CMAKE_MATCH_1}" STREQUAL "LANG") # handle CMAKE_LANG here
+ set(lang "${CMAKE_MATCH_2}")
+ else()
+ set(CMAKE_${CMAKE_MATCH_1} "${CMAKE_MATCH_2}" PARENT_SCOPE)
+ list(APPEND outcmvars "CMAKE_${CMAKE_MATCH_1}")
+ endif()
+ else()
+ string(APPEND outstr "${line}\n")
+ endif()
+ endforeach()
+ if(NOT lang)
+ message("load_compiler_info: ${infile} no LANG info; default to C")
+ set(lang C)
+ endif()
+ set(${lang_var} "${lang}" PARENT_SCOPE)
+ set(${outcmvars_var} "${outcmvars}" PARENT_SCOPE)
+ set(${outstr_var} "${outstr}" PARENT_SCOPE)
+endfunction()
+
+#
+# unload_compiler_info: clear out any CMAKE_* vars load previously set
+#
+function(unload_compiler_info cmvars)
+ foreach(var IN LISTS cmvars)
+ unset("${var}" PARENT_SCOPE)
+ endforeach()
+endfunction()
+
+#
+# main test loop
+#
+foreach(t ${targets})
+ set(infile "${CMAKE_SOURCE_DIR}/data/${t}.input")
+ set(outfile "${CMAKE_SOURCE_DIR}/data/${t}.output")
+ if (NOT EXISTS ${infile} OR NOT EXISTS ${outfile})
+ message("missing files for target ${t} in ${CMAKE_SOURCE_DIR}/data")
+ continue()
+ endif()
+ load_compiler_info(${infile} lang cmvars input)
+ file(READ ${outfile} output)
+ string(STRIP "${output}" output)
+ cmake_parse_implicit_include_info("${input}" "${lang}" idirs log state)
+ if(t MATCHES "-empty$") # empty isn't supposed to parse
+ if("${state}" STREQUAL "done")
+ message("empty parse failed: ${idirs}, log=${log}")
+ endif()
+ elseif(NOT "${state}" STREQUAL "done" OR NOT "${idirs}" MATCHES "^${output}$")
+ message("parse failed: state=${state}, '${idirs}' does not match '^${output}$', log=${log}")
+ endif()
+ unload_compiler_info("${cmvars}")
+endforeach(t)
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/RunCMakeTest.cmake b/Tests/RunCMake/ParseImplicitIncludeInfo/RunCMakeTest.cmake
new file mode 100644
index 000000000..6266b500d
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(ParseImplicitIncludeInfo)
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/CMakeLists.txt b/Tests/RunCMake/ParseImplicitIncludeInfo/data/CMakeLists.txt
new file mode 100644
index 000000000..bffe819a8
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/CMakeLists.txt
@@ -0,0 +1,90 @@
+#
+# helper CMakeLists.txt file that can be used to generate input files
+# for the Tests/RunCMake/ParseImplicitIncludeInfo test.
+#
+# usage:
+# [create a temporary build directory and chdir to it]
+# cmake [-D options] $CMAKE_SRC/Tests/RunCMake/ParseImplicitIncludeInfo/data
+#
+# where useful -D options include:
+# -DLANGUAGES="C;CXX" -- list of languages to generate inputs for
+# -DUNAME="Darwin" -- operating system name (def: CMAKE_SYSTEM_NAME)
+#
+
+cmake_minimum_required(VERSION 3.3)
+if(POLICY CMP0089)
+ cmake_policy(SET CMP0089 NEW)
+endif()
+
+set(lngs C CXX)
+set(LANGUAGES "${lngs}" CACHE STRING "List of languages to generate inputs for")
+
+project(gen_implicit_include_data ${LANGUAGES})
+
+set(UNAME "${CMAKE_SYSTEM_NAME}" CACHE STRING "System uname")
+string(TOLOWER "${UNAME}" UNAME)
+message("Generate input for system type: ${UNAME}")
+
+# CMAKE_<LANG>_COMPILER_* variables we save in the resultfile
+set(compvars ABI AR ARCHITECTURE_ID EXTERNAL_TOOLCHAIN ID LAUNCHER LOADED
+ RANLIB TARGET VERSION VERSION_INTERAL)
+
+foreach(lang IN ITEMS ${LANGUAGES})
+
+ if("${lang}" STREQUAL "C")
+ set(file ${CMAKE_ROOT}/Modules/CMakeCCompilerABI.c)
+ elseif("${lang}" STREQUAL "CXX")
+ set(file ${CMAKE_ROOT}/Modules/CMakeCXXCompilerABI.cpp)
+ elseif("${lang}" STREQUAL "CUDA")
+ set(file ${CMAKE_ROOT}/Modules/CMakeCUDACompilerABI.cu)
+ elseif("${lang}" STREQUAL "Fortran")
+ set(file ${CMAKE_ROOT}/Modules/CMakeFortranCompilerABI.F)
+ else()
+ message(FATAL_ERROR "unknown language ${lang}")
+ endif()
+
+ set(resultfile "${CMAKE_BINARY_DIR}/")
+ string(APPEND resultfile ${UNAME}-${lang}-${CMAKE_${lang}_COMPILER_ID})
+ string(APPEND resultfile -${CMAKE_${lang}_COMPILER_VERSION})
+ string(APPEND resultfile .input)
+ message("Generate input for language ${lang}")
+ message("Input file: ${file}")
+ message("Result file: ${resultfile}")
+
+ # replicate logic from CMakeDetermineCompilerABI
+ set(outfile "${CMAKE_PLATFORM_INFO_DIR}/test${lang}.out")
+ set(CMAKE_FLAGS )
+ set(COMPILE_DEFINITIONS )
+ if(DEFINED CMAKE_${lang}_VERBOSE_FLAG)
+ set(CMAKE_FLAGS "-DEXE_LINKER_FLAGS=${CMAKE_${lang}_VERBOSE_FLAG}")
+ set(COMPILE_DEFINITIONS "${CMAKE_${lang}_VERBOSE_FLAG}")
+ endif()
+ if(DEFINED CMAKE_${lang}_VERBOSE_COMPILE_FLAG)
+ set(COMPILE_DEFINITIONS "${CMAKE_${lang}_VERBOSE_COMPILE_FLAG}")
+ endif()
+ if(NOT "x${CMAKE_${lang}_COMPILER_ID}" STREQUAL "xMSVC")
+ # Avoid adding our own platform standard libraries for compilers
+ # from which we might detect implicit link libraries.
+ list(APPEND CMAKE_FLAGS "-DCMAKE_${lang}_STANDARD_LIBRARIES=")
+ endif()
+
+ try_compile(rv ${CMAKE_BINARY_DIR} ${file}
+ CMAKE_FLAGS ${CMAKE_FLAGS}
+ COMPILE_DEFINITIONS ${COMPILE_DEFINITIONS}
+ CMAKE_FLAGS ${CMAKE_FLAGS}
+ OUTPUT_VARIABLE output
+ COPY_FILE "${outfile}"
+ COPY_FILE_ERROR copy_error)
+
+ if(NOT rv)
+ message(FATAL_ERROR "${lang} compile failed!!")
+ endif()
+
+ set(result "CMAKE_LANG=${lang}\n")
+ foreach(var IN ITEMS ${compvars})
+ list(APPEND result
+ "CMAKE_${lang}_COMPILER_${var}=${CMAKE_${lang}_COMPILER_${var}}\n")
+ endforeach()
+
+ file(WRITE ${resultfile} ${result} ${output})
+endforeach()
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/README b/Tests/RunCMake/ParseImplicitIncludeInfo/data/README
new file mode 100644
index 000000000..4f19b3c23
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/README
@@ -0,0 +1,25 @@
+This directory contains sample input files for the implicit include
+directories parser for testing. For each configuration there is one
+".input" file and one ".output" file.
+
+To generate ".input" files for a system, create a temporary build
+directory and chdir to it. Then run cmake pointing to this directory.
+The CMakeLists.txt file here will generate ".input" files in your
+build directory. The default set of languages is C and CXX. This
+can be changed with -DLANGUAGES=language_list. For example:
+-DLANGUAGES=Fortran will generate Fortran parser input.
+
+The ".output" files should be generated by hand from the input files.
+The test will compare the parser output to the manually generated
+".output" file. The two should match.
+
+For compilers that support "-nostdinc"-like flags, you can generate
+a test for this with a command like:
+cmake -DUNAME=netbsd_nostdinc \
+ -DCMAKE_C_FLAGS=-nostdinc -DCMAKE_CXX_FLAGS=-nostdinc .
+
+Here is an example for testing the XL compiler with both -I and nostdinc:
+
+env CC=xlc CXX=xlC cmake -DUNAME=linux_nostdinc_i \
+ -DCMAKE_C_FLAGS='-qnostdinc -I/tmp/ii/test_c' \
+ -DCMAKE_CXX_FLAGS='-qnostdinc -I/tmp/ii/test_c -I/tmp/ii/test_cxx' .
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XL-13.1.3.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XL-13.1.3.input
new file mode 100644
index 000000000..14517c5cb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XL-13.1.3.input
@@ -0,0 +1,40 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=XL
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=13.1.3
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_424d1/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_424d1.dir/build.make CMakeFiles/cmTC_424d1.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_424d1.dir/CMakeCCompilerABI.c.o
+/opt/IBM/xlc/13.1.3/bin/xlc -qthreaded -qhalt=e -V -o CMakeFiles/cmTC_424d1.dir/CMakeCCompilerABI.c.o -c /tmp/CMake/Modules/CMakeCCompilerABI.c
+export XL_CONFIG=/opt/IBM/xlc/13.1.3/etc/xlc.cfg.72:xlc
+export XL_ASMOBJFILES=/tmp/xlcASvf7aid
+export "XL_DIS=/opt/IBM/xlc/13.1.3/exe/dis -o "CMakeFiles/cmTC_424d1.dir/CMakeCCompilerABI.c.o" "CMakeCCompilerABI.o""
+/opt/IBM/xlc/13.1.3/exe/xlcentry -qosvar=aix.7.2 -qlanglvl=extc99 -qcpluscmt -qkeyword=inline -qalias=ansi -D_AIX -D_AIX32 -D_AIX41 -D_AIX43 -D_AIX50 -D_AIX51 -D_AIX52 -D_AIX53 -D_AIX61 -D_AIX71 -D_AIX72 -D_IBMR2 -D_POWER -qthreaded -qhalt=e -qasm_as=/bin/as -qc_stdinc=/opt/IBM/xlc/13.1.3/include:/opt/IBM/xlmass/8.1.3/include:/usr/include -qvac_include_path=/opt/IBM/xlc/13.1.3/include -oCMakeFiles/cmTC_424d1.dir/CMakeCCompilerABI.c.o /tmp/CMake/Modules/CMakeCCompilerABI.c /tmp/xlcW0uR7aia /tmp/xlcW1uV7aib /dev/null /tmp/xlcLvj7aieF.lst /dev/null /tmp/xlcW2vb7aic
+export XL_BACKEND=/opt/IBM/xlc/13.1.3/exe/xlCcode
+export XL_LINKER=/bin/ld
+/opt/IBM/xlc/13.1.3/exe/xlCcode -qlanglvl=extc99 -qcpluscmt -qkeyword=inline -qalias=ansi -qthreaded -qhalt=e /tmp/xlcW0uR7aia /tmp/xlcW1uV7aib CMakeFiles/cmTC_424d1.dir/CMakeCCompilerABI.c.o /tmp/xlcLvj7aieB.lst /tmp/xlcW2vb7aic
+rm /tmp/xlcASvf7aid
+rm /tmp/xlcLvj7aie
+rm /tmp/xlcW0uR7aia
+rm /tmp/xlcW1uV7aib
+rm /tmp/xlcW2vb7aic
+Linking C executable cmTC_424d1
+/tmp/CMake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_424d1.dir/link.txt --verbose=1
+/opt/IBM/xlc/13.1.3/bin/xlc -qthreaded -qhalt=e -Wl,-bnoipath -Wl,-brtl -V -Wl,-bexpall CMakeFiles/cmTC_424d1.dir/CMakeCCompilerABI.c.o -o cmTC_424d1 -Wl,-blibpath:/usr/lib:/lib
+export XL_CONFIG=/opt/IBM/xlc/13.1.3/etc/xlc.cfg.72:xlc
+/bin/ld -b32 /lib/crt0.o -bpT:0x10000000 -bpD:0x20000000 -bnoipath -brtl -bexpall CMakeFiles/cmTC_424d1.dir/CMakeCCompilerABI.c.o -o cmTC_424d1 -blibpath:/usr/lib:/lib -L/opt/IBM/xlmass/8.1.3/lib/aix61 -L/opt/IBM/xlc/13.1.3/lib -lxlopt -lxlipa -lxl -lc
+rm /tmp/xlcW0wn7aia
+rm /tmp/xlcW1wr7aib
+rm /tmp/xlcW2wz7aic
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XL-13.1.3.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XL-13.1.3.output
new file mode 100644
index 000000000..91b35ad15
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XL-13.1.3.output
@@ -0,0 +1 @@
+/opt/IBM/xlc/13.1.3/include;/opt/IBM/xlmass/8.1.3/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XLClang-16.1.0.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XLClang-16.1.0.1.input
new file mode 100644
index 000000000..2f018e624
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XLClang-16.1.0.1.input
@@ -0,0 +1,40 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=XLClang
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=16.1.0.1
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command(s):/usr/bin/gmake cmTC_fcf21/fast
+/usr/bin/gmake -f CMakeFiles/cmTC_fcf21.dir/build.make CMakeFiles/cmTC_fcf21.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_fcf21.dir/CMakeCCompilerABI.c.o
+/opt/IBM/xlC/16.1.0/bin/xlclang -V -o CMakeFiles/cmTC_fcf21.dir/CMakeCCompilerABI.c.o -c /tmp/CMake/Modules/CMakeCCompilerABI.c
+export XL_CONFIG=/opt/IBM/xlc/16.1.0/etc/xlc.cfg.72:xlclang
+export XL_ASMOBJFILES=/tmp/xlcASuz87id
+export "XL_DIS=/opt/IBM/xlc/16.1.0/exe/dis -o "CMakeFiles/cmTC_fcf21.dir/CMakeCCompilerABI.c.o" "CMakeCCompilerABI.o""
+/opt/IBM/xlC/16.1.0/exe/xlC2entry -qosvar=aix.7.2 -qalias=ansi -qthreaded -D_THREAD_SAFE -Wno-parentheses -Wno-unused-value -D_AIX -D_AIX32 -D_AIX41 -D_AIX43 -D_AIX50 -D_AIX51 -D_AIX52 -D_AIX53 -D_AIX61 -D_AIX71 -D_AIX72 -D_IBMR2 -D_POWER -xc -qasm_as=/bin/as -qc_stdinc=/opt/IBM/xlC/16.1.0/include2:/opt/IBM/xlC/16.1.0/include2/aix:/opt/IBM/xlmass/9.1.0/include:/usr/include -qvac_include_path=/opt/IBM/xlc/16.1.0/include -oCMakeFiles/cmTC_fcf21.dir/CMakeCCompilerABI.c.o /tmp/CMake/Modules/CMakeCCompilerABI.c /tmp/xlcW0tZ87ia /tmp/xlcW1ub87ib /dev/null /tmp/xlcLu487ieF.lst /dev/null /tmp/xlcW2uj87ic
+export XL_BACKEND=/opt/IBM/xlc/16.1.0/exe/xlCcode
+export XL_LINKER=/bin/ld
+/opt/IBM/xlc/16.1.0/exe/xlCcode -qalias=ansi -qthreaded /tmp/xlcW0tZ87ia /tmp/xlcW1ub87ib CMakeFiles/cmTC_fcf21.dir/CMakeCCompilerABI.c.o /tmp/xlcLu487ieB.lst /tmp/xlcW2uj87ic
+rm /tmp/xlcASuz87id
+rm /tmp/xlcLu487ie
+rm /tmp/xlcW0tZ87ia
+rm /tmp/xlcW1ub87ib
+rm /tmp/xlcW2uj87ic
+Linking C executable cmTC_fcf21
+/tmp/CMake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_fcf21.dir/link.txt --verbose=1
+/opt/IBM/xlC/16.1.0/bin/xlclang -Wl,-bnoipath -Wl,-brtl -V -Wl,-bexpall CMakeFiles/cmTC_fcf21.dir/CMakeCCompilerABI.c.o -o cmTC_fcf21 -Wl,-blibpath:/usr/lib:/lib
+export XL_CONFIG=/opt/IBM/xlc/16.1.0/etc/xlc.cfg.72:xlclang
+/bin/ld -b32 /lib/crt0.o -bpT:0x10000000 -bpD:0x20000000 -bnoipath -brtl -bexpall CMakeFiles/cmTC_fcf21.dir/CMakeCCompilerABI.c.o -o cmTC_fcf21 -blibpath:/usr/lib:/lib -L/opt/IBM/xlmass/9.1.0/lib/aix61 -L/opt/IBM/xlc/16.1.0/lib -lxlopt -lxlipa -lxl -lc -lpthreads
+rm /tmp/xlcW0vJG7ia
+rm /tmp/xlcW1vNG7ib
+rm /tmp/xlcW2vRG7ic
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XLClang-16.1.0.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XLClang-16.1.0.1.output
new file mode 100644
index 000000000..85399b75b
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-C-XLClang-16.1.0.1.output
@@ -0,0 +1 @@
+/opt/IBM/xlC/16.1.0/include2;/opt/IBM/xlC/16.1.0/include2/aix;/opt/IBM/xlmass/9.1.0/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XL-13.1.3.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XL-13.1.3.input
new file mode 100644
index 000000000..5aec849e1
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XL-13.1.3.input
@@ -0,0 +1,44 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=XL
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=13.1.3
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_e8f3a/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_e8f3a.dir/build.make CMakeFiles/cmTC_e8f3a.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_e8f3a.dir/CMakeCXXCompilerABI.cpp.o
+/opt/IBM/xlC/13.1.3/bin/xlC -+ -qthreaded -qhalt=s -V -o CMakeFiles/cmTC_e8f3a.dir/CMakeCXXCompilerABI.cpp.o -c /tmp/CMake/Modules/CMakeCXXCompilerABI.cpp
+export XL_CONFIG=/opt/IBM/xlc/13.1.3/etc/xlc.cfg.72:xlC
+export XL_XLCMP_PATH=/opt/IBM/xlc/13.1.3:/opt/IBM/xlC/13.1.3
+export XL_COMPILER=xlc++
+export XL_ASMOBJFILES=/tmp/xlcAS3F7aid
+export "XL_DIS=/opt/IBM/xlc/13.1.3/exe/dis -o "CMakeFiles/cmTC_e8f3a.dir/CMakeCXXCompilerABI.cpp.o" "CMakeCXXCompilerABI.o""
+/opt/IBM/xlC/13.1.3/exe/xlCentry -qosvar=aix.7.2 -qalias=ansi -D_AIX -D_AIX32 -D_AIX41 -D_AIX43 -D_AIX50 -D_AIX51 -D_AIX52 -D_AIX53 -D_AIX61 -D_AIX71 -D_AIX72 -D_IBMR2 -D_POWER -qthreaded -qhalt=s -qasm_as=/bin/as -qcpp_stdinc=/opt/IBM/xlC/13.1.3/include:/opt/IBM/xlmass/8.1.3/include:/usr/include -qc_stdinc=/opt/IBM/xlc/13.1.3/include:/opt/IBM/xlmass/8.1.3/include:/usr/include -oCMakeFiles/cmTC_e8f3a.dir/CMakeCXXCompilerABI.cpp.o /tmp/CMake/Modules/CMakeCXXCompilerABI.cpp /tmp/xlcW03r7aia /tmp/xlcW1347aib /dev/null /tmp/xlcL3J7aieF.lst /dev/null /tmp/xlcW2387aic
+export XL_BACKEND=/opt/IBM/xlc/13.1.3/exe/xlCcode
+export XL_LINKER=/bin/ld
+/opt/IBM/xlc/13.1.3/exe/xlCcode -qalias=ansi -qthreaded -qhalt=s /tmp/xlcW03r7aia /tmp/xlcW1347aib CMakeFiles/cmTC_e8f3a.dir/CMakeCXXCompilerABI.cpp.o /tmp/xlcL3J7aieB.lst /tmp/xlcW2387aic
+rm /tmp/xlcAS3F7aid
+rm /tmp/xlcL3J7aie
+rm /tmp/xlcW03r7aia
+rm /tmp/xlcW1347aib
+rm /tmp/xlcW2387aic
+Linking CXX executable cmTC_e8f3a
+/tmp/CMake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_e8f3a.dir/link.txt --verbose=1
+/opt/IBM/xlC/13.1.3/bin/xlC -qthreaded -qhalt=s -Wl,-bnoipath -Wl,-brtl -V -Wl,-bexpall CMakeFiles/cmTC_e8f3a.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_e8f3a -Wl,-blibpath:/usr/lib:/lib
+export XL_CONFIG=/opt/IBM/xlc/13.1.3/etc/xlc.cfg.72:xlC
+/bin/ld -b32 /lib/crt0.o /lib/crti.o -bpT:0x10000000 -bpD:0x20000000 -bnoipath -brtl -bexpall CMakeFiles/cmTC_e8f3a.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_e8f3a -blibpath:/usr/lib:/lib -bcdtors:all:0:s -btmplrename -L/opt/IBM/xlmass/8.1.3/lib/aix61 -L/opt/IBM/xlc/13.1.3/lib -lxlopt -lxlipa -lxl -L/opt/IBM/xlC/13.1.3/lib -lC -lm -lc |
+/opt/IBM/xlC/13.1.3/bin/c++filt -S |
+/bin/sed '/317.*::virtual-fn-table-ptr$/ s/^\(.*: \)*{*\([^}]*\)\(}*.*\)::virtual-fn-table-ptr$/\1Virtual table for class "\2": Some possible causes are: first non-inline virtual function in "\2" is not defined or the class is a template instantiation and an explicit instantiation definition of the class is missing./'
+rm /tmp/xlcW04Jtaea
+rm /tmp/xlcW14Vtaeb
+rm /tmp/xlcW24Vtaec
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XL-13.1.3.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XL-13.1.3.output
new file mode 100644
index 000000000..264e4fe3b
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XL-13.1.3.output
@@ -0,0 +1 @@
+/opt/IBM/xlC/13.1.3/include;/opt/IBM/xlmass/8.1.3/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XLClang-16.1.0.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XLClang-16.1.0.1.input
new file mode 100644
index 000000000..da16db3a0
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XLClang-16.1.0.1.input
@@ -0,0 +1,44 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=XLClang
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=16.1.0.1
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command(s):/usr/bin/gmake cmTC_b8490/fast
+/usr/bin/gmake -f CMakeFiles/cmTC_b8490.dir/build.make CMakeFiles/cmTC_b8490.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_b8490.dir/CMakeCXXCompilerABI.cpp.o
+/opt/IBM/xlC/16.1.0/bin/xlclang++ -x c++ -V -o CMakeFiles/cmTC_b8490.dir/CMakeCXXCompilerABI.cpp.o -c /tmp/CMake/Modules/CMakeCXXCompilerABI.cpp
+export XL_CONFIG=/opt/IBM/xlc/16.1.0/etc/xlc.cfg.72:xlclang++
+export XL_XLCMP_PATH=/opt/IBM/xlc/16.1.0:/opt/IBM/xlC/16.1.0
+export XL_COMPILER=xlc++
+export XL_ASMOBJFILES=/tmp/xlcAS3IXqid
+export "XL_DIS=/opt/IBM/xlc/16.1.0/exe/dis -o "CMakeFiles/cmTC_b8490.dir/CMakeCXXCompilerABI.cpp.o" "CMakeCXXCompilerABI.o""
+/opt/IBM/xlC/16.1.0/exe/xlC2entry -qosvar=aix.7.2 -qalias=ansi -qthreaded -D_THREAD_SAFE -Wno-parentheses -Wno-unused-value -D_AIX -D_AIX32 -D_AIX41 -D_AIX43 -D_AIX50 -D_AIX51 -D_AIX52 -D_AIX53 -D_AIX61 -D_AIX71 -D_AIX72 -D_IBMR2 -D_POWER -xc++ -qasm_as=/bin/as -qcpp_stdinc=/opt/IBM/xlC/16.1.0/include2/c++:/opt/IBM/xlC/16.1.0/include2:/opt/IBM/xlC/16.1.0/include2/aix:/opt/IBM/xlmass/9.1.0/include:/usr/include -qc_stdinc=/opt/IBM/xlC/16.1.0/include2:/opt/IBM/xlC/16.1.0/include2/aix:/opt/IBM/xlmass/9.1.0/include:/usr/include -oCMakeFiles/cmTC_b8490.dir/CMakeCXXCompilerABI.cpp.o /tmp/CMake/Modules/CMakeCXXCompilerABI.cpp /tmp/xlcW03uXqia /tmp/xlcW137Xqib /dev/null /tmp/xlcL3QXqieF.lst /dev/null /tmp/xlcW23AXqic
+export XL_BACKEND=/opt/IBM/xlc/16.1.0/exe/xlCcode
+export XL_LINKER=/bin/ld
+/opt/IBM/xlc/16.1.0/exe/xlCcode -qalias=ansi -qthreaded /tmp/xlcW03uXqia /tmp/xlcW137Xqib CMakeFiles/cmTC_b8490.dir/CMakeCXXCompilerABI.cpp.o /tmp/xlcL3QXqieB.lst /tmp/xlcW23AXqic
+rm /tmp/xlcAS3IXqid
+rm /tmp/xlcL3QXqie
+rm /tmp/xlcW03uXqia
+rm /tmp/xlcW137Xqib
+rm /tmp/xlcW23AXqic
+Linking CXX executable cmTC_b8490
+/tmp/CMake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_b8490.dir/link.txt --verbose=1
+/opt/IBM/xlC/16.1.0/bin/xlclang++ -Wl,-bnoipath -Wl,-brtl -V -Wl,-bexpall CMakeFiles/cmTC_b8490.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_b8490 -Wl,-blibpath:/usr/lib:/lib
+export XL_CONFIG=/opt/IBM/xlc/16.1.0/etc/xlc.cfg.72:xlclang++
+/bin/ld -b32 /lib/crt0.o /lib/crti.o -bpT:0x10000000 -bpD:0x20000000 -bnoipath -brtl -bexpall CMakeFiles/cmTC_b8490.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_b8490 -blibpath:/usr/lib:/lib -bcdtors:all:0:s -btmplrename -L/opt/IBM/xlmass/9.1.0/lib/aix61 -L/opt/IBM/xlc/16.1.0/lib -lxlopt -lxlipa -lxl -L/opt/IBM/xlC/16.1.0/lib -lc++ -lCcore -lpthreads -lm -lc |
+/opt/IBM/xlC/16.1.0/bin/c++filt -S |
+/bin/sed '/317.*::virtual-fn-table-ptr$/ s/^\(.*: \)*{*\([^}]*\)\(}*.*\)::virtual-fn-table-ptr$/\1Virtual table for class "\2": Some possible causes are: first non-inline virtual function in "\2" is not defined or the class is a template instantiation and an explicit instantiation definition of the class is missing./'
+rm /tmp/xlcW05fS7ia
+rm /tmp/xlcW15rS7ib
+rm /tmp/xlcW25vS7ic
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XLClang-16.1.0.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XLClang-16.1.0.1.output
new file mode 100644
index 000000000..7666f7e81
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/aix-CXX-XLClang-16.1.0.1.output
@@ -0,0 +1 @@
+/opt/IBM/xlC/16.1.0/include2/c\+\+;/opt/IBM/xlC/16.1.0/include2;/opt/IBM/xlC/16.1.0/include2/aix;/opt/IBM/xlmass/9.1.0/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-8.7.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-8.7.input
new file mode 100644
index 000000000..b3218a2f5
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-8.7.input
@@ -0,0 +1,53 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=Cray
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=8.7
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_cb7b8/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_cb7b8.dir/build.make CMakeFiles/cmTC_cb7b8.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_cb7b8.dir/CMakeCCompilerABI.c.o
+/opt/cray/pe/craype/2.5.15/bin/cc -v -o CMakeFiles/cmTC_cb7b8.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake/Modules/CMakeCCompilerABI.c
+rm /tmp/pe_15430/CMakeCCompilerABI_1.s
+
+/opt/cray/pe/cce/8.7.4/cce/x86_64/bin/ccfe -hc -hcpu=haswell -D __CRAYXC -D __CRAY_HASWELL -D __CRAYXT_COMPUTE_LINUX_TARGET -hnetwork=aries -nostdinc -isystem /opt/cray/pe/cce/8.7.4/cce/x86_64/include/craylibs -isystem /opt/cray/pe/cce/8.7.4/cce/x86_64/include/basic -isystem /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0/include -isystem /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0/include-fixed -isystem /opt/gcc/6.1.0/snos/include -isystem /usr/include -I /opt/cray/pe/libsci/18.07.1/CRAY/8.6/x86_64/include -I /opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/include -I /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I /opt/cray/dmapp/7.1.1-6.0.5.0_49.8__g1125556.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I /opt/cray-hss-devel/8.0.0/include -D__PEDRVR_GCC_BASE_ACTIVE__ -hpl=/tmp/pe_15430//pldir -rx8503 -ru87000 -CZ /tmp/pe_15430/CMakeCCompilerABI.T -Cx -CX /tmp/pe_15430/CMakeCCompilerABI.xml -hdecompile=/tmp/ii/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_cb7b8.dir/CMakeCCompilerABI. -S /tmp/pe_15430/CMakeCCompilerABI_1.s -hipa3 -ufile_id=1 /usr/share/cmake/Modules/CMakeCCompilerABI.c
+
+/opt/cray/pe/cce/8.7.4/cce/x86_64/bin/optcg /tmp/pe_15430//pldir 1
+
+/opt/cray/pe/cce/8.7.4/binutils/x86_64/x86_64-pc-linux-gnu/bin/as -o CMakeFiles/cmTC_cb7b8.dir/CMakeCCompilerABI.c.o --64 /tmp/pe_15430/CMakeCCompilerABI_1.s
+rm /tmp/pe_15430/CMakeCCompilerABI_1.s
+rm /tmp/pe_15430//CMakeCCompilerABI_1.cif.Ttmp
+rm /tmp/pe_15430//CMakeCCompilerABI.Tfe
+rm /tmp/pe_15430//CMakeCCompilerABI.T
+rm /tmp/pe_15430//CMakeCCompilerABI_1.xml.Ttmp
+rm /tmp/pe_15430//pldir/PL_path
+rm /tmp/pe_15430//pldir/iline_1
+rm /tmp/pe_15430//pldir/PL_module_list
+rm /tmp/pe_15430//pldir/CMakeCCompilerABI_1.inl
+rm /tmp/pe_15430//pldir/gline_1
+rm /tmp/pe_15430//pldir/PL_global_data
+rmdir /tmp/pe_15430//pldir
+rm /tmp/pe_15430//CMakeCCompilerABI.xml
+rmdir /tmp/pe_15430/
+Linking C executable cmTC_cb7b8
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_cb7b8.dir/link.txt --verbose=1
+/opt/cray/pe/craype/2.5.15/bin/cc -v CMakeFiles/cmTC_cb7b8.dir/CMakeCCompilerABI.c.o -o cmTC_cb7b8
+
+/opt/cray/pe/cce/8.7.4/binutils/x86_64/x86_64-pc-linux-gnu/bin/ld /usr/lib64//crt1.o /usr/lib64//crti.o /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0//crtbeginT.o /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0//crtfastmath.o /opt/cray/pe/cce/8.7.4/cce/x86_64/lib/no_mmap.o CMakeFiles/cmTC_cb7b8.dir/CMakeCCompilerABI.c.o -Bstatic -rpath=/opt/cray/pe/cce/8.7.4/cce/x86_64/lib -L /opt/gcc/6.1.0/snos/lib64 -rpath=/opt/cray/pe/gcc-libs -L /opt/cray/pe/libsci/18.07.1/CRAY/8.6/x86_64/lib -L /opt/cray/dmapp/default/lib64 -L /opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/lib -L /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64 -L /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64 -L /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64 -L /opt/cray/dmapp/7.1.1-6.0.5.0_49.8__g1125556.ari/lib64 -L /opt/cray/pe/pmi/5.0.14/lib64 -L /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64 -L /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64 -L /opt/cray/pe/atp/2.1.3/libApp -L /opt/cray/pe/cce/8.7.4/cce/x86_64/lib/pkgconfig/../ -L /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64 --no-as-needed -lAtpSigHandler -lAtpSigHCommData --undefined=_ATP_Data_Globals --undefined=__atpHandlerInstall -L /usr/lib64 -L /lib64 -rpath=/usr/lib64 -rpath=/lib64 -lpthread -lsci_cray_mpi_mp -lm -lf -lsci_cray_mp -lcraymp -lm -lpthread -lf -lhugetlbfs -lmpich_cray -lrt -lpthread -lugni -lpmi -lpgas-dmapp -lfi -lu -lrt --undefined=dmapp_get_flag_nbi -ldmapp -lugni -ludreg -lpthread -lm -lcray-c++-rts -lstdc++ -lxpmem -ldmapp -lpthread -lpmi -lpthread -lalpslli -lpthread -lwlm_detect -lugni -lpthread -lalpsutil -lpthread -lrca -ludreg -lquadmath -lm -lomp -lrt -lcraymp -lpthread -lrt -ldl -lcray-c++-rts -lstdc++ -lm -lmodules -lm -lrt -lfi -lm -lquadmath -lrt -lcraymath -lm -lgfortran -lquadmath -lrt -lf -lm -lpthread -lrt -lu -lrt -ldl -lcray-c++-rts -lstdc++ -lm -lcsup -lrt --as-needed -latomic --no-as-needed -lstdc++ -lpthread --start-group -lc -lcsup -lgcc_eh -lm -lgcc --end-group -T/opt/cray/pe/cce/8.7.4/cce/x86_64/lib/2.23.1.cce.ld -L /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0 -L /opt/cray/pe/cce/8.7.4/binutils/x86_64/x86_64-pc-linux-gnu/..//x86_64-unknown-linux-gnu/lib -EL -o cmTC_cb7b8 --undefined=__pthread_initialize_minimal /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0//crtend.o /usr/lib64//crtn.o
+
+/opt/cray/pe/cce/8.7.4/binutils/x86_64/bin/objcopy --remove-section=.note.ftn_module_data cmTC_cb7b8
+rm /tmp/pe_15450//pldir/PL_path
+rm /tmp/pe_15450//pldir/PL_module_list
+rm /tmp/pe_15450//pldir/PL_global_data
+rmdir /tmp/pe_15450//pldir
+rmdir /tmp/pe_15450/
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-8.7.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-8.7.output
new file mode 100644
index 000000000..cbd213278
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-8.7.output
@@ -0,0 +1 @@
+/opt/cray/pe/cce/8.7.4/cce/x86_64/include/craylibs;/opt/cray/pe/cce/8.7.4/cce/x86_64/include/basic;/opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0/include;/opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0/include-fixed;/opt/gcc/6.1.0/snos/include;/usr/include;/opt/cray/pe/libsci/18.07.1/CRAY/8.6/x86_64/include;/opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/include;/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include;/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include;/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include;/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include;/opt/cray/dmapp/7.1.1-6.0.5.0_49.8__g1125556.ari/include;/opt/cray/pe/pmi/5.0.14/include;/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include;/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include;/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include;/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include;/opt/cray-hss-devel/8.0.0/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-9.0-hlist-ad.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-9.0-hlist-ad.input
new file mode 100644
index 000000000..e82bd97c1
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-9.0-hlist-ad.input
@@ -0,0 +1,54 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=Cray
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=9.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp
+
+Run Build Command(s):/usr/bin/gmake cmTC_9ceca/fast && /usr/bin/gmake -f CMakeFiles/cmTC_9ceca.dir/build.make CMakeFiles/cmTC_9ceca.dir/build
+gmake[1]: Entering directory '/home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_9ceca.dir/CMakeCCompilerABI.c.o
+/opt/cray/pe/craype/2.6.0/bin/cc -hlist=ad -v -o CMakeFiles/cmTC_9ceca.dir/CMakeCCompilerABI.c.o -c /home/generic.user/Code/cmake/source/master/Modules/CMakeCCompilerABI.c
+rm /lus/scratch/tmp/pe_14877/CMakeCCompilerABI_1.s
+
+/opt/cray/pe/cce/9.0.0/cce/x86_64/bin/ccfe -hc -hcpu=broadwell -D __CRAYXC -D __CRAY_BROADWELL -D __CRAYXT_COMPUTE_LINUX_TARGET -hnetwork=aries -hdecomp -nostdinc -isystem /opt/cray/pe/cce/9.0.0/cce/x86_64/include/craylibs -isystem /opt/cray/pe/cce/9.0.0/cce/x86_64/include/basic -isystem /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include -isystem /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include-fixed -isystem /opt/gcc/8.1.0/snos/include -isystem /usr/include -I /opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/include -I /opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/include -I /opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/xpmem/2.2.15-6.0.7.1_5.8__g7549d06.ari/include -I /opt/cray/dmapp/7.1.1-6.0.7.0_34.3__g5a674e0.ari/include -I /opt/cray/gni-headers/5.0.12.0-6.0.7.0_24.1__g3b1768f.ari/include -I /opt/cray/ugni/6.0.14.0-6.0.7.0_23.1__gea11d3d.ari/include -I /opt/cray/udreg/2.3.2-6.0.7.0_33.18__g5196236.ari/include -I /opt/cray/alps/6.6.43-6.0.7.0_26.4__ga796da3.ari/include -I /opt/cray/wlm_detect/1.3.3-6.0.7.0_47.2__g7109084.ari/include -I /opt/cray/krca/2.2.4-6.0.7.1_5.23__g8505b97.ari/include -I /opt/cray-hss-devel/8.0.0/include -D__PEDRVR_GCC_BASE_ACTIVE__ -hpl=/lus/scratch/tmp/pe_14877//pldir -CY "driver.cc -h cpu=broadwell -h dynamic -D __CRAYXC -D __CRAY_BROADWELL -D __CRAYXT_COMPUTE_LINUX_TARGET -h network=aries -h list=ad -v -o CMakeFiles/cmTC_9ceca.dir/CMakeCCompilerABI.c.o -c /home/generic.user/Code/cmake/source/master/Modules/CMakeCCompilerABI.c -isystem /opt/cray/pe/cce/9.0.0/cce/x86_64/include/craylibs -isystem /opt/cray/pe/cce/9.0.0/cce/x86_64/include/basic -isystem /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include -isystem /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include-fixed -isystem /opt/gcc/8.1.0/snos/include -isystem /usr/include -I /opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/include -I /opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/include -I /opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/xpmem/2.2.15-6.0.7.1_5.8__g7549d06.ari/include -I /opt/cray/dmapp/7.1.1-6.0.7.0_34.3__g5a674e0.ari/include -I /opt/cray/gni-headers/5.0.12.0-6.0.7.0_24.1__g3b1768f.ari/include -I /opt/cray/ugni/6.0.14.0-6.0.7.0_23.1__gea11d3d.ari/include -I /opt/cray/udreg/2.3.2-6.0.7.0_33.18__g5196236.ari/include -I /opt/cray/alps/6.6.43-6.0.7.0_26.4__ga796da3.ari/include -I /opt/cray/wlm_detect/1.3.3-6.0.7.0_47.2__g7109084.ari/include -I /opt/cray/krca/2.2.4-6.0.7.1_5.23__g8505b97.ari/include -I /opt/cray-hss-devel/8.0.0/include" -ru87000 -CZ /lus/scratch/tmp/pe_14877/CMakeCCompilerABI.T -Cx -CX /lus/scratch/tmp/pe_14877/CMakeCCompilerABI.xml -CL -hdecompile=/home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_9ceca.dir/CMakeCCompilerABI. -S /lus/scratch/tmp/pe_14877/CMakeCCompilerABI_1.s -hipa3 -ufile_id=1 /home/generic.user/Code/cmake/source/master/Modules/CMakeCCompilerABI.c
+
+/opt/cray/pe/cce/9.0.0/cce/x86_64/bin/optcg /lus/scratch/tmp/pe_14877//pldir 1
+
+/opt/cray/pe/cce/9.0.0/binutils/x86_64/x86_64-pc-linux-gnu/bin/as -o CMakeFiles/cmTC_9ceca.dir/CMakeCCompilerABI.c.o --64 /lus/scratch/tmp/pe_14877/CMakeCCompilerABI_1.s
+rm /lus/scratch/tmp/pe_14877/CMakeCCompilerABI_1.s
+
+/opt/cray/pe/cce/9.0.0/cce/x86_64/bin/clx -ra -q -o CMakeFiles/cmTC_9ceca.dir/CMakeCCompilerABI.lst /home/generic.user/Code/cmake/source/master/Modules/CMakeCCompilerABI.c /lus/scratch/tmp/pe_14877/CMakeCCompilerABI.T
+rm /lus/scratch/tmp/pe_14877/CMakeCCompilerABI.T
+rm /lus/scratch/tmp/pe_14877//CMakeCCompilerABI.xml
+rm /lus/scratch/tmp/pe_14877//CMakeCCompilerABI_1.xml.Ttmp
+rm /lus/scratch/tmp/pe_14877//CMakeCCompilerABI.Tfe
+rm /lus/scratch/tmp/pe_14877//CMakeCCompilerABI_1.cif.Ttmp
+rm /lus/scratch/tmp/pe_14877//pldir/gline_1
+rm /lus/scratch/tmp/pe_14877//pldir/PL_path
+rm /lus/scratch/tmp/pe_14877//pldir/CMakeCCompilerABI_1.inl
+rm /lus/scratch/tmp/pe_14877//pldir/PL_global_data
+rm /lus/scratch/tmp/pe_14877//pldir/iline_1
+rm /lus/scratch/tmp/pe_14877//pldir/PL_module_list
+rmdir /lus/scratch/tmp/pe_14877//pldir
+rmdir /lus/scratch/tmp/pe_14877/
+Linking C executable cmTC_9ceca
+/home/generic.user/Code/cmake/build/master/bin/cmake -E cmake_link_script CMakeFiles/cmTC_9ceca.dir/link.txt --verbose=1
+/opt/cray/pe/craype/2.6.0/bin/cc -hlist=ad -v -dynamic CMakeFiles/cmTC_9ceca.dir/CMakeCCompilerABI.c.o -o cmTC_9ceca
+
+/opt/cray/pe/cce/9.0.0/binutils/x86_64/x86_64-pc-linux-gnu/bin/ld --eh-frame-hdr -m elf_x86_64 --enable-new-dtags --dynamic-linker /lib64/ld-linux-x86-64.so.2 /usr/lib64//crt1.o /usr/lib64//crti.o /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0//crtbegin.o /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0//crtfastmath.o /opt/cray/pe/cce/9.0.0/cce/x86_64/lib/no_mmap.o CMakeFiles/cmTC_9ceca.dir/CMakeCCompilerABI.c.o -Bdynamic -rpath=/opt/cray/pe/cce/9.0.0/cce/x86_64/lib -L /opt/gcc/8.1.0/snos/lib64 -rpath=/opt/cray/pe/gcc-libs -L /opt/cray/dmapp/default/lib64 -L /opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/lib -L /opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/lib -L /opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/lib64 -L /opt/cray/pe/atp/2.1.3/libApp -L /opt/cray/pe/cce/9.0.0/cce/x86_64/lib/pkgconfig/../ --no-as-needed -lAtpSigHandler -lAtpSigHCommData --undefined=_ATP_Data_Globals --undefined=__atpHandlerInstall -L /usr/lib64 -L /lib64 -rpath=/usr/lib64 -rpath=/lib64 -lrca --as-needed -lmpich_cray_90 --no-as-needed --as-needed -lsci_cray_mpi --no-as-needed --as-needed -lsci_cray --no-as-needed --as-needed -lpgas-dmapp --no-as-needed -lquadmath -lmodules -lfi -lcraymath -lf -lu -lcsup --as-needed -latomic --no-as-needed --whole-archive -ltcmalloc_minimal --no-whole-archive -lcray-c++-rts -lstdc++ -lpthread -L /opt/cray/pe/cce/9.0.0/cce-clang/x86_64/lib/clang/9.0.0/lib/linux --start-group -lc -lcsup -lgcc_eh -lm -lclang_rt.craypgo-x86_64 -lgcc --end-group -L /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0 -L /opt/cray/pe/cce/9.0.0/binutils/x86_64/x86_64-pc-linux-gnu/..//x86_64-unknown-linux-gnu/lib -EL -o cmTC_9ceca /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0//crtend.o /usr/lib64//crtn.o
+
+/opt/cray/pe/cce/9.0.0/binutils/x86_64/bin/objcopy --remove-section=.note.ftn_module_data cmTC_9ceca
+rm /lus/scratch/tmp/pe_14889//pldir/PL_path
+rm /lus/scratch/tmp/pe_14889//pldir/PL_global_data
+rm /lus/scratch/tmp/pe_14889//pldir/PL_module_list
+rmdir /lus/scratch/tmp/pe_14889//pldir
+rmdir /lus/scratch/tmp/pe_14889/
+gmake[1]: Leaving directory '/home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-9.0-hlist-ad.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-9.0-hlist-ad.output
new file mode 100644
index 000000000..42b194acf
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Cray-9.0-hlist-ad.output
@@ -0,0 +1 @@
+/opt/cray/pe/cce/9.0.0/cce/x86_64/include/craylibs;/opt/cray/pe/cce/9.0.0/cce/x86_64/include/basic;/opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include;/opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include-fixed;/opt/gcc/8.1.0/snos/include;/usr/include;/opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/include;/opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/include;/opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/include;/opt/cray/pe/pmi/5.0.14/include;/opt/cray/xpmem/2.2.15-6.0.7.1_5.8__g7549d06.ari/include;/opt/cray/dmapp/7.1.1-6.0.7.0_34.3__g5a674e0.ari/include;/opt/cray/gni-headers/5.0.12.0-6.0.7.0_24.1__g3b1768f.ari/include;/opt/cray/ugni/6.0.14.0-6.0.7.0_23.1__gea11d3d.ari/include;/opt/cray/udreg/2.3.2-6.0.7.0_33.18__g5196236.ari/include;/opt/cray/alps/6.6.43-6.0.7.0_26.4__ga796da3.ari/include;/opt/cray/wlm_detect/1.3.3-6.0.7.0_47.2__g7109084.ari/include;/opt/cray/krca/2.2.4-6.0.7.1_5.23__g8505b97.ari/include;/opt/cray-hss-devel/8.0.0/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-GNU-7.3.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-GNU-7.3.0.input
new file mode 100644
index 000000000..2dc60aff2
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-GNU-7.3.0.input
@@ -0,0 +1,79 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=GNU
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=7.3.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_61245/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_61245.dir/build.make CMakeFiles/cmTC_61245.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_61245.dir/CMakeCCompilerABI.c.o
+/opt/cray/pe/craype/2.5.15/bin/cc -v -o CMakeFiles/cmTC_61245.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake/Modules/CMakeCCompilerABI.c
+Using built-in specs.
+COLLECT_GCC=/opt/gcc/7.3.0/bin/../snos/bin/gcc
+Target: x86_64-suse-linux
+Configured with: ../cray-gcc-7.3.0-201801270210.d61239fc6000b/configure --prefix=/opt/gcc/7.3.0/snos --disable-nls --libdir=/opt/gcc/7.3.0/snos/lib --enable-languages=c,c++,fortran --with-gxx-include-dir=/opt/gcc/7.3.0/snos/include/g++ --with-slibdir=/opt/gcc/7.3.0/snos/lib --with-system-zlib --enable-shared --enable-__cxa_atexit --build=x86_64-suse-linux --with-ppl --with-cloog --disable-multilib
+Thread model: posix
+gcc version 7.3.0 20180125 (Cray Inc.) (GCC)
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-static' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-u' 'pthread_mutex_destroy' '-D' '__TARGET_LINUX__' '-v' '-o' 'CMakeFiles/cmTC_61245.dir/CMakeCCompilerABI.c.o' '-c' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include'
+ /opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/cc1 -quiet -v -I /opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include -I /opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include -I /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I /opt/cray-hss-devel/8.0.0/include -D __CRAYXC -D __CRAY_HASWELL -D __CRAYXT_COMPUTE_LINUX_TARGET -D __TARGET_LINUX__ /usr/share/cmake/Modules/CMakeCCompilerABI.c -quiet -dumpbase CMakeCCompilerABI.c -march=core-avx2 -auxbase-strip CMakeFiles/cmTC_61245.dir/CMakeCCompilerABI.c.o -version -o /tmp/ccNvdQ8R.s
+GNU C11 (GCC) version 7.3.0 20180125 (Cray Inc.) (x86_64-suse-linux)
+ compiled by GNU C version 7.3.0 20180125 (Cray Inc.), GMP version 6.0.0, MPFR version 3.1.3, MPC version 1.0.3, isl version isl-0.15-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+ignoring nonexistent directory "/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../x86_64-suse-linux/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include
+ /opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include
+ /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include
+ /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include
+ /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include
+ /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include
+ /opt/cray/pe/pmi/5.0.14/include
+ /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include
+ /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include
+ /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include
+ /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include
+ /opt/cray-hss-devel/8.0.0/include
+ /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include
+ /usr/local/include
+ /opt/gcc/7.3.0/snos/include
+ /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include-fixed
+ /usr/include
+End of search list.
+GNU C11 (GCC) version 7.3.0 20180125 (Cray Inc.) (x86_64-suse-linux)
+ compiled by GNU C version 7.3.0 20180125 (Cray Inc.), GMP version 6.0.0, MPFR version 3.1.3, MPC version 1.0.3, isl version isl-0.15-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+Compiler executable checksum: 4ecdcb30ed2f7ac4fb078d81fd42f086
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-static' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-u' 'pthread_mutex_destroy' '-D' '__TARGET_LINUX__' '-v' '-o' 'CMakeFiles/cmTC_61245.dir/CMakeCCompilerABI.c.o' '-c' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include'
+ as -v -I /opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include -I /opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include -I /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I /opt/cray-hss-devel/8.0.0/include --64 -o CMakeFiles/cmTC_61245.dir/CMakeCCompilerABI.c.o /tmp/ccNvdQ8R.s
+GNU assembler version 2.31.1 (x86_64-suse-linux) using BFD version (GNU Binutils SUSE Linux Enterprise 12) 2.31.1.20180828-9.26
+COMPILER_PATH=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/
+LIBRARY_PATH=/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../lib64/:/lib/../lib64/:/usr/lib/../lib64/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-static' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-u' 'pthread_mutex_destroy' '-D' '__TARGET_LINUX__' '-v' '-o' 'CMakeFiles/cmTC_61245.dir/CMakeCCompilerABI.c.o' '-c' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include'
+Linking C executable cmTC_61245
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_61245.dir/link.txt --verbose=1
+/opt/cray/pe/craype/2.5.15/bin/cc -v CMakeFiles/cmTC_61245.dir/CMakeCCompilerABI.c.o -o cmTC_61245
+Using built-in specs.
+COLLECT_GCC=/opt/gcc/7.3.0/bin/../snos/bin/gcc
+COLLECT_LTO_WRAPPER=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/lto-wrapper
+Target: x86_64-suse-linux
+Configured with: ../cray-gcc-7.3.0-201801270210.d61239fc6000b/configure --prefix=/opt/gcc/7.3.0/snos --disable-nls --libdir=/opt/gcc/7.3.0/snos/lib --enable-languages=c,c++,fortran --with-gxx-include-dir=/opt/gcc/7.3.0/snos/include/g++ --with-slibdir=/opt/gcc/7.3.0/snos/lib --with-system-zlib --enable-shared --enable-__cxa_atexit --build=x86_64-suse-linux --with-ppl --with-cloog --disable-multilib
+Thread model: posix
+gcc version 7.3.0 20180125 (Cray Inc.) (GCC)
+COMPILER_PATH=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/
+LIBRARY_PATH=/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../lib64/:/lib/../lib64/:/usr/lib/../lib64/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-static' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-u' 'pthread_mutex_destroy' '-D' '__TARGET_LINUX__' '-v' '-o' 'cmTC_61245' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include' '-L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64' '-L/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64' '-L/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64' '-L/opt/cray/pe/pmi/5.0.14/lib64' '-L/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64' '-L/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64' '-L/opt/cray/pe/atp/2.1.3/libApp' '-L/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64'
+ /opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/collect2 -plugin /opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/liblto_plugin.so -plugin-opt=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/lto-wrapper -plugin-opt=-fresolution=/tmp/ccG3uxpY.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_eh -plugin-opt=-pass-through=-lc -m elf_x86_64 -static -o cmTC_61245 -u pthread_mutex_destroy /usr/lib/../lib64/crt1.o /usr/lib/../lib64/crti.o /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/crtbeginT.o -L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib -L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64 -L/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64 -L/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64 -L/opt/cray/pe/pmi/5.0.14/lib64 -L/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64 -L/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64 -L/opt/cray/pe/atp/2.1.3/libApp -L/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64 -L/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0 -L/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../.. CMakeFiles/cmTC_61245.dir/CMakeCCompilerABI.c.o -rpath=/opt/cray/pe/gcc-libs --no-as-needed -lAtpSigHandler -lAtpSigHCommData --undefined=_ATP_Data_Globals --undefined=__atpHandlerInstall -lpthread -lsci_gnu_71_mpi -lsci_gnu_71 -lpthread -lhugetlbfs -lmpich_gnu_71 -lrt -lugni -lpthread -lpmi -lpthread -lalpslli -lpthread -lwlm_detect -lalpsutil -lpthread -lrca -lxpmem -lugni -lpthread -ludreg --as-needed -lgfortran -lquadmath --no-as-needed --as-needed -lmvec --no-as-needed --as-needed -lm --no-as-needed --as-needed -lpthread --no-as-needed --start-group -lgcc -lgcc_eh -lc --end-group /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/crtend.o /usr/lib/../lib64/crtn.o
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-static' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-u' 'pthread_mutex_destroy' '-D' '__TARGET_LINUX__' '-v' '-o' 'cmTC_61245' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include' '-L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64' '-L/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64' '-L/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64' '-L/opt/cray/pe/pmi/5.0.14/lib64' '-L/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64' '-L/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64' '-L/opt/cray/pe/atp/2.1.3/libApp' '-L/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64'
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-GNU-7.3.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-GNU-7.3.0.output
new file mode 100644
index 000000000..64f127ef2
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-GNU-7.3.0.output
@@ -0,0 +1 @@
+/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include;/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include;/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include;/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include;/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include;/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include;/opt/cray/pe/pmi/5.0.14/include;/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include;/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include;/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include;/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include;/opt/cray-hss-devel/8.0.0/include;/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include;/usr/local/include;/opt/gcc/7.3.0/snos/include;/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include-fixed;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Intel-18.0.2.20180210.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Intel-18.0.2.20180210.input
new file mode 100644
index 000000000..8c68e5bf5
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Intel-18.0.2.20180210.input
@@ -0,0 +1,40 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=Intel
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=18.0.2.20180210
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_96fde/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_96fde.dir/build.make CMakeFiles/cmTC_96fde.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.o
+/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/bin/intel64/icc -v -o CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake/Modules/CMakeCCompilerABI.c
+icc version 18.0.2 (gcc version 6.3.0 compatibility)
+/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/mcpcom --target_efi2 --lang=c -_g -mP3OPT_inline_alloca -D__ICC=1800 -D__INTEL_COMPILER=1800 -D__INTEL_COMPILER_UPDATE=2 -D__PTRDIFF_TYPE__=long "-D__SIZE_TYPE__=unsigned long" -D__WCHAR_TYPE__=int "-D__WINT_TYPE__=unsigned int" "-D__INTMAX_TYPE__=long int" "-D__UINTMAX_TYPE__=long unsigned int" -D__LONG_MAX__=9223372036854775807L -D__QMSPP_ -D__OPTIMIZE__ -D__NO_MATH_INLINES -D__NO_STRING_INLINES -D__GNUC_GNU_INLINE__ -D__GNUC__=6 -D__GNUC_MINOR__=3 -D__GNUC_PATCHLEVEL__=0 -D__LP64__ -D_LP64 -D__GXX_ABI_VERSION=1010 "-D__USER_LABEL_PREFIX__= " -D__REGISTER_PREFIX__= -D__INTEL_RTTI__ -D__unix__ -D__unix -D__linux__ -D__linux -D__gnu_linux__ -B -Dunix -Dlinux "-_Asystem(unix)" -D__ELF__ -D__x86_64 -D__x86_64__ -D__amd64 -D__amd64__ "-_Acpu(x86_64)" "-_Amachine(x86_64)" -D__INTEL_COMPILER_BUILD_DATE=20180210 -D__INTEL_OFFLOAD -D__i686 -D__i686__ -D__pentiumpro -D__pentiumpro__ -D__pentium4 -D__pentium4__ -D__tune_pentium4__ -D__SSE2__ -D__SSE2_MATH__ -D__SSE__ -D__SSE_MATH__ -D__MMX__ -_k -_8 -_l --has_new_stdarg_support -_a -_b --gnu_version=60300 -_W5 --gcc-extern-inline --multibyte_chars -mGLOB_diag_suppress_sys --system_preinclude /usr/include/stdc-predef.h --array_section --simd --simd_func --offload_mode=1 --offload_target_names=gfx,GFX,mic,MIC --offload_unique_string=icc1641499230JViDRp -mGLOB_em64t=TRUE -mP1OPT_version=18.0-intel64 -mGLOB_diag_file=CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.diag -mGLOB_long_size_64 -mGLOB_routine_pointer_size_64 -mP1OPT_print_version=FALSE -mCG_use_gas_got_workaround=F -mP2OPT_align_option_used=TRUE -mGLOB_gcc_version=630 "-mGLOB_options_string=-v -o CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.o -c" -mGLOB_cxx_limited_range=FALSE -mCG_extend_parms=FALSE -mGLOB_compiler_bin_directory=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64 -mGLOB_as_output_backup_file_name=/tmp/icc6TGEr2as_.s -mIPOPT_activate -mIPOPT_lite -mGLOB_instruction_tuning=0x0 -mGLOB_uarch_tuning=0x0 -mGLOB_product_id_code=0x22006d92 -mCG_bnl_movbe=T -mGLOB_extended_instructions=0x8 -mP3OPT_use_mspp_call_convention -mP2OPT_subs_out_of_bound=FALSE -mP2OPT_disam_type_based_disam=2 -mP2OPT_disam_assume_ansi_c -mP2OPT_checked_disam_ansi_alias=TRUE -mGLOB_ansi_alias -mPGOPTI_value_profile_use=T -mP2OPT_il0_array_sections=TRUE -mGLOB_offload_mode=1 -mP2OPT_offload_unique_var_string=icc1641499230JViDRp -mP2OPT_hlo_level=2 -mP2OPT_hlo -mP2OPT_hpo_rtt_control=0 -mIPOPT_args_in_regs=0 -mP2OPT_disam_assume_nonstd_intent_in=FALSE -mGLOB_imf_mapping_library=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/libiml_attr.so -mPGOPTI_gen_threadsafe_level=0 -mIPOPT_lto_object_enabled -mIPOPT_lto_object_value=1 -mIPOPT_obj_output_file_name=CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.o -mIPOPT_whole_archive_fixup_file_name=/tmp/iccwarchM4gS0h -mGLOB_linker_version=2.31.1.20180828 -mGLOB_driver_tempfile_name=/tmp/icctempfileMGADNU -mP3OPT_asm_target=P3OPT_ASM_TARGET_GAS -mGLOB_async_unwind_tables=TRUE -mGLOB_obj_output_file=CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.o -mGLOB_source_dialect=GLOB_SOURCE_DIALECT_C -mP1OPT_source_file_name=/usr/share/cmake/Modules/CMakeCCompilerABI.c -mP1OPT_full_source_file_name=/usr/share/cmake/Modules/CMakeCCompilerABI.c /usr/share/cmake/Modules/CMakeCCompilerABI.c
+#include "..." search starts here:
+#include <...> search starts here:
+ /opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/include
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/intel64
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/icc
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include
+ /usr/local/include
+ /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include
+ /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include-fixed
+ /opt/gcc/6.3.0/snos/include/
+ /usr/include
+End of search list.
+Linking C executable cmTC_96fde
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_96fde.dir/link.txt --verbose=1
+/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/bin/intel64/icc -v CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.o -o cmTC_96fde -rdynamic
+icc version 18.0.2 (gcc version 6.3.0 compatibility)
+/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/mcpcom -mGLOB_em64t=TRUE -mP1OPT_version=18.0-intel64 -mGLOB_diag_file=CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.diag -mGLOB_long_size_64 -mGLOB_routine_pointer_size_64 -mP1OPT_print_version=FALSE -mCG_use_gas_got_workaround=F -mP2OPT_align_option_used=TRUE -mGLOB_gcc_version=630 "-mGLOB_options_string=-v -o cmTC_96fde -rdynamic" -mGLOB_cxx_limited_range=FALSE -mCG_extend_parms=FALSE -mGLOB_compiler_bin_directory=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64 -mGLOB_as_output_backup_file_name=/tmp/iccRJ58KYas_.s -mGLOB_dashboard_use_source_name -mIPOPT_activate -mGLOB_product_id_code=0x22006d92 -mP3OPT_use_mspp_call_convention -mP2OPT_subs_out_of_bound=FALSE -mP2OPT_disam_type_based_disam=2 -mP2OPT_disam_assume_ansi_c -mP2OPT_checked_disam_ansi_alias=TRUE -mGLOB_ansi_alias -mPGOPTI_value_profile_use=T -mGLOB_opt_report_use_source_name -mP2OPT_il0_array_sections=TRUE -mGLOB_offload_mode=1 -mP2OPT_offload_unique_var_string=icc0762718770pMrhfB -mP2OPT_hlo -mP2OPT_hpo_rtt_control=0 -mIPOPT_args_in_regs=0 -mP2OPT_disam_assume_nonstd_intent_in=FALSE -mGLOB_imf_mapping_library=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/libiml_attr.so -mPGOPTI_gen_threadsafe_level=0 -mIPOPT_link -mIPOPT_ipo_activate -mIPOPT_mo_activate -mIPOPT_source_files_list=/tmp/iccslisYmrmw5 -mIPOPT_mo_global_data -mIPOPT_link_script_file=/tmp/iccscript8Dy5AI "-mIPOPT_cmdline_link="/usr/lib/../lib64/crt1.o" "/usr/lib/../lib64/crti.o" "/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtbegin.o" "-export-dynamic" "--eh-frame-hdr" "--build-id" "-dynamic-linker" "/lib64/ld-linux-x86-64.so.2" "-m" "elf_x86_64" "-o" "cmTC_96fde" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64/" "-L/lib/../lib64" "-L/lib/../lib64/" "-L/usr/lib/../lib64" "-L/usr/lib/../lib64/" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64/" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../" "-L/lib64" "-L/lib/" "-L/usr/lib64" "-L/usr/lib" "CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.o" "-Bdynamic" "-Bstatic" "-limf" "-lsvml" "-lirng" "-Bdynamic" "-lm" "-Bstatic" "-lipgo" "-ldecimal" "--as-needed" "-Bdynamic" "-lcilkrts" "-lstdc++" "--no-as-needed" "-lgcc" "-lgcc_s" "-Bstatic" "-lirc" "-lsvml" "-Bdynamic" "-lc" "-lgcc" "-lgcc_s" "-Bstatic" "-lirc_s" "-Bdynamic" "-ldl" "-lc" "/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtend.o" "/usr/lib/../lib64/crtn.o"" -mIPOPT_il_in_obj -mIPOPT_ipo_activate_warn=FALSE -mIPOPT_obj_output_file_name=/tmp/ipo_icclnz13i.o -mIPOPT_whole_archive_fixup_file_name=/tmp/iccwarch0d1B2R -mGLOB_linker_version=2.31.1.20180828 -mGLOB_driver_tempfile_name=/tmp/icctempfilelBn98u -mP3OPT_asm_target=P3OPT_ASM_TARGET_GAS -mGLOB_async_unwind_tables=TRUE -mGLOB_obj_output_file=/tmp/ipo_icclnz13i.o -mGLOB_source_dialect=GLOB_SOURCE_DIALECT_NONE -mP1OPT_source_file_name=ipo_out.c CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.o -mIPOPT_object_files=T -mIPOPT_assembly_files=/tmp/iccalisA2xsdz -mIPOPT_generated_tempfiles=/tmp/iccelisbUgbic -mIPOPT_embedded_object_base_name=/tmp/icceobjEt9TmP -mIPOPT_cmdline_link_new_name=/tmp/iccllisYEcDrs
+ld /usr/lib/../lib64/crt1.o /usr/lib/../lib64/crti.o /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtbegin.o -export-dynamic --eh-frame-hdr --build-id -dynamic-linker /lib64/ld-linux-x86-64.so.2 -m elf_x86_64 -o cmTC_96fde -L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64 -L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/ -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64 -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64/ -L/lib/../lib64 -L/lib/../lib64/ -L/usr/lib/../lib64 -L/usr/lib/../lib64/ -L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64/ -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../ -L/lib64 -L/lib/ -L/usr/lib64 -L/usr/lib CMakeFiles/cmTC_96fde.dir/CMakeCCompilerABI.c.o -Bdynamic -Bstatic -limf -lsvml -lirng -Bdynamic -lm -Bstatic -lipgo -ldecimal --as-needed -Bdynamic -lcilkrts -lstdc++ --no-as-needed -lgcc -lgcc_s -Bstatic -lirc -lsvml -Bdynamic -lc -lgcc -lgcc_s -Bstatic -lirc_s -Bdynamic -ldl -lc /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtend.o /usr/lib/../lib64/crtn.o
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Intel-18.0.2.20180210.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Intel-18.0.2.20180210.output
new file mode 100644
index 000000000..a26a007ce
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-C-Intel-18.0.2.20180210.output
@@ -0,0 +1 @@
+/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/include;/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/intel64;/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/icc;/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include;/usr/local/include;/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include;/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include-fixed;/opt/gcc/6.3.0/snos/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-8.7.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-8.7.input
new file mode 100644
index 000000000..73c9c8a7f
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-8.7.input
@@ -0,0 +1,53 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=Cray
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=8.7
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_f3b1f/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_f3b1f.dir/build.make CMakeFiles/cmTC_f3b1f.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_f3b1f.dir/CMakeCXXCompilerABI.cpp.o
+/opt/cray/pe/craype/2.5.15/bin/CC -v -o CMakeFiles/cmTC_f3b1f.dir/CMakeCXXCompilerABI.cpp.o -c /usr/share/cmake/Modules/CMakeCXXCompilerABI.cpp
+rm /tmp/pe_15530/CMakeCXXCompilerABI_1.s
+
+/opt/cray/pe/cce/8.7.4/cce/x86_64/bin/ccfe -hcpu=haswell -D __CRAYXC -D __CRAY_HASWELL -D __CRAYXT_COMPUTE_LINUX_TARGET -hnetwork=aries -nostdinc -isystem /opt/cray/pe/cce/8.7.4/cce/x86_64/include/craylibs -isystem /opt/gcc/6.1.0/snos/include/g++ -isystem /opt/gcc/6.1.0/snos/include/g++/x86_64-suse-linux -isystem /opt/gcc/6.1.0/snos/include/g++/backward -isystem /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0/include -isystem /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0/include-fixed -isystem /opt/cray/pe/cce/8.7.4/cce/x86_64/include/c++ -isystem /opt/cray/pe/cce/8.7.4/cce/x86_64/include/basic -isystem /opt/gcc/6.1.0/snos/include -isystem /usr/include -I /opt/cray/pe/libsci/18.07.1/CRAY/8.6/x86_64/include -I /opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/include -I /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I /opt/cray/dmapp/7.1.1-6.0.5.0_49.8__g1125556.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I /opt/cray-hss-devel/8.0.0/include -D__PEDRVR_GCC_BASE_ACTIVE__ -hpl=/tmp/pe_15530//pldir -rx8503 -ru87000 -hipafrom=/opt/cray/pe/cce/8.7.4/cce/x86_64/lib/libcray-c++-rts.a -CZ /tmp/pe_15530/CMakeCXXCompilerABI.T -Cx -CX /tmp/pe_15530/CMakeCXXCompilerABI.xml -hdecompile=/tmp/ii/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_f3b1f.dir/CMakeCXXCompilerABI. -S /tmp/pe_15530/CMakeCXXCompilerABI_1.s -hipa4 -ufile_id=1 /usr/share/cmake/Modules/CMakeCXXCompilerABI.cpp
+
+/opt/cray/pe/cce/8.7.4/cce/x86_64/bin/optcg /tmp/pe_15530//pldir 1
+
+/opt/cray/pe/cce/8.7.4/binutils/x86_64/x86_64-pc-linux-gnu/bin/as -o CMakeFiles/cmTC_f3b1f.dir/CMakeCXXCompilerABI.cpp.o --64 /tmp/pe_15530/CMakeCXXCompilerABI_1.s
+rm /tmp/pe_15530/CMakeCXXCompilerABI_1.s
+rm /tmp/pe_15530//CMakeCXXCompilerABI.xml
+rm /tmp/pe_15530//CMakeCXXCompilerABI_1.cif.Ttmp
+rm /tmp/pe_15530//CMakeCXXCompilerABI.T
+rm /tmp/pe_15530//pldir/PL_path
+rm /tmp/pe_15530//pldir/CMakeCXXCompilerABI_1.inl
+rm /tmp/pe_15530//pldir/iline_1
+rm /tmp/pe_15530//pldir/PL_module_list
+rm /tmp/pe_15530//pldir/gline_1
+rm /tmp/pe_15530//pldir/PL_global_data
+rmdir /tmp/pe_15530//pldir
+rm /tmp/pe_15530//CMakeCXXCompilerABI.Tfe
+rm /tmp/pe_15530//CMakeCXXCompilerABI_1.xml.Ttmp
+rmdir /tmp/pe_15530/
+Linking CXX executable cmTC_f3b1f
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_f3b1f.dir/link.txt --verbose=1
+/opt/cray/pe/craype/2.5.15/bin/CC -v CMakeFiles/cmTC_f3b1f.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_f3b1f
+
+/opt/cray/pe/cce/8.7.4/binutils/x86_64/x86_64-pc-linux-gnu/bin/ld /usr/lib64//crt1.o /usr/lib64//crti.o /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0//crtbeginT.o /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0//crtfastmath.o /opt/cray/pe/cce/8.7.4/cce/x86_64/lib/no_mmap.o CMakeFiles/cmTC_f3b1f.dir/CMakeCXXCompilerABI.cpp.o -Bstatic -rpath=/opt/cray/pe/cce/8.7.4/cce/x86_64/lib -L /opt/gcc/6.1.0/snos/lib64 -rpath=/opt/cray/pe/gcc-libs -L /opt/cray/pe/libsci/18.07.1/CRAY/8.6/x86_64/lib -L /opt/cray/dmapp/default/lib64 -L /opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/lib -L /opt/cray/dmapp/default/lib64 -L /opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/lib -L /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64 -L /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64 -L /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64 -L /opt/cray/dmapp/7.1.1-6.0.5.0_49.8__g1125556.ari/lib64 -L /opt/cray/pe/pmi/5.0.14/lib64 -L /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64 -L /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64 -L /opt/cray/pe/atp/2.1.3/libApp -L /opt/cray/pe/cce/8.7.4/cce/x86_64/lib/pkgconfig/../ -L /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64 --no-as-needed -lAtpSigHandler -lAtpSigHCommData --undefined=_ATP_Data_Globals --undefined=__atpHandlerInstall -L /usr/lib64 -L /lib64 -rpath=/usr/lib64 -rpath=/lib64 -lpthread -lsci_cray_mpi_mp -lm -lf -lsci_cray_mp -lcraymp -lm -lpthread -lf -lhugetlbfs -lmpichcxx_cray -lrt -lpthread -lugni -lpmi -lmpich_cray -lrt -lpthread -lugni -lpmi -lpgas-dmapp -lfi -lu -lrt --undefined=dmapp_get_flag_nbi -ldmapp -lugni -ludreg -lpthread -lm -lcray-c++-rts -lstdc++ -lxpmem -ldmapp -lpthread -lpmi -lpthread -lalpslli -lpthread -lwlm_detect -lugni -lpthread -lalpsutil -lpthread -lrca -ludreg -lquadmath -lm -lomp -lrt -lcraymp -lpthread -lrt -ldl -lcray-c++-rts -lstdc++ -lm -lmodules -lm -lrt -lfi -lm -lquadmath -lrt -lcraymath -lm -lgfortran -lquadmath -lrt -lf -lm -lpthread -lrt -lu -lrt -ldl -lcray-c++-rts -lstdc++ -lm -lcsup -lrt --as-needed -latomic --no-as-needed -lcray-c++-rts -lstdc++ -lsupc++ -lstdc++ -lpthread --start-group -lc -lcsup -lgcc_eh -lm -lgcc --end-group -T/opt/cray/pe/cce/8.7.4/cce/x86_64/lib/2.23.1.cce.ld -L /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0 -L /opt/cray/pe/cce/8.7.4/binutils/x86_64/x86_64-pc-linux-gnu/..//x86_64-unknown-linux-gnu/lib -EL -o cmTC_f3b1f --undefined=__pthread_initialize_minimal /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0//crtend.o /usr/lib64//crtn.o
+
+/opt/cray/pe/cce/8.7.4/binutils/x86_64/bin/objcopy --remove-section=.note.ftn_module_data cmTC_f3b1f
+rm /tmp/pe_15566//pldir/PL_path
+rm /tmp/pe_15566//pldir/PL_module_list
+rm /tmp/pe_15566//pldir/PL_global_data
+rmdir /tmp/pe_15566//pldir
+rmdir /tmp/pe_15566/
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-8.7.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-8.7.output
new file mode 100644
index 000000000..263f8cb25
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-8.7.output
@@ -0,0 +1 @@
+/opt/cray/pe/cce/8.7.4/cce/x86_64/include/craylibs;/opt/gcc/6.1.0/snos/include/g\+\+;/opt/gcc/6.1.0/snos/include/g\+\+/x86_64-suse-linux;/opt/gcc/6.1.0/snos/include/g\+\+/backward;/opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0/include;/opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0/include-fixed;/opt/cray/pe/cce/8.7.4/cce/x86_64/include/c\+\+;/opt/cray/pe/cce/8.7.4/cce/x86_64/include/basic;/opt/gcc/6.1.0/snos/include;/usr/include;/opt/cray/pe/libsci/18.07.1/CRAY/8.6/x86_64/include;/opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/include;/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include;/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include;/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include;/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include;/opt/cray/dmapp/7.1.1-6.0.5.0_49.8__g1125556.ari/include;/opt/cray/pe/pmi/5.0.14/include;/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include;/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include;/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include;/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include;/opt/cray-hss-devel/8.0.0/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-9.0-hlist-ad.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-9.0-hlist-ad.input
new file mode 100644
index 000000000..06a4ac929
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-9.0-hlist-ad.input
@@ -0,0 +1,54 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=Cray
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=9.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp
+
+Run Build Command(s):/usr/bin/gmake cmTC_aa1be/fast && /usr/bin/gmake -f CMakeFiles/cmTC_aa1be.dir/build.make CMakeFiles/cmTC_aa1be.dir/build
+gmake[1]: Entering directory '/home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_aa1be.dir/CMakeCXXCompilerABI.cpp.o
+/opt/cray/pe/craype/2.6.0/bin/CC -hlist=ad -v -o CMakeFiles/cmTC_aa1be.dir/CMakeCXXCompilerABI.cpp.o -c /home/generic.user/Code/cmake/source/master/Modules/CMakeCXXCompilerABI.cpp
+rm /lus/scratch/tmp/pe_14901/CMakeCXXCompilerABI_1.s
+
+/opt/cray/pe/cce/9.0.0/cce/x86_64/bin/ccfe -hcpu=broadwell -D __CRAYXC -D __CRAY_BROADWELL -D __CRAYXT_COMPUTE_LINUX_TARGET -hnetwork=aries -hdecomp -nostdinc -isystem /opt/cray/pe/cce/9.0.0/cce/x86_64/include/craylibs -isystem /opt/gcc/8.1.0/snos/include/g++ -isystem /opt/gcc/8.1.0/snos/include/g++/x86_64-suse-linux -isystem /opt/gcc/8.1.0/snos/include/g++/backward -isystem /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include -isystem /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include-fixed -isystem /opt/cray/pe/cce/9.0.0/cce/x86_64/include/c++ -isystem /opt/cray/pe/cce/9.0.0/cce/x86_64/include/basic -isystem /opt/gcc/8.1.0/snos/include -isystem /usr/include -I /opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/include -I /opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/include -I /opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/xpmem/2.2.15-6.0.7.1_5.8__g7549d06.ari/include -I /opt/cray/dmapp/7.1.1-6.0.7.0_34.3__g5a674e0.ari/include -I /opt/cray/gni-headers/5.0.12.0-6.0.7.0_24.1__g3b1768f.ari/include -I /opt/cray/ugni/6.0.14.0-6.0.7.0_23.1__gea11d3d.ari/include -I /opt/cray/udreg/2.3.2-6.0.7.0_33.18__g5196236.ari/include -I /opt/cray/alps/6.6.43-6.0.7.0_26.4__ga796da3.ari/include -I /opt/cray/wlm_detect/1.3.3-6.0.7.0_47.2__g7109084.ari/include -I /opt/cray/krca/2.2.4-6.0.7.1_5.23__g8505b97.ari/include -I /opt/cray-hss-devel/8.0.0/include -D__PEDRVR_GCC_BASE_ACTIVE__ -hpl=/lus/scratch/tmp/pe_14901//pldir -CY "driver.CC -h cpu=broadwell -h dynamic -D __CRAYXC -D __CRAY_BROADWELL -D __CRAYXT_COMPUTE_LINUX_TARGET -h network=aries -h list=ad -v -o CMakeFiles/cmTC_aa1be.dir/CMakeCXXCompilerABI.cpp.o -c /home/generic.user/Code/cmake/source/master/Modules/CMakeCXXCompilerABI.cpp -isystem /opt/cray/pe/cce/9.0.0/cce/x86_64/include/craylibs -isystem /opt/gcc/8.1.0/snos/include/g++ -isystem /opt/gcc/8.1.0/snos/include/g++/x86_64-suse-linux -isystem /opt/gcc/8.1.0/snos/include/g++/backward -isystem /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include -isystem /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include-fixed -isystem /opt/cray/pe/cce/9.0.0/cce/x86_64/include/c++ -isystem /opt/cray/pe/cce/9.0.0/cce/x86_64/include/basic -isystem /opt/gcc/8.1.0/snos/include -isystem /usr/include -I /opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/include -I /opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/include -I /opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/xpmem/2.2.15-6.0.7.1_5.8__g7549d06.ari/include -I /opt/cray/dmapp/7.1.1-6.0.7.0_34.3__g5a674e0.ari/include -I /opt/cray/gni-headers/5.0.12.0-6.0.7.0_24.1__g3b1768f.ari/include -I /opt/cray/ugni/6.0.14.0-6.0.7.0_23.1__gea11d3d.ari/include -I /opt/cray/udreg/2.3.2-6.0.7.0_33.18__g5196236.ari/include -I /opt/cray/alps/6.6.43-6.0.7.0_26.4__ga796da3.ari/include -I /opt/cray/wlm_detect/1.3.3-6.0.7.0_47.2__g7109084.ari/include -I /opt/cray/krca/2.2.4-6.0.7.1_5.23__g8505b97.ari/include -I /opt/cray-hss-devel/8.0.0/include" -ru87000 -hipafrom=/opt/cray/pe/cce/9.0.0/cce/x86_64/lib/libcray-c++-rts.a -CZ /lus/scratch/tmp/pe_14901/CMakeCXXCompilerABI.T -Cx -CX /lus/scratch/tmp/pe_14901/CMakeCXXCompilerABI.xml -CL -hdecompile=/home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_aa1be.dir/CMakeCXXCompilerABI. -S /lus/scratch/tmp/pe_14901/CMakeCXXCompilerABI_1.s -hipa4 -ufile_id=1 /home/generic.user/Code/cmake/source/master/Modules/CMakeCXXCompilerABI.cpp
+
+/opt/cray/pe/cce/9.0.0/cce/x86_64/bin/optcg /lus/scratch/tmp/pe_14901//pldir 1
+
+/opt/cray/pe/cce/9.0.0/binutils/x86_64/x86_64-pc-linux-gnu/bin/as -o CMakeFiles/cmTC_aa1be.dir/CMakeCXXCompilerABI.cpp.o --64 /lus/scratch/tmp/pe_14901/CMakeCXXCompilerABI_1.s
+rm /lus/scratch/tmp/pe_14901/CMakeCXXCompilerABI_1.s
+
+/opt/cray/pe/cce/9.0.0/cce/x86_64/bin/clx -ra -q -o CMakeFiles/cmTC_aa1be.dir/CMakeCXXCompilerABI.lst /home/generic.user/Code/cmake/source/master/Modules/CMakeCXXCompilerABI.cpp /lus/scratch/tmp/pe_14901/CMakeCXXCompilerABI.T
+rm /lus/scratch/tmp/pe_14901/CMakeCXXCompilerABI.T
+rm /lus/scratch/tmp/pe_14901//CMakeCXXCompilerABI_1.xml.Ttmp
+rm /lus/scratch/tmp/pe_14901//CMakeCXXCompilerABI_1.cif.Ttmp
+rm /lus/scratch/tmp/pe_14901//CMakeCXXCompilerABI.Tfe
+rm /lus/scratch/tmp/pe_14901//CMakeCXXCompilerABI.xml
+rm /lus/scratch/tmp/pe_14901//pldir/gline_1
+rm /lus/scratch/tmp/pe_14901//pldir/PL_path
+rm /lus/scratch/tmp/pe_14901//pldir/CMakeCXXCompilerABI_1.inl
+rm /lus/scratch/tmp/pe_14901//pldir/PL_global_data
+rm /lus/scratch/tmp/pe_14901//pldir/iline_1
+rm /lus/scratch/tmp/pe_14901//pldir/PL_module_list
+rmdir /lus/scratch/tmp/pe_14901//pldir
+rmdir /lus/scratch/tmp/pe_14901/
+Linking CXX executable cmTC_aa1be
+/home/generic.user/Code/cmake/build/master/bin/cmake -E cmake_link_script CMakeFiles/cmTC_aa1be.dir/link.txt --verbose=1
+/opt/cray/pe/craype/2.6.0/bin/CC -hlist=ad -v -dynamic CMakeFiles/cmTC_aa1be.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_aa1be
+
+/opt/cray/pe/cce/9.0.0/binutils/x86_64/x86_64-pc-linux-gnu/bin/ld --eh-frame-hdr -m elf_x86_64 --enable-new-dtags --dynamic-linker /lib64/ld-linux-x86-64.so.2 /usr/lib64//crt1.o /usr/lib64//crti.o /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0//crtbegin.o /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0//crtfastmath.o /opt/cray/pe/cce/9.0.0/cce/x86_64/lib/no_mmap.o CMakeFiles/cmTC_aa1be.dir/CMakeCXXCompilerABI.cpp.o -Bdynamic -rpath=/opt/cray/pe/cce/9.0.0/cce/x86_64/lib -L /opt/gcc/8.1.0/snos/lib64 -rpath=/opt/cray/pe/gcc-libs -L /opt/cray/dmapp/default/lib64 -L /opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/lib -L /opt/cray/dmapp/default/lib64 -L /opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/lib -L /opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/lib -L /opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/lib64 -L /opt/cray/pe/atp/2.1.3/libApp -L /opt/cray/pe/cce/9.0.0/cce/x86_64/lib/pkgconfig/../ --no-as-needed -lAtpSigHandler -lAtpSigHCommData --undefined=_ATP_Data_Globals --undefined=__atpHandlerInstall -L /usr/lib64 -L /lib64 -rpath=/usr/lib64 -rpath=/lib64 -lrca --as-needed -lmpich_cray_90 --no-as-needed --as-needed -lmpichcxx_cray_90 --no-as-needed --as-needed -lsci_cray_mpi --no-as-needed --as-needed -lsci_cray --no-as-needed --as-needed -lpgas-dmapp --no-as-needed -lquadmath -lmodules -lfi -lcraymath -lf -lu -lcsup --as-needed -latomic --no-as-needed -lcray-c++-rts -lcray-c++-rts -lstdc++ -lsupc++ --whole-archive -ltcmalloc_minimal --no-whole-archive -lcray-c++-rts -lstdc++ -lpthread -L /opt/cray/pe/cce/9.0.0/cce-clang/x86_64/lib/clang/9.0.0/lib/linux --start-group -lc -lcsup -lgcc_eh -lm -lclang_rt.craypgo-x86_64 -lgcc --end-group -L /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0 -L /opt/cray/pe/cce/9.0.0/binutils/x86_64/x86_64-pc-linux-gnu/..//x86_64-unknown-linux-gnu/lib -EL -o cmTC_aa1be /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0//crtend.o /usr/lib64//crtn.o
+
+/opt/cray/pe/cce/9.0.0/binutils/x86_64/bin/objcopy --remove-section=.note.ftn_module_data cmTC_aa1be
+rm /lus/scratch/tmp/pe_14913//pldir/PL_path
+rm /lus/scratch/tmp/pe_14913//pldir/PL_global_data
+rm /lus/scratch/tmp/pe_14913//pldir/PL_module_list
+rmdir /lus/scratch/tmp/pe_14913//pldir
+rmdir /lus/scratch/tmp/pe_14913/
+gmake[1]: Leaving directory '/home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-9.0-hlist-ad.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-9.0-hlist-ad.output
new file mode 100644
index 000000000..a3b876813
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Cray-9.0-hlist-ad.output
@@ -0,0 +1 @@
+/opt/cray/pe/cce/9.0.0/cce/x86_64/include/craylibs;/opt/gcc/8.1.0/snos/include/g\+\+;/opt/gcc/8.1.0/snos/include/g\+\+/x86_64-suse-linux;/opt/gcc/8.1.0/snos/include/g\+\+/backward;/opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include;/opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0/include-fixed;/opt/cray/pe/cce/9.0.0/cce/x86_64/include/c\+\+;/opt/cray/pe/cce/9.0.0/cce/x86_64/include/basic;/opt/gcc/8.1.0/snos/include;/usr/include;/opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/include;/opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/include;/opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/include;/opt/cray/pe/pmi/5.0.14/include;/opt/cray/xpmem/2.2.15-6.0.7.1_5.8__g7549d06.ari/include;/opt/cray/dmapp/7.1.1-6.0.7.0_34.3__g5a674e0.ari/include;/opt/cray/gni-headers/5.0.12.0-6.0.7.0_24.1__g3b1768f.ari/include;/opt/cray/ugni/6.0.14.0-6.0.7.0_23.1__gea11d3d.ari/include;/opt/cray/udreg/2.3.2-6.0.7.0_33.18__g5196236.ari/include;/opt/cray/alps/6.6.43-6.0.7.0_26.4__ga796da3.ari/include;/opt/cray/wlm_detect/1.3.3-6.0.7.0_47.2__g7109084.ari/include;/opt/cray/krca/2.2.4-6.0.7.1_5.23__g8505b97.ari/include;/opt/cray-hss-devel/8.0.0/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-GNU-7.3.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-GNU-7.3.0.input
new file mode 100644
index 000000000..50f2859c7
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-GNU-7.3.0.input
@@ -0,0 +1,82 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=GNU
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=7.3.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_66e70/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_66e70.dir/build.make CMakeFiles/cmTC_66e70.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_66e70.dir/CMakeCXXCompilerABI.cpp.o
+/opt/cray/pe/craype/2.5.15/bin/CC -v -o CMakeFiles/cmTC_66e70.dir/CMakeCXXCompilerABI.cpp.o -c /usr/share/cmake/Modules/CMakeCXXCompilerABI.cpp
+Using built-in specs.
+COLLECT_GCC=/opt/gcc/7.3.0/bin/../snos/bin/g++
+Target: x86_64-suse-linux
+Configured with: ../cray-gcc-7.3.0-201801270210.d61239fc6000b/configure --prefix=/opt/gcc/7.3.0/snos --disable-nls --libdir=/opt/gcc/7.3.0/snos/lib --enable-languages=c,c++,fortran --with-gxx-include-dir=/opt/gcc/7.3.0/snos/include/g++ --with-slibdir=/opt/gcc/7.3.0/snos/lib --with-system-zlib --enable-shared --enable-__cxa_atexit --build=x86_64-suse-linux --with-ppl --with-cloog --disable-multilib
+Thread model: posix
+gcc version 7.3.0 20180125 (Cray Inc.) (GCC)
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-static' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-u' 'pthread_mutex_destroy' '-D' '__TARGET_LINUX__' '-v' '-o' 'CMakeFiles/cmTC_66e70.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include'
+ /opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/cc1plus -quiet -v -I /opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include -I /opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include -I /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I /opt/cray-hss-devel/8.0.0/include -D_GNU_SOURCE -D __CRAYXC -D __CRAY_HASWELL -D __CRAYXT_COMPUTE_LINUX_TARGET -D __TARGET_LINUX__ /usr/share/cmake/Modules/CMakeCXXCompilerABI.cpp -quiet -dumpbase CMakeCXXCompilerABI.cpp -march=core-avx2 -auxbase-strip CMakeFiles/cmTC_66e70.dir/CMakeCXXCompilerABI.cpp.o -version -o /tmp/ccH9m9Qh.s
+GNU C++14 (GCC) version 7.3.0 20180125 (Cray Inc.) (x86_64-suse-linux)
+ compiled by GNU C version 7.3.0 20180125 (Cray Inc.), GMP version 6.0.0, MPFR version 3.1.3, MPC version 1.0.3, isl version isl-0.15-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+ignoring nonexistent directory "/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../x86_64-suse-linux/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include
+ /opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include
+ /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include
+ /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include
+ /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include
+ /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include
+ /opt/cray/pe/pmi/5.0.14/include
+ /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include
+ /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include
+ /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include
+ /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include
+ /opt/cray-hss-devel/8.0.0/include
+ /opt/gcc/7.3.0/snos/include/g++
+ /opt/gcc/7.3.0/snos/include/g++/x86_64-suse-linux
+ /opt/gcc/7.3.0/snos/include/g++/backward
+ /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include
+ /usr/local/include
+ /opt/gcc/7.3.0/snos/include
+ /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include-fixed
+ /usr/include
+End of search list.
+GNU C++14 (GCC) version 7.3.0 20180125 (Cray Inc.) (x86_64-suse-linux)
+ compiled by GNU C version 7.3.0 20180125 (Cray Inc.), GMP version 6.0.0, MPFR version 3.1.3, MPC version 1.0.3, isl version isl-0.15-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+Compiler executable checksum: f544672a0be6a74646c0fce634253d7e
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-static' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-u' 'pthread_mutex_destroy' '-D' '__TARGET_LINUX__' '-v' '-o' 'CMakeFiles/cmTC_66e70.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include'
+ as -v -I /opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include -I /opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include -I /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I /opt/cray-hss-devel/8.0.0/include --64 -o CMakeFiles/cmTC_66e70.dir/CMakeCXXCompilerABI.cpp.o /tmp/ccH9m9Qh.s
+GNU assembler version 2.31.1 (x86_64-suse-linux) using BFD version (GNU Binutils SUSE Linux Enterprise 12) 2.31.1.20180828-9.26
+COMPILER_PATH=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/
+LIBRARY_PATH=/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../lib64/:/lib/../lib64/:/usr/lib/../lib64/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-static' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-u' 'pthread_mutex_destroy' '-D' '__TARGET_LINUX__' '-v' '-o' 'CMakeFiles/cmTC_66e70.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include'
+Linking CXX executable cmTC_66e70
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_66e70.dir/link.txt --verbose=1
+/opt/cray/pe/craype/2.5.15/bin/CC -v CMakeFiles/cmTC_66e70.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_66e70
+Using built-in specs.
+COLLECT_GCC=/opt/gcc/7.3.0/bin/../snos/bin/g++
+COLLECT_LTO_WRAPPER=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/lto-wrapper
+Target: x86_64-suse-linux
+Configured with: ../cray-gcc-7.3.0-201801270210.d61239fc6000b/configure --prefix=/opt/gcc/7.3.0/snos --disable-nls --libdir=/opt/gcc/7.3.0/snos/lib --enable-languages=c,c++,fortran --with-gxx-include-dir=/opt/gcc/7.3.0/snos/include/g++ --with-slibdir=/opt/gcc/7.3.0/snos/lib --with-system-zlib --enable-shared --enable-__cxa_atexit --build=x86_64-suse-linux --with-ppl --with-cloog --disable-multilib
+Thread model: posix
+gcc version 7.3.0 20180125 (Cray Inc.) (GCC)
+COMPILER_PATH=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/
+LIBRARY_PATH=/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../lib64/:/lib/../lib64/:/usr/lib/../lib64/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-static' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-u' 'pthread_mutex_destroy' '-D' '__TARGET_LINUX__' '-v' '-o' 'cmTC_66e70' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include' '-L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64' '-L/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64' '-L/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64' '-L/opt/cray/pe/pmi/5.0.14/lib64' '-L/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64' '-L/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64' '-L/opt/cray/pe/atp/2.1.3/libApp' '-L/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64'
+ /opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/collect2 -plugin /opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/liblto_plugin.so -plugin-opt=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/lto-wrapper -plugin-opt=-fresolution=/tmp/ccPBC8Um.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_eh -plugin-opt=-pass-through=-lc -m elf_x86_64 -static -o cmTC_66e70 -u pthread_mutex_destroy /usr/lib/../lib64/crt1.o /usr/lib/../lib64/crti.o /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/crtbeginT.o -L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib -L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64 -L/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64 -L/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64 -L/opt/cray/pe/pmi/5.0.14/lib64 -L/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64 -L/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64 -L/opt/cray/pe/atp/2.1.3/libApp -L/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64 -L/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0 -L/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../.. CMakeFiles/cmTC_66e70.dir/CMakeCXXCompilerABI.cpp.o -rpath=/opt/cray/pe/gcc-libs --no-as-needed -lAtpSigHandler -lAtpSigHCommData --undefined=_ATP_Data_Globals --undefined=__atpHandlerInstall -lpthread -lsci_gnu_71_mpi -lsci_gnu_71 -lpthread -lhugetlbfs -lmpichcxx_gnu_71 -lrt -lugni -lpthread -lpmi -lmpich_gnu_71 -lrt -lugni -lpthread -lpmi -lpthread -lalpslli -lpthread -lwlm_detect -lalpsutil -lpthread -lrca -lugni -lpthread -lxpmem -ludreg --as-needed -lgfortran -lquadmath --no-as-needed --as-needed -lmvec --no-as-needed --as-needed -lm --no-as-needed --as-needed -lpthread --no-as-needed -lstdc++ -lm --start-group -lgcc -lgcc_eh -lc --end-group /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/crtend.o /usr/lib/../lib64/crtn.o
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-static' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-u' 'pthread_mutex_destroy' '-D' '__TARGET_LINUX__' '-v' '-o' 'cmTC_66e70' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include' '-L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64' '-L/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64' '-L/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64' '-L/opt/cray/pe/pmi/5.0.14/lib64' '-L/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64' '-L/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64' '-L/opt/cray/pe/atp/2.1.3/libApp' '-L/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64'
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-GNU-7.3.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-GNU-7.3.0.output
new file mode 100644
index 000000000..b76c5dbb9
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-GNU-7.3.0.output
@@ -0,0 +1 @@
+/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include;/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include;/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include;/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include;/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include;/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include;/opt/cray/pe/pmi/5.0.14/include;/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include;/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include;/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include;/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include;/opt/cray-hss-devel/8.0.0/include;/opt/gcc/7.3.0/snos/include/g\+\+;/opt/gcc/7.3.0/snos/include/g\+\+/x86_64-suse-linux;/opt/gcc/7.3.0/snos/include/g\+\+/backward;/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include;/usr/local/include;/opt/gcc/7.3.0/snos/include;/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include-fixed;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Intel-18.0.2.20180210.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Intel-18.0.2.20180210.input
new file mode 100644
index 000000000..e25f7cf9d
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Intel-18.0.2.20180210.input
@@ -0,0 +1,43 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=Intel
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=18.0.2.20180210
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_7f9a2/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_7f9a2.dir/build.make CMakeFiles/cmTC_7f9a2.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.o
+/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/bin/intel64/icpc -v -o CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.o -c /usr/share/cmake/Modules/CMakeCXXCompilerABI.cpp
+icpc version 18.0.2 (gcc version 6.3.0 compatibility)
+/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/mcpcom --target_efi2 --lang=c++ -_g -mP3OPT_inline_alloca -D__ICC=1800 -D__INTEL_COMPILER=1800 -D__INTEL_COMPILER_UPDATE=2 -D__PTRDIFF_TYPE__=long "-D__SIZE_TYPE__=unsigned long" -D__WCHAR_TYPE__=int "-D__WINT_TYPE__=unsigned int" "-D__INTMAX_TYPE__=long int" "-D__UINTMAX_TYPE__=long unsigned int" -D__GLIBCXX_TYPE_INT_N_0=__int128 -D__GLIBCXX_BITSIZE_INT_N_0=128 -D__LONG_MAX__=9223372036854775807L -D__QMSPP_ -D__OPTIMIZE__ -D__NO_MATH_INLINES -D__NO_STRING_INLINES -D__GNUC_GNU_INLINE__ -D__GNUG__=6 -D__GNUC__=6 -D__GNUC_MINOR__=3 -D__GNUC_PATCHLEVEL__=0 -D__LP64__ -D_LP64 -D_GNU_SOURCE=1 -D__DEPRECATED=1 -D__GXX_WEAK__=1 -D__GXX_ABI_VERSION=1010 "-D__USER_LABEL_PREFIX__= " -D__REGISTER_PREFIX__= -D__INTEL_RTTI__ -D__EXCEPTIONS=1 -D__unix__ -D__unix -D__linux__ -D__linux -D__gnu_linux__ -B -Dunix -Dlinux "-_Asystem(unix)" -D__ELF__ -D__x86_64 -D__x86_64__ -D__amd64 -D__amd64__ "-_Acpu(x86_64)" "-_Amachine(x86_64)" -D__INTEL_COMPILER_BUILD_DATE=20180210 -D__INTEL_OFFLOAD -D__i686 -D__i686__ -D__pentiumpro -D__pentiumpro__ -D__pentium4 -D__pentium4__ -D__tune_pentium4__ -D__SSE2__ -D__SSE2_MATH__ -D__SSE__ -D__SSE_MATH__ -D__MMX__ -_k -_8 -_l --has_new_stdarg_support -_a -_b --gnu_version=60300 -_W5 --gcc-extern-inline -p --bool -tused -x --multibyte_chars -mGLOB_diag_suppress_sys --system_preinclude /usr/include/stdc-predef.h --array_section --simd --simd_func --offload_mode=1 --offload_target_names=gfx,GFX,mic,MIC --offload_unique_string=icpc0677339003u7vp5M --bool -mGLOB_em64t=TRUE -mP1OPT_version=18.0-intel64 -mGLOB_diag_file=CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.diag -mGLOB_long_size_64 -mGLOB_routine_pointer_size_64 -mP1OPT_print_version=FALSE -mCG_use_gas_got_workaround=F -mP2OPT_align_option_used=TRUE -mGLOB_gcc_version=630 "-mGLOB_options_string=-v -o CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.o -c" -mGLOB_cxx_limited_range=FALSE -mCG_extend_parms=FALSE -mGLOB_compiler_bin_directory=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64 -mGLOB_as_output_backup_file_name=/tmp/icpc9QgBnwas_.s -mIPOPT_activate -mIPOPT_lite -mGLOB_instruction_tuning=0x0 -mGLOB_uarch_tuning=0x0 -mGLOB_product_id_code=0x22006d8f -mCG_bnl_movbe=T -mGLOB_extended_instructions=0x8 -mP3OPT_use_mspp_call_convention -mP2OPT_subs_out_of_bound=FALSE -mP2OPT_disam_type_based_disam=2 -mP2OPT_disam_assume_ansi_c -mP2OPT_checked_disam_ansi_alias=TRUE -mGLOB_ansi_alias -mPGOPTI_value_profile_use=T -mP2OPT_il0_array_sections=TRUE -mGLOB_offload_mode=1 -mP2OPT_offload_unique_var_string=icpc0677339003u7vp5M -mP2OPT_hlo_level=2 -mP2OPT_hlo -mP2OPT_hpo_rtt_control=0 -mIPOPT_args_in_regs=0 -mP2OPT_disam_assume_nonstd_intent_in=FALSE -mGLOB_imf_mapping_library=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/libiml_attr.so -mPGOPTI_gen_threadsafe_level=0 -mIPOPT_lto_object_enabled -mIPOPT_lto_object_value=1 -mIPOPT_obj_output_file_name=CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.o -mIPOPT_whole_archive_fixup_file_name=/tmp/icpcwarchdKZxrN -mGLOB_linker_version=2.31.1.20180828 -mGLOB_driver_tempfile_name=/tmp/icpctempfilejCzFYq -mP3OPT_asm_target=P3OPT_ASM_TARGET_GAS -mGLOB_async_unwind_tables=TRUE -mGLOB_obj_output_file=CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.o -mGLOB_source_dialect=GLOB_SOURCE_DIALECT_C_PLUS_PLUS -mP1OPT_source_file_name=/usr/share/cmake/Modules/CMakeCXXCompilerABI.cpp -mP1OPT_full_source_file_name=/usr/share/cmake/Modules/CMakeCXXCompilerABI.cpp -mGLOB_eh_linux /usr/share/cmake/Modules/CMakeCXXCompilerABI.cpp
+#include "..." search starts here:
+#include <...> search starts here:
+ /opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/include
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/intel64
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/icc
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include
+ /opt/gcc/6.3.0/snos/include/g++
+ /opt/gcc/6.3.0/snos/include/g++/x86_64-suse-linux
+ /opt/gcc/6.3.0/snos/include/g++/backward
+ /usr/local/include
+ /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include
+ /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include-fixed
+ /opt/gcc/6.3.0/snos/include/
+ /usr/include
+End of search list.
+Linking CXX executable cmTC_7f9a2
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_7f9a2.dir/link.txt --verbose=1
+/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/bin/intel64/icpc -v CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_7f9a2 -rdynamic
+icpc version 18.0.2 (gcc version 6.3.0 compatibility)
+/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/mcpcom -mGLOB_em64t=TRUE -mP1OPT_version=18.0-intel64 -mGLOB_diag_file=CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.diag -mGLOB_long_size_64 -mGLOB_routine_pointer_size_64 -mP1OPT_print_version=FALSE -mCG_use_gas_got_workaround=F -mP2OPT_align_option_used=TRUE -mGLOB_gcc_version=630 "-mGLOB_options_string=-v -o cmTC_7f9a2 -rdynamic" -mGLOB_cxx_limited_range=FALSE -mCG_extend_parms=FALSE -mGLOB_compiler_bin_directory=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64 -mGLOB_as_output_backup_file_name=/tmp/icpczXhKsFas_.s -mGLOB_dashboard_use_source_name -mIPOPT_activate -mGLOB_product_id_code=0x22006d8f -mP3OPT_use_mspp_call_convention -mP2OPT_subs_out_of_bound=FALSE -mP2OPT_disam_type_based_disam=2 -mP2OPT_disam_assume_ansi_c -mP2OPT_checked_disam_ansi_alias=TRUE -mGLOB_ansi_alias -mPGOPTI_value_profile_use=T -mGLOB_opt_report_use_source_name -mP2OPT_il0_array_sections=TRUE -mGLOB_offload_mode=1 -mP2OPT_offload_unique_var_string=icpc0782944392Xjn3gY -mP2OPT_hlo -mP2OPT_hpo_rtt_control=0 -mIPOPT_args_in_regs=0 -mP2OPT_disam_assume_nonstd_intent_in=FALSE -mGLOB_imf_mapping_library=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/libiml_attr.so -mPGOPTI_gen_threadsafe_level=0 -mIPOPT_link -mIPOPT_ipo_activate -mIPOPT_mo_activate -mIPOPT_source_files_list=/tmp/icpcslis0WLMWJ -mIPOPT_mo_global_data -mIPOPT_link_script_file=/tmp/icpcscriptx5xyMn "-mIPOPT_cmdline_link="/usr/lib/../lib64/crt1.o" "/usr/lib/../lib64/crti.o" "/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtbegin.o" "-export-dynamic" "--eh-frame-hdr" "--build-id" "-dynamic-linker" "/lib64/ld-linux-x86-64.so.2" "-m" "elf_x86_64" "-o" "cmTC_7f9a2" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64/" "-L/lib/../lib64" "-L/lib/../lib64/" "-L/usr/lib/../lib64" "-L/usr/lib/../lib64/" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64/" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../" "-L/lib64" "-L/lib/" "-L/usr/lib64" "-L/usr/lib" "CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.o" "-Bdynamic" "-Bstatic" "-limf" "-lsvml" "-lirng" "-Bdynamic" "-lstdc++" "-lm" "-Bstatic" "-lipgo" "-ldecimal" "--as-needed" "-Bdynamic" "-lcilkrts" "--no-as-needed" "-lstdc++" "-lgcc" "-lgcc_s" "-Bstatic" "-lirc" "-lsvml" "-Bdynamic" "-lc" "-lgcc" "-lgcc_s" "-Bstatic" "-lirc_s" "-Bdynamic" "-ldl" "-lc" "/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtend.o" "/usr/lib/../lib64/crtn.o"" -mIPOPT_il_in_obj -mIPOPT_ipo_activate_warn=FALSE -mIPOPT_obj_output_file_name=/tmp/ipo_icpcP4kcWS.o -mIPOPT_whole_archive_fixup_file_name=/tmp/icpcwarchR2OJ1A -mGLOB_linker_version=2.31.1.20180828 -mGLOB_driver_tempfile_name=/tmp/icpctempfileWiVxTe -mP3OPT_asm_target=P3OPT_ASM_TARGET_GAS -mGLOB_async_unwind_tables=TRUE -mGLOB_obj_output_file=/tmp/ipo_icpcP4kcWS.o -mGLOB_source_dialect=GLOB_SOURCE_DIALECT_NONE -mP1OPT_source_file_name=ipo_out.c CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.o -mIPOPT_object_files=T -mIPOPT_assembly_files=/tmp/icpcalis76IIBa -mIPOPT_generated_tempfiles=/tmp/icpcelisj58trO -mIPOPT_embedded_object_base_name=/tmp/icpceobjgmHfhs -mIPOPT_cmdline_link_new_name=/tmp/icpcllis3p9065
+ld /usr/lib/../lib64/crt1.o /usr/lib/../lib64/crti.o /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtbegin.o -export-dynamic --eh-frame-hdr --build-id -dynamic-linker /lib64/ld-linux-x86-64.so.2 -m elf_x86_64 -o cmTC_7f9a2 -L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64 -L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/ -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64 -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64/ -L/lib/../lib64 -L/lib/../lib64/ -L/usr/lib/../lib64 -L/usr/lib/../lib64/ -L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64/ -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../ -L/lib64 -L/lib/ -L/usr/lib64 -L/usr/lib CMakeFiles/cmTC_7f9a2.dir/CMakeCXXCompilerABI.cpp.o -Bdynamic -Bstatic -limf -lsvml -lirng -Bdynamic -lstdc++ -lm -Bstatic -lipgo -ldecimal --as-needed -Bdynamic -lcilkrts --no-as-needed -lstdc++ -lgcc -lgcc_s -Bstatic -lirc -lsvml -Bdynamic -lc -lgcc -lgcc_s -Bstatic -lirc_s -Bdynamic -ldl -lc /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtend.o /usr/lib/../lib64/crtn.o
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Intel-18.0.2.20180210.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Intel-18.0.2.20180210.output
new file mode 100644
index 000000000..031c32440
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-CXX-Intel-18.0.2.20180210.output
@@ -0,0 +1 @@
+/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/include;/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/intel64;/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/icc;/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include;/opt/gcc/6.3.0/snos/include/g\+\+;/opt/gcc/6.3.0/snos/include/g\+\+/x86_64-suse-linux;/opt/gcc/6.3.0/snos/include/g\+\+/backward;/usr/local/include;/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include;/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include-fixed;/opt/gcc/6.3.0/snos/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-8.7.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-8.7.input
new file mode 100644
index 000000000..4c4e2f483
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-8.7.input
@@ -0,0 +1,52 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=ELF
+CMAKE_Fortran_COMPILER_AR=
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=Cray
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=8.7
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_9c3ab/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_9c3ab.dir/build.make CMakeFiles/cmTC_9c3ab.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_9c3ab.dir/CMakeFortranCompilerABI.F.o
+/opt/cray/pe/craype/2.5.15/bin/ftn -em -J. -v -c /usr/projects/hpcsoft/cle6.0/common/cmake/3.10.2/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_9c3ab.dir/CMakeFortranCompilerABI.F.o
+
+/opt/cray/pe/cce/8.7.4/cce/x86_64/bin/ftnfe -h cpu=haswell -D__CRAYXC -D__CRAY_HASWELL -D__CRAYXT_COMPUTE_LINUX_TARGET -h network=aries -em -J. -I/opt/cray/pe/cce/8.7.4/cce/x86_64/include/craylibs -I/usr/include -I/usr/include -I/opt/cray/pe/libsci/18.07.1/CRAY/8.6/x86_64/include -I/opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/include -I/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I/opt/cray/dmapp/7.1.1-6.0.5.0_49.8__g1125556.ari/include -I/opt/cray/pe/pmi/5.0.14/include -I/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I/opt/cray-hss-devel/8.0.0/include -hpl=/tmp/pe_32428//pldir -usystem_mod=/opt/cray/pe/cce/8.7.4/cce/x86_64/lib/libmodules.a -usystem_mod=/opt/cray/pe/cce/8.7.4/cce/x86_64/lib/libomp.a -usystem_mod=/opt/cray/pe/cce/8.7.4/cce/x86_64/lib/omp_lib.a -usystem_mod=/opt/cray/pe/cce/8.7.4/cce/x86_64/lib/libopenacc.a -usystem_mod=/opt/cray/pe/libsci/18.07.1/CRAY/8.6/x86_64/include -usystem_mod=/opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/include -usystem_mod=/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -usystem_mod=/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -usystem_mod=/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -usystem_mod=/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -usystem_mod=/opt/cray/dmapp/7.1.1-6.0.5.0_49.8__g1125556.ari/include -usystem_mod=/opt/cray/pe/pmi/5.0.14/include -usystem_mod=/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -usystem_mod=/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -usystem_mod=/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -usystem_mod=/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -usystem_mod=/opt/cray-hss-devel/8.0.0/include -ux=x8503 -udv=87000 -ffixed -CZ/tmp/pe_32428/CMakeFortranCompilerABI.T -Cx -CX/tmp/pe_32428/CMakeFortranCompilerABI.xml -hdecompile=/tmp/ii/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_9c3ab.dir/CMakeFortranCompilerABI. -S /tmp/pe_32428/CMakeFortranCompilerABI_1.s -Oipa3 -uo=/tmp/ii/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_9c3ab.dir/CMakeFortranCompilerABI.F.o -ufile_id=1 /usr/projects/hpcsoft/cle6.0/common/cmake/3.10.2/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F
+
+/opt/cray/pe/cce/8.7.4/cce/x86_64/bin/optcg /tmp/pe_32428//pldir 1
+
+/opt/cray/pe/cce/8.7.4/binutils/x86_64/x86_64-pc-linux-gnu/bin/as -o CMakeFiles/cmTC_9c3ab.dir/CMakeFortranCompilerABI.F.o --64 /tmp/pe_32428/CMakeFortranCompilerABI_1.s
+rm /tmp/pe_32428/CMakeFortranCompilerABI_1.s
+rm /tmp/pe_32428//pldir/PL_path
+rm /tmp/pe_32428//pldir/iline_1
+rm /tmp/pe_32428//pldir/gline_1
+rm /tmp/pe_32428//pldir/PL_global_data
+rm /tmp/pe_32428//pldir/PL_module_list
+rm /tmp/pe_32428//pldir/CMakeFortranCompilerABI_1.inl
+rmdir /tmp/pe_32428//pldir
+rm /tmp/pe_32428//CMakeFortranCompilerABI_1.xml.Ttmp
+rm /tmp/pe_32428//CMakeFortranCompilerABI.T
+rm /tmp/pe_32428//CMakeFortranCompilerABI_1.cif.Ttmp
+rm /tmp/pe_32428//CMakeFortranCompilerABI.Tfe
+rm /tmp/pe_32428//CMakeFortranCompilerABI.xml
+rmdir /tmp/pe_32428/
+Linking Fortran executable cmTC_9c3ab
+/usr/projects/hpcsoft/cle6.0/common/cmake/3.10.2/bin/cmake -E cmake_link_script CMakeFiles/cmTC_9c3ab.dir/link.txt --verbose=1
+/opt/cray/pe/craype/2.5.15/bin/ftn -v -dynamic CMakeFiles/cmTC_9c3ab.dir/CMakeFortranCompilerABI.F.o -o cmTC_9c3ab
+
+/opt/cray/pe/cce/8.7.4/binutils/x86_64/x86_64-pc-linux-gnu/bin/ld --eh-frame-hdr -m elf_x86_64 --enable-new-dtags --dynamic-linker /lib64/ld-linux-x86-64.so.2 /usr/lib64//crt1.o /usr/lib64//crti.o /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0//crtbegin.o /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0//crtfastmath.o /opt/cray/pe/cce/8.7.4/cce/x86_64/lib/no_mmap.o CMakeFiles/cmTC_9c3ab.dir/CMakeFortranCompilerABI.F.o -Bdynamic -rpath=/opt/cray/pe/cce/8.7.4/cce/x86_64/lib -L/opt/gcc/6.1.0/snos/lib64 -rpath=/opt/cray/pe/gcc-libs -L/opt/cray/pe/libsci/18.07.1/CRAY/8.6/x86_64/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/lib -L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64 -L/opt/cray/pe/atp/2.1.3/libApp -L/opt/cray/pe/cce/8.7.4/cce/x86_64/lib/pkgconfig/../ --no-as-needed -lAtpSigHandler -lAtpSigHCommData --undefined=_ATP_Data_Globals --undefined=__atpHandlerInstall -L/usr/lib64 -L/lib64 -rpath=/usr/lib64 -rpath=/lib64 -lrca --as-needed -lsci_cray_mpi_mp --no-as-needed --as-needed -lsci_cray_mp --no-as-needed --as-needed -lmpich_cray --no-as-needed --as-needed -lmpichf90_cray --no-as-needed --as-needed -lpgas-dmapp --no-as-needed -lquadmath -lomp -lcraymp -lmodules -lfi -lcraymath -lf -lu -lcsup --as-needed -latomic --no-as-needed --as-needed -lgfortran --no-as-needed --whole-archive -ltcmalloc_minimal --no-whole-archive -lstdc++ -lpthread --start-group -lc -lcsup -lgcc_eh -lm -lgcc --end-group -L /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0 -L /opt/cray/pe/cce/8.7.4/binutils/x86_64/x86_64-pc-linux-gnu/..//x86_64-unknown-linux-gnu/lib -EL -o cmTC_9c3ab /opt/gcc/6.1.0/snos/lib/gcc/x86_64-suse-linux/6.1.0//crtend.o /usr/lib64//crtn.o
+
+/opt/cray/pe/cce/8.7.4/binutils/x86_64/bin/objcopy --remove-section=.note.ftn_module_data cmTC_9c3ab
+rm /tmp/pe_32450//pldir/PL_path
+rm /tmp/pe_32450//pldir/PL_global_data
+rm /tmp/pe_32450//pldir/PL_module_list
+rmdir /tmp/pe_32450//pldir
+rmdir /tmp/pe_32450/
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-8.7.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-8.7.output
new file mode 100644
index 000000000..daa34e2ea
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-8.7.output
@@ -0,0 +1 @@
+/opt/cray/pe/cce/8.7.4/cce/x86_64/include/craylibs;/usr/include;/opt/cray/pe/libsci/18.07.1/CRAY/8.6/x86_64/include;/opt/cray/pe/mpt/7.7.3/gni/mpich-cray/8.6/include;/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include;/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include;/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include;/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include;/opt/cray/dmapp/7.1.1-6.0.5.0_49.8__g1125556.ari/include;/opt/cray/pe/pmi/5.0.14/include;/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include;/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include;/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include;/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include;/opt/cray-hss-devel/8.0.0/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-9.0-hlist-ad.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-9.0-hlist-ad.input
new file mode 100644
index 000000000..0ba430a4f
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-9.0-hlist-ad.input
@@ -0,0 +1,53 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=ELF
+CMAKE_Fortran_COMPILER_AR=
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=Cray
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=9.0
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp
+
+Run Build Command(s):/usr/bin/gmake cmTC_61c1d/fast && /usr/bin/gmake -f CMakeFiles/cmTC_61c1d.dir/build.make CMakeFiles/cmTC_61c1d.dir/build
+gmake[1]: Entering directory '/home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_61c1d.dir/CMakeFortranCompilerABI.F.o
+/opt/cray/pe/craype/2.6.0/bin/ftn -hlist=ad -em -J. -v -c /home/generic.user/Code/cmake/source/master/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_61c1d.dir/CMakeFortranCompilerABI.F.o
+
+/opt/cray/pe/cce/9.0.0/cce/x86_64/bin/ftnfe -h cpu=broadwell -D__CRAYXC -D__CRAY_BROADWELL -D__CRAYXT_COMPUTE_LINUX_TARGET -h network=aries -hdecomp -em -J. -I/opt/cray/pe/cce/9.0.0/cce/x86_64/include/craylibs -I/usr/include -I/usr/include -I/opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/include -I/opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/include -I/opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/include -I/opt/cray/pe/pmi/5.0.14/include -I/opt/cray/xpmem/2.2.15-6.0.7.1_5.8__g7549d06.ari/include -I/opt/cray/dmapp/7.1.1-6.0.7.0_34.3__g5a674e0.ari/include -I/opt/cray/gni-headers/5.0.12.0-6.0.7.0_24.1__g3b1768f.ari/include -I/opt/cray/ugni/6.0.14.0-6.0.7.0_23.1__gea11d3d.ari/include -I/opt/cray/udreg/2.3.2-6.0.7.0_33.18__g5196236.ari/include -I/opt/cray/alps/6.6.43-6.0.7.0_26.4__ga796da3.ari/include -I/opt/cray/wlm_detect/1.3.3-6.0.7.0_47.2__g7109084.ari/include -I/opt/cray/krca/2.2.4-6.0.7.1_5.23__g8505b97.ari/include -I/opt/cray-hss-devel/8.0.0/include -hpl=/lus/scratch/tmp/pe_16260//pldir -Ca -CY "ftn_driver.exe -hcpu=broadwell -hdynamic -D__CRAYXC -D__CRAY_BROADWELL -D__CRAYXT_COMPUTE_LINUX_TARGET -hnetwork=aries -hlist=ad -em -J. -v -c /home/generic.user/Code/cmake/source/master/Modules/CMakeFortranCompilerABI.F -oCMakeFiles/cmTC_61c1d.dir/CMakeFortranCompilerABI.F.o -I/opt/cray/pe/cce/9.0.0/cce/x86_64/include/craylibs -I/usr/include -I/usr/include -I/opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/include -I/opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/include -I/opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/include -I/opt/cray/pe/pmi/5.0.14/include -I/opt/cray/xpmem/2.2.15-6.0.7.1_5.8__g7549d06.ari/include -I/opt/cray/dmapp/7.1.1-6.0.7.0_34.3__g5a674e0.ari/include -I/opt/cray/gni-headers/5.0.12.0-6.0.7.0_24.1__g3b1768f.ari/include -I/opt/cray/ugni/6.0.14.0-6.0.7.0_23.1__gea11d3d.ari/include -I/opt/cray/udreg/2.3.2-6.0.7.0_33.18__g5196236.ari/include -I/opt/cray/alps/6.6.43-6.0.7.0_26.4__ga796da3.ari/include -I/opt/cray/wlm_detect/1.3.3-6.0.7.0_47.2__g7109084.ari/include -I/opt/cray/krca/2.2.4-6.0.7.1_5.23__g8505b97.ari/include -I/opt/cray-hss-devel/8.0.0/include" -usystem_mod=/opt/cray/pe/cce/9.0.0/cce/x86_64/lib/libmodules.a -usystem_mod=/opt/cray/pe/cce/9.0.0/cce/x86_64/lib/libomp.a -usystem_mod=/opt/cray/pe/cce/9.0.0/cce/x86_64/lib/omp_lib.a -usystem_mod=/opt/cray/pe/cce/9.0.0/cce/x86_64/lib/libopenacc.a -usystem_mod=/opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/include -usystem_mod=/opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/include -usystem_mod=/opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/include -usystem_mod=/opt/cray/pe/pmi/5.0.14/include -usystem_mod=/opt/cray/xpmem/2.2.15-6.0.7.1_5.8__g7549d06.ari/include -usystem_mod=/opt/cray/dmapp/7.1.1-6.0.7.0_34.3__g5a674e0.ari/include -usystem_mod=/opt/cray/gni-headers/5.0.12.0-6.0.7.0_24.1__g3b1768f.ari/include -usystem_mod=/opt/cray/ugni/6.0.14.0-6.0.7.0_23.1__gea11d3d.ari/include -usystem_mod=/opt/cray/udreg/2.3.2-6.0.7.0_33.18__g5196236.ari/include -usystem_mod=/opt/cray/alps/6.6.43-6.0.7.0_26.4__ga796da3.ari/include -usystem_mod=/opt/cray/wlm_detect/1.3.3-6.0.7.0_47.2__g7109084.ari/include -usystem_mod=/opt/cray/krca/2.2.4-6.0.7.1_5.23__g8505b97.ari/include -usystem_mod=/opt/cray-hss-devel/8.0.0/include -usystem_mod=/opt/cray/pe/cce/9.0.0/cce/x86_64/lib/libcraymp.a -udv -ffixed -CZ/lus/scratch/tmp/pe_16260/CMakeFortranCompilerABI.T -Cx -CX/lus/scratch/tmp/pe_16260/CMakeFortranCompilerABI.xml -hdecompile=/home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_61c1d.dir/CMakeFortranCompilerABI. -S /lus/scratch/tmp/pe_16260/CMakeFortranCompilerABI_1.s -Oipa3 -uo=/home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_61c1d.dir/CMakeFortranCompilerABI.F.o -ufile_id=1 /home/generic.user/Code/cmake/source/master/Modules/CMakeFortranCompilerABI.F
+
+/opt/cray/pe/cce/9.0.0/cce/x86_64/bin/optcg /lus/scratch/tmp/pe_16260//pldir 1
+
+/opt/cray/pe/cce/9.0.0/binutils/x86_64/x86_64-pc-linux-gnu/bin/as -o CMakeFiles/cmTC_61c1d.dir/CMakeFortranCompilerABI.F.o --64 /lus/scratch/tmp/pe_16260/CMakeFortranCompilerABI_1.s
+rm /lus/scratch/tmp/pe_16260/CMakeFortranCompilerABI_1.s
+
+/opt/cray/pe/cce/9.0.0/cce/x86_64/bin/ftnlx -ra -q -o CMakeFiles/cmTC_61c1d.dir/CMakeFortranCompilerABI.lst /home/generic.user/Code/cmake/source/master/Modules/CMakeFortranCompilerABI.F /lus/scratch/tmp/pe_16260/CMakeFortranCompilerABI.T
+rm /lus/scratch/tmp/pe_16260/CMakeFortranCompilerABI.T
+rm /lus/scratch/tmp/pe_16260//CMakeFortranCompilerABI.xml
+rm /lus/scratch/tmp/pe_16260//CMakeFortranCompilerABI_1.cif.Ttmp
+rm /lus/scratch/tmp/pe_16260//CMakeFortranCompilerABI_1.xml.Ttmp
+rm /lus/scratch/tmp/pe_16260//pldir/gline_1
+rm /lus/scratch/tmp/pe_16260//pldir/PL_path
+rm /lus/scratch/tmp/pe_16260//pldir/CMakeFortranCompilerABI_1.inl
+rm /lus/scratch/tmp/pe_16260//pldir/PL_global_data
+rm /lus/scratch/tmp/pe_16260//pldir/iline_1
+rm /lus/scratch/tmp/pe_16260//pldir/PL_module_list
+rmdir /lus/scratch/tmp/pe_16260//pldir
+rm /lus/scratch/tmp/pe_16260//CMakeFortranCompilerABI.Tfe
+rmdir /lus/scratch/tmp/pe_16260/
+Linking Fortran executable cmTC_61c1d
+/home/generic.user/Code/cmake/build/master/bin/cmake -E cmake_link_script CMakeFiles/cmTC_61c1d.dir/link.txt --verbose=1
+/opt/cray/pe/craype/2.6.0/bin/ftn -v -hlist=ad CMakeFiles/cmTC_61c1d.dir/CMakeFortranCompilerABI.F.o -o cmTC_61c1d
+
+/opt/cray/pe/cce/9.0.0/binutils/x86_64/x86_64-pc-linux-gnu/bin/ld --eh-frame-hdr -m elf_x86_64 --enable-new-dtags --dynamic-linker /lib64/ld-linux-x86-64.so.2 /usr/lib64//crt1.o /usr/lib64//crti.o /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0//crtbegin.o /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0//crtfastmath.o /opt/cray/pe/cce/9.0.0/cce/x86_64/lib/no_mmap.o CMakeFiles/cmTC_61c1d.dir/CMakeFortranCompilerABI.F.o -Bdynamic -rpath=/opt/cray/pe/cce/9.0.0/cce/x86_64/lib -L/opt/gcc/8.1.0/snos/lib64 -rpath=/opt/cray/pe/gcc-libs -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/lib -L/opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/lib -L/opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/lib64 -L/opt/cray/pe/atp/2.1.3/libApp -L/opt/cray/pe/cce/9.0.0/cce/x86_64/lib/pkgconfig/../ --no-as-needed -lAtpSigHandler -lAtpSigHCommData --undefined=_ATP_Data_Globals --undefined=__atpHandlerInstall -L/usr/lib64 -L/lib64 -rpath=/usr/lib64 -rpath=/lib64 -lrca --as-needed -lmpich_cray_90 --no-as-needed --as-needed -lmpichf90_cray_90 --no-as-needed --as-needed -lsci_cray_mpi --no-as-needed --as-needed -lsci_cray --no-as-needed --as-needed -lpgas-dmapp --no-as-needed -lquadmath -lmodules -lfi -lcraymath -lf -lu -lcsup --as-needed -lgfortran --no-as-needed --whole-archive -ltcmalloc_minimal --no-whole-archive -lcray-c++-rts -lstdc++ -lpthread -L/opt/cray/pe/cce/9.0.0/cce-clang/x86_64/lib/clang/9.0.0/lib/linux --start-group -lc -lcsup -lgcc_eh -lm -lclang_rt.craypgo-x86_64 -lgcc --end-group -L /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0 -L /opt/cray/pe/cce/9.0.0/binutils/x86_64/x86_64-pc-linux-gnu/..//x86_64-unknown-linux-gnu/lib -EL -o cmTC_61c1d /opt/gcc/8.1.0/snos/lib/gcc/x86_64-suse-linux/8.1.0//crtend.o /usr/lib64//crtn.o
+
+/opt/cray/pe/cce/9.0.0/binutils/x86_64/bin/objcopy --remove-section=.note.ftn_module_data cmTC_61c1d
+rm /lus/scratch/tmp/pe_16273//pldir/PL_path
+rm /lus/scratch/tmp/pe_16273//pldir/PL_global_data
+rm /lus/scratch/tmp/pe_16273//pldir/PL_module_list
+rmdir /lus/scratch/tmp/pe_16273//pldir
+rmdir /lus/scratch/tmp/pe_16273/
+gmake[1]: Leaving directory '/home/generic.user/Code/tmp/build/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-9.0-hlist-ad.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-9.0-hlist-ad.output
new file mode 100644
index 000000000..234483b4e
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Cray-9.0-hlist-ad.output
@@ -0,0 +1 @@
+/opt/cray/pe/cce/9.0.0/cce/x86_64/include/craylibs;/usr/include;/opt/cray/pe/mpt/7.7.8/gni/mpich-cray/9.0/include;/opt/cray/pe/libsci/19.06.1/CRAY/9.0/x86_64/include;/opt/cray/rca/2.2.18-6.0.7.0_33.3__g2aa4f39.ari/include;/opt/cray/pe/pmi/5.0.14/include;/opt/cray/xpmem/2.2.15-6.0.7.1_5.8__g7549d06.ari/include;/opt/cray/dmapp/7.1.1-6.0.7.0_34.3__g5a674e0.ari/include;/opt/cray/gni-headers/5.0.12.0-6.0.7.0_24.1__g3b1768f.ari/include;/opt/cray/ugni/6.0.14.0-6.0.7.0_23.1__gea11d3d.ari/include;/opt/cray/udreg/2.3.2-6.0.7.0_33.18__g5196236.ari/include;/opt/cray/alps/6.6.43-6.0.7.0_26.4__ga796da3.ari/include;/opt/cray/wlm_detect/1.3.3-6.0.7.0_47.2__g7109084.ari/include;/opt/cray/krca/2.2.4-6.0.7.1_5.23__g8505b97.ari/include;/opt/cray-hss-devel/8.0.0/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-GNU-7.3.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-GNU-7.3.0.input
new file mode 100644
index 000000000..bee298c37
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-GNU-7.3.0.input
@@ -0,0 +1,83 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=
+CMAKE_Fortran_COMPILER_AR=/usr/bin/gcc-ar
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=GNU
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=/usr/bin/gcc-ranlib
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=7.3.0
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_390ef/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_390ef.dir/build.make CMakeFiles/cmTC_390ef.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_390ef.dir/CMakeFortranCompilerABI.F.o
+/opt/cray/pe/craype/2.5.15/bin/ftn -v -c /usr/projects/hpcsoft/cle6.0/common/cmake/3.10.2/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_390ef.dir/CMakeFortranCompilerABI.F.o
+Using built-in specs.
+COLLECT_GCC=/opt/gcc/7.3.0/bin/../snos/bin/gfortran
+Target: x86_64-suse-linux
+Configured with: ../cray-gcc-7.3.0-201801270210.d61239fc6000b/configure --prefix=/opt/gcc/7.3.0/snos --disable-nls --libdir=/opt/gcc/7.3.0/snos/lib --enable-languages=c,c++,fortran --with-gxx-include-dir=/opt/gcc/7.3.0/snos/include/g++ --with-slibdir=/opt/gcc/7.3.0/snos/lib --with-system-zlib --enable-shared --enable-__cxa_atexit --build=x86_64-suse-linux --with-ppl --with-cloog --disable-multilib
+Thread model: posix
+gcc version 7.3.0 20180125 (Cray Inc.) (GCC)
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-D' '__TARGET_LINUX__' '-v' '-c' '-o' 'CMakeFiles/cmTC_390ef.dir/CMakeFortranCompilerABI.F.o' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include'
+ /opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/f951 /usr/projects/hpcsoft/cle6.0/common/cmake/3.10.2/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -ffixed-form -cpp=/tmp/ccxLli6i.f90 -quiet -v -I /opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include -I /opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include -I /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I /opt/cray-hss-devel/8.0.0/include -D __CRAYXC -D __CRAY_HASWELL -D __CRAYXT_COMPUTE_LINUX_TARGET -D __TARGET_LINUX__ /usr/projects/hpcsoft/cle6.0/common/cmake/3.10.2/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -quiet -dumpbase CMakeFortranCompilerABI.F -march=core-avx2 -auxbase-strip CMakeFiles/cmTC_390ef.dir/CMakeFortranCompilerABI.F.o -version -fintrinsic-modules-path /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/finclude -o /tmp/ccqY0cGk.s
+GNU Fortran (GCC) version 7.3.0 20180125 (Cray Inc.) (x86_64-suse-linux)
+ compiled by GNU C version 7.3.0 20180125 (Cray Inc.), GMP version 6.0.0, MPFR version 3.1.3, MPC version 1.0.3, isl version isl-0.15-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+ignoring nonexistent directory "/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../x86_64-suse-linux/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include
+ /opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include
+ /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include
+ /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include
+ /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include
+ /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include
+ /opt/cray/pe/pmi/5.0.14/include
+ /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include
+ /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include
+ /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include
+ /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include
+ /opt/cray-hss-devel/8.0.0/include
+ /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/finclude
+ /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include
+ /usr/local/include
+ /opt/gcc/7.3.0/snos/include
+ /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include-fixed
+ /usr/include
+End of search list.
+GNU Fortran2008 (GCC) version 7.3.0 20180125 (Cray Inc.) (x86_64-suse-linux)
+ compiled by GNU C version 7.3.0 20180125 (Cray Inc.), GMP version 6.0.0, MPFR version 3.1.3, MPC version 1.0.3, isl version isl-0.15-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-D' '__TARGET_LINUX__' '-v' '-c' '-o' 'CMakeFiles/cmTC_390ef.dir/CMakeFortranCompilerABI.F.o' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include'
+ as -v -I /opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include -I /opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include -I /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I /opt/cray/pe/pmi/5.0.14/include -I /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I /opt/cray-hss-devel/8.0.0/include --64 -o CMakeFiles/cmTC_390ef.dir/CMakeFortranCompilerABI.F.o /tmp/ccqY0cGk.s
+GNU assembler version 2.31.1 (x86_64-suse-linux) using BFD version (GNU Binutils SUSE Linux Enterprise 12) 2.31.1.20180828-9.26
+COMPILER_PATH=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/
+LIBRARY_PATH=/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../lib64/:/lib/../lib64/:/usr/lib/../lib64/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-D' '__TARGET_LINUX__' '-v' '-c' '-o' 'CMakeFiles/cmTC_390ef.dir/CMakeFortranCompilerABI.F.o' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include'
+Linking Fortran executable cmTC_390ef
+/usr/projects/hpcsoft/cle6.0/common/cmake/3.10.2/bin/cmake -E cmake_link_script CMakeFiles/cmTC_390ef.dir/link.txt --verbose=1
+/opt/cray/pe/craype/2.5.15/bin/ftn -v -dynamic CMakeFiles/cmTC_390ef.dir/CMakeFortranCompilerABI.F.o -o cmTC_390ef
+Driving: /opt/gcc/7.3.0/bin/../snos/bin/gfortran -march=core-avx2 -D__CRAYXC -D__CRAY_HASWELL -D__CRAYXT_COMPUTE_LINUX_TARGET -D__TARGET_LINUX__ -v CMakeFiles/cmTC_390ef.dir/CMakeFortranCompilerABI.F.o -o cmTC_390ef -Wl,-rpath=/opt/cray/pe/gcc-libs -Wl,-Bdynamic -I/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include -I/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include -I/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I/opt/cray/pe/pmi/5.0.14/include -I/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I/opt/cray-hss-devel/8.0.0/include -L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib -L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64 -L/opt/cray/pe/atp/2.1.3/libApp -Wl,--no-as-needed,-lAtpSigHandler,-lAtpSigHCommData -Wl,--undefined=_ATP_Data_Globals -Wl,--undefined=__atpHandlerInstall -lrca -Wl,--as-needed,-lsci_gnu_71_mpi,--no-as-needed -Wl,--as-needed,-lsci_gnu_71,--no-as-needed -Wl,--as-needed,-lmpich_gnu_71,--no-as-needed -Wl,--as-needed,-lmpichf90_gnu_71,--no-as-needed -Wl,--as-needed,-lgfortran,-lquadmath,--no-as-needed -Wl,--as-needed,-lpthread,--no-as-needed -l gfortran -l m -shared-libgcc
+Using built-in specs.
+COLLECT_GCC=/opt/gcc/7.3.0/bin/../snos/bin/gfortran
+COLLECT_LTO_WRAPPER=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/lto-wrapper
+Target: x86_64-suse-linux
+Configured with: ../cray-gcc-7.3.0-201801270210.d61239fc6000b/configure --prefix=/opt/gcc/7.3.0/snos --disable-nls --libdir=/opt/gcc/7.3.0/snos/lib --enable-languages=c,c++,fortran --with-gxx-include-dir=/opt/gcc/7.3.0/snos/include/g++ --with-slibdir=/opt/gcc/7.3.0/snos/lib --with-system-zlib --enable-shared --enable-__cxa_atexit --build=x86_64-suse-linux --with-ppl --with-cloog --disable-multilib
+Thread model: posix
+gcc version 7.3.0 20180125 (Cray Inc.) (GCC)
+Reading specs from /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../lib64/libgfortran.spec
+rename spec lib to liborig
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-D' '__TARGET_LINUX__' '-v' '-o' 'cmTC_390ef' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include' '-L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64' '-L/opt/cray/pe/atp/2.1.3/libApp' '-shared-libgcc'
+COMPILER_PATH=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/
+LIBRARY_PATH=/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../lib64/:/lib/../lib64/:/usr/lib/../lib64/:/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-D' '__TARGET_LINUX__' '-v' '-o' 'cmTC_390ef' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include' '-L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64' '-L/opt/cray/pe/atp/2.1.3/libApp' '-shared-libgcc'
+ /opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/collect2 -plugin /opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/liblto_plugin.so -plugin-opt=/opt/gcc/7.3.0/snos/libexec/gcc/x86_64-suse-linux/7.3.0/lto-wrapper -plugin-opt=-fresolution=/tmp/cc1AyzSl.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lquadmath -plugin-opt=-pass-through=-lm -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o cmTC_390ef /usr/lib/../lib64/crt1.o /usr/lib/../lib64/crti.o /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/crtbegin.o -L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib -L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64 -L/opt/cray/pe/atp/2.1.3/libApp -L/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0 -L/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/../../.. CMakeFiles/cmTC_390ef.dir/CMakeFortranCompilerABI.F.o -rpath=/opt/cray/pe/gcc-libs -Bdynamic --no-as-needed -lAtpSigHandler -lAtpSigHCommData --undefined=_ATP_Data_Globals --undefined=__atpHandlerInstall -lrca --as-needed -lsci_gnu_71_mpi --no-as-needed --as-needed -lsci_gnu_71 --no-as-needed --as-needed -lmpich_gnu_71 --no-as-needed --as-needed -lmpichf90_gnu_71 --no-as-needed --as-needed -lgfortran -lquadmath --no-as-needed --as-needed -lpthread --no-as-needed -lgfortran -lm -lgcc_s -lgcc -lquadmath -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/crtend.o /usr/lib/../lib64/crtn.o
+COLLECT_GCC_OPTIONS='-march=core-avx2' '-D' '__CRAYXC' '-D' '__CRAY_HASWELL' '-D' '__CRAYXT_COMPUTE_LINUX_TARGET' '-D' '__TARGET_LINUX__' '-v' '-o' 'cmTC_390ef' '-I' '/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include' '-I' '/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include' '-I' '/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include' '-I' '/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include' '-I' '/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include' '-I' '/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include' '-I' '/opt/cray/pe/pmi/5.0.14/include' '-I' '/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include' '-I' '/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include' '-I' '/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include' '-I' '/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include' '-I' '/opt/cray-hss-devel/8.0.0/include' '-L/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/dmapp/default/lib64' '-L/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/lib' '-L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64' '-L/opt/cray/pe/atp/2.1.3/libApp' '-shared-libgcc'
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-GNU-7.3.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-GNU-7.3.0.output
new file mode 100644
index 000000000..5b96c9d08
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-GNU-7.3.0.output
@@ -0,0 +1 @@
+/opt/cray/pe/libsci/18.07.1/GNU/7.1/x86_64/include;/opt/cray/pe/mpt/7.7.3/gni/mpich-gnu/7.1/include;/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include;/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include;/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include;/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include;/opt/cray/pe/pmi/5.0.14/include;/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include;/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include;/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include;/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include;/opt/cray-hss-devel/8.0.0/include;/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/finclude;/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include;/usr/local/include;/opt/gcc/7.3.0/snos/include;/opt/gcc/7.3.0/snos/lib/gcc/x86_64-suse-linux/7.3.0/include-fixed;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Intel-18.0.2.20180210.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Intel-18.0.2.20180210.input
new file mode 100644
index 000000000..4cdff74ec
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Intel-18.0.2.20180210.input
@@ -0,0 +1,80 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=ELF
+CMAKE_Fortran_COMPILER_AR=
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=Intel
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=18.0.2.20180210
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_7523d/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_7523d.dir/build.make CMakeFiles/cmTC_7523d.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.o
+/opt/cray/pe/craype/2.5.15/bin/ftn -v -c /usr/share/cmake/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.o
+ifort version 18.0.2
+/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/fpp -D__INTEL_COMPILER=1800 -D__INTEL_COMPILER_UPDATE=2 -D__unix__ -D__unix -D__linux__ -D__linux -D__gnu_linux__ -Dunix -Dlinux -D__ELF__ -D__x86_64 -D__x86_64__ -D__amd64 -D__amd64__ -D__INTEL_COMPILER_BUILD_DATE=20180210 -D__INTEL_OFFLOAD -D__pentium4 -D__pentium4__ -D__tune_pentium4__ -D__SSE2__ -D__SSE2_MATH__ -D__SSE3__ -D__SSSE3__ -D__SSE4_1__ -D__SSE4_2__ -D__SSE__ -D__SSE_MATH__ -D__MMX__ -D__AVX__ -D__AVX_I__ -D__AVX2__ -D__FMA__ -D__CRAYXC -D__CRAY_HASWELL -D__CRAYXT_COMPUTE_LINUX_TARGET -I. -I/opt/cray/pe/libsci/18.07.1/INTEL/16.0/x86_64/include -I/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/include -I/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I/opt/cray/pe/pmi/5.0.14/include -I/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I/opt/cray-hss-devel/8.0.0/include -I/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/include -I/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/intel64 -I/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/icc -I/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include -I/usr/local/include -I/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include -I/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include-fixed -I/opt/gcc/6.3.0/snos/include/ -I/usr/include -fixed -4Ycpp -4Ncvf -f_com=yes -MX /usr/share/cmake/Modules/CMakeFortranCompilerABI.F /tmp/ifortjocHCJ.i
+#include "..." search starts here:
+#include <...> search starts here:
+ .
+ /opt/cray/pe/libsci/18.07.1/INTEL/16.0/x86_64/include
+ /opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/include
+ /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include
+ /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include
+ /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include
+ /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include
+ /opt/cray/pe/pmi/5.0.14/include
+ /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include
+ /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include
+ /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include
+ /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include
+ /opt/cray-hss-devel/8.0.0/include
+ /opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/include
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/intel64
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/icc
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include
+ /usr/local/include
+ /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include
+ /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include-fixed
+ /opt/gcc/6.3.0/snos/include/
+ /usr/include
+End of search list.
+/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/fortcom -D__INTEL_COMPILER=1800 -D__INTEL_COMPILER_UPDATE=2 -D__unix__ -D__unix -D__linux__ -D__linux -D__gnu_linux__ -Dunix -Dlinux -D__ELF__ -D__x86_64 -D__x86_64__ -D__amd64 -D__amd64__ -D__INTEL_COMPILER_BUILD_DATE=20180210 -D__INTEL_OFFLOAD -D__pentium4 -D__pentium4__ -D__tune_pentium4__ -D__SSE2__ -D__SSE2_MATH__ -D__SSE3__ -D__SSSE3__ -D__SSE4_1__ -D__SSE4_2__ -D__SSE__ -D__SSE_MATH__ -D__MMX__ -D__AVX__ -D__AVX_I__ -D__AVX2__ -D__FMA__ -mGLOB_pack_sort_init_list -I/usr/share/cmake/Modules -I. -I/opt/cray/pe/libsci/18.07.1/INTEL/16.0/x86_64/include -I/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/include -I/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I/opt/cray/pe/pmi/5.0.14/include -I/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I/opt/cray-hss-devel/8.0.0/include -I/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/include -I/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/intel64 -I/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/icc -I/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include -I/usr/local/include -I/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include -I/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include-fixed -I/opt/gcc/6.3.0/snos/include/ -I/usr/include -D__CRAYXC -D__CRAY_HASWELL -D__CRAYXT_COMPUTE_LINUX_TARGET -O2 "-reentrancy none" -simd -offload_host -mGLOB_em64t=TRUE -mP1OPT_version=18.0-intel64 -mGLOB_diag_file=CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.diag -mGLOB_long_size_64 -mGLOB_routine_pointer_size_64 -mGLOB_source_language=GLOB_SOURCE_LANGUAGE_F90 -mP2OPT_static_promotion -mP1OPT_print_version=FALSE -mCG_use_gas_got_workaround=F -mP2OPT_align_option_used=TRUE -mGLOB_gcc_version=630 "-mGLOB_options_string=-I/opt/cray/pe/libsci/18.07.1/INTEL/16.0/x86_64/include -I/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/include -I/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I/opt/cray/pe/pmi/5.0.14/include -I/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I/opt/cray-hss-devel/8.0.0/include -xCORE-AVX2 -static -D__CRAYXC -D__CRAY_HASWELL -D__CRAYXT_COMPUTE_LINUX_TARGET -v -c -o CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.o" -mGLOB_cxx_limited_range=FALSE -mCG_extend_parms=FALSE -mGLOB_compiler_bin_directory=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64 -mGLOB_as_output_backup_file_name=/tmp/ifortYH2Bi3as_.s -mIPOPT_activate -mIPOPT_lite -mGLOB_instruction_tuning=0x0 -mGLOB_uarch_tuning=0x0 -mGLOB_product_id_code=0x22006d90 -mCG_bnl_movbe=T -mGLOB_extended_instructions=0x4000 -mGLOB_advanced_optim=TRUE -mP3OPT_use_mspp_call_convention -mP2OPT_subs_out_of_bound=FALSE -mP2OPT_disam_type_based_disam=2 -mGLOB_ansi_alias -mPGOPTI_value_profile_use=T -mP2OPT_il0_array_sections=TRUE -mGLOB_offload_mode=1 -mP2OPT_offload_unique_var_string=ifort0690104118gDFZUy -mP2OPT_hlo_level=2 -mP2OPT_hlo -mP2OPT_hpo_rtt_control=0 -mIPOPT_args_in_regs=0 -mP2OPT_disam_assume_nonstd_intent_in=FALSE -mGLOB_imf_mapping_library=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/libiml_attr.so -mPGOPTI_gen_threadsafe_level=0 -mIPOPT_lto_object_enabled -mIPOPT_lto_object_value=1 -mIPOPT_obj_output_file_name=CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.o -mIPOPT_whole_archive_fixup_file_name=/tmp/ifortwarch8cLx6A -mGLOB_linker_version=2.31.1.20180828 -mGLOB_driver_tempfile_name=/tmp/iforttempfiledtmF0m -mP3OPT_asm_target=P3OPT_ASM_TARGET_GAS -mGLOB_async_unwind_tables=TRUE -mGLOB_obj_output_file=CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.o -mGLOB_source_dialect=GLOB_SOURCE_DIALECT_FORTRAN -mP1OPT_source_file_name=/usr/share/cmake/Modules/CMakeFortranCompilerABI.F -mP1OPT_full_source_file_name=/usr/share/cmake/Modules/CMakeFortranCompilerABI.F -mP2OPT_symtab_type_copy=true /tmp/ifortjocHCJ.i
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/share/cmake/Modules
+ .
+ /opt/cray/pe/libsci/18.07.1/INTEL/16.0/x86_64/include
+ /opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/include
+ /opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include
+ /opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include
+ /opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include
+ /opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include
+ /opt/cray/pe/pmi/5.0.14/include
+ /opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include
+ /opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include
+ /opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include
+ /opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include
+ /opt/cray-hss-devel/8.0.0/include
+ /opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/include
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/intel64
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/icc
+ /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include
+ /usr/local/include
+ /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include
+ /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include-fixed
+ /opt/gcc/6.3.0/snos/include/
+ /usr/include
+End of search list.
+Linking Fortran executable cmTC_7523d
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_7523d.dir/link.txt --verbose=1
+/opt/cray/pe/craype/2.5.15/bin/ftn -v CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.o -o cmTC_7523d
+ifort version 18.0.2
+/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/fortcom -mGLOB_em64t=TRUE -mP1OPT_version=18.0-intel64 -mGLOB_diag_file=CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.diag -mGLOB_long_size_64 -mGLOB_routine_pointer_size_64 -mGLOB_source_language=GLOB_SOURCE_LANGUAGE_F90 -mP2OPT_static_promotion -mP1OPT_print_version=FALSE -mCG_use_gas_got_workaround=F -mP2OPT_align_option_used=TRUE -mGLOB_gcc_version=630 "-mGLOB_options_string=-I/opt/cray/pe/libsci/18.07.1/INTEL/16.0/x86_64/include -I/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/include -I/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include -I/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include -I/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include -I/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include -I/opt/cray/pe/pmi/5.0.14/include -I/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include -I/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include -I/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include -I/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include -I/opt/cray-hss-devel/8.0.0/include -xCORE-AVX2 -static -D__CRAYXC -D__CRAY_HASWELL -D__CRAYXT_COMPUTE_LINUX_TARGET -v -o cmTC_7523d -L/opt/cray/pe/libsci/18.07.1/INTEL/16.0/x86_64/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/lib -L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64 -L/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64 -L/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64 -L/opt/cray/pe/pmi/5.0.14/lib64 -L/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64 -L/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64 -L/opt/cray/pe/atp/2.1.3/libApp -L/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64 -Wl,-Ttext-segment=0x20000000,-zmax-page-size=0x20000000 -Wl,--whole-archive,-lhugetlbfs,--no-whole-archive -Wl,--no-as-needed,-lAtpSigHandler,-lAtpSigHCommData -Wl,--undefined=_ATP_Data_Globals -Wl,--undefined=__atpHandlerInstall -lpthread -lmpichf90_intel -lrt -lugni -lpmi -lm -lpthread -ldl -lsci_intel_mpi -lsci_intel -lm -ldl -lmpich_intel -lrt -lugni -lpthread -lpmi -lm -ldl -lpmi -lpthread -lalpslli -lpthread -lwlm_detect -lalpsutil -lpthread -lrca -lxpmem -lugni -lpthread -ludreg -lsci_intel -lm -lpthread -ldl -lhugetlbfs -Wl,--as-needed,-limf,--no-as-needed -Wl,--as-needed,-lm,--no-as-needed -Wl,--as-needed,-lpthread,--no-as-needed" -mGLOB_cxx_limited_range=FALSE -mCG_extend_parms=FALSE -mGLOB_compiler_bin_directory=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64 -mGLOB_as_output_backup_file_name=/tmp/ifort3JZMSVas_.s -mGLOB_dashboard_use_source_name -mIPOPT_activate -mGLOB_product_id_code=0x22006d90 -mGLOB_extended_instructions=0x4000 -mGLOB_advanced_optim=TRUE -mP3OPT_use_mspp_call_convention -mP2OPT_subs_out_of_bound=FALSE -mP2OPT_disam_type_based_disam=2 -mGLOB_ansi_alias -mPGOPTI_value_profile_use=T -mGLOB_opt_report_use_source_name -mP2OPT_il0_array_sections=TRUE -mGLOB_offload_mode=1 -mP2OPT_offload_unique_var_string=ifort0690373519HAIHNw -mP2OPT_hlo -mP2OPT_hpo_rtt_control=0 -mIPOPT_args_in_regs=0 -mP2OPT_disam_assume_nonstd_intent_in=FALSE -mGLOB_imf_mapping_library=/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/bin/intel64/libiml_attr.so -mPGOPTI_gen_threadsafe_level=0 -mIPOPT_link -mIPOPT_ipo_activate -mIPOPT_mo_activate -mIPOPT_source_files_list=/tmp/ifortslis6v0DlA -mIPOPT_mo_global_data -mIPOPT_link_script_file=/tmp/ifortscriptsKB8Qm "-mIPOPT_cmdline_link="/usr/lib/../lib64/crt1.o" "/usr/lib/../lib64/crti.o" "/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtbeginT.o" "--build-id" "-static" "-m" "elf_x86_64" "-L/opt/cray/pe/libsci/18.07.1/INTEL/16.0/x86_64/lib" "-L/opt/cray/dmapp/default/lib64" "-L/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/lib" "-L/opt/cray/dmapp/default/lib64" "-L/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/lib" "-L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64" "-L/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64" "-L/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64" "-L/opt/cray/pe/pmi/5.0.14/lib64" "-L/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64" "-L/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64" "-L/opt/cray/pe/atp/2.1.3/libApp" "-L/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64" "-o" "cmTC_7523d" "/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin/for_main.o" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64/" "-L/lib/../lib64" "-L/lib/../lib64/" "-L/usr/lib/../lib64" "-L/usr/lib/../lib64/" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64/" "-L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../" "-L/lib64" "-L/lib/" "-L/usr/lib64" "-L/usr/lib" "CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.o" "-Ttext-segment=0x20000000" "-zmax-page-size=0x20000000" "--whole-archive" "-lhugetlbfs" "--no-whole-archive" "--no-as-needed" "-lAtpSigHandler" "-lAtpSigHCommData" "--undefined=_ATP_Data_Globals" "--undefined=__atpHandlerInstall" "-lpthread" "-lmpichf90_intel" "-lrt" "-lugni" "-lpmi" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin" "-limf" "-lm" "-lpthread" "-ldl" "-lsci_intel_mpi" "-lsci_intel" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin" "-limf" "-lm" "-ldl" "-lmpich_intel" "-lrt" "-lugni" "-lpthread" "-lpmi" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin" "-limf" "-lm" "-ldl" "-lpmi" "-lpthread" "-lalpslli" "-lpthread" "-lwlm_detect" "-lalpsutil" "-lpthread" "-lrca" "-lxpmem" "-lugni" "-lpthread" "-ludreg" "-lsci_intel" "-L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin" "-limf" "-lm" "-lpthread" "-ldl" "-lhugetlbfs" "--as-needed" "-limf" "--no-as-needed" "--as-needed" "-lm" "--no-as-needed" "--as-needed" "-lpthread" "--no-as-needed" "-lifport" "-lifcore" "-limf" "-lsvml" "-lm" "-lipgo" "-lirc" "-lsvml" "-lc" "-lgcc" "-lgcc_eh" "-lirc_s" "-ldl" "-lc" "/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtend.o" "/usr/lib/../lib64/crtn.o"" -mIPOPT_il_in_obj -mIPOPT_ipo_activate_warn=FALSE -mIPOPT_obj_output_file_name=/tmp/ipo_ifort5KgIiT.o -mIPOPT_whole_archive_fixup_file_name=/tmp/ifortwarchltBXsh -mGLOB_linker_version=2.31.1.20180828 -mGLOB_driver_tempfile_name=/tmp/iforttempfilesugt03 -mP3OPT_asm_target=P3OPT_ASM_TARGET_GAS -mGLOB_async_unwind_tables=TRUE -mGLOB_obj_output_file=/tmp/ipo_ifort5KgIiT.o -mGLOB_source_dialect=GLOB_SOURCE_DIALECT_NONE -mP1OPT_source_file_name=ipo_out.f -mP2OPT_symtab_type_copy=true CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.o -mIPOPT_object_files=T -mIPOPT_assembly_files=/tmp/ifortalisCY2Fjs -mIPOPT_generated_tempfiles=/tmp/ifortelisXEqaPe -mIPOPT_embedded_object_base_name=/tmp/iforteobjRoVEk1 -mIPOPT_cmdline_link_new_name=/tmp/ifortllisJHg9PN
+ld /usr/lib/../lib64/crt1.o /usr/lib/../lib64/crti.o /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtbeginT.o --build-id -static -m elf_x86_64 -L/opt/cray/pe/libsci/18.07.1/INTEL/16.0/x86_64/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/lib -L/opt/cray/dmapp/default/lib64 -L/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/lib -L/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/lib64 -L/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/lib64 -L/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/lib64 -L/opt/cray/pe/pmi/5.0.14/lib64 -L/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/lib64 -L/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/lib64 -L/opt/cray/pe/atp/2.1.3/libApp -L/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/lib64 -o cmTC_7523d /opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin/for_main.o -L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64 -L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/ -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64 -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../../lib64/ -L/lib/../lib64 -L/lib/../lib64/ -L/usr/lib/../lib64 -L/usr/lib/../lib64/ -L/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/lib/intel64/ -L/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/../../../ -L/lib64 -L/lib/ -L/usr/lib64 -L/usr/lib CMakeFiles/cmTC_7523d.dir/CMakeFortranCompilerABI.F.o -Ttext-segment=0x20000000 -zmax-page-size=0x20000000 --whole-archive -lhugetlbfs --no-whole-archive --no-as-needed -lAtpSigHandler -lAtpSigHCommData --undefined=_ATP_Data_Globals --undefined=__atpHandlerInstall -lpthread -lmpichf90_intel -lrt -lugni -lpmi -L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin -limf -lm -lpthread -ldl -lsci_intel_mpi -lsci_intel -L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin -limf -lm -ldl -lmpich_intel -lrt -lugni -lpthread -lpmi -L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin -limf -lm -ldl -lpmi -lpthread -lalpslli -lpthread -lwlm_detect -lalpsutil -lpthread -lrca -lxpmem -lugni -lpthread -ludreg -lsci_intel -L/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/lib/intel64_lin -limf -lm -lpthread -ldl -lhugetlbfs --as-needed -limf --no-as-needed --as-needed -lm --no-as-needed --as-needed -lpthread --no-as-needed -lifport -lifcore -limf -lsvml -lm -lipgo -lirc -lsvml -lc -lgcc -lgcc_eh -lirc_s -ldl -lc /opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/crtend.o /usr/lib/../lib64/crtn.o
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Intel-18.0.2.20180210.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Intel-18.0.2.20180210.output
new file mode 100644
index 000000000..8e484bca6
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/craype-Fortran-Intel-18.0.2.20180210.output
@@ -0,0 +1 @@
+/opt/cray/pe/libsci/18.07.1/INTEL/16.0/x86_64/include;/opt/cray/pe/mpt/7.7.3/gni/mpich-intel/16.0/include;/opt/cray/rca/2.2.16-6.0.5.0_15.34__g5e09e6d.ari/include;/opt/cray/alps/6.5.28-6.0.5.0_18.6__g13a91b6.ari/include;/opt/cray/xpmem/2.2.4-6.0.5.1_8.26__g35d5e73.ari/include;/opt/cray/gni-headers/5.0.12-6.0.5.0_2.15__g2ef1ebc.ari/include;/opt/cray/pe/pmi/5.0.14/include;/opt/cray/ugni/6.0.14-6.0.5.0_16.9__g19583bb.ari/include;/opt/cray/udreg/2.3.2-6.0.5.0_13.12__ga14955a.ari/include;/opt/cray/wlm_detect/1.3.2-6.0.5.0_3.1__g388ccd5.ari/include;/opt/cray/krca/2.2.2-6.0.5.1_13.47__g4614cf3.ari/include;/opt/cray-hss-devel/8.0.0/include;/opt/intel/2018.2.199/compilers_and_libraries_2018/linux/mkl/include;/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/intel64;/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include/icc;/opt/intel/2018.2.199/compilers_and_libraries_2018.2.199/linux/compiler/include;/usr/local/include;/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include;/opt/gcc/6.3.0/snos/lib/gcc/x86_64-suse-linux/6.3.0/include-fixed;/opt/gcc/6.3.0/snos/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-C-AppleClang-8.0.0.8000042.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-C-AppleClang-8.0.0.8000042.input
new file mode 100644
index 000000000..4bc26bcba
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-C-AppleClang-8.0.0.8000042.input
@@ -0,0 +1,50 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=AppleClang
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=8.0.0.8000042
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_0c33e/fast"
+/Applications/Xcode.app/Contents/Developer/usr/bin/make -f CMakeFiles/cmTC_0c33e.dir/build.make CMakeFiles/cmTC_0c33e.dir/build
+Building C object CMakeFiles/cmTC_0c33e.dir/CMakeCCompilerABI.c.o
+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -v -Wl,-v -o CMakeFiles/cmTC_0c33e.dir/CMakeCCompilerABI.c.o -c /usr/local/pkg.1804/share/cmake-3.10/Modules/CMakeCCompilerABI.c
+Apple LLVM version 8.0.0 (clang-800.0.42.1)
+Target: x86_64-apple-darwin15.6.0
+Thread model: posix
+InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
+clang: warning: -Wl,-v: 'linker' input unused
+ "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.11.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCCompilerABI.c -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 274.2 -v -dwarf-column-info -debugger-tuning=lldb -coverage-file /private/tmp/ii/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_0c33e.dir/CMakeCCompilerABI.c.o -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0 -fdebug-compilation-dir /private/tmp/ii/CMakeFiles/CMakeTmp -ferror-limit 19 -fmessage-length 0 -stack-protector 1 -fblocks -fobjc-runtime=macosx-10.11.0 -fencode-extended-block-signature -fmax-type-align=16 -fdiagnostics-show-option -o CMakeFiles/cmTC_0c33e.dir/CMakeCCompilerABI.c.o -x c /usr/local/pkg.1804/share/cmake-3.10/Modules/CMakeCCompilerABI.c
+clang -cc1 version 8.0.0 (clang-800.0.42.1) default target x86_64-apple-darwin15.6.0
+ignoring nonexistent directory "/usr/local/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0/include
+ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
+ /usr/include
+ /System/Library/Frameworks (framework directory)
+ /Library/Frameworks (framework directory)
+End of search list.
+Linking C executable cmTC_0c33e
+/usr/local/pkg.1804/bin/cmake -E cmake_link_script CMakeFiles/cmTC_0c33e.dir/link.txt --verbose=1
+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_0c33e.dir/CMakeCCompilerABI.c.o -o cmTC_0c33e
+Apple LLVM version 8.0.0 (clang-800.0.42.1)
+Target: x86_64-apple-darwin15.6.0
+Thread model: posix
+InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
+ "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -dynamic -arch x86_64 -macosx_version_min 10.11.0 -o cmTC_0c33e -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_0c33e.dir/CMakeCCompilerABI.c.o -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0/lib/darwin/libclang_rt.osx.a
+@(#)PROGRAM:ld PROJECT:ld64-274.2
+configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em (tvOS)
+Library search paths:
+ /usr/lib
+ /usr/local/lib
+Framework search paths:
+ /Library/Frameworks/
+ /System/Library/Frameworks/
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-C-AppleClang-8.0.0.8000042.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-C-AppleClang-8.0.0.8000042.output
new file mode 100644
index 000000000..20f9b0e94
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-C-AppleClang-8.0.0.8000042.output
@@ -0,0 +1 @@
+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/8.0.0/include;/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-CXX-AppleClang-8.0.0.8000042.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-CXX-AppleClang-8.0.0.8000042.input
new file mode 100644
index 000000000..907a92e24
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-CXX-AppleClang-8.0.0.8000042.input
@@ -0,0 +1,52 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=AppleClang
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=8.0.0.8000042
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_b7e96/fast"
+/Applications/Xcode.app/Contents/Developer/usr/bin/make -f CMakeFiles/cmTC_b7e96.dir/build.make CMakeFiles/cmTC_b7e96.dir/build
+Building CXX object CMakeFiles/cmTC_b7e96.dir/CMakeCXXCompilerABI.cpp.o
+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -v -Wl,-v -o CMakeFiles/cmTC_b7e96.dir/CMakeCXXCompilerABI.cpp.o -c /usr/local/pkg.1804/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp
+Apple LLVM version 8.0.0 (clang-800.0.42.1)
+Target: x86_64-apple-darwin15.6.0
+Thread model: posix
+InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
+clang: warning: -Wl,-v: 'linker' input unused
+ "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.11.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 274.2 -v -dwarf-column-info -debugger-tuning=lldb -coverage-file /private/tmp/ii/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_b7e96.dir/CMakeCXXCompilerABI.cpp.o -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0 -stdlib=libc++ -fdeprecated-macro -fdebug-compilation-dir /private/tmp/ii/CMakeFiles/CMakeTmp -ferror-limit 19 -fmessage-length 0 -stack-protector 1 -fblocks -fobjc-runtime=macosx-10.11.0 -fencode-extended-block-signature -fcxx-exceptions -fexceptions -fmax-type-align=16 -fdiagnostics-show-option -o CMakeFiles/cmTC_b7e96.dir/CMakeCXXCompilerABI.cpp.o -x c++ /usr/local/pkg.1804/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp
+clang -cc1 version 8.0.0 (clang-800.0.42.1) default target x86_64-apple-darwin15.6.0
+ignoring nonexistent directory "/usr/include/c++/v1"
+ignoring nonexistent directory "/usr/local/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1
+ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0/include
+ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
+ /usr/include
+ /System/Library/Frameworks (framework directory)
+ /Library/Frameworks (framework directory)
+End of search list.
+Linking CXX executable cmTC_b7e96
+/usr/local/pkg.1804/bin/cmake -E cmake_link_script CMakeFiles/cmTC_b7e96.dir/link.txt --verbose=1
+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -Wl,-search_paths_first -Wl,-headerpad_max_install_names -v -Wl,-v CMakeFiles/cmTC_b7e96.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_b7e96
+Apple LLVM version 8.0.0 (clang-800.0.42.1)
+Target: x86_64-apple-darwin15.6.0
+Thread model: posix
+InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
+ "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -dynamic -arch x86_64 -macosx_version_min 10.11.0 -o cmTC_b7e96 -search_paths_first -headerpad_max_install_names -v CMakeFiles/cmTC_b7e96.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0/lib/darwin/libclang_rt.osx.a
+@(#)PROGRAM:ld PROJECT:ld64-274.2
+configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em (tvOS)
+Library search paths:
+ /usr/lib
+ /usr/local/lib
+Framework search paths:
+ /Library/Frameworks/
+ /System/Library/Frameworks/
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-CXX-AppleClang-8.0.0.8000042.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-CXX-AppleClang-8.0.0.8000042.output
new file mode 100644
index 000000000..de0f91f43
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin-CXX-AppleClang-8.0.0.8000042.output
@@ -0,0 +1 @@
+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c\+\+/v1;/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/8.0.0/include;/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-C-AppleClang-8.0.0.8000042.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-C-AppleClang-8.0.0.8000042.input
new file mode 100644
index 000000000..effaedf55
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-C-AppleClang-8.0.0.8000042.input
@@ -0,0 +1,44 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=AppleClang
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=8.0.0.8000042
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_ba7aa/fast"
+/Applications/Xcode.app/Contents/Developer/usr/bin/make -f CMakeFiles/cmTC_ba7aa.dir/build.make CMakeFiles/cmTC_ba7aa.dir/build
+Building C object CMakeFiles/cmTC_ba7aa.dir/CMakeCCompilerABI.c.o
+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -nostdinc -v -Wl,-v -o CMakeFiles/cmTC_ba7aa.dir/CMakeCCompilerABI.c.o -c /usr/local/pkg.1804/share/cmake-3.10/Modules/CMakeCCompilerABI.c
+Apple LLVM version 8.0.0 (clang-800.0.42.1)
+Target: x86_64-apple-darwin15.6.0
+Thread model: posix
+InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
+clang: warning: -Wl,-v: 'linker' input unused
+ "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.11.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCCompilerABI.c -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 274.2 -v -dwarf-column-info -debugger-tuning=lldb -coverage-file /private/tmp/ii/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_ba7aa.dir/CMakeCCompilerABI.c.o -nostdsysteminc -nobuiltininc -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0 -fdebug-compilation-dir /private/tmp/ii/CMakeFiles/CMakeTmp -ferror-limit 19 -fmessage-length 0 -stack-protector 1 -fblocks -fobjc-runtime=macosx-10.11.0 -fencode-extended-block-signature -fmax-type-align=16 -fdiagnostics-show-option -o CMakeFiles/cmTC_ba7aa.dir/CMakeCCompilerABI.c.o -x c /usr/local/pkg.1804/share/cmake-3.10/Modules/CMakeCCompilerABI.c
+clang -cc1 version 8.0.0 (clang-800.0.42.1) default target x86_64-apple-darwin15.6.0
+#include "..." search starts here:
+End of search list.
+Linking C executable cmTC_ba7aa
+/usr/local/pkg.1804/bin/cmake -E cmake_link_script CMakeFiles/cmTC_ba7aa.dir/link.txt --verbose=1
+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -nostdinc -v -Wl,-v -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/cmTC_ba7aa.dir/CMakeCCompilerABI.c.o -o cmTC_ba7aa
+Apple LLVM version 8.0.0 (clang-800.0.42.1)
+Target: x86_64-apple-darwin15.6.0
+Thread model: posix
+InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
+clang: warning: argument unused during compilation: '-nostdinc'
+ "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -dynamic -arch x86_64 -macosx_version_min 10.11.0 -o cmTC_ba7aa -v -search_paths_first -headerpad_max_install_names CMakeFiles/cmTC_ba7aa.dir/CMakeCCompilerABI.c.o -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0/lib/darwin/libclang_rt.osx.a
+@(#)PROGRAM:ld PROJECT:ld64-274.2
+configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em (tvOS)
+Library search paths:
+ /usr/lib
+ /usr/local/lib
+Framework search paths:
+ /Library/Frameworks/
+ /System/Library/Frameworks/
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-C-AppleClang-8.0.0.8000042.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-C-AppleClang-8.0.0.8000042.output
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-C-AppleClang-8.0.0.8000042.output
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-CXX-AppleClang-8.0.0.8000042.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-CXX-AppleClang-8.0.0.8000042.input
new file mode 100644
index 000000000..5504e9472
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-CXX-AppleClang-8.0.0.8000042.input
@@ -0,0 +1,44 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=AppleClang
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=8.0.0.8000042
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_638bd/fast"
+/Applications/Xcode.app/Contents/Developer/usr/bin/make -f CMakeFiles/cmTC_638bd.dir/build.make CMakeFiles/cmTC_638bd.dir/build
+Building CXX object CMakeFiles/cmTC_638bd.dir/CMakeCXXCompilerABI.cpp.o
+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -nostdinc -v -Wl,-v -o CMakeFiles/cmTC_638bd.dir/CMakeCXXCompilerABI.cpp.o -c /usr/local/pkg.1804/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp
+Apple LLVM version 8.0.0 (clang-800.0.42.1)
+Target: x86_64-apple-darwin15.6.0
+Thread model: posix
+InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
+clang: warning: -Wl,-v: 'linker' input unused
+ "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.11.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 274.2 -v -dwarf-column-info -debugger-tuning=lldb -coverage-file /private/tmp/ii/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_638bd.dir/CMakeCXXCompilerABI.cpp.o -nostdsysteminc -nobuiltininc -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0 -stdlib=libc++ -fdeprecated-macro -fdebug-compilation-dir /private/tmp/ii/CMakeFiles/CMakeTmp -ferror-limit 19 -fmessage-length 0 -stack-protector 1 -fblocks -fobjc-runtime=macosx-10.11.0 -fencode-extended-block-signature -fcxx-exceptions -fexceptions -fmax-type-align=16 -fdiagnostics-show-option -o CMakeFiles/cmTC_638bd.dir/CMakeCXXCompilerABI.cpp.o -x c++ /usr/local/pkg.1804/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp
+clang -cc1 version 8.0.0 (clang-800.0.42.1) default target x86_64-apple-darwin15.6.0
+#include "..." search starts here:
+End of search list.
+Linking CXX executable cmTC_638bd
+/usr/local/pkg.1804/bin/cmake -E cmake_link_script CMakeFiles/cmTC_638bd.dir/link.txt --verbose=1
+/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -nostdinc -v -Wl,-v -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/cmTC_638bd.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_638bd
+Apple LLVM version 8.0.0 (clang-800.0.42.1)
+Target: x86_64-apple-darwin15.6.0
+Thread model: posix
+InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
+clang: warning: argument unused during compilation: '-nostdinc'
+ "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -dynamic -arch x86_64 -macosx_version_min 10.11.0 -o cmTC_638bd -v -search_paths_first -headerpad_max_install_names CMakeFiles/cmTC_638bd.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/8.0.0/lib/darwin/libclang_rt.osx.a
+@(#)PROGRAM:ld PROJECT:ld64-274.2
+configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em (tvOS)
+Library search paths:
+ /usr/lib
+ /usr/local/lib
+Framework search paths:
+ /Library/Frameworks/
+ /System/Library/Frameworks/
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-CXX-AppleClang-8.0.0.8000042.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-CXX-AppleClang-8.0.0.8000042.output
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/darwin_nostdinc-CXX-AppleClang-8.0.0.8000042.output
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-C-Clang-3.3.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-C-Clang-3.3.0.input
new file mode 100644
index 000000000..81626f932
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-C-Clang-3.3.0.input
@@ -0,0 +1,38 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=Clang
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=3.3.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/local/bin/gmake" "cmTC_0c44b/fast"
+/usr/local/bin/gmake -f CMakeFiles/cmTC_0c44b.dir/build.make CMakeFiles/cmTC_0c44b.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_0c44b.dir/CMakeCCompilerABI.c.o
+/usr/bin/cc -v -o CMakeFiles/cmTC_0c44b.dir/CMakeCCompilerABI.c.o -c /usr/local/share/cmake-3.7/Modules/CMakeCCompilerABI.c
+FreeBSD clang version 3.3 (tags/RELEASE_33/final 183502) 20130610
+Target: x86_64-unknown-freebsd10.0
+Thread model: posix
+ "/usr/bin/cc" -cc1 -triple x86_64-unknown-freebsd10.0 -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -main-file-name CMakeCCompilerABI.c -mrelocation-model static -mdisable-fp-elim -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -v -coverage-file /tmp/ii/CMakeFiles/cmTC_0c44b.dir/CMakeCCompilerABI.c.o -resource-dir /usr/bin/../lib/clang/3.3 -fdebug-compilation-dir /tmp/ii/CMakeFiles/CMakeTmp -ferror-limit 19 -fmessage-length 0 -mstackrealign -fobjc-runtime=gnustep -fobjc-default-synthesize-properties -fdiagnostics-show-option -backend-option -vectorize-loops -o CMakeFiles/cmTC_0c44b.dir/CMakeCCompilerABI.c.o -x c /usr/local/share/cmake-3.7/Modules/CMakeCCompilerABI.c
+clang -cc1 version 3.3 based upon LLVM 3.3 default target x86_64-unknown-freebsd10.0
+ignoring nonexistent directory "/usr/bin/../lib/clang/3.3/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/include/clang/3.3
+ /usr/include
+End of search list.
+Linking C executable cmTC_0c44b
+/usr/local/bin/cmake -E cmake_link_script CMakeFiles/cmTC_0c44b.dir/link.txt --verbose=1
+/usr/bin/cc -v CMakeFiles/cmTC_0c44b.dir/CMakeCCompilerABI.c.o -o cmTC_0c44b
+FreeBSD clang version 3.3 (tags/RELEASE_33/final 183502) 20130610
+Target: x86_64-unknown-freebsd10.0
+Thread model: posix
+ "/usr/bin/ld" --eh-frame-hdr -dynamic-linker /libexec/ld-elf.so.1 --hash-style=both --enable-new-dtags -o cmTC_0c44b /usr/lib/crt1.o /usr/lib/crti.o /usr/lib/crtbegin.o -L/usr/lib CMakeFiles/cmTC_0c44b.dir/CMakeCCompilerABI.c.o -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /usr/lib/crtend.o /usr/lib/crtn.o
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-C-Clang-3.3.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-C-Clang-3.3.0.output
new file mode 100644
index 000000000..893ec4972
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-C-Clang-3.3.0.output
@@ -0,0 +1 @@
+/usr/include/clang/3.3;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-CXX-Clang-3.3.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-CXX-Clang-3.3.0.input
new file mode 100644
index 000000000..1f7758b17
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-CXX-Clang-3.3.0.input
@@ -0,0 +1,45 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=Clang
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=3.3.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/local/bin/gmake" "cmTC_c3442/fast"
+/usr/local/bin/gmake -f CMakeFiles/cmTC_c3442.dir/build.make CMakeFiles/cmTC_c3442.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_c3442.dir/CMakeCXXCompilerABI.cpp.o
+/usr/bin/CC -v -o CMakeFiles/cmTC_c3442.dir/CMakeCXXCompilerABI.cpp.o -c /usr/local/share/cmake-3.7/Modules/CMakeCXXCompilerABI.cpp
+FreeBSD clang version 3.3 (tags/RELEASE_33/final 183502) 20130610
+Target: x86_64-unknown-freebsd10.0
+Thread model: posix
+ "/usr/bin/CC" -cc1 -triple x86_64-unknown-freebsd10.0 -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model static -mdisable-fp-elim -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -v -coverage-file /tmp/ii/CMakeFiles/cmTC_c3442.dir/CMakeCXXCompilerABI.cpp.o -resource-dir /usr/bin/../lib/clang/3.3 -internal-isystem /usr/include/c++/v1 -fdeprecated-macro -fdebug-compilation-dir /tmp/ii/CMakeFiles/CMakeTmp -ferror-limit 19 -fmessage-length 0 -mstackrealign -fobjc-runtime=gnustep -fobjc-default-synthesize-properties -fcxx-exceptions -fexceptions -fdiagnostics-show-option -backend-option -vectorize-loops -o CMakeFiles/cmTC_c3442.dir/CMakeCXXCompilerABI.cpp.o -x c++ /usr/local/share/cmake-3.7/Modules/CMakeCXXCompilerABI.cpp
+clang -cc1 version 3.3 based upon LLVM 3.3 default target x86_64-unknown-freebsd10.0
+ignoring nonexistent directory "/usr/include/c++/4.2/backward/backward"
+ignoring nonexistent directory "/usr/bin/../lib/clang/3.3/include"
+ignoring duplicate directory "/usr/include/c++/4.2"
+ignoring duplicate directory "/usr/include/c++/4.2/backward"
+ignoring duplicate directory "/usr/include/c++/4.2/backward"
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/include/c++/v1
+ /usr/include/c++/4.2
+ /usr/include/c++/4.2/backward
+ /usr/include/clang/3.3
+ /usr/include
+End of search list.
+Linking CXX executable cmTC_c3442
+/usr/local/bin/cmake -E cmake_link_script CMakeFiles/cmTC_c3442.dir/link.txt --verbose=1
+/usr/bin/CC -v CMakeFiles/cmTC_c3442.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_c3442
+FreeBSD clang version 3.3 (tags/RELEASE_33/final 183502) 20130610
+Target: x86_64-unknown-freebsd10.0
+Thread model: posix
+ "/usr/bin/ld" --eh-frame-hdr -dynamic-linker /libexec/ld-elf.so.1 --hash-style=both --enable-new-dtags -o cmTC_c3442 /usr/lib/crt1.o /usr/lib/crti.o /usr/lib/crtbegin.o -L/usr/lib CMakeFiles/cmTC_c3442.dir/CMakeCXXCompilerABI.cpp.o -lc++ -lm -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /usr/lib/crtend.o /usr/lib/crtn.o
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-CXX-Clang-3.3.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-CXX-Clang-3.3.0.output
new file mode 100644
index 000000000..97410f20a
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-CXX-Clang-3.3.0.output
@@ -0,0 +1 @@
+/usr/include/c\+\+/v1;/usr/include/c\+\+/4.2;/usr/include/c\+\+/4.2/backward;/usr/include/clang/3.3;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-Fortran-GNU-4.6.4.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-Fortran-GNU-4.6.4.input
new file mode 100644
index 000000000..8a5d7411a
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-Fortran-GNU-4.6.4.input
@@ -0,0 +1,78 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=
+CMAKE_Fortran_COMPILER_AR=
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=GNU
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=4.6.4
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/local/bin/gmake" "cmTC_9ec75/fast"
+/usr/local/bin/gmake -f CMakeFiles/cmTC_9ec75.dir/build.make CMakeFiles/cmTC_9ec75.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_9ec75.dir/CMakeFortranCompilerABI.F.o
+/usr/local/bin/gfortran46 -v -c /usr/local/share/cmake-3.7/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_9ec75.dir/CMakeFortranCompilerABI.F.o
+Using built-in specs.
+COLLECT_GCC=/usr/local/bin/gfortran46
+COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/lto-wrapper
+Target: x86_64-portbld-freebsd10.0
+Configured with: ./../gcc-4.6.4/configure --disable-bootstrap --disable-nls --libdir=/usr/local/lib/gcc46 --libexecdir=/usr/local/libexec/gcc46 --program-suffix=46 --with-as=/usr/local/bin/as --with-gmp=/usr/local --with-gxx-include-dir=/usr/local/lib/gcc46/include/c++/ --with-ld=/usr/local/bin/ld --with-pkgversion='FreeBSD Ports Collection' --with-system-zlib --disable-libgcj --enable-languages=c,c++,objc,fortran --prefix=/usr/local --mandir=/usr/local/man --infodir=/usr/local/info/gcc46 --build=x86_64-portbld-freebsd10.0
+Thread model: posix
+gcc version 4.6.4 (FreeBSD Ports Collection)
+COLLECT_GCC_OPTIONS='-v' '-c' '-o' 'CMakeFiles/cmTC_9ec75.dir/CMakeFortranCompilerABI.F.o' '-mtune=generic' '-march=x86-64'
+ /usr/local/libexec/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/f951 /usr/local/share/cmake-3.7/Modules/CMakeFortranCompilerABI.F -ffixed-form -cpp=/tmp//ccp5PsLd.f90 -quiet -v /usr/local/share/cmake-3.7/Modules/CMakeFortranCompilerABI.F -quiet -dumpbase CMakeFortranCompilerABI.F -mtune=generic -march=x86-64 -auxbase-strip CMakeFiles/cmTC_9ec75.dir/CMakeFortranCompilerABI.F.o -version -fintrinsic-modules-path /usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/finclude -o /tmp//ccGWxrQ5.s
+GNU Fortran (FreeBSD Ports Collection) version 4.6.4 (x86_64-portbld-freebsd10.0)
+ compiled by GNU C version 4.2.1 Compatible FreeBSD Clang 3.3 (tags/RELEASE_33/final 183502), GMP version 5.1.3, MPFR version 3.1.2, MPC version 1.0.1
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+ignoring nonexistent directory "/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/../../../../../x86_64-portbld-freebsd10.0/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/finclude
+ /usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/include
+ /usr/local/include
+ /usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/include-fixed
+ /usr/include
+End of search list.
+GNU Fortran (FreeBSD Ports Collection) version 4.6.4 (x86_64-portbld-freebsd10.0)
+ compiled by GNU C version 4.2.1 Compatible FreeBSD Clang 3.3 (tags/RELEASE_33/final 183502), GMP version 5.1.3, MPFR version 3.1.2, MPC version 1.0.1
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+COLLECT_GCC_OPTIONS='-v' '-c' '-o' 'CMakeFiles/cmTC_9ec75.dir/CMakeFortranCompilerABI.F.o' '-mtune=generic' '-march=x86-64'
+ /usr/local/bin/as -v -o CMakeFiles/cmTC_9ec75.dir/CMakeFortranCompilerABI.F.o /tmp//ccGWxrQ5.s
+GNU assembler version 2.23.2 (x86_64-portbld-freebsd10.0) using BFD version (GNU Binutils) 2.23.2
+COMPILER_PATH=/usr/local/libexec/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/:/usr/local/libexec/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/:/usr/local/libexec/gcc46/gcc/x86_64-portbld-freebsd10.0/:/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/:/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/:/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/../../../../../x86_64-portbld-freebsd10.0/bin/
+LIBRARY_PATH=/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/:/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/../../../../../x86_64-portbld-freebsd10.0/lib/:/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-c' '-o' 'CMakeFiles/cmTC_9ec75.dir/CMakeFortranCompilerABI.F.o' '-mtune=generic' '-march=x86-64'
+Linking Fortran executable cmTC_9ec75
+/usr/local/bin/cmake -E cmake_link_script CMakeFiles/cmTC_9ec75.dir/link.txt --verbose=1
+/usr/local/bin/gfortran46 -v CMakeFiles/cmTC_9ec75.dir/CMakeFortranCompilerABI.F.o -o cmTC_9ec75
+Driving: /usr/local/bin/gfortran46 -v CMakeFiles/cmTC_9ec75.dir/CMakeFortranCompilerABI.F.o -o cmTC_9ec75 -l gfortran -l m -shared-libgcc
+Using built-in specs.
+COLLECT_GCC=/usr/local/bin/gfortran46
+COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/lto-wrapper
+Target: x86_64-portbld-freebsd10.0
+Configured with: ./../gcc-4.6.4/configure --disable-bootstrap --disable-nls --libdir=/usr/local/lib/gcc46 --libexecdir=/usr/local/libexec/gcc46 --program-suffix=46 --with-as=/usr/local/bin/as --with-gmp=/usr/local --with-gxx-include-dir=/usr/local/lib/gcc46/include/c++/ --with-ld=/usr/local/bin/ld --with-pkgversion='FreeBSD Ports Collection' --with-system-zlib --disable-libgcj --enable-languages=c,c++,objc,fortran --prefix=/usr/local --mandir=/usr/local/man --infodir=/usr/local/info/gcc46 --build=x86_64-portbld-freebsd10.0
+Thread model: posix
+gcc version 4.6.4 (FreeBSD Ports Collection)
+Reading specs from /usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/../../../libgfortran.spec
+rename spec lib to liborig
+COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_9ec75' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+COMPILER_PATH=/usr/local/libexec/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/:/usr/local/libexec/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/:/usr/local/libexec/gcc46/gcc/x86_64-portbld-freebsd10.0/:/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/:/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/:/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/../../../../../x86_64-portbld-freebsd10.0/bin/
+LIBRARY_PATH=/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/:/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/../../../../../x86_64-portbld-freebsd10.0/lib/:/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_9ec75' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+ /usr/local/libexec/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/collect2 --eh-frame-hdr -V -dynamic-linker /libexec/ld-elf.so.1 -o cmTC_9ec75 /usr/lib/crt1.o /usr/lib/crti.o /usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/crtbegin.o -L/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4 -L/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/../../../../../x86_64-portbld-freebsd10.0/lib -L/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/../../.. CMakeFiles/cmTC_9ec75.dir/CMakeFortranCompilerABI.F.o -lgfortran -lm -lgcc_s -lgcc -lquadmath -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/crtend.o /usr/lib/crtn.o
+GNU ld (GNU Binutils) 2.23.2
+ Supported emulations:
+ elf_x86_64_fbsd
+ elf_i386_fbsd
+ elf_x86_64
+ elf_i386
+ elf_l1om
+ elf_l1om_fbsd
+ elf_k1om
+ elf_k1om_fbsd
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-Fortran-GNU-4.6.4.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-Fortran-GNU-4.6.4.output
new file mode 100644
index 000000000..c0aee1118
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/freebsd-Fortran-GNU-4.6.4.output
@@ -0,0 +1 @@
+/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/finclude;/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/include;/usr/local/include;/usr/local/lib/gcc46/gcc/x86_64-portbld-freebsd10.0/4.6.4/include-fixed;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-empty.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-empty.input
new file mode 100644
index 000000000..b27eb027d
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-empty.input
@@ -0,0 +1,14 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=/usr/bin/gcc-ar-7
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=GNU
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=/usr/bin/gcc-ranlib-7
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=7.3.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+
+This is a test and there is nothing here to parse.
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-empty.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-empty.output
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-empty.output
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-relative.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-relative.input
new file mode 100644
index 000000000..dd846e33f
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-relative.input
@@ -0,0 +1,21 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=/usr/bin/gcc-ar-7
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=GNU
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=/usr/bin/gcc-ranlib-7
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=7.3.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+
+This is a hand-written test case.
+
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/local/include
+ ../../../adaptive/relative/include
+ /usr/include
+End of search list.
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-relative.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-relative.output
new file mode 100644
index 000000000..e43139b73
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-C-relative.output
@@ -0,0 +1 @@
+ /usr/local/include;[^;]*/Tests/RunCMake/ParseImplicitIncludeInfo/adaptive/relative/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-empty.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-empty.input
new file mode 100644
index 000000000..b983d6b63
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-empty.input
@@ -0,0 +1,14 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=/usr/bin/gcc-ar-7
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=GNU
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=/usr/bin/gcc-ranlib-7
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=7.3.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+
+This is a test and there is nothing here to parse.
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-empty.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-empty.output
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-empty.output
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-relative.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-relative.input
new file mode 100644
index 000000000..54cc4db46
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-relative.input
@@ -0,0 +1,21 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=/usr/bin/gcc-ar-7
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=GNU
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=/usr/bin/gcc-ranlib-7
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=7.3.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+
+This is a hand-written test case.
+
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/local/include
+ ../../../adaptive/relative/include
+ /usr/include
+End of search list.
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-relative.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-relative.output
new file mode 100644
index 000000000..e43139b73
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/hand-CXX-relative.output
@@ -0,0 +1 @@
+ /usr/local/include;[^;]*/Tests/RunCMake/ParseImplicitIncludeInfo/adaptive/relative/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-GNU-7.3.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-GNU-7.3.0.input
new file mode 100644
index 000000000..ee296a7a1
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-GNU-7.3.0.input
@@ -0,0 +1,72 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=/usr/bin/gcc-ar-7
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=GNU
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=/usr/bin/gcc-ranlib-7
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=7.3.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_1f304/fast"
+/usr/bin/make -f CMakeFiles/cmTC_1f304.dir/build.make CMakeFiles/cmTC_1f304.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_1f304.dir/CMakeCCompilerABI.c.o
+/usr/bin/cc -v -o CMakeFiles/cmTC_1f304.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c
+Using built-in specs.
+COLLECT_GCC=/usr/bin/cc
+OFFLOAD_TARGET_NAMES=nvptx-none
+OFFLOAD_TARGET_DEFAULT=1
+Target: x86_64-linux-gnu
+Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.3.0-27ubuntu1~18.04' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
+Thread model: posix
+gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_1f304.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64'
+ /usr/lib/gcc/x86_64-linux-gnu/7/cc1 -quiet -v -imultiarch x86_64-linux-gnu /usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c -quiet -dumpbase CMakeCCompilerABI.c -mtune=generic -march=x86-64 -auxbase-strip CMakeFiles/cmTC_1f304.dir/CMakeCCompilerABI.c.o -version -fstack-protector-strong -Wformat -Wformat-security -o /tmp/cc3JNm0a.s
+GNU C11 (Ubuntu 7.3.0-27ubuntu1~18.04) version 7.3.0 (x86_64-linux-gnu)
+ compiled by GNU C version 7.3.0, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0, isl version isl-0.19-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
+ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/7/../../../../x86_64-linux-gnu/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/lib/gcc/x86_64-linux-gnu/7/include
+ /usr/local/include
+ /usr/lib/gcc/x86_64-linux-gnu/7/include-fixed
+ /usr/include/x86_64-linux-gnu
+ /usr/include
+End of search list.
+GNU C11 (Ubuntu 7.3.0-27ubuntu1~18.04) version 7.3.0 (x86_64-linux-gnu)
+ compiled by GNU C version 7.3.0, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0, isl version isl-0.19-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+Compiler executable checksum: c8081a99abb72bbfd9129549110a350c
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_1f304.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64'
+ as -v --64 -o CMakeFiles/cmTC_1f304.dir/CMakeCCompilerABI.c.o /tmp/cc3JNm0a.s
+GNU assembler version 2.30 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.30
+COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/
+LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_1f304.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64'
+Linking C executable cmTC_1f304
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_1f304.dir/link.txt --verbose=1
+/usr/bin/cc -v -rdynamic CMakeFiles/cmTC_1f304.dir/CMakeCCompilerABI.c.o -o cmTC_1f304
+Using built-in specs.
+COLLECT_GCC=/usr/bin/cc
+COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
+OFFLOAD_TARGET_NAMES=nvptx-none
+OFFLOAD_TARGET_DEFAULT=1
+Target: x86_64-linux-gnu
+Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.3.0-27ubuntu1~18.04' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
+Thread model: posix
+gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)
+COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/
+LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_1f304' '-mtune=generic' '-march=x86-64'
+ /usr/lib/gcc/x86_64-linux-gnu/7/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/7/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper -plugin-opt=-fresolution=/tmp/ccg3L1R6.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --sysroot=/ --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -export-dynamic -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_1f304 /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/7 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/7/../../.. CMakeFiles/cmTC_1f304.dir/CMakeCCompilerABI.c.o -lgcc --push-state --as-needed -lgcc_s --pop-state -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-linux-gnu/7/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crtn.o
+COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_1f304' '-mtune=generic' '-march=x86-64'
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-GNU-7.3.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-GNU-7.3.0.output
new file mode 100644
index 000000000..dcd6565d7
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-GNU-7.3.0.output
@@ -0,0 +1 @@
+/usr/lib/gcc/x86_64-linux-gnu/7/include;/usr/local/include;/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed;/usr/include/x86_64-linux-gnu;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-Intel-18.0.0.20170811.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-Intel-18.0.0.20170811.input
new file mode 100644
index 000000000..1e6544b90
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-Intel-18.0.0.20170811.input
@@ -0,0 +1,43 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=Intel
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=18.0.0.20170811
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_a5f0a/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_a5f0a.dir/build.make CMakeFiles/cmTC_a5f0a.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.o
+/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/icc -v -o CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.o -c /tmp/CMake/Modules/CMakeCCompilerABI.c
+icc version 18.0.0 (gcc version 4.8.5 compatibility)
+/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/mcpcom --target_efi2 --lang=c -_g -mP3OPT_inline_alloca -D__ICC=1800 -D__INTEL_COMPILER=1800 -D__INTEL_COMPILER_UPDATE=0 -D__PTRDIFF_TYPE__=long "-D__SIZE_TYPE__=unsigned long" -D__WCHAR_TYPE__=int "-D__WINT_TYPE__=unsigned int" "-D__INTMAX_TYPE__=long int" "-D__UINTMAX_TYPE__=long unsigned int" -D__LONG_MAX__=9223372036854775807L -D__QMSPP_ -D__OPTIMIZE__ -D__NO_MATH_INLINES -D__NO_STRING_INLINES -D__GNUC_GNU_INLINE__ -D__GNUC__=4 -D__GNUC_MINOR__=8 -D__GNUC_PATCHLEVEL__=5 -D__LP64__ -D_LP64 -D__GXX_ABI_VERSION=1002 "-D__USER_LABEL_PREFIX__= " -D__REGISTER_PREFIX__= -D__INTEL_RTTI__ -D__unix__ -D__unix -D__linux__ -D__linux -D__gnu_linux__ -B -Dunix -Dlinux "-_Asystem(unix)" -D__ELF__ -D__x86_64 -D__x86_64__ -D__amd64 -D__amd64__ "-_Acpu(x86_64)" "-_Amachine(x86_64)" -D__INTEL_COMPILER_BUILD_DATE=20170811 -D__INTEL_OFFLOAD -D__i686 -D__i686__ -D__pentiumpro -D__pentiumpro__ -D__pentium4 -D__pentium4__ -D__tune_pentium4__ -D__SSE2__ -D__SSE2_MATH__ -D__SSE__ -D__SSE_MATH__ -D__MMX__ -_k -_8 -_l --has_new_stdarg_support -_a -_b --gnu_version=40805 -_W5 --gcc-extern-inline --multibyte_chars -mGLOB_diag_suppress_sys --system_preinclude /usr/include/stdc-predef.h --array_section --simd --simd_func --offload_mode=1 --offload_target_names=gfx,GFX,mic,MIC --offload_unique_string=icc1018727407m03RCD -mGLOB_em64t=TRUE -mP1OPT_version=18.0-intel64 -mGLOB_diag_file=CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.diag -mGLOB_long_size_64 -mGLOB_routine_pointer_size_64 -mP1OPT_print_version=FALSE -mCG_use_gas_got_workaround=F -mP2OPT_align_option_used=TRUE -mGLOB_gcc_version=485 "-mGLOB_options_string=-v -o CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.o -c" -mGLOB_cxx_limited_range=FALSE -mCG_extend_parms=FALSE -mGLOB_compiler_bin_directory=/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64 -mGLOB_as_output_backup_file_name=/tmp/iccMjPSufas_.s -mIPOPT_activate -mIPOPT_lite -mGLOB_instruction_tuning=0x0 -mGLOB_uarch_tuning=0x0 -mGLOB_product_id_code=0x22006d92 -mCG_bnl_movbe=T -mGLOB_extended_instructions=0x8 -mP3OPT_use_mspp_call_convention -mP2OPT_subs_out_of_bound=FALSE -mP2OPT_disam_type_based_disam=2 -mP2OPT_disam_assume_ansi_c -mP2OPT_checked_disam_ansi_alias=TRUE -mGLOB_ansi_alias -mPGOPTI_value_profile_use=T -mP2OPT_il0_array_sections=TRUE -mGLOB_offload_mode=1 -mP2OPT_offload_unique_var_string=icc1018727407m03RCD -mP2OPT_hlo_level=2 -mP2OPT_hlo -mP2OPT_hpo_rtt_control=0 -mIPOPT_args_in_regs=0 -mP2OPT_disam_assume_nonstd_intent_in=FALSE -mGLOB_imf_mapping_library=/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/libiml_attr.so -mPGOPTI_gen_threadsafe_level=0 -mIPOPT_lto_object_enabled -mIPOPT_lto_object_value=1 -mIPOPT_obj_output_file_name=CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.o -mIPOPT_whole_archive_fixup_file_name=/tmp/iccwarchDkkYqW -mGLOB_linker_version=2.27 -mGLOB_driver_tempfile_name=/tmp/icctempfileg2vfUM -mP3OPT_asm_target=P3OPT_ASM_TARGET_GAS -mGLOB_async_unwind_tables=TRUE -mGLOB_obj_output_file=CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.o -mGLOB_source_dialect=GLOB_SOURCE_DIALECT_C -mP1OPT_source_file_name=/tmp/CMake/Modules/CMakeCCompilerABI.c -mP1OPT_full_source_file_name=/tmp/CMake/Modules/CMakeCCompilerABI.c /tmp/CMake/Modules/CMakeCCompilerABI.c
+#include "..." search starts here:
+#include <...> search starts here:
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/include
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/include
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/pstl/include
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/include
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/include
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include/intel64
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include/icc
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include
+ /usr/local/include
+ /usr/lib/gcc/x86_64-redhat-linux/4.8.5/include
+ /usr/include/
+ /usr/include
+End of search list.
+Linking C executable cmTC_a5f0a
+/tmp/CMake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_a5f0a.dir/link.txt --verbose=1
+/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/icc -v -rdynamic CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.o -o cmTC_a5f0a
+icc version 18.0.0 (gcc version 4.8.5 compatibility)
+/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/mcpcom -mGLOB_em64t=TRUE -mP1OPT_version=18.0-intel64 -mGLOB_diag_file=CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.diag -mGLOB_long_size_64 -mGLOB_routine_pointer_size_64 -mP1OPT_print_version=FALSE -mCG_use_gas_got_workaround=F -mP2OPT_align_option_used=TRUE -mGLOB_gcc_version=485 "-mGLOB_options_string=-v -rdynamic -o cmTC_a5f0a" -mGLOB_cxx_limited_range=FALSE -mCG_extend_parms=FALSE -mGLOB_compiler_bin_directory=/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64 -mGLOB_as_output_backup_file_name=/tmp/iccSNrbyQas_.s -mGLOB_dashboard_use_source_name -mIPOPT_activate -mGLOB_product_id_code=0x22006d92 -mP3OPT_use_mspp_call_convention -mP2OPT_subs_out_of_bound=FALSE -mP2OPT_disam_type_based_disam=2 -mP2OPT_disam_assume_ansi_c -mP2OPT_checked_disam_ansi_alias=TRUE -mGLOB_ansi_alias -mPGOPTI_value_profile_use=T -mGLOB_opt_report_use_source_name -mP2OPT_il0_array_sections=TRUE -mGLOB_offload_mode=1 -mP2OPT_offload_unique_var_string=icc0131594309ugIRtJ -mP2OPT_hlo -mP2OPT_hpo_rtt_control=0 -mIPOPT_args_in_regs=0 -mP2OPT_disam_assume_nonstd_intent_in=FALSE -mGLOB_imf_mapping_library=/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/libiml_attr.so -mPGOPTI_gen_threadsafe_level=0 -mIPOPT_link -mIPOPT_ipo_activate -mIPOPT_mo_activate -mIPOPT_source_files_list=/tmp/iccslis4FFYii -mIPOPT_mo_global_data -mIPOPT_link_script_file=/tmp/iccscriptV37728 "-mIPOPT_cmdline_link="/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o" "/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crti.o" "/usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtbegin.o" "-export-dynamic" "--eh-frame-hdr" "--build-id" "-dynamic-linker" "/lib64/ld-linux-x86-64.so.2" "-m" "elf_x86_64" "-o" "cmTC_a5f0a" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/lib/intel64" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/lib/intel64_lin" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin" "-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/" "-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64" "-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/" "-L/lib/../lib64" "-L/lib/../lib64/" "-L/usr/lib/../lib64" "-L/usr/lib/../lib64/" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/lib/intel64/" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin/" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/lib/intel64_lin/" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7/" "-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../" "-L/lib64" "-L/lib/" "-L/usr/lib64" "-L/usr/lib" "CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.o" "-Bdynamic" "-Bstatic" "-limf" "-lsvml" "-lirng" "-Bdynamic" "-lm" "-Bstatic" "-lipgo" "-ldecimal" "--as-needed" "-Bdynamic" "-lcilkrts" "-lstdc++" "--no-as-needed" "-lgcc" "-lgcc_s" "-Bstatic" "-lirc" "-lsvml" "-Bdynamic" "-lc" "-lgcc" "-lgcc_s" "-Bstatic" "-lirc_s" "-Bdynamic" "-ldl" "-lc" "/usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtend.o" "/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crtn.o"" -mIPOPT_il_in_obj -mIPOPT_ipo_activate_warn=FALSE -mIPOPT_obj_output_file_name=/tmp/ipo_iccYpsdQb.o -mIPOPT_whole_archive_fixup_file_name=/tmp/iccwarchgEXmQo -mGLOB_linker_version=2.27 -mGLOB_driver_tempfile_name=/tmp/icctempfilemNLlCf -mP3OPT_asm_target=P3OPT_ASM_TARGET_GAS -mGLOB_async_unwind_tables=TRUE -mGLOB_obj_output_file=/tmp/ipo_iccYpsdQb.o -mGLOB_source_dialect=GLOB_SOURCE_DIALECT_NONE -mP1OPT_source_file_name=ipo_out.c CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.o -mIPOPT_object_files=T -mIPOPT_assembly_files=/tmp/iccalisRmwrkT -mIPOPT_generated_tempfiles=/tmp/iccelisUgbz4J -mIPOPT_embedded_object_base_name=/tmp/icceobj0agHOA -mIPOPT_cmdline_link_new_name=/tmp/iccllis0qIPyr
+ld /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crti.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtbegin.o -export-dynamic --eh-frame-hdr --build-id -dynamic-linker /lib64/ld-linux-x86-64.so.2 -m elf_x86_64 -o cmTC_a5f0a -L/opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/lib/intel64 -L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin -L/opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/lib/intel64_lin -L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7 -L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7 -L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/ -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/ -L/lib/../lib64 -L/lib/../lib64/ -L/usr/lib/../lib64 -L/usr/lib/../lib64/ -L/opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/lib/intel64/ -L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin/ -L/opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/lib/intel64_lin/ -L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7/ -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../ -L/lib64 -L/lib/ -L/usr/lib64 -L/usr/lib CMakeFiles/cmTC_a5f0a.dir/CMakeCCompilerABI.c.o -Bdynamic -Bstatic -limf -lsvml -lirng -Bdynamic -lm -Bstatic -lipgo -ldecimal --as-needed -Bdynamic -lcilkrts -lstdc++ --no-as-needed -lgcc -lgcc_s -Bstatic -lirc -lsvml -Bdynamic -lc -lgcc -lgcc_s -Bstatic -lirc_s -Bdynamic -ldl -lc /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtend.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crtn.o
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-Intel-18.0.0.20170811.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-Intel-18.0.0.20170811.output
new file mode 100644
index 000000000..714131c3e
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-Intel-18.0.0.20170811.output
@@ -0,0 +1 @@
+/opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/include;/opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/include;/opt/intel/compilers_and_libraries_2018.0.128/linux/pstl/include;/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/include;/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include/intel64;/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include/icc;/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include;/usr/local/include;/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-PGI-18.10.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-PGI-18.10.1.input
new file mode 100644
index 000000000..cfc3e7b1c
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-PGI-18.10.1.input
@@ -0,0 +1,36 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=PGI
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=18.10.1
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_81a12/fast"
+/usr/bin/make -f CMakeFiles/cmTC_81a12.dir/build.make CMakeFiles/cmTC_81a12.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_81a12.dir/CMakeCCompilerABI.c.o
+/mnt/pgi/linux86-64/2018/bin/pgcc -v -o CMakeFiles/cmTC_81a12.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/mnt/pgi/linux86-64/18.10/bin/pgc /usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c -opt 1 -x 119 0xa10000 -x 122 0x40 -x 123 0x1000 -x 127 4 -x 127 17 -x 19 0x400000 -x 28 0x40000 -x 120 0x10000000 -x 70 0x8000 -x 122 1 -x 125 0x20000 -quad -x 59 4 -tp k8 -x 120 0x1000 -astype 0 -stdinc /mnt/pgi/linux86-64/18.10/include-gcc70:/mnt/pgi/linux86-64/18.10/include:/usr/lib/gcc/x86_64-linux-gnu/7/include:/usr/local/include:/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed:/usr/include/x86_64-linux-gnu:/usr/include -def unix -def __unix -def __unix__ -def linux -def __linux -def __linux__ -def __NO_MATH_INLINES -def __LP64__ -def __x86_64 -def __x86_64__ -def __LONG_MAX__=9223372036854775807L -def '__SIZE_TYPE__=unsigned long int' -def '__PTRDIFF_TYPE__=long int' -def __extension__= -def __amd_64__amd64__ -def __k8 -def __k8__ -def __SSE__ -def __MMX__ -def __SSE2__ -def __SSE3__ -predicate '#machine(x86_64) #lint(off) #system(posix) #cpu(x86_64)' -cmdline '+pgcc /usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c -v -o CMakeFiles/cmTC_81a12.dir/CMakeCCompilerABI.c.o -c' -outfile CMakeFiles/cmTC_81a12.dir/CMakeCCompilerABI.c.o -x 123 0x80000000 -x 123 4 -x 2 0x400 -preinclude _c_macros.h -x 119 0x20 -def __pgnu_vsn=70300 -x 120 0x200000 -x 70 0x40000000 -x 164 0x800000 -y 163 0xc0000000 -x 189 0x10 -y 189 0x4000000 -asm /tmp/pgccl1BeHkOmG3zk.s
+PGC/x86-64 Linux 18.10-1: compilation successful
+
+/usr/bin/as /tmp/pgccl1BeHkOmG3zk.s -o CMakeFiles/cmTC_81a12.dir/CMakeCCompilerABI.c.o
+Unlinking /tmp/pgccl1BeHkOmG3zk.s
+Unlinking /tmp/pgccJ1BePEjJHZ9x.ll
+Linking C executable cmTC_81a12
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_81a12.dir/link.txt --verbose=1
+/mnt/pgi/linux86-64/2018/bin/pgcc -v CMakeFiles/cmTC_81a12.dir/CMakeCCompilerABI.c.o -o cmTC_81a12
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/usr/bin/ld /usr/lib/x86_64-linux-gnu/crt1.o /usr/lib/x86_64-linux-gnu/crti.o /mnt/pgi/linux86-64/18.10/lib/trace_init.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbegin.o /mnt/pgi/linux86-64/18.10/lib/initmp.o --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 /mnt/pgi/linux86-64/18.10/lib/pgi.ld -L/mnt/pgi/linux86-64/18.10/lib -L/usr/lib64 -L/usr/lib/gcc/x86_64-linux-gnu/7 CMakeFiles/cmTC_81a12.dir/CMakeCCompilerABI.c.o -rpath /mnt/pgi/linux86-64/18.10/lib -rpath /usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -o cmTC_81a12 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -lpgmp -lnuma -lpthread --start-group -lpgmath -lnspgc -lpgc --end-group -lm -lgcc -lc -lgcc -lgcc_s /usr/lib/gcc/x86_64-linux-gnu/7/crtend.o /usr/lib/x86_64-linux-gnu/crtn.o
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-PGI-18.10.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-PGI-18.10.1.output
new file mode 100644
index 000000000..289c530a6
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-PGI-18.10.1.output
@@ -0,0 +1 @@
+/mnt/pgi/linux86-64/18.10/include-gcc70;/mnt/pgi/linux86-64/18.10/include;/usr/lib/gcc/x86_64-linux-gnu/7/include;/usr/local/include;/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed;/usr/include/x86_64-linux-gnu;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-12.1.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-12.1.0.input
new file mode 100644
index 000000000..a6d9e5a48
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-12.1.0.input
@@ -0,0 +1,42 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=XL
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=12.1.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_79cdf/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_79cdf.dir/build.make CMakeFiles/cmTC_79cdf.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_79cdf.dir/CMakeCCompilerABI.c.o
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/bin/xlc -qthreaded -qhalt=e -V -o CMakeFiles/cmTC_79cdf.dir/CMakeCCompilerABI.c.o -c /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCCompilerABI.c
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlc
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+export XL_ASMOBJFILES=/tmp/xlcASgBamaX
+export "XL_DIS=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/dis -o "CMakeFiles/cmTC_79cdf.dir/CMakeCCompilerABI.c.o" "CMakeCCompilerABI.o""
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlcentry -qosvar=rhel.6.9 -qlanglvl=extc99 -qcpluscmt -qkeyword=inline -qalias=ansi -qtls -D_CALL_SYSV -D__null=0 -D__NO_MATH_INLINES -qtls -q64 -qgnu_version=4.4.7 -qthreaded -qhalt=e -qasm_as=/usr/bin/as -qc_stdinc=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include -qgcc_c_stdinc=/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qcomplexgccincl=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include:/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qvac_include_path=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include -oCMakeFiles/cmTC_79cdf.dir/CMakeCCompilerABI.c.o /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCCompilerABI.c /tmp/xlcW06RQxFR /tmp/xlcW1Og9D2y /dev/null /tmp/xlcLUravVDF.lst /dev/null /tmp/xlcW2kTjRpg
+export XL_BACKEND=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode
+export XL_LINKER=/usr/bin/ld
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode -qlanglvl=extc99 -qcpluscmt -qkeyword=inline -qalias=ansi -qtls -qtls -qthreaded -qhalt=e /tmp/xlcW06RQxFR /tmp/xlcW1Og9D2y CMakeFiles/cmTC_79cdf.dir/CMakeCCompilerABI.c.o /tmp/xlcLUravVDB.lst /tmp/xlcW2kTjRpg
+rm /tmp/xlcASgBamaX
+rm /tmp/xlcLUravVD
+rm /tmp/xlcW06RQxFR
+rm /tmp/xlcW1Og9D2y
+rm /tmp/xlcW2kTjRpg
+Linking C executable cmTC_79cdf
+/soft/buildtools/cmake/3.5.2/bin/cmake -E cmake_link_script CMakeFiles/cmTC_79cdf.dir/link.txt --verbose=1
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/bin/xlc -qthreaded -qhalt=e -V CMakeFiles/cmTC_79cdf.dir/CMakeCCompilerABI.c.o -o cmTC_79cdf -Wl,-export-dynamic
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlc
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+/usr/bin/ld --eh-frame-hdr -Qy -melf64ppc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crt1.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crti.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtbegin.o -L/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/lib64 -L/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/lib64 -L/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/lib64 -L/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/lib64 -R/soft/compilers/ibmcmp-oct2017/lib64/bg -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../.. CMakeFiles/cmTC_79cdf.dir/CMakeCCompilerABI.c.o -o cmTC_79cdf -export-dynamic -dynamic-linker /lib64/ld64.so.1 -lxlopt -lxl -ldl -lgcc_s -lgcc -lm -lc -lgcc_s -lgcc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtend.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crtn.o
+rm /tmp/xlcW0JVPZO4
+rm /tmp/xlcW1cwDxtZ
+rm /tmp/xlcW2j5Va8T
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-12.1.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-12.1.0.output
new file mode 100644
index 000000000..eceacf954
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-12.1.0.output
@@ -0,0 +1 @@
+/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include;/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include;/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include;/usr/local/include;/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-16.1.0.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-16.1.0.0.input
new file mode 100644
index 000000000..97fa28be9
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-16.1.0.0.input
@@ -0,0 +1,40 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=XL
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=16.1.0.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_56ad1/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_56ad1.dir/build.make CMakeFiles/cmTC_56ad1.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_56ad1.dir/CMakeCCompilerABI.c.o
+/opt/ibm/xlC/16.1.0/bin/xlc -qthreaded -V -o CMakeFiles/cmTC_56ad1.dir/CMakeCCompilerABI.c.o -c "/tmp/CMake/Modules/CMakeCCompilerABI.c"
+export XL_CONFIG=/opt/ibm/xlC/16.1.0/etc/xlc.cfg.centos.7.gcc.4.8.5:xlc
+export XL_ASMOBJFILES=/tmp/xlcASSb1cI4
+export "XL_DIS=/opt/ibm/xlC/16.1.0/exe/dis -o "CMakeFiles/cmTC_56ad1.dir/CMakeCCompilerABI.c.o" "CMakeCCompilerABI.o""
+/opt/ibm/xlC/16.1.0/exe/xlCentry -qosvar=centos.7.0 -qlanglvl=extc99 -qalias=ansi -qthreaded -D_REENTRANT -D__VACPP_MULTI__ -qtls -q64 -D_CALL_SYSV -D__NO_MATH_INLINES -D_CALL_ELF=2 -Wno-parentheses -Wno-unused-value -maltivec -qtls -q64 -qgnu_version=4.8.5 -qthreaded -qasm_as=/usr/bin/as -qc_stdinc=/opt/ibm/xlsmp/5.1.0/include:/opt/ibm/xlsmp/5.1.0/include:/opt/ibm/xlmass/9.1.0/include:/opt/ibm/xlC/16.1.0/include -qgcc_c_stdinc=/opt/ibm/xlC/16.1.0/include:/usr/local/include:/opt/ibm/xlC/16.1.0/include:/usr/include -qcomplexgccincl=/opt/ibm/xlsmp/5.1.0/include:/opt/ibm/xlmass/9.1.0/include:/opt/ibm/xlC/16.1.0/include:/opt/ibm/xlC/16.1.0/include:/usr/local/include:/opt/ibm/xlC/16.1.0/include:/usr/include -qvac_include_path=/opt/ibm/xlC/16.1.0/include -oCMakeFiles/cmTC_56ad1.dir/CMakeCCompilerABI.c.o "/tmp/CMake/Modules/CMakeCCompilerABI.c" /tmp/xlcW0T1FYwj /tmp/xlcW1fu4lVT /dev/null /tmp/xlcLWBpG6EF.lst /dev/null /tmp/xlcW2TKQJju
+export XL_BACKEND=/opt/ibm/xlC/16.1.0/exe/xlCcode
+export XL_LINKER=/usr/bin/ld
+/opt/ibm/xlC/16.1.0/exe/xlCcode -qlanglvl=extc99 -qalias=ansi -qthreaded -qtls -maltivec -qtls -qthreaded /tmp/xlcW0T1FYwj /tmp/xlcW1fu4lVT CMakeFiles/cmTC_56ad1.dir/CMakeCCompilerABI.c.o /tmp/xlcLWBpG6EB.lst /tmp/xlcW2TKQJju
+rm /tmp/xlcASSb1cI4
+rm /tmp/xlcLWBpG6E
+rm /tmp/xlcW0T1FYwj
+rm /tmp/xlcW1fu4lVT
+rm /tmp/xlcW2TKQJju
+Linking C executable cmTC_56ad1
+"/tmp/CMake/bin/cmake" -E cmake_link_script CMakeFiles/cmTC_56ad1.dir/link.txt --verbose=1
+/opt/ibm/xlC/16.1.0/bin/xlc -qthreaded -V -Wl,-export-dynamic CMakeFiles/cmTC_56ad1.dir/CMakeCCompilerABI.c.o -o cmTC_56ad1
+export XL_CONFIG=/opt/ibm/xlC/16.1.0/etc/xlc.cfg.centos.7.gcc.4.8.5:xlc
+/usr/bin/ld --eh-frame-hdr -Qy -melf64lppc -dynamic-linker /lib64/ld64.so.2 --enable-new-dtags /usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../lib64/crt1.o /usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../lib64/crti.o /usr/lib/gcc/ppc64le-redhat-linux/4.8.5/crtbegin.o -L/opt/ibm/xlsmp/5.1.0/lib -L/opt/ibm/xlmass/9.1.0/lib -L/opt/ibm/xlC/16.1.0/lib -R/opt/ibm/lib -L/usr/lib/gcc/ppc64le-redhat-linux/4.8.5 -L/usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../.. -export-dynamic CMakeFiles/cmTC_56ad1.dir/CMakeCCompilerABI.c.o -o cmTC_56ad1 -lxlopt -lxl --as-needed -ldl --no-as-needed -lgcc_s --as-needed -lpthread --no-as-needed -lgcc -lm -lc -lgcc_s -lgcc /usr/lib/gcc/ppc64le-redhat-linux/4.8.5/crtend.o /usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../lib64/crtn.o
+rm /tmp/xlcW0S2fv6n
+rm /tmp/xlcW11wDdxY
+rm /tmp/xlcW2JqnWXy
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-16.1.0.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-16.1.0.0.output
new file mode 100644
index 000000000..6dac25fb4
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-C-XL-16.1.0.0.output
@@ -0,0 +1 @@
+/opt/ibm/xlsmp/5.1.0/include;/opt/ibm/xlmass/9.1.0/include;/opt/ibm/xlC/16.1.0/include;/usr/local/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CUDA-NVIDIA-9.2.148.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CUDA-NVIDIA-9.2.148.input
new file mode 100644
index 000000000..5dd36508e
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CUDA-NVIDIA-9.2.148.input
@@ -0,0 +1,124 @@
+CMAKE_LANG=CUDA
+CMAKE_CUDA_COMPILER_ABI=ELF
+CMAKE_CUDA_COMPILER_AR=
+CMAKE_CUDA_COMPILER_ARCHITECTURE_ID=
+CMAKE_CUDA_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CUDA_COMPILER_ID=NVIDIA
+CMAKE_CUDA_COMPILER_LAUNCHER=
+CMAKE_CUDA_COMPILER_LOADED=1
+CMAKE_CUDA_COMPILER_RANLIB=
+CMAKE_CUDA_COMPILER_TARGET=
+CMAKE_CUDA_COMPILER_VERSION=9.2.148
+CMAKE_CUDA_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_5996d/fast"
+/usr/bin/make -f CMakeFiles/cmTC_5996d.dir/build.make CMakeFiles/cmTC_5996d.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CUDA object CMakeFiles/cmTC_5996d.dir/CMakeCUDACompilerABI.cu.o
+/usr/bin/nvcc -Xcompiler=-v -x cu -c "/tmp/CMake/Modules/CMakeCUDACompilerABI.cu" -o CMakeFiles/cmTC_5996d.dir/CMakeCUDACompilerABI.cu.o
+Using built-in specs.
+COLLECT_GCC=gcc-5
+Target: x86_64-linux-gnu
+Configured with: ../src/configure -v --with-pkgversion='Debian 5.5.0-12' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --enable-objc-gc --enable-multiarch --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
+Thread model: posix
+gcc version 5.5.0 20171010 (Debian 5.5.0-12)
+COLLECT_GCC_OPTIONS='-std=c++14' '-D' '__CUDA_ARCH__=300' '-E' '-D' 'CUDA_DOUBLE_MATH_FUNCTIONS' '-D' '__CUDACC__' '-D' '__NVCC__' '-v' '-D' '__CUDACC_VER_BUILD__=148' '-D' '__CUDACC_VER_MINOR__=2' '-D' '__CUDACC_VER_MAJOR__=9' '-include' 'cuda_runtime.h' '-m64' '-mtune=generic' '-march=x86-64'
+ /usr/lib/gcc/x86_64-linux-gnu/5/cc1plus -E -quiet -v -imultiarch x86_64-linux-gnu -D_GNU_SOURCE -D __CUDA_ARCH__=300 -D CUDA_DOUBLE_MATH_FUNCTIONS -D __CUDACC__ -D __NVCC__ -D __CUDACC_VER_BUILD__=148 -D __CUDACC_VER_MINOR__=2 -D __CUDACC_VER_MAJOR__=9 -include cuda_runtime.h /tmp/CMake/Modules/CMakeCUDACompilerABI.cu -m64 -mtune=generic -march=x86-64 -std=c++14
+ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/5"
+ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
+ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/5/../../../../x86_64-linux-gnu/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/include/c++/5
+ /usr/include/x86_64-linux-gnu/c++/5
+ /usr/include/c++/5/backward
+ /usr/lib/gcc/x86_64-linux-gnu/5/include
+ /usr/local/include
+ /usr/lib/gcc/x86_64-linux-gnu/5/include-fixed
+ /usr/include/x86_64-linux-gnu
+ /usr/include
+End of search list.
+COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/
+LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-std=c++14' '-D' '__CUDA_ARCH__=300' '-E' '-D' 'CUDA_DOUBLE_MATH_FUNCTIONS' '-D' '__CUDACC__' '-D' '__NVCC__' '-v' '-D' '__CUDACC_VER_BUILD__=148' '-D' '__CUDACC_VER_MINOR__=2' '-D' '__CUDACC_VER_MAJOR__=9' '-include' 'cuda_runtime.h' '-m64' '-mtune=generic' '-march=x86-64'
+Using built-in specs.
+COLLECT_GCC=gcc-5
+Target: x86_64-linux-gnu
+Configured with: ../src/configure -v --with-pkgversion='Debian 5.5.0-12' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --enable-objc-gc --enable-multiarch --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
+Thread model: posix
+gcc version 5.5.0 20171010 (Debian 5.5.0-12)
+COLLECT_GCC_OPTIONS='-std=c++14' '-E' '-D' '__CUDACC__' '-D' '__NVCC__' '-v' '-D' '__CUDACC_VER_BUILD__=148' '-D' '__CUDACC_VER_MINOR__=2' '-D' '__CUDACC_VER_MAJOR__=9' '-include' 'cuda_runtime.h' '-m64' '-mtune=generic' '-march=x86-64'
+ /usr/lib/gcc/x86_64-linux-gnu/5/cc1plus -E -quiet -v -imultiarch x86_64-linux-gnu -D_GNU_SOURCE -D __CUDACC__ -D __NVCC__ -D __CUDACC_VER_BUILD__=148 -D __CUDACC_VER_MINOR__=2 -D __CUDACC_VER_MAJOR__=9 -include cuda_runtime.h /tmp/CMake/Modules/CMakeCUDACompilerABI.cu -m64 -mtune=generic -march=x86-64 -std=c++14
+ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/5"
+ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
+ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/5/../../../../x86_64-linux-gnu/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/include/c++/5
+ /usr/include/x86_64-linux-gnu/c++/5
+ /usr/include/c++/5/backward
+ /usr/lib/gcc/x86_64-linux-gnu/5/include
+ /usr/local/include
+ /usr/lib/gcc/x86_64-linux-gnu/5/include-fixed
+ /usr/include/x86_64-linux-gnu
+ /usr/include
+End of search list.
+COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/
+LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-std=c++14' '-E' '-D' '__CUDACC__' '-D' '__NVCC__' '-v' '-D' '__CUDACC_VER_BUILD__=148' '-D' '__CUDACC_VER_MINOR__=2' '-D' '__CUDACC_VER_MAJOR__=9' '-include' 'cuda_runtime.h' '-m64' '-mtune=generic' '-march=x86-64'
+Using built-in specs.
+COLLECT_GCC=gcc-5
+Target: x86_64-linux-gnu
+Configured with: ../src/configure -v --with-pkgversion='Debian 5.5.0-12' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --enable-objc-gc --enable-multiarch --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
+Thread model: posix
+gcc version 5.5.0 20171010 (Debian 5.5.0-12)
+COLLECT_GCC_OPTIONS='-std=c++14' '-D' '__CUDA_ARCH__=300' '-c' '-D' 'CUDA_DOUBLE_MATH_FUNCTIONS' '-v' '-m64' '-o' 'CMakeFiles/cmTC_5996d.dir/CMakeCUDACompilerABI.cu.o' '-mtune=generic' '-march=x86-64'
+ /usr/lib/gcc/x86_64-linux-gnu/5/cc1plus -quiet -v -imultiarch x86_64-linux-gnu -D_GNU_SOURCE -D __CUDA_ARCH__=300 -D CUDA_DOUBLE_MATH_FUNCTIONS /tmp/tmpxft_00002df4_00000000-5_CMakeCUDACompilerABI.cudafe1.cpp -quiet -dumpbase tmpxft_00002df4_00000000-5_CMakeCUDACompilerABI.cudafe1.cpp -m64 -mtune=generic -march=x86-64 -auxbase-strip CMakeFiles/cmTC_5996d.dir/CMakeCUDACompilerABI.cu.o -std=c++14 -version -o /tmp/ccSDI00n.s
+GNU C++14 (Debian 5.5.0-12) version 5.5.0 20171010 (x86_64-linux-gnu)
+ compiled by GNU C version 5.5.0 20171010, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0
+warning: MPFR header version 4.0.1 differs from library version 4.0.2-rc1.
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/5"
+ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
+ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/5/../../../../x86_64-linux-gnu/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/include/c++/5
+ /usr/include/x86_64-linux-gnu/c++/5
+ /usr/include/c++/5/backward
+ /usr/lib/gcc/x86_64-linux-gnu/5/include
+ /usr/local/include
+ /usr/lib/gcc/x86_64-linux-gnu/5/include-fixed
+ /usr/include/x86_64-linux-gnu
+ /usr/include
+End of search list.
+GNU C++14 (Debian 5.5.0-12) version 5.5.0 20171010 (x86_64-linux-gnu)
+ compiled by GNU C version 5.5.0 20171010, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0
+warning: MPFR header version 4.0.1 differs from library version 4.0.2-rc1.
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+Compiler executable checksum: 3caa6244fa07ed8a2b405a77ac6cb692
+COLLECT_GCC_OPTIONS='-std=c++14' '-D' '__CUDA_ARCH__=300' '-c' '-D' 'CUDA_DOUBLE_MATH_FUNCTIONS' '-v' '-m64' '-o' 'CMakeFiles/cmTC_5996d.dir/CMakeCUDACompilerABI.cu.o' '-mtune=generic' '-march=x86-64'
+ as -v --64 -o CMakeFiles/cmTC_5996d.dir/CMakeCUDACompilerABI.cu.o /tmp/ccSDI00n.s
+GNU assembler version 2.31.1 (x86_64-linux-gnu) using BFD version (GNU Binutils for Debian) 2.31.1
+COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/
+LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-std=c++14' '-D' '__CUDA_ARCH__=300' '-c' '-D' 'CUDA_DOUBLE_MATH_FUNCTIONS' '-v' '-m64' '-o' 'CMakeFiles/cmTC_5996d.dir/CMakeCUDACompilerABI.cu.o' '-mtune=generic' '-march=x86-64'
+Linking CUDA device code CMakeFiles/cmTC_5996d.dir/cmake_device_link.o
+"/tmp/CMake/bin/cmake" -E cmake_link_script CMakeFiles/cmTC_5996d.dir/dlink.txt --verbose=1
+/usr/bin/nvcc -Xcompiler=-fPIC -Wno-deprecated-gpu-targets -shared -dlink CMakeFiles/cmTC_5996d.dir/CMakeCUDACompilerABI.cu.o -o CMakeFiles/cmTC_5996d.dir/cmake_device_link.o -L"/usr/lib/x86_64-linux-gnu"
+Linking CUDA executable cmTC_5996d
+"/tmp/CMake/bin/cmake" -E cmake_link_script CMakeFiles/cmTC_5996d.dir/link.txt --verbose=1
+/usr/lib/nvidia-cuda-toolkit/bin/g++ -v CMakeFiles/cmTC_5996d.dir/CMakeCUDACompilerABI.cu.o CMakeFiles/cmTC_5996d.dir/cmake_device_link.o -o cmTC_5996d -L"/usr/lib/x86_64-linux-gnu/stubs" -lcudadevrt -lcudart_static -lrt -lpthread -ldl
+Using built-in specs.
+COLLECT_GCC=g++-5
+COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper
+Target: x86_64-linux-gnu
+Configured with: ../src/configure -v --with-pkgversion='Debian 5.5.0-12' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --enable-objc-gc --enable-multiarch --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
+Thread model: posix
+gcc version 5.5.0 20171010 (Debian 5.5.0-12)
+COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/
+LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_5996d' '-L/usr/lib/x86_64-linux-gnu/stubs' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+ /usr/lib/gcc/x86_64-linux-gnu/5/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/5/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper -plugin-opt=-fresolution=/tmp/cc85GscA.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --sysroot=/ --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o cmTC_5996d /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/5/crtbegin.o -L/usr/lib/x86_64-linux-gnu/stubs -L/usr/lib/gcc/x86_64-linux-gnu/5 -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/5/../../.. CMakeFiles/cmTC_5996d.dir/CMakeCUDACompilerABI.cu.o CMakeFiles/cmTC_5996d.dir/cmake_device_link.o -lcudadevrt -lcudart_static -lrt -lpthread -ldl -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/5/crtend.o /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crtn.o
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CUDA-NVIDIA-9.2.148.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CUDA-NVIDIA-9.2.148.output
new file mode 100644
index 000000000..497fb887b
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CUDA-NVIDIA-9.2.148.output
@@ -0,0 +1 @@
+/usr/include/c\+\+/5;/usr/include/x86_64-linux-gnu/c\+\+/5;/usr/include/c\+\+/5/backward;/usr/lib/gcc/x86_64-linux-gnu/5/include;/usr/local/include;/usr/lib/gcc/x86_64-linux-gnu/5/include-fixed;/usr/include/x86_64-linux-gnu;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-GNU-7.3.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-GNU-7.3.0.input
new file mode 100644
index 000000000..633a0efa7
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-GNU-7.3.0.input
@@ -0,0 +1,76 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=/usr/bin/gcc-ar-7
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=GNU
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=/usr/bin/gcc-ranlib-7
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=7.3.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_63146/fast"
+/usr/bin/make -f CMakeFiles/cmTC_63146.dir/build.make CMakeFiles/cmTC_63146.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_63146.dir/CMakeCXXCompilerABI.cpp.o
+/usr/bin/c++ -v -o CMakeFiles/cmTC_63146.dir/CMakeCXXCompilerABI.cpp.o -c /usr/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp
+Using built-in specs.
+COLLECT_GCC=/usr/bin/c++
+OFFLOAD_TARGET_NAMES=nvptx-none
+OFFLOAD_TARGET_DEFAULT=1
+Target: x86_64-linux-gnu
+Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.3.0-27ubuntu1~18.04' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
+Thread model: posix
+gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_63146.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+ /usr/lib/gcc/x86_64-linux-gnu/7/cc1plus -quiet -v -imultiarch x86_64-linux-gnu -D_GNU_SOURCE /usr/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp -quiet -dumpbase CMakeCXXCompilerABI.cpp -mtune=generic -march=x86-64 -auxbase-strip CMakeFiles/cmTC_63146.dir/CMakeCXXCompilerABI.cpp.o -version -fstack-protector-strong -Wformat -Wformat-security -o /tmp/ccXqnn3f.s
+GNU C++14 (Ubuntu 7.3.0-27ubuntu1~18.04) version 7.3.0 (x86_64-linux-gnu)
+ compiled by GNU C version 7.3.0, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0, isl version isl-0.19-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/7"
+ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
+ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/7/../../../../x86_64-linux-gnu/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/include/c++/7
+ /usr/include/x86_64-linux-gnu/c++/7
+ /usr/include/c++/7/backward
+ /usr/lib/gcc/x86_64-linux-gnu/7/include
+ /usr/local/include
+ /usr/lib/gcc/x86_64-linux-gnu/7/include-fixed
+ /usr/include/x86_64-linux-gnu
+ /usr/include
+End of search list.
+GNU C++14 (Ubuntu 7.3.0-27ubuntu1~18.04) version 7.3.0 (x86_64-linux-gnu)
+ compiled by GNU C version 7.3.0, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0, isl version isl-0.19-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+Compiler executable checksum: 1bfae38ae5df64de6196cbd8c3b07d86
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_63146.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+ as -v --64 -o CMakeFiles/cmTC_63146.dir/CMakeCXXCompilerABI.cpp.o /tmp/ccXqnn3f.s
+GNU assembler version 2.30 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.30
+COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/
+LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_63146.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+Linking CXX executable cmTC_63146
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_63146.dir/link.txt --verbose=1
+/usr/bin/c++ -v -rdynamic CMakeFiles/cmTC_63146.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_63146
+Using built-in specs.
+COLLECT_GCC=/usr/bin/c++
+COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
+OFFLOAD_TARGET_NAMES=nvptx-none
+OFFLOAD_TARGET_DEFAULT=1
+Target: x86_64-linux-gnu
+Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.3.0-27ubuntu1~18.04' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
+Thread model: posix
+gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)
+COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/
+LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_63146' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+ /usr/lib/gcc/x86_64-linux-gnu/7/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/7/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper -plugin-opt=-fresolution=/tmp/cca3NVun.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --sysroot=/ --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -export-dynamic -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_63146 /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/7 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/7/../../.. CMakeFiles/cmTC_63146.dir/CMakeCXXCompilerABI.cpp.o -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/7/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crtn.o
+COLLECT_GCC_OPTIONS='-v' '-rdynamic' '-o' 'cmTC_63146' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-GNU-7.3.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-GNU-7.3.0.output
new file mode 100644
index 000000000..af33ba8fe
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-GNU-7.3.0.output
@@ -0,0 +1 @@
+/usr/include/c\+\+/7;/usr/include/x86_64-linux-gnu/c\+\+/7;/usr/include/c\+\+/7/backward;/usr/lib/gcc/x86_64-linux-gnu/7/include;/usr/local/include;/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed;/usr/include/x86_64-linux-gnu;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-Intel-18.0.0.20170811.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-Intel-18.0.0.20170811.input
new file mode 100644
index 000000000..22d871598
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-Intel-18.0.0.20170811.input
@@ -0,0 +1,46 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=Intel
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=18.0.0.20170811
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_d768a/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_d768a.dir/build.make CMakeFiles/cmTC_d768a.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.o
+/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/icpc -v -o CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.o -c /tmp/CMake/Modules/CMakeCXXCompilerABI.cpp
+icpc version 18.0.0 (gcc version 4.8.5 compatibility)
+/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/mcpcom --target_efi2 --lang=c++ -_g -mP3OPT_inline_alloca -D__ICC=1800 -D__INTEL_COMPILER=1800 -D__INTEL_COMPILER_UPDATE=0 -D__PTRDIFF_TYPE__=long "-D__SIZE_TYPE__=unsigned long" -D__WCHAR_TYPE__=int "-D__WINT_TYPE__=unsigned int" "-D__INTMAX_TYPE__=long int" "-D__UINTMAX_TYPE__=long unsigned int" -D__LONG_MAX__=9223372036854775807L -D__QMSPP_ -D__OPTIMIZE__ -D__NO_MATH_INLINES -D__NO_STRING_INLINES -D__GNUC_GNU_INLINE__ -D__GNUG__=4 -D__GNUC__=4 -D__GNUC_MINOR__=8 -D__GNUC_PATCHLEVEL__=5 -D__LP64__ -D_LP64 -D_GNU_SOURCE=1 -D__DEPRECATED=1 -D__GXX_WEAK__=1 -D__GXX_ABI_VERSION=1002 "-D__USER_LABEL_PREFIX__= " -D__REGISTER_PREFIX__= -D__INTEL_RTTI__ -D__EXCEPTIONS=1 -D__unix__ -D__unix -D__linux__ -D__linux -D__gnu_linux__ -B -Dunix -Dlinux "-_Asystem(unix)" -D__ELF__ -D__x86_64 -D__x86_64__ -D__amd64 -D__amd64__ "-_Acpu(x86_64)" "-_Amachine(x86_64)" -D__INTEL_COMPILER_BUILD_DATE=20170811 -D__INTEL_OFFLOAD -D__i686 -D__i686__ -D__pentiumpro -D__pentiumpro__ -D__pentium4 -D__pentium4__ -D__tune_pentium4__ -D__SSE2__ -D__SSE2_MATH__ -D__SSE__ -D__SSE_MATH__ -D__MMX__ -_k -_8 -_l --has_new_stdarg_support -_a -_b --gnu_version=40805 -_W5 --gcc-extern-inline -p --bool -tused -x --multibyte_chars -mGLOB_diag_suppress_sys --system_preinclude /usr/include/stdc-predef.h --array_section --simd --simd_func --offload_mode=1 --offload_target_names=gfx,GFX,mic,MIC --offload_unique_string=icpc1792177319iuY4UR --bool -mGLOB_em64t=TRUE -mP1OPT_version=18.0-intel64 -mGLOB_diag_file=CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.diag -mGLOB_long_size_64 -mGLOB_routine_pointer_size_64 -mP1OPT_print_version=FALSE -mCG_use_gas_got_workaround=F -mP2OPT_align_option_used=TRUE -mGLOB_gcc_version=485 "-mGLOB_options_string=-v -o CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.o -c" -mGLOB_cxx_limited_range=FALSE -mCG_extend_parms=FALSE -mGLOB_compiler_bin_directory=/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64 -mGLOB_as_output_backup_file_name=/tmp/icpcv8rR8Aas_.s -mIPOPT_activate -mIPOPT_lite -mGLOB_instruction_tuning=0x0 -mGLOB_uarch_tuning=0x0 -mGLOB_product_id_code=0x22006d8f -mCG_bnl_movbe=T -mGLOB_extended_instructions=0x8 -mP3OPT_use_mspp_call_convention -mP2OPT_subs_out_of_bound=FALSE -mP2OPT_disam_type_based_disam=2 -mP2OPT_disam_assume_ansi_c -mP2OPT_checked_disam_ansi_alias=TRUE -mGLOB_ansi_alias -mPGOPTI_value_profile_use=T -mP2OPT_il0_array_sections=TRUE -mGLOB_offload_mode=1 -mP2OPT_offload_unique_var_string=icpc1792177319iuY4UR -mP2OPT_hlo_level=2 -mP2OPT_hlo -mP2OPT_hpo_rtt_control=0 -mIPOPT_args_in_regs=0 -mP2OPT_disam_assume_nonstd_intent_in=FALSE -mGLOB_imf_mapping_library=/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/libiml_attr.so -mPGOPTI_gen_threadsafe_level=0 -mIPOPT_lto_object_enabled -mIPOPT_lto_object_value=1 -mIPOPT_obj_output_file_name=CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.o -mIPOPT_whole_archive_fixup_file_name=/tmp/icpcwarchqQRwIj -mGLOB_linker_version=2.27 -mGLOB_driver_tempfile_name=/tmp/icpctempfilekXiB0a -mP3OPT_asm_target=P3OPT_ASM_TARGET_GAS -mGLOB_async_unwind_tables=TRUE -mGLOB_obj_output_file=CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.o -mGLOB_source_dialect=GLOB_SOURCE_DIALECT_C_PLUS_PLUS -mP1OPT_source_file_name=/tmp/CMake/Modules/CMakeCXXCompilerABI.cpp -mP1OPT_full_source_file_name=/tmp/CMake/Modules/CMakeCXXCompilerABI.cpp -mGLOB_eh_linux /tmp/CMake/Modules/CMakeCXXCompilerABI.cpp
+#include "..." search starts here:
+#include <...> search starts here:
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/include
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/include
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/pstl/include
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/include
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/include
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include/intel64
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include/icc
+ /opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include
+ /usr/include/c++/4.8.5
+ /usr/include/c++/4.8.5/x86_64-redhat-linux
+ /usr/include/c++/4.8.5/backward
+ /usr/local/include
+ /usr/lib/gcc/x86_64-redhat-linux/4.8.5/include
+ /usr/include/
+ /usr/include
+End of search list.
+Linking CXX executable cmTC_d768a
+/tmp/CMake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_d768a.dir/link.txt --verbose=1
+/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/icpc -v -rdynamic CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_d768a
+icpc version 18.0.0 (gcc version 4.8.5 compatibility)
+/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/mcpcom -mGLOB_em64t=TRUE -mP1OPT_version=18.0-intel64 -mGLOB_diag_file=CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.diag -mGLOB_long_size_64 -mGLOB_routine_pointer_size_64 -mP1OPT_print_version=FALSE -mCG_use_gas_got_workaround=F -mP2OPT_align_option_used=TRUE -mGLOB_gcc_version=485 "-mGLOB_options_string=-v -rdynamic -o cmTC_d768a" -mGLOB_cxx_limited_range=FALSE -mCG_extend_parms=FALSE -mGLOB_compiler_bin_directory=/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64 -mGLOB_as_output_backup_file_name=/tmp/icpczjpPCuas_.s -mGLOB_dashboard_use_source_name -mIPOPT_activate -mGLOB_product_id_code=0x22006d8f -mP3OPT_use_mspp_call_convention -mP2OPT_subs_out_of_bound=FALSE -mP2OPT_disam_type_based_disam=2 -mP2OPT_disam_assume_ansi_c -mP2OPT_checked_disam_ansi_alias=TRUE -mGLOB_ansi_alias -mPGOPTI_value_profile_use=T -mGLOB_opt_report_use_source_name -mP2OPT_il0_array_sections=TRUE -mGLOB_offload_mode=1 -mP2OPT_offload_unique_var_string=icpc1401760296yQqGc2 -mP2OPT_hlo -mP2OPT_hpo_rtt_control=0 -mIPOPT_args_in_regs=0 -mP2OPT_disam_assume_nonstd_intent_in=FALSE -mGLOB_imf_mapping_library=/opt/intel/compilers_and_libraries_2018.0.128/linux/bin/intel64/libiml_attr.so -mPGOPTI_gen_threadsafe_level=0 -mIPOPT_link -mIPOPT_ipo_activate -mIPOPT_mo_activate -mIPOPT_source_files_list=/tmp/icpcslis4PdBUT -mIPOPT_mo_global_data -mIPOPT_link_script_file=/tmp/icpcscript0uzJtL "-mIPOPT_cmdline_link="/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o" "/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crti.o" "/usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtbegin.o" "-export-dynamic" "--eh-frame-hdr" "--build-id" "-dynamic-linker" "/lib64/ld-linux-x86-64.so.2" "-m" "elf_x86_64" "-o" "cmTC_d768a" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/lib/intel64" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/lib/intel64_lin" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin" "-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/" "-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64" "-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/" "-L/lib/../lib64" "-L/lib/../lib64/" "-L/usr/lib/../lib64" "-L/usr/lib/../lib64/" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/lib/intel64/" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin/" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/lib/intel64_lin/" "-L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7/" "-L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../" "-L/lib64" "-L/lib/" "-L/usr/lib64" "-L/usr/lib" "CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.o" "-Bdynamic" "-Bstatic" "-limf" "-lsvml" "-lirng" "-Bdynamic" "-lstdc++" "-lm" "-Bstatic" "-lipgo" "-ldecimal" "--as-needed" "-Bdynamic" "-lcilkrts" "--no-as-needed" "-lstdc++" "-lgcc" "-lgcc_s" "-Bstatic" "-lirc" "-lsvml" "-Bdynamic" "-lc" "-lgcc" "-lgcc_s" "-Bstatic" "-lirc_s" "-Bdynamic" "-ldl" "-lc" "/usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtend.o" "/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crtn.o"" -mIPOPT_il_in_obj -mIPOPT_ipo_activate_warn=FALSE -mIPOPT_obj_output_file_name=/tmp/ipo_icpcGEmWvI.o -mIPOPT_whole_archive_fixup_file_name=/tmp/icpcwarchvs7jo5 -mGLOB_linker_version=2.27 -mGLOB_driver_tempfile_name=/tmp/icpctempfileQPMrZW -mP3OPT_asm_target=P3OPT_ASM_TARGET_GAS -mGLOB_async_unwind_tables=TRUE -mGLOB_obj_output_file=/tmp/ipo_icpcGEmWvI.o -mGLOB_source_dialect=GLOB_SOURCE_DIALECT_NONE -mP1OPT_source_file_name=ipo_out.c CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.o -mIPOPT_object_files=T -mIPOPT_assembly_files=/tmp/icpcalisfym8Dr -mIPOPT_generated_tempfiles=/tmp/icpcelisfz0edj -mIPOPT_embedded_object_base_name=/tmp/icpceobjS73lMa -mIPOPT_cmdline_link_new_name=/tmp/icpcllisTgrtl2
+ld /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crti.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtbegin.o -export-dynamic --eh-frame-hdr --build-id -dynamic-linker /lib64/ld-linux-x86-64.so.2 -m elf_x86_64 -o cmTC_d768a -L/opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/lib/intel64 -L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin -L/opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/lib/intel64_lin -L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7 -L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7 -L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/ -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64 -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/ -L/lib/../lib64 -L/lib/../lib64/ -L/usr/lib/../lib64 -L/usr/lib/../lib64/ -L/opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/lib/intel64/ -L/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/lib/intel64_lin/ -L/opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/lib/intel64_lin/ -L/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/lib/intel64/gcc4.7/ -L/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../ -L/lib64 -L/lib/ -L/usr/lib64 -L/usr/lib CMakeFiles/cmTC_d768a.dir/CMakeCXXCompilerABI.cpp.o -Bdynamic -Bstatic -limf -lsvml -lirng -Bdynamic -lstdc++ -lm -Bstatic -lipgo -ldecimal --as-needed -Bdynamic -lcilkrts --no-as-needed -lstdc++ -lgcc -lgcc_s -Bstatic -lirc -lsvml -Bdynamic -lc -lgcc -lgcc_s -Bstatic -lirc_s -Bdynamic -ldl -lc /usr/lib/gcc/x86_64-redhat-linux/4.8.5/crtend.o /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crtn.o
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-Intel-18.0.0.20170811.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-Intel-18.0.0.20170811.output
new file mode 100644
index 000000000..95bdf991c
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-Intel-18.0.0.20170811.output
@@ -0,0 +1 @@
+/opt/intel/compilers_and_libraries_2018.0.128/linux/ipp/include;/opt/intel/compilers_and_libraries_2018.0.128/linux/mkl/include;/opt/intel/compilers_and_libraries_2018.0.128/linux/pstl/include;/opt/intel/compilers_and_libraries_2018.0.128/linux/tbb/include;/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include/intel64;/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include/icc;/opt/intel/compilers_and_libraries_2018.0.128/linux/compiler/include;/usr/include/c\+\+/4.8.5;/usr/include/c\+\+/4.8.5/x86_64-redhat-linux;/usr/include/c\+\+/4.8.5/backward;/usr/local/include;/usr/lib/gcc/x86_64-redhat-linux/4.8.5/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-PGI-18.10.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-PGI-18.10.1.input
new file mode 100644
index 000000000..f95627ee4
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-PGI-18.10.1.input
@@ -0,0 +1,40 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=PGI
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=18.10.1
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_9932f/fast"
+/usr/bin/make -f CMakeFiles/cmTC_9932f.dir/build.make CMakeFiles/cmTC_9932f.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_9932f.dir/CMakeCXXCompilerABI.cpp.o
+/mnt/pgi/linux86-64/2018/bin/pgc++ -v -o CMakeFiles/cmTC_9932f.dir/CMakeCXXCompilerABI.cpp.o -c /usr/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/mnt/pgi/linux86-64/18.10/bin/pggpp1 --llalign -Dunix -D__unix -D__unix__ -Dlinux -D__linux -D__linux__ -D__NO_MATH_INLINES -D__LP64__ -D__x86_64 -D__x86_64__ -D__LONG_MAX__=9223372036854775807L '-D__SIZE_TYPE__=unsigned long int' '-D__PTRDIFF_TYPE__=long int' -D__extension__= -D__amd_64__amd64__ -D__k8 -D__k8__ -D__SSE__ -D__MMX__ -D__SSE2__ -D__SSE3__ -D__PGI -D_GNU_SOURCE -D_PGCG_SOURCE -I- -I/mnt/pgi/linux86-64/18.10/include-gcc70 -I/mnt/pgi/linux86-64/18.10/include -I/usr/include/c++/7 -I/usr/include/x86_64-linux-gnu/c++/7 -I/usr/include/c++/7/backward -I/usr/lib/gcc/x86_64-linux-gnu/7/include -I/usr/local/include -I/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed -I/usr/include/x86_64-linux-gnu -I/usr/include --preinclude _cplus_preinclude.h --preinclude_macros _cplus_macros.h --gnu_version=70300 -D__pgnu_vsn=70300 -q -o /tmp/pgc++9bCe3jXUexoO.il /usr/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp
+
+/mnt/pgi/linux86-64/18.10/bin/pggpp2 /usr/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp -opt 1 -x 119 0xa10000 -x 122 0x40 -x 123 0x1000 -x 127 4 -x 127 17 -x 19 0x400000 -x 28 0x40000 -x 120 0x10000000 -x 70 0x8000 -x 122 1 -x 125 0x20000 -quad -x 59 4 -tp k8 -x 120 0x1000 -astype 0 -fn /usr/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp -il /tmp/pgc++9bCe3jXUexoO.il -x 117 0x600 -x 123 0x80000000 -x 123 4 -x 119 0x20 -def __pgnu_vsn=70300 -x 120 0x200000 -x 70 0x40000000 -x 164 0x800000 -y 163 0xc0000000 -x 189 0x10 -y 189 0x4000000 -gnuvsn 70300 -x 69 0x200 -cmdline '+pgc++ /tmp/pgc++9bCe3jXUexoO.il -v -o CMakeFiles/cmTC_9932f.dir/CMakeCXXCompilerABI.cpp.o -c' -asm /tmp/pgc++LbCeVyAxx_Yt.s
+PGCC/x86 Linux 18.10-1: compilation successful
+
+/usr/bin/as /tmp/pgc++LbCeVyAxx_Yt.s -o CMakeFiles/cmTC_9932f.dir/CMakeCXXCompilerABI.cpp.o
+Action(ReadTIFile(./CMakeCXXCompilerABI.ti))
+Unlinking /tmp/pgc++9bCe3jXUexoO.il
+Unlinking /tmp/pgc++LbCeVyAxx_Yt.s
+Unlinking /tmp/pgc++nbCeNEnzNVv3.ll
+Linking CXX executable cmTC_9932f
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_9932f.dir/link.txt --verbose=1
+/mnt/pgi/linux86-64/2018/bin/pgc++ -v CMakeFiles/cmTC_9932f.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_9932f
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/usr/bin/ld /usr/lib/x86_64-linux-gnu/crt1.o /usr/lib/x86_64-linux-gnu/crti.o /mnt/pgi/linux86-64/18.10/lib/trace_init.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbegin.o /mnt/pgi/linux86-64/18.10/lib/initmp.o --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 /mnt/pgi/linux86-64/18.10/lib/pgi.ld -L/mnt/pgi/linux86-64/18.10/lib -L/usr/lib64 -L/usr/lib/gcc/x86_64-linux-gnu/7 CMakeFiles/cmTC_9932f.dir/CMakeCXXCompilerABI.cpp.o -rpath /mnt/pgi/linux86-64/18.10/lib -rpath /usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -o cmTC_9932f -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -latomic -lpgatm -lstdc++ -lpgmp -lnuma -lpthread --start-group -lpgmath -lnspgc -lpgc --end-group -lm -lgcc -lc -lgcc -lgcc_s /usr/lib/gcc/x86_64-linux-gnu/7/crtend.o /usr/lib/x86_64-linux-gnu/crtn.o
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-PGI-18.10.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-PGI-18.10.1.output
new file mode 100644
index 000000000..8eb97c84e
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-PGI-18.10.1.output
@@ -0,0 +1 @@
+/mnt/pgi/linux86-64/18.10/include-gcc70;/mnt/pgi/linux86-64/18.10/include;/usr/include/c\+\+/7;/usr/include/x86_64-linux-gnu/c\+\+/7;/usr/include/c\+\+/7/backward;/usr/lib/gcc/x86_64-linux-gnu/7/include;/usr/local/include;/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed;/usr/include/x86_64-linux-gnu;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-12.1.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-12.1.0.input
new file mode 100644
index 000000000..494b45c14
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-12.1.0.input
@@ -0,0 +1,42 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=XL
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=12.1.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_a9a18/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_a9a18.dir/build.make CMakeFiles/cmTC_a9a18.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_a9a18.dir/CMakeCXXCompilerABI.cpp.o
+/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/bin/xlc++ -+ -qthreaded -qhalt=e -V -o CMakeFiles/cmTC_a9a18.dir/CMakeCXXCompilerABI.cpp.o -c /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCXXCompilerABI.cpp
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlc++
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+export XL_ASMOBJFILES=/tmp/xlcAS0adOWz
+export "XL_DIS=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/dis -o "CMakeFiles/cmTC_a9a18.dir/CMakeCXXCompilerABI.cpp.o" "CMakeCXXCompilerABI.o""
+/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/exe/xlCentry -qosvar=rhel.6.9 -qalias=ansi -qtls -D_CALL_SYSV -D__null=0 -D__NO_MATH_INLINES -qtls -q64 -qgnu_version=4.4.7 -qthreaded -qhalt=e -qasm_as=/usr/bin/as -qcpp_stdinc=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/include -qc_stdinc=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include -qgcc_cpp_stdinc=/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../include/c++/4.4.7:/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ppc64-redhat-linux:/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/backward:/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qgcc_c_stdinc=/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qcomplexgccincl=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include:/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -oCMakeFiles/cmTC_a9a18.dir/CMakeCXXCompilerABI.cpp.o /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCXXCompilerABI.cpp /tmp/xlcW0C4fVNg /tmp/xlcW1gn9wsn /dev/null /tmp/xlcLo7QvMFF.lst /dev/null /tmp/xlcW2svId7t
+export XL_BACKEND=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode
+export XL_LINKER=/usr/bin/ld
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode -qalias=ansi -qtls -qtls -qthreaded -qhalt=e /tmp/xlcW0C4fVNg /tmp/xlcW1gn9wsn CMakeFiles/cmTC_a9a18.dir/CMakeCXXCompilerABI.cpp.o /tmp/xlcLo7QvMFB.lst /tmp/xlcW2svId7t
+rm /tmp/xlcAS0adOWz
+rm /tmp/xlcLo7QvMF
+rm /tmp/xlcW0C4fVNg
+rm /tmp/xlcW1gn9wsn
+rm /tmp/xlcW2svId7t
+Linking CXX executable cmTC_a9a18
+/soft/buildtools/cmake/3.5.2/bin/cmake -E cmake_link_script CMakeFiles/cmTC_a9a18.dir/link.txt --verbose=1
+/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/bin/xlc++ -qthreaded -qhalt=e -V CMakeFiles/cmTC_a9a18.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_a9a18 -Wl,-export-dynamic
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlc++
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+/usr/bin/ld --eh-frame-hdr -Qy -melf64ppc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crt1.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crti.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtbegin.o -L/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/lib64 -L/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/lib64 -L/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/lib64 -L/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/lib64 -R/soft/compilers/ibmcmp-oct2017/lib64/bg -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../.. -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../.. CMakeFiles/cmTC_a9a18.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_a9a18 -export-dynamic -dynamic-linker /lib64/ld64.so.1 -lxlopt -lxl -libmc++ -lxlopt -lxl -lstdc++ -lm -ldl -lgcc_s -lgcc -lm -lc -lgcc_s -lgcc -ldl -lgcc_s -lgcc -lm -lc -lgcc_s -lgcc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtend.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crtn.o
+rm /tmp/xlcW0zyCKVs
+rm /tmp/xlcW1UOt3GL
+rm /tmp/xlcW2lKGvs4
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-12.1.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-12.1.0.output
new file mode 100644
index 000000000..d6d3e58fd
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-12.1.0.output
@@ -0,0 +1 @@
+/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include;/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include;/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/include;/usr/include/c\+\+/4.4.7;/usr/include/c\+\+/4.4.7/ppc64-redhat-linux;/usr/include/c\+\+/4.4.7/backward;/usr/local/include;/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-16.1.0.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-16.1.0.0.input
new file mode 100644
index 000000000..37aa450fb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-16.1.0.0.input
@@ -0,0 +1,40 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=XL
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=16.1.0.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_f0c9c/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_f0c9c.dir/build.make CMakeFiles/cmTC_f0c9c.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_f0c9c.dir/CMakeCXXCompilerABI.cpp.o
+/opt/ibm/xlC/16.1.0/bin/xlc++ -+ -qthreaded -V -o CMakeFiles/cmTC_f0c9c.dir/CMakeCXXCompilerABI.cpp.o -c "/tmp/CMake/Modules/CMakeCXXCompilerABI.cpp"
+export XL_CONFIG=/opt/ibm/xlC/16.1.0/etc/xlc.cfg.centos.7.gcc.4.8.5:xlc++
+export XL_ASMOBJFILES=/tmp/xlcASfU5Npd
+export "XL_DIS=/opt/ibm/xlC/16.1.0/exe/dis -o "CMakeFiles/cmTC_f0c9c.dir/CMakeCXXCompilerABI.cpp.o" "CMakeCXXCompilerABI.o""
+/opt/ibm/xlC/16.1.0/exe/xlCentry -qosvar=centos.7.0 -qalias=ansi -qthreaded -D_REENTRANT -D__VACPP_MULTI__ -qtls -q64 -D_CALL_SYSV -D__NO_MATH_INLINES -D_CALL_ELF=2 -Wno-parentheses -Wno-unused-value -maltivec -qtls -q64 -qgnu_version=4.8.5 -qthreaded -xc++ -qasm_as=/usr/bin/as -qcpp_stdinc=/opt/ibm/xlsmp/5.1.0/include:/opt/ibm/xlmass/9.1.0/include:/opt/ibm/xlC/16.1.0/include -qc_stdinc=/opt/ibm/xlsmp/5.1.0/include:/opt/ibm/xlsmp/5.1.0/include:/opt/ibm/xlmass/9.1.0/include:/opt/ibm/xlC/16.1.0/include -qgcc_cpp_stdinc=/usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../include/c++/4.8.5:/usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../include/c++/4.8.5/ppc64le-redhat-linux:/usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../include/c++/4.8.5/backward:/opt/ibm/xlC/16.1.0/include:/usr/local/include:/opt/ibm/xlC/16.1.0/include:/usr/include -qgcc_c_stdinc=/opt/ibm/xlC/16.1.0/include:/usr/local/include:/opt/ibm/xlC/16.1.0/include:/usr/include -qcomplexgccincl=/opt/ibm/xlsmp/5.1.0/include:/opt/ibm/xlmass/9.1.0/include:/opt/ibm/xlC/16.1.0/include:/opt/ibm/xlC/16.1.0/include:/usr/local/include:/opt/ibm/xlC/16.1.0/include:/usr/include -oCMakeFiles/cmTC_f0c9c.dir/CMakeCXXCompilerABI.cpp.o "/tmp/CMake/Modules/CMakeCXXCompilerABI.cpp" /tmp/xlcW02F8mZr /tmp/xlcW1xG0Ns2 /dev/null /tmp/xlcLI57mTNF.lst /dev/null /tmp/xlcW2qVifWC
+export XL_BACKEND=/opt/ibm/xlC/16.1.0/exe/xlCcode
+export XL_LINKER=/usr/bin/ld
+/opt/ibm/xlC/16.1.0/exe/xlCcode -qalias=ansi -qthreaded -qtls -maltivec -qtls -qthreaded /tmp/xlcW02F8mZr /tmp/xlcW1xG0Ns2 CMakeFiles/cmTC_f0c9c.dir/CMakeCXXCompilerABI.cpp.o /tmp/xlcLI57mTNB.lst /tmp/xlcW2qVifWC
+rm /tmp/xlcASfU5Npd
+rm /tmp/xlcLI57mTN
+rm /tmp/xlcW02F8mZr
+rm /tmp/xlcW1xG0Ns2
+rm /tmp/xlcW2qVifWC
+Linking CXX executable cmTC_f0c9c
+"/tmp/CMake/bin/cmake" -E cmake_link_script CMakeFiles/cmTC_f0c9c.dir/link.txt --verbose=1
+/opt/ibm/xlC/16.1.0/bin/xlc++ -qthreaded -V -Wl,-export-dynamic CMakeFiles/cmTC_f0c9c.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_f0c9c
+export XL_CONFIG=/opt/ibm/xlC/16.1.0/etc/xlc.cfg.centos.7.gcc.4.8.5:xlc++
+/usr/bin/ld --eh-frame-hdr -Qy -melf64lppc -dynamic-linker /lib64/ld64.so.2 --enable-new-dtags /usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../lib64/crt1.o /usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../lib64/crti.o /usr/lib/gcc/ppc64le-redhat-linux/4.8.5/crtbegin.o -L/opt/ibm/xlsmp/5.1.0/lib -L/opt/ibm/xlmass/9.1.0/lib -L/opt/ibm/xlC/16.1.0/lib -R/opt/ibm/lib -L/usr/lib/gcc/ppc64le-redhat-linux/4.8.5 -L/usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../.. -export-dynamic CMakeFiles/cmTC_f0c9c.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_f0c9c -lxlopt -lxl -libmc++ -lstdc++ -lm -ldl -lgcc_s -lgcc --as-needed -lpthread --no-as-needed -lm -lc -lgcc_s -lgcc /usr/lib/gcc/ppc64le-redhat-linux/4.8.5/crtend.o /usr/lib/gcc/ppc64le-redhat-linux/4.8.5/../../../../lib64/crtn.o
+rm /tmp/xlcW0HSoDlw
+rm /tmp/xlcW1dUcwR6
+rm /tmp/xlcW25pPonH
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-16.1.0.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-16.1.0.0.output
new file mode 100644
index 000000000..9e118fc5a
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-CXX-XL-16.1.0.0.output
@@ -0,0 +1 @@
+/opt/ibm/xlsmp/5.1.0/include;/opt/ibm/xlmass/9.1.0/include;/opt/ibm/xlC/16.1.0/include;/usr/include/c\+\+/4.8.5;/usr/include/c\+\+/4.8.5/ppc64le-redhat-linux;/usr/include/c\+\+/4.8.5/backward;/usr/local/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-GNU-7.3.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-GNU-7.3.0.input
new file mode 100644
index 000000000..4582433de
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-GNU-7.3.0.input
@@ -0,0 +1,76 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=
+CMAKE_Fortran_COMPILER_AR=/usr/bin/gcc-ar-7
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=GNU
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=/usr/bin/gcc-ranlib-7
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=7.3.0
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_1cf45/fast"
+/usr/bin/make -f CMakeFiles/cmTC_1cf45.dir/build.make CMakeFiles/cmTC_1cf45.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_1cf45.dir/CMakeFortranCompilerABI.F.o
+/usr/bin/f95 -v -c /proj/TableFS/data/chuck/cmake/f/share/cmake-3.13/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_1cf45.dir/CMakeFortranCompilerABI.F.o
+Using built-in specs.
+COLLECT_GCC=/usr/bin/f95
+OFFLOAD_TARGET_NAMES=nvptx-none
+OFFLOAD_TARGET_DEFAULT=1
+Target: x86_64-linux-gnu
+Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.3.0-27ubuntu1~18.04' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
+Thread model: posix
+gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)
+COLLECT_GCC_OPTIONS='-v' '-c' '-o' 'CMakeFiles/cmTC_1cf45.dir/CMakeFortranCompilerABI.F.o' '-mtune=generic' '-march=x86-64'
+ /usr/lib/gcc/x86_64-linux-gnu/7/f951 /proj/TableFS/data/chuck/cmake/f/share/cmake-3.13/Modules/CMakeFortranCompilerABI.F -ffixed-form -cpp=/tmp/cc9yADLU.f90 -quiet -v -imultiarch x86_64-linux-gnu /proj/TableFS/data/chuck/cmake/f/share/cmake-3.13/Modules/CMakeFortranCompilerABI.F -quiet -dumpbase CMakeFortranCompilerABI.F -mtune=generic -march=x86-64 -auxbase-strip CMakeFiles/cmTC_1cf45.dir/CMakeFortranCompilerABI.F.o -version -fintrinsic-modules-path /usr/lib/gcc/x86_64-linux-gnu/7/finclude -o /tmp/ccH7qQQk.s
+GNU Fortran (Ubuntu 7.3.0-27ubuntu1~18.04) version 7.3.0 (x86_64-linux-gnu)
+ compiled by GNU C version 7.3.0, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0, isl version isl-0.19-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"
+ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/7/../../../../x86_64-linux-gnu/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/lib/gcc/x86_64-linux-gnu/7/finclude
+ /usr/lib/gcc/x86_64-linux-gnu/7/include
+ /usr/local/include
+ /usr/lib/gcc/x86_64-linux-gnu/7/include-fixed
+ /usr/include/x86_64-linux-gnu
+ /usr/include
+End of search list.
+GNU Fortran2008 (Ubuntu 7.3.0-27ubuntu1~18.04) version 7.3.0 (x86_64-linux-gnu)
+ compiled by GNU C version 7.3.0, GMP version 6.1.2, MPFR version 4.0.1, MPC version 1.1.0, isl version isl-0.19-GMP
+
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+COLLECT_GCC_OPTIONS='-v' '-c' '-o' 'CMakeFiles/cmTC_1cf45.dir/CMakeFortranCompilerABI.F.o' '-mtune=generic' '-march=x86-64'
+ as -v --64 -o CMakeFiles/cmTC_1cf45.dir/CMakeFortranCompilerABI.F.o /tmp/ccH7qQQk.s
+GNU assembler version 2.30 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.30
+COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/
+LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-c' '-o' 'CMakeFiles/cmTC_1cf45.dir/CMakeFortranCompilerABI.F.o' '-mtune=generic' '-march=x86-64'
+Linking Fortran executable cmTC_1cf45
+/proj/TableFS/data/chuck/cmake/f/bin/cmake -E cmake_link_script CMakeFiles/cmTC_1cf45.dir/link.txt --verbose=1
+/usr/bin/f95 -v CMakeFiles/cmTC_1cf45.dir/CMakeFortranCompilerABI.F.o -o cmTC_1cf45
+Driving: /usr/bin/f95 -v CMakeFiles/cmTC_1cf45.dir/CMakeFortranCompilerABI.F.o -o cmTC_1cf45 -l gfortran -l m -shared-libgcc
+Using built-in specs.
+COLLECT_GCC=/usr/bin/f95
+COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
+OFFLOAD_TARGET_NAMES=nvptx-none
+OFFLOAD_TARGET_DEFAULT=1
+Target: x86_64-linux-gnu
+Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.3.0-27ubuntu1~18.04' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
+Thread model: posix
+gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)
+Reading specs from /usr/lib/gcc/x86_64-linux-gnu/7/libgfortran.spec
+rename spec lib to liborig
+COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_1cf45' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/
+LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/7/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/7/../../../:/lib/:/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_1cf45' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+ /usr/lib/gcc/x86_64-linux-gnu/7/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/7/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper -plugin-opt=-fresolution=/tmp/ccS0UYIY.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lquadmath -plugin-opt=-pass-through=-lm -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --sysroot=/ --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_1cf45 /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/7 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/7/../../.. CMakeFiles/cmTC_1cf45.dir/CMakeFortranCompilerABI.F.o -lgfortran -lm -lgcc_s -lgcc -lquadmath -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/7/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/crtn.o
+COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_1cf45' '-shared-libgcc' '-mtune=generic' '-march=x86-64'
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-GNU-7.3.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-GNU-7.3.0.output
new file mode 100644
index 000000000..d84842b6f
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-GNU-7.3.0.output
@@ -0,0 +1 @@
+/usr/lib/gcc/x86_64-linux-gnu/7/finclude;/usr/lib/gcc/x86_64-linux-gnu/7/include;/usr/local/include;/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed;/usr/include/x86_64-linux-gnu;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-PGI-18.10.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-PGI-18.10.1.input
new file mode 100644
index 000000000..fe49bcdee
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-PGI-18.10.1.input
@@ -0,0 +1,47 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=
+CMAKE_Fortran_COMPILER_AR=
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=PGI
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=18.10.1
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_1e8d2/fast"
+/usr/bin/make -f CMakeFiles/cmTC_1e8d2.dir/build.make CMakeFiles/cmTC_1e8d2.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_1e8d2.dir/CMakeFortranCompilerABI.F.o
+/mnt/pgi/linux86-64/2018/bin/pgfortran -v -c /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_1e8d2.dir/CMakeFortranCompilerABI.F.o
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/mnt/pgi/linux86-64/18.10/bin/pgf901 /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -opt 1 -nohpf -nostatic -x 19 0x400000 -quad -x 59 4 -x 15 2 -x 49 0x400004 -x 51 0x20 -x 57 0x4c -x 58 0x10000 -x 124 0x1000 -tp k8 -x 57 0xfb0000 -x 58 0x78031040 -x 47 0x08 -x 48 4608 -x 49 0x100 -x 120 0x200 -stdinc /mnt/pgi/linux86-64/18.10/include-gcc70:/mnt/pgi/linux86-64/18.10/include:/usr/lib/gcc/x86_64-linux-gnu/7/include:/usr/local/include:/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed:/usr/include/x86_64-linux-gnu:/usr/include -cmdline '+pgfortran /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -v -c -o CMakeFiles/cmTC_1e8d2.dir/CMakeFortranCompilerABI.F.o' -def unix -def __unix -def __unix__ -def linux -def __linux -def __linux__ -def __NO_MATH_INLINES -def __LP64__ -def __x86_64 -def __x86_64__ -def __LONG_MAX__=9223372036854775807L -def '__SIZE_TYPE__=unsigned long int' -def '__PTRDIFF_TYPE__=long int' -def __extension__= -def __amd_64__amd64__ -def __k8 -def __k8__ -def __SSE__ -def __MMX__ -def __SSE2__ -def __SSE3__ -preprocess -nofreeform -vect 48 -x 54 1 -x 70 0x40000000 -y 163 0xc0000000 -x 189 0x10 -modexport /tmp/pgfortranSoCeegQjDEd5.cmod -modindex /tmp/pgfortranmoCeK26CaVn7.cmdx -output /tmp/pgfortranSoCeeXSv8E7w.ilm
+ 0 inform, 0 warnings, 0 severes, 0 fatal for cmakefortrancompilerabi
+PGF90/x86-64 Linux 18.10-1: compilation successful
+
+/mnt/pgi/linux86-64/18.10/bin/pgf902 /tmp/pgfortranSoCeeXSv8E7w.ilm -fn /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -opt 1 -x 51 0x20 -x 119 0xa10000 -x 122 0x40 -x 123 0x1000 -x 127 4 -x 127 17 -x 19 0x400000 -x 28 0x40000 -x 120 0x10000000 -x 70 0x8000 -x 122 1 -x 125 0x20000 -quad -x 59 4 -tp k8 -x 120 0x1000 -x 124 0x1400 -y 15 2 -x 57 0x3b0000 -x 58 0x48000000 -x 49 0x100 -x 120 0x200 -astype 0 -x 68 0x20 -x 70 0x40000000 -x 164 0x800000 -x 124 1 -y 163 0xc0000000 -x 189 0x10 -y 189 0x4000000 -cmdline '+pgfortran /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -v -c -o CMakeFiles/cmTC_1e8d2.dir/CMakeFortranCompilerABI.F.o' -asm /tmp/pgfortranSoCeeRr681iB.s
+ 0 inform, 0 warnings, 0 severes, 0 fatal for cmakefortrancompilerabi
+PGF90/x86-64 Linux 18.10-1: compilation successful
+
+/usr/bin/as /tmp/pgfortranSoCeeRr681iB.s -o CMakeFiles/cmTC_1e8d2.dir/CMakeFortranCompilerABI.F.o
+
+/mnt/pgi/linux86-64/18.10/bin/pgappend -noerror CMakeFiles/cmTC_1e8d2.dir/CMakeFortranCompilerABI.F.o -name .IPDINFO /tmp/pgfortranSoCeegQjDEd5.cmod -name .IPEINFO /tmp/pgfortranmoCeK26CaVn7.cmdx
+Unlinking /tmp/pgfortranSoCeeXSv8E7w.ilm
+Unlinking /tmp/pgfortranmoCeK5sPGGfq.stb
+Unlinking /tmp/pgfortranSoCeegQjDEd5.cmod
+Unlinking /tmp/pgfortranmoCeK26CaVn7.cmdx
+Unlinking /tmp/pgfortranSoCeeRr681iB.s
+Unlinking /tmp/pgfortranmoCeKdFYP9Gu.ll
+Linking Fortran executable cmTC_1e8d2
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_1e8d2.dir/link.txt --verbose=1
+/mnt/pgi/linux86-64/2018/bin/pgfortran -v CMakeFiles/cmTC_1e8d2.dir/CMakeFortranCompilerABI.F.o -o cmTC_1e8d2
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/usr/bin/ld /usr/lib/x86_64-linux-gnu/crt1.o /usr/lib/x86_64-linux-gnu/crti.o /mnt/pgi/linux86-64/18.10/lib/trace_init.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbegin.o /mnt/pgi/linux86-64/18.10/lib/initmp.o /mnt/pgi/linux86-64/18.10/lib/f90main.o --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 /mnt/pgi/linux86-64/18.10/lib/pgi.ld -L/mnt/pgi/linux86-64/18.10/lib -L/usr/lib64 -L/usr/lib/gcc/x86_64-linux-gnu/7 CMakeFiles/cmTC_1e8d2.dir/CMakeFortranCompilerABI.F.o -rpath /mnt/pgi/linux86-64/18.10/lib -rpath /usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -o cmTC_1e8d2 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -lpgf90rtl -lpgf90 -lpgf90_rpm1 -lpgf902 -lpgf90rtl -lpgftnrtl -lpgmp -lnuma -lpthread --start-group -lpgmath -lnspgc -lpgc --end-group -lrt -lpthread -lm -lgcc -lc -lgcc -lgcc_s /usr/lib/gcc/x86_64-linux-gnu/7/crtend.o /usr/lib/x86_64-linux-gnu/crtn.o
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-PGI-18.10.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-PGI-18.10.1.output
new file mode 100644
index 000000000..289c530a6
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-PGI-18.10.1.output
@@ -0,0 +1 @@
+/mnt/pgi/linux86-64/18.10/include-gcc70;/mnt/pgi/linux86-64/18.10/include;/usr/lib/gcc/x86_64-linux-gnu/7/include;/usr/local/include;/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed;/usr/include/x86_64-linux-gnu;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-XL-14.1.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-XL-14.1.0.input
new file mode 100644
index 000000000..d80cedef7
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-XL-14.1.0.input
@@ -0,0 +1,50 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=ELF
+CMAKE_Fortran_COMPILER_AR=
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=XL
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=14.1.0
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_d05a9/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_d05a9.dir/build.make CMakeFiles/cmTC_d05a9.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_d05a9.dir/CMakeFortranCompilerABI.F.o
+/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/bin/xlf -qthreaded -qhalt=e -V -c /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_d05a9.dir/CMakeFortranCompilerABI.F.o
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/etc/xlf.cfg.rhel6.9.gcc447:xlf
+export XLF_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/etc/V1R2M4.xlf.cfg.rhel6.9.gcc447
+export "XL_DIS=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/dis -o "CMakeFiles/cmTC_d05a9.dir/CMakeFortranCompilerABI.F.o" "CMakeFortranCompilerABI.o""
+/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/cpp /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeFortranCompilerABI.F /tmp/F841970obBXFf -C -I/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include -I/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/include
+/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/xlfentry /tmp/F841970obBXFf /tmp/F841970QXWvB4 /tmp/F841970QXWvB4F.lst xlfsmsg.cat xlfmsg.cat /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeFortranCompilerABI.F "OSVAR(rhel.6.9)" NOZEROSIZE SAVE "ALIAS(intptr)" "POSITION(appendold)" "XLF90(noautodealloc,nosignedzero,oldpad)" "XLF77(intarg,intxor,persistent,noleadzero,gedit77,noblankpad,oldboz,softeof)" "XLF2003(nopolymorphic,nobozlitargs,nostopexcept,novolatile,noautorealloc,oldnaninf)" "XLF2008(nocheckpresence)" 64 "GNU_VERSION(4.4.7)" "SAVEOPTFILE(/tmp/optf.41970mydp8V)" "SAVEVERSIONFILE(/tmp/version.41970sjsfYH)" THREADED "HALT(e)" "WSTREAMS(/tmp/F8419704oFzOth1,/tmp/F8419704oFzOtb1,/tmp/F8419704oFzOts1)" "DEFMSG(/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/msg/en_US)" -I/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include -I/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/include
+COMMAND LINE 1520-061 (W) The XLF77(PERSISTENT) option stores entities in static storage. This may affect the thread safety of your code.
+COMMAND LINE 1520-061 (W) The SAVE option stores entities in static storage. This may affect the thread safety of your code.
+** cmakefortrancompilerabi === End of Compilation 1 ===
+rm /tmp/F841970obBXFf
+export XL_FRONTEND=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/xlfentry
+export XL_ASTI=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/xlfhot
+export XL_BACKEND=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/xlfcode
+export XL_LINKER=/usr/bin/ld
+export XL_BOLT=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/bolt
+/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/xlfhot /tmp/F8419704oFzOth1 /tmp/F8419704oFzOth2 /tmp/F8419704oFzOtb1 /tmp/F8419704oFzOtb2 /tmp/F8419704oFzOts1 /tmp/F8419704oFzOts2 /tmp/F841970QXWvB4 /tmp/F841970QXWvB4A.lst
+export XL_FRONTEND=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/xlfentry
+export XL_ASTI=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/xlfhot
+export XL_BACKEND=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/xlfcode
+export XL_LINKER=/usr/bin/ld
+export XL_BOLT=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/bolt
+/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/exe/xlfcode /tmp/F8419704oFzOth2 /tmp/F8419704oFzOtb2 CMakeFiles/cmTC_d05a9.dir/CMakeFortranCompilerABI.F.o /tmp/F841970QXWvB4B.lst /tmp/F8419704oFzOts2
+1501-510 Compilation successful for file CMakeFortranCompilerABI.F.
+rm /tmp/optf.41970mydp8V
+Linking Fortran executable cmTC_d05a9
+/soft/buildtools/cmake/3.5.2/bin/cmake -E cmake_link_script CMakeFiles/cmTC_d05a9.dir/link.txt --verbose=1
+/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/bin/xlf -V -qthreaded -qhalt=e CMakeFiles/cmTC_d05a9.dir/CMakeFortranCompilerABI.F.o -o cmTC_d05a9 -Wl,-export-dynamic
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/etc/xlf.cfg.rhel6.9.gcc447:xlf
+export XLF_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/etc/V1R2M4.xlf.cfg.rhel6.9.gcc447
+/usr/bin/ld --eh-frame-hdr -Qy -melf64ppc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crt1.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crti.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtbegin.o -L/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/lib64 -L/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/lib64 -L/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/lib64 -R/soft/compilers/ibmcmp-oct2017/lib64/bg -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../.. CMakeFiles/cmTC_d05a9.dir/CMakeFortranCompilerABI.F.o -o cmTC_d05a9 -export-dynamic -dynamic-linker /lib64/ld64.so.1 -lxlf90 -lxlopt -lxlomp_ser -lxl -lxlfmath -lgcc_s -ldl -lrt -lpthread -lgcc -lm -lc -lgcc_s -lgcc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtend.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crtn.o
+rm /tmp/optf.419839KEged
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-XL-14.1.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-XL-14.1.0.output
new file mode 100644
index 000000000..39a28a46b
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux-Fortran-XL-14.1.0.output
@@ -0,0 +1 @@
+/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include;/soft/compilers/ibmcmp-oct2017/xlf/bg/14.1/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-PGI-18.10.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-PGI-18.10.1.input
new file mode 100644
index 000000000..5e2e49ab8
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-PGI-18.10.1.input
@@ -0,0 +1,36 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=PGI
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=18.10.1
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_a7f0d/fast"
+/usr/bin/make -f CMakeFiles/cmTC_a7f0d.dir/build.make CMakeFiles/cmTC_a7f0d.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_a7f0d.dir/CMakeCCompilerABI.c.o
+/mnt/pgi/linux86-64/2018/bin/pgcc -Mnostdinc -v -o CMakeFiles/cmTC_a7f0d.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/mnt/pgi/linux86-64/18.10/bin/pgc /usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c -opt 1 -x 119 0xa10000 -x 122 0x40 -x 123 0x1000 -x 127 4 -x 127 17 -x 19 0x400000 -x 28 0x40000 -x 120 0x10000000 -x 70 0x8000 -x 122 1 -x 125 0x20000 -quad -x 59 4 -tp k8 -x 120 0x1000 -astype 0 -nostdinc -def unix -def __unix -def __unix__ -def linux -def __linux -def __linux__ -def __NO_MATH_INLINES -def __LP64__ -def __x86_64 -def __x86_64__ -def __LONG_MAX__=9223372036854775807L -def '__SIZE_TYPE__=unsigned long int' -def '__PTRDIFF_TYPE__=long int' -def __extension__= -def __amd_64__amd64__ -def __k8 -def __k8__ -def __SSE__ -def __MMX__ -def __SSE2__ -def __SSE3__ -predicate '#machine(x86_64) #lint(off) #system(posix) #cpu(x86_64)' -cmdline '+pgcc /usr/share/cmake-3.10/Modules/CMakeCCompilerABI.c -Mnostdinc -v -o CMakeFiles/cmTC_a7f0d.dir/CMakeCCompilerABI.c.o -c' -outfile CMakeFiles/cmTC_a7f0d.dir/CMakeCCompilerABI.c.o -x 123 0x80000000 -x 123 4 -x 2 0x400 -x 119 0x20 -def __pgnu_vsn=70300 -x 120 0x200000 -x 70 0x40000000 -x 164 0x800000 -y 163 0xc0000000 -x 189 0x10 -y 189 0x4000000 -asm /tmp/pgccjRkfBrHQsITu.s
+PGC/x86-64 Linux 18.10-1: compilation successful
+
+/usr/bin/as /tmp/pgccjRkfBrHQsITu.s -o CMakeFiles/cmTC_a7f0d.dir/CMakeCCompilerABI.c.o
+Unlinking /tmp/pgccjRkfBrHQsITu.s
+Unlinking /tmp/pgccrRkfZClhdaSG.ll
+Linking C executable cmTC_a7f0d
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_a7f0d.dir/link.txt --verbose=1
+/mnt/pgi/linux86-64/2018/bin/pgcc -Mnostdinc -v CMakeFiles/cmTC_a7f0d.dir/CMakeCCompilerABI.c.o -o cmTC_a7f0d
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/usr/bin/ld /usr/lib/x86_64-linux-gnu/crt1.o /usr/lib/x86_64-linux-gnu/crti.o /mnt/pgi/linux86-64/18.10/lib/trace_init.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbegin.o /mnt/pgi/linux86-64/18.10/lib/initmp.o --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 /mnt/pgi/linux86-64/18.10/lib/pgi.ld -L/mnt/pgi/linux86-64/18.10/lib -L/usr/lib64 -L/usr/lib/gcc/x86_64-linux-gnu/7 CMakeFiles/cmTC_a7f0d.dir/CMakeCCompilerABI.c.o -rpath /mnt/pgi/linux86-64/18.10/lib -rpath /usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -o cmTC_a7f0d -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -lpgmp -lnuma -lpthread --start-group -lpgmath -lnspgc -lpgc --end-group -lm -lgcc -lc -lgcc -lgcc_s /usr/lib/gcc/x86_64-linux-gnu/7/crtend.o /usr/lib/x86_64-linux-gnu/crtn.o
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-PGI-18.10.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-PGI-18.10.1.output
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-PGI-18.10.1.output
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-XL-12.1.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-XL-12.1.0.input
new file mode 100644
index 000000000..8b1e2860b
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-XL-12.1.0.input
@@ -0,0 +1,42 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=XL
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=12.1.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_b8c4a/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_b8c4a.dir/build.make CMakeFiles/cmTC_b8c4a.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_b8c4a.dir/CMakeCCompilerABI.c.o
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/bin/xlc -qnostdinc -V -o CMakeFiles/cmTC_b8c4a.dir/CMakeCCompilerABI.c.o -c /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCCompilerABI.c
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlc
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+export XL_ASMOBJFILES=/tmp/xlcASEFMkoN
+export "XL_DIS=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/dis -o "CMakeFiles/cmTC_b8c4a.dir/CMakeCCompilerABI.c.o" "CMakeCCompilerABI.o""
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlcentry -qosvar=rhel.6.9 -qlanglvl=extc99 -qcpluscmt -qkeyword=inline -qalias=ansi -qtls -D_CALL_SYSV -D__null=0 -D__NO_MATH_INLINES -qtls -q64 -qgnu_version=4.4.7 -qnostdinc -qasm_as=/usr/bin/as -qc_stdinc=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include -qgcc_c_stdinc=/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qcomplexgccincl=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include:/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qvac_include_path=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include -oCMakeFiles/cmTC_b8c4a.dir/CMakeCCompilerABI.c.o /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCCompilerABI.c /tmp/xlcW0cUFNRj /tmp/xlcW1YJsgzt /dev/null /tmp/xlcLI4MvwXF.lst /dev/null /tmp/xlcW2sIonhD
+export XL_BACKEND=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode
+export XL_LINKER=/usr/bin/ld
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode -qlanglvl=extc99 -qcpluscmt -qkeyword=inline -qalias=ansi -qtls -qtls -qnostdinc /tmp/xlcW0cUFNRj /tmp/xlcW1YJsgzt CMakeFiles/cmTC_b8c4a.dir/CMakeCCompilerABI.c.o /tmp/xlcLI4MvwXB.lst /tmp/xlcW2sIonhD
+rm /tmp/xlcASEFMkoN
+rm /tmp/xlcLI4MvwX
+rm /tmp/xlcW0cUFNRj
+rm /tmp/xlcW1YJsgzt
+rm /tmp/xlcW2sIonhD
+Linking C executable cmTC_b8c4a
+/soft/buildtools/cmake/3.5.2/bin/cmake -E cmake_link_script CMakeFiles/cmTC_b8c4a.dir/link.txt --verbose=1
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/bin/xlc -qnostdinc -V CMakeFiles/cmTC_b8c4a.dir/CMakeCCompilerABI.c.o -o cmTC_b8c4a -Wl,-export-dynamic
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlc
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+/usr/bin/ld --eh-frame-hdr -Qy -melf64ppc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crt1.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crti.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtbegin.o -L/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/lib64 -L/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/lib64 -L/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/lib64 -L/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/lib64 -R/soft/compilers/ibmcmp-oct2017/lib64/bg -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../.. CMakeFiles/cmTC_b8c4a.dir/CMakeCCompilerABI.c.o -o cmTC_b8c4a -export-dynamic -dynamic-linker /lib64/ld64.so.1 -lxlopt -lxl -ldl -lgcc_s -lgcc -lm -lc -lgcc_s -lgcc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtend.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crtn.o
+rm /tmp/xlcW03gDCly
+rm /tmp/xlcW1oa6XxW
+rm /tmp/xlcW2fQXnKk
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-XL-12.1.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-XL-12.1.0.output
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-C-XL-12.1.0.output
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-PGI-18.10.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-PGI-18.10.1.input
new file mode 100644
index 000000000..dd2b55d91
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-PGI-18.10.1.input
@@ -0,0 +1,40 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=PGI
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=18.10.1
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_90855/fast"
+/usr/bin/make -f CMakeFiles/cmTC_90855.dir/build.make CMakeFiles/cmTC_90855.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_90855.dir/CMakeCXXCompilerABI.cpp.o
+/mnt/pgi/linux86-64/2018/bin/pgc++ -Mnostdinc -v -o CMakeFiles/cmTC_90855.dir/CMakeCXXCompilerABI.cpp.o -c /usr/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/mnt/pgi/linux86-64/18.10/bin/pggpp1 --llalign -Dunix -D__unix -D__unix__ -Dlinux -D__linux -D__linux__ -D__NO_MATH_INLINES -D__LP64__ -D__x86_64 -D__x86_64__ -D__LONG_MAX__=9223372036854775807L '-D__SIZE_TYPE__=unsigned long int' '-D__PTRDIFF_TYPE__=long int' -D__extension__= -D__amd_64__amd64__ -D__k8 -D__k8__ -D__SSE__ -D__MMX__ -D__SSE2__ -D__SSE3__ -D__PGI -D_GNU_SOURCE -D_PGCG_SOURCE -I- -I/mnt/pgi/linux86-64/18.10/include-gcc70 -I/mnt/pgi/linux86-64/18.10/include -I/usr/include/c++/7 -I/usr/include/x86_64-linux-gnu/c++/7 -I/usr/include/c++/7/backward -I/usr/lib/gcc/x86_64-linux-gnu/7/include -I/usr/local/include -I/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed -I/usr/include/x86_64-linux-gnu -I/usr/include --preinclude _cplus_preinclude.h --preinclude_macros _cplus_macros.h --gnu_version=70300 -D__pgnu_vsn=70300 -q -o /tmp/pgc++X3kftwl3x0Hl.il /usr/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp
+
+/mnt/pgi/linux86-64/18.10/bin/pggpp2 /usr/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp -opt 1 -x 119 0xa10000 -x 122 0x40 -x 123 0x1000 -x 127 4 -x 127 17 -x 19 0x400000 -x 28 0x40000 -x 120 0x10000000 -x 70 0x8000 -x 122 1 -x 125 0x20000 -quad -x 59 4 -tp k8 -x 120 0x1000 -astype 0 -fn /usr/share/cmake-3.10/Modules/CMakeCXXCompilerABI.cpp -il /tmp/pgc++X3kftwl3x0Hl.il -x 117 0x600 -x 123 0x80000000 -x 123 4 -x 119 0x20 -def __pgnu_vsn=70300 -x 120 0x200000 -x 70 0x40000000 -x 164 0x800000 -y 163 0xc0000000 -x 189 0x10 -y 189 0x4000000 -gnuvsn 70300 -x 69 0x200 -cmdline '+pgc++ /tmp/pgc++X3kftwl3x0Hl.il -Mnostdinc -v -o CMakeFiles/cmTC_90855.dir/CMakeCXXCompilerABI.cpp.o -c' -asm /tmp/pgc++53kfRignAQXZ.s
+PGCC/x86 Linux 18.10-1: compilation successful
+
+/usr/bin/as /tmp/pgc++53kfRignAQXZ.s -o CMakeFiles/cmTC_90855.dir/CMakeCXXCompilerABI.cpp.o
+Action(ReadTIFile(./CMakeCXXCompilerABI.ti))
+Unlinking /tmp/pgc++X3kftwl3x0Hl.il
+Unlinking /tmp/pgc++53kfRignAQXZ.s
+Unlinking /tmp/pgc++b3kfdox2AAgc.ll
+Linking CXX executable cmTC_90855
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_90855.dir/link.txt --verbose=1
+/mnt/pgi/linux86-64/2018/bin/pgc++ -Mnostdinc -v CMakeFiles/cmTC_90855.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_90855
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/usr/bin/ld /usr/lib/x86_64-linux-gnu/crt1.o /usr/lib/x86_64-linux-gnu/crti.o /mnt/pgi/linux86-64/18.10/lib/trace_init.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbegin.o /mnt/pgi/linux86-64/18.10/lib/initmp.o --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 /mnt/pgi/linux86-64/18.10/lib/pgi.ld -L/mnt/pgi/linux86-64/18.10/lib -L/usr/lib64 -L/usr/lib/gcc/x86_64-linux-gnu/7 CMakeFiles/cmTC_90855.dir/CMakeCXXCompilerABI.cpp.o -rpath /mnt/pgi/linux86-64/18.10/lib -rpath /usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -o cmTC_90855 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -latomic -lpgatm -lstdc++ -lpgmp -lnuma -lpthread --start-group -lpgmath -lnspgc -lpgc --end-group -lm -lgcc -lc -lgcc -lgcc_s /usr/lib/gcc/x86_64-linux-gnu/7/crtend.o /usr/lib/x86_64-linux-gnu/crtn.o
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-PGI-18.10.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-PGI-18.10.1.output
new file mode 100644
index 000000000..8eb97c84e
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-PGI-18.10.1.output
@@ -0,0 +1 @@
+/mnt/pgi/linux86-64/18.10/include-gcc70;/mnt/pgi/linux86-64/18.10/include;/usr/include/c\+\+/7;/usr/include/x86_64-linux-gnu/c\+\+/7;/usr/include/c\+\+/7/backward;/usr/lib/gcc/x86_64-linux-gnu/7/include;/usr/local/include;/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed;/usr/include/x86_64-linux-gnu;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-XL-12.1.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-XL-12.1.0.input
new file mode 100644
index 000000000..f6b5d9111
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-XL-12.1.0.input
@@ -0,0 +1,42 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=XL
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=12.1.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_98791/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_98791.dir/build.make CMakeFiles/cmTC_98791.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_98791.dir/CMakeCXXCompilerABI.cpp.o
+/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/bin/xlC -+ -qnostdinc -V -o CMakeFiles/cmTC_98791.dir/CMakeCXXCompilerABI.cpp.o -c /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCXXCompilerABI.cpp
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlC
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+export XL_ASMOBJFILES=/tmp/xlcAS82INiZ
+export "XL_DIS=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/dis -o "CMakeFiles/cmTC_98791.dir/CMakeCXXCompilerABI.cpp.o" "CMakeCXXCompilerABI.o""
+/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/exe/xlCentry -qosvar=rhel.6.9 -qalias=ansi -qtls -D_CALL_SYSV -D__null=0 -D__NO_MATH_INLINES -qtls -q64 -qgnu_version=4.4.7 -qnostdinc -qasm_as=/usr/bin/as -qcpp_stdinc=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/include -qc_stdinc=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include -qgcc_cpp_stdinc=/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../include/c++/4.4.7:/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ppc64-redhat-linux:/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/backward:/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qgcc_c_stdinc=/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qcomplexgccincl=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include:/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -oCMakeFiles/cmTC_98791.dir/CMakeCXXCompilerABI.cpp.o /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCXXCompilerABI.cpp /tmp/xlcW0SEqGeR /tmp/xlcW1AfQ1jy /dev/null /tmp/xlcLmUAPcJF.lst /dev/null /tmp/xlcW2OCErpf
+export XL_BACKEND=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode
+export XL_LINKER=/usr/bin/ld
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode -qalias=ansi -qtls -qtls -qnostdinc /tmp/xlcW0SEqGeR /tmp/xlcW1AfQ1jy CMakeFiles/cmTC_98791.dir/CMakeCXXCompilerABI.cpp.o /tmp/xlcLmUAPcJB.lst /tmp/xlcW2OCErpf
+rm /tmp/xlcAS82INiZ
+rm /tmp/xlcLmUAPcJ
+rm /tmp/xlcW0SEqGeR
+rm /tmp/xlcW1AfQ1jy
+rm /tmp/xlcW2OCErpf
+Linking CXX executable cmTC_98791
+/soft/buildtools/cmake/3.5.2/bin/cmake -E cmake_link_script CMakeFiles/cmTC_98791.dir/link.txt --verbose=1
+/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/bin/xlC -qnostdinc -V CMakeFiles/cmTC_98791.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_98791 -Wl,-export-dynamic
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlC
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+/usr/bin/ld --eh-frame-hdr -Qy -melf64ppc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crt1.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crti.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtbegin.o -L/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/lib64 -L/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/lib64 -L/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/lib64 -L/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/lib64 -R/soft/compilers/ibmcmp-oct2017/lib64/bg -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../.. -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../.. CMakeFiles/cmTC_98791.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_98791 -export-dynamic -dynamic-linker /lib64/ld64.so.1 -lxlopt -lxl -libmc++ -lxlopt -lxl -lstdc++ -lm -ldl -lgcc_s -lgcc -lm -lc -lgcc_s -lgcc -ldl -lgcc_s -lgcc -lm -lc -lgcc_s -lgcc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtend.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crtn.o
+rm /tmp/xlcW0DcBWi8
+rm /tmp/xlcW14NqGs6
+rm /tmp/xlcW2Z8nuC4
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-XL-12.1.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-XL-12.1.0.output
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-CXX-XL-12.1.0.output
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-Fortran-PGI-18.10.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-Fortran-PGI-18.10.1.input
new file mode 100644
index 000000000..12727f048
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-Fortran-PGI-18.10.1.input
@@ -0,0 +1,47 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=
+CMAKE_Fortran_COMPILER_AR=
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=PGI
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=18.10.1
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_b7462/fast"
+/usr/bin/make -f CMakeFiles/cmTC_b7462.dir/build.make CMakeFiles/cmTC_b7462.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_b7462.dir/CMakeFortranCompilerABI.F.o
+/mnt/pgi/linux86-64/2018/bin/pgfortran -Mnostdinc -v -c /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_b7462.dir/CMakeFortranCompilerABI.F.o
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/mnt/pgi/linux86-64/18.10/bin/pgf901 /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -opt 1 -nohpf -nostatic -x 19 0x400000 -quad -x 59 4 -x 15 2 -x 49 0x400004 -x 51 0x20 -x 57 0x4c -x 58 0x10000 -x 124 0x1000 -tp k8 -x 57 0xfb0000 -x 58 0x78031040 -x 47 0x08 -x 48 4608 -x 49 0x100 -x 120 0x200 -nostdinc -cmdline '+pgfortran /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -Mnostdinc -v -c -o CMakeFiles/cmTC_b7462.dir/CMakeFortranCompilerABI.F.o' -def unix -def __unix -def __unix__ -def linux -def __linux -def __linux__ -def __NO_MATH_INLINES -def __LP64__ -def __x86_64 -def __x86_64__ -def __LONG_MAX__=9223372036854775807L -def '__SIZE_TYPE__=unsigned long int' -def '__PTRDIFF_TYPE__=long int' -def __extension__= -def __amd_64__amd64__ -def __k8 -def __k8__ -def __SSE__ -def __MMX__ -def __SSE2__ -def __SSE3__ -preprocess -nofreeform -vect 48 -x 54 1 -x 70 0x40000000 -y 163 0xc0000000 -x 189 0x10 -modexport /tmp/pgfortranoelfQQWHVV3l.cmod -modindex /tmp/pgfortran_elf6-1UcVhp.cmdx -output /tmp/pgfortranUelfk_cqURUw.ilm
+ 0 inform, 0 warnings, 0 severes, 0 fatal for cmakefortrancompilerabi
+PGF90/x86-64 Linux 18.10-1: compilation successful
+
+/mnt/pgi/linux86-64/18.10/bin/pgf902 /tmp/pgfortranUelfk_cqURUw.ilm -fn /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -opt 1 -x 51 0x20 -x 119 0xa10000 -x 122 0x40 -x 123 0x1000 -x 127 4 -x 127 17 -x 19 0x400000 -x 28 0x40000 -x 120 0x10000000 -x 70 0x8000 -x 122 1 -x 125 0x20000 -quad -x 59 4 -tp k8 -x 120 0x1000 -x 124 0x1400 -y 15 2 -x 57 0x3b0000 -x 58 0x48000000 -x 49 0x100 -x 120 0x200 -astype 0 -x 68 0x20 -x 70 0x40000000 -x 164 0x800000 -x 124 1 -y 163 0xc0000000 -x 189 0x10 -y 189 0x4000000 -cmdline '+pgfortran /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -Mnostdinc -v -c -o CMakeFiles/cmTC_b7462.dir/CMakeFortranCompilerABI.F.o' -asm /tmp/pgfortranUelfk-LC2Ixm.s
+ 0 inform, 0 warnings, 0 severes, 0 fatal for cmakefortrancompilerabi
+PGF90/x86-64 Linux 18.10-1: compilation successful
+
+/usr/bin/as /tmp/pgfortranUelfk-LC2Ixm.s -o CMakeFiles/cmTC_b7462.dir/CMakeFortranCompilerABI.F.o
+
+/mnt/pgi/linux86-64/18.10/bin/pgappend -noerror CMakeFiles/cmTC_b7462.dir/CMakeFortranCompilerABI.F.o -name .IPDINFO /tmp/pgfortranoelfQQWHVV3l.cmod -name .IPEINFO /tmp/pgfortran_elf6-1UcVhp.cmdx
+Unlinking /tmp/pgfortranUelfk_cqURUw.ilm
+Unlinking /tmp/pgfortranEelfAVAFcE2q.stb
+Unlinking /tmp/pgfortranoelfQQWHVV3l.cmod
+Unlinking /tmp/pgfortran_elf6-1UcVhp.cmdx
+Unlinking /tmp/pgfortranUelfk-LC2Ixm.s
+Unlinking /tmp/pgfortranEelfA4vWZ2Nt.ll
+Linking Fortran executable cmTC_b7462
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_b7462.dir/link.txt --verbose=1
+/mnt/pgi/linux86-64/2018/bin/pgfortran -v -Mnostdinc CMakeFiles/cmTC_b7462.dir/CMakeFortranCompilerABI.F.o -o cmTC_b7462
+Export PGI_CURR_CUDA_HOME=/mnt/pgi/linux86-64/2018/cuda/9.1
+Export PGI=/mnt/pgi
+
+/usr/bin/ld /usr/lib/x86_64-linux-gnu/crt1.o /usr/lib/x86_64-linux-gnu/crti.o /mnt/pgi/linux86-64/18.10/lib/trace_init.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbegin.o /mnt/pgi/linux86-64/18.10/lib/initmp.o /mnt/pgi/linux86-64/18.10/lib/f90main.o --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 /mnt/pgi/linux86-64/18.10/lib/pgi.ld -L/mnt/pgi/linux86-64/18.10/lib -L/usr/lib64 -L/usr/lib/gcc/x86_64-linux-gnu/7 CMakeFiles/cmTC_b7462.dir/CMakeFortranCompilerABI.F.o -rpath /mnt/pgi/linux86-64/18.10/lib -rpath /usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -o cmTC_b7462 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -lpgf90rtl -lpgf90 -lpgf90_rpm1 -lpgf902 -lpgf90rtl -lpgftnrtl -lpgmp -lnuma -lpthread --start-group -lpgmath -lnspgc -lpgc --end-group -lrt -lpthread -lm -lgcc -lc -lgcc -lgcc_s /usr/lib/gcc/x86_64-linux-gnu/7/crtend.o /usr/lib/x86_64-linux-gnu/crtn.o
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-Fortran-PGI-18.10.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-Fortran-PGI-18.10.1.output
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc-Fortran-PGI-18.10.1.output
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-C-XL-12.1.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-C-XL-12.1.0.input
new file mode 100644
index 000000000..a552d7052
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-C-XL-12.1.0.input
@@ -0,0 +1,42 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=XL
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=12.1.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_76ec2/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_76ec2.dir/build.make CMakeFiles/cmTC_76ec2.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_76ec2.dir/CMakeCCompilerABI.c.o
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/bin/xlc -qnostdinc -I/tmp/ii/test_c -V -o CMakeFiles/cmTC_76ec2.dir/CMakeCCompilerABI.c.o -c /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCCompilerABI.c
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlc
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+export XL_ASMOBJFILES=/tmp/xlcASknvctJ
+export "XL_DIS=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/dis -o "CMakeFiles/cmTC_76ec2.dir/CMakeCCompilerABI.c.o" "CMakeCCompilerABI.o""
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlcentry -qosvar=rhel.6.9 -qlanglvl=extc99 -qcpluscmt -qkeyword=inline -qalias=ansi -qtls -D_CALL_SYSV -D__null=0 -D__NO_MATH_INLINES -qtls -q64 -qgnu_version=4.4.7 -qnostdinc -I/tmp/ii/test_c -qasm_as=/usr/bin/as -qc_stdinc=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include -qgcc_c_stdinc=/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qcomplexgccincl=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include:/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qvac_include_path=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include -oCMakeFiles/cmTC_76ec2.dir/CMakeCCompilerABI.c.o /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCCompilerABI.c /tmp/xlcW0buijl3 /tmp/xlcW1Cx9kxW /dev/null /tmp/xlcLVbqvUBF.lst /dev/null /tmp/xlcW2hWVoJP
+export XL_BACKEND=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode
+export XL_LINKER=/usr/bin/ld
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode -qlanglvl=extc99 -qcpluscmt -qkeyword=inline -qalias=ansi -qtls -qtls -qnostdinc /tmp/xlcW0buijl3 /tmp/xlcW1Cx9kxW CMakeFiles/cmTC_76ec2.dir/CMakeCCompilerABI.c.o /tmp/xlcLVbqvUBB.lst /tmp/xlcW2hWVoJP
+rm /tmp/xlcASknvctJ
+rm /tmp/xlcLVbqvUB
+rm /tmp/xlcW0buijl3
+rm /tmp/xlcW1Cx9kxW
+rm /tmp/xlcW2hWVoJP
+Linking C executable cmTC_76ec2
+/soft/buildtools/cmake/3.5.2/bin/cmake -E cmake_link_script CMakeFiles/cmTC_76ec2.dir/link.txt --verbose=1
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/bin/xlc -qnostdinc -I/tmp/ii/test_c -V CMakeFiles/cmTC_76ec2.dir/CMakeCCompilerABI.c.o -o cmTC_76ec2 -Wl,-export-dynamic
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlc
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+/usr/bin/ld --eh-frame-hdr -Qy -melf64ppc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crt1.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crti.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtbegin.o -L/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/lib64 -L/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/lib64 -L/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/lib64 -L/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/lib64 -R/soft/compilers/ibmcmp-oct2017/lib64/bg -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../.. CMakeFiles/cmTC_76ec2.dir/CMakeCCompilerABI.c.o -o cmTC_76ec2 -export-dynamic -dynamic-linker /lib64/ld64.so.1 -lxlopt -lxl -ldl -lgcc_s -lgcc -lm -lc -lgcc_s -lgcc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtend.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crtn.o
+rm /tmp/xlcW0ka8GHg
+rm /tmp/xlcW1k1R1fn
+rm /tmp/xlcW2s4HnOt
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-C-XL-12.1.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-C-XL-12.1.0.output
new file mode 100644
index 000000000..38f0b3734
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-C-XL-12.1.0.output
@@ -0,0 +1 @@
+/tmp/ii/test_c
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-CXX-XL-12.1.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-CXX-XL-12.1.0.input
new file mode 100644
index 000000000..4b20f2ee4
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-CXX-XL-12.1.0.input
@@ -0,0 +1,42 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=XL
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=12.1.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/gmake" "cmTC_026f6/fast"
+/usr/bin/gmake -f CMakeFiles/cmTC_026f6.dir/build.make CMakeFiles/cmTC_026f6.dir/build
+gmake[1]: Entering directory `/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_026f6.dir/CMakeCXXCompilerABI.cpp.o
+/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/bin/xlC -+ -qnostdinc -I/tmp/ii/test_c -I/tmp/ii/test_cxx -V -o CMakeFiles/cmTC_026f6.dir/CMakeCXXCompilerABI.cpp.o -c /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCXXCompilerABI.cpp
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlC
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+export XL_ASMOBJFILES=/tmp/xlcAS6jiX2k
+export "XL_DIS=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/dis -o "CMakeFiles/cmTC_026f6.dir/CMakeCXXCompilerABI.cpp.o" "CMakeCXXCompilerABI.o""
+/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/exe/xlCentry -qosvar=rhel.6.9 -qalias=ansi -qtls -D_CALL_SYSV -D__null=0 -D__NO_MATH_INLINES -qtls -q64 -qgnu_version=4.4.7 -qnostdinc -I/tmp/ii/test_c -I/tmp/ii/test_cxx -qasm_as=/usr/bin/as -qcpp_stdinc=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/include -qc_stdinc=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include -qgcc_cpp_stdinc=/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../include/c++/4.4.7:/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ppc64-redhat-linux:/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/backward:/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qgcc_c_stdinc=/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -qcomplexgccincl=/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/include:/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/include:/usr/local/include:/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/crt/include:/usr/include -oCMakeFiles/cmTC_026f6.dir/CMakeCXXCompilerABI.cpp.o /soft/buildtools/cmake/3.5.2/share/cmake-3.5/Modules/CMakeCXXCompilerABI.cpp /tmp/xlcW00ICris /tmp/xlcW1eYwBrK /dev/null /tmp/xlcLG2pVwDF.lst /dev/null /tmp/xlcW2YVJhA2
+export XL_BACKEND=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode
+export XL_LINKER=/usr/bin/ld
+/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/exe/xlCcode -qalias=ansi -qtls -qtls -qnostdinc /tmp/xlcW00ICris /tmp/xlcW1eYwBrK CMakeFiles/cmTC_026f6.dir/CMakeCXXCompilerABI.cpp.o /tmp/xlcLG2pVwDB.lst /tmp/xlcW2YVJhA2
+rm /tmp/xlcAS6jiX2k
+rm /tmp/xlcLG2pVwD
+rm /tmp/xlcW00ICris
+rm /tmp/xlcW1eYwBrK
+rm /tmp/xlcW2YVJhA2
+Linking CXX executable cmTC_026f6
+/soft/buildtools/cmake/3.5.2/bin/cmake -E cmake_link_script CMakeFiles/cmTC_026f6.dir/link.txt --verbose=1
+/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/bin/xlC -qnostdinc -I/tmp/ii/test_c -I/tmp/ii/test_cxx -V CMakeFiles/cmTC_026f6.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_026f6 -Wl,-export-dynamic
+export XL_CONFIG=/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/etc/vac.cfg.rhel6.9.gcc447:xlC
+export XLC_USR_CONFIG=/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/etc/V1R2M4.vac.cfg.rhel6.9.gcc447
+/usr/bin/ld --eh-frame-hdr -Qy -melf64ppc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crt1.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crti.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtbegin.o -L/soft/compilers/ibmcmp-oct2017/xlsmp/bg/3.1/lib64 -L/soft/compilers/ibmcmp-oct2017/xlmass/bg/7.3/lib64 -L/soft/compilers/ibmcmp-oct2017/vac/bg/12.1/lib64 -L/soft/compilers/ibmcmp-oct2017/vacpp/bg/12.1/lib64 -R/soft/compilers/ibmcmp-oct2017/lib64/bg -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../.. -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64 -L/lib/../lib64 -L/usr/lib/../lib64 -L/usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../.. CMakeFiles/cmTC_026f6.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_026f6 -export-dynamic -dynamic-linker /lib64/ld64.so.1 -lxlopt -lxl -libmc++ -lxlopt -lxl -lstdc++ -lm -ldl -lgcc_s -lgcc -lm -lc -lgcc_s -lgcc -ldl -lgcc_s -lgcc -lm -lc -lgcc_s -lgcc /usr/lib/gcc/ppc64-redhat-linux/4.4.7/crtend.o /usr/lib/gcc/ppc64-redhat-linux/4.4.7/../../../../lib64/crtn.o
+rm /tmp/xlcW0rO54CG
+rm /tmp/xlcW1Q6xB5c
+rm /tmp/xlcW2TnvdyJ
+gmake[1]: Leaving directory `/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-CXX-XL-12.1.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-CXX-XL-12.1.0.output
new file mode 100644
index 000000000..727afdbc0
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_nostdinc_i-CXX-XL-12.1.0.output
@@ -0,0 +1 @@
+/tmp/ii/test_c;/tmp/ii/test_cxx
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_pgf77-Fortran-PGI-18.10.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_pgf77-Fortran-PGI-18.10.1.input
new file mode 100644
index 000000000..01abe8d50
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_pgf77-Fortran-PGI-18.10.1.input
@@ -0,0 +1,35 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=
+CMAKE_Fortran_COMPILER_AR=
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=PGI
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=18.10.1
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_ea063/fast"
+/usr/bin/make -f CMakeFiles/cmTC_ea063.dir/build.make CMakeFiles/cmTC_ea063.dir/build
+make[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_ea063.dir/CMakeFortranCompilerABI.F.o
+/mnt/pgi/linux86-64/2018/bin/pgf77 -v -c /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_ea063.dir/CMakeFortranCompilerABI.F.o
+Export PGI=/mnt/pgi
+
+/mnt/pgi/linux86-64/18.10/bin/pgftnc /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -opt 1 -x 119 0xa10000 -x 122 0x40 -x 123 0x1000 -x 127 4 -x 127 17 -x 19 0x400000 -x 28 0x40000 -x 120 0x10000000 -x 70 0x8000 -x 122 1 -x 125 0x20000 -quad -x 59 4 -tp k8 -x 120 0x1000 -x 51 0x20 -x 124 0x1401 -astype 0 -stdinc /mnt/pgi/linux86-64/18.10/include-gcc70:/mnt/pgi/linux86-64/18.10/include:/usr/lib/gcc/x86_64-linux-gnu/7/include:/usr/local/include:/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed:/usr/include/x86_64-linux-gnu:/usr/include -def unix -def __unix -def __unix__ -def linux -def __linux -def __linux__ -def __NO_MATH_INLINES -def __LP64__ -def __x86_64 -def __x86_64__ -def __LONG_MAX__=9223372036854775807L -def '__SIZE_TYPE__=unsigned long int' -def '__PTRDIFF_TYPE__=long int' -def __extension__= -def __amd_64__amd64__ -def __k8 -def __k8__ -def __SSE__ -def __MMX__ -def __SSE2__ -def __SSE3__ -preprocess -cmdline '+pgf77 /usr/share/cmake-3.10/Modules/CMakeFortranCompilerABI.F -v -c -o CMakeFiles/cmTC_ea063.dir/CMakeFortranCompilerABI.F.o' -x 70 0x40000000 -x 164 0x800000 -x 124 1 -asm /tmp/pgf77RxHebkuzkjES.s
+ 0 inform, 0 warnings, 0 severes, 0 fatal for cmakefortrancompilerabi
+PGFTN/x86-64 Linux 18.10-1: compilation successful
+
+/usr/bin/as /tmp/pgf77RxHebkuzkjES.s -o CMakeFiles/cmTC_ea063.dir/CMakeFortranCompilerABI.F.o
+Unlinking /tmp/pgf77RxHebkuzkjES.s
+Unlinking /tmp/pgf77dxHejAvLAzcs.ll
+Linking Fortran executable cmTC_ea063
+/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_ea063.dir/link.txt --verbose=1
+/mnt/pgi/linux86-64/2018/bin/pgf77 -v CMakeFiles/cmTC_ea063.dir/CMakeFortranCompilerABI.F.o -o cmTC_ea063
+Export PGI=/mnt/pgi
+
+/usr/bin/ld /usr/lib/x86_64-linux-gnu/crt1.o /usr/lib/x86_64-linux-gnu/crti.o /mnt/pgi/linux86-64/18.10/lib/trace_init.o /usr/lib/gcc/x86_64-linux-gnu/7/crtbegin.o /mnt/pgi/linux86-64/18.10/lib/initmp.o /mnt/pgi/linux86-64/18.10/lib/pgfmain.o --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 /mnt/pgi/linux86-64/18.10/lib/pgi.ld -L/mnt/pgi/linux86-64/18.10/lib -L/usr/lib64 -L/usr/lib/gcc/x86_64-linux-gnu/7 CMakeFiles/cmTC_ea063.dir/CMakeFortranCompilerABI.F.o -rpath /mnt/pgi/linux86-64/18.10/lib -rpath /usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -o cmTC_ea063 -L/usr/lib/gcc/x86_64-linux-gnu/7/../../../../lib64 -lpgftnrtl -lpgmp -lnuma -lpthread --start-group -lpgmath -lnspgc -lpgc --end-group -lrt -lpthread -lm -lgcc -lc -lgcc -lgcc_s /usr/lib/gcc/x86_64-linux-gnu/7/crtend.o /usr/lib/x86_64-linux-gnu/crtn.o
+make[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_pgf77-Fortran-PGI-18.10.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_pgf77-Fortran-PGI-18.10.1.output
new file mode 100644
index 000000000..289c530a6
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/linux_pgf77-Fortran-PGI-18.10.1.output
@@ -0,0 +1 @@
+/mnt/pgi/linux86-64/18.10/include-gcc70;/mnt/pgi/linux86-64/18.10/include;/usr/lib/gcc/x86_64-linux-gnu/7/include;/usr/local/include;/usr/lib/gcc/x86_64-linux-gnu/7/include-fixed;/usr/include/x86_64-linux-gnu;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-C-GNU-4.9.3.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-C-GNU-4.9.3.input
new file mode 100644
index 000000000..81e9ee04b
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-C-GNU-4.9.3.input
@@ -0,0 +1,70 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=
+CMAKE_C_COMPILER_AR=C:/DoesNotExist/MinGW/bin/gcc-ar.exe
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=GNU
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=C:/DoesNotExist/MinGW/bin/gcc-ranlib.exe
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=4.9.3
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: C:/tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"C:/DoesNotExist/MinGW/bin/mingw32-make.exe" "cmTC_ab097/fast"
+C:/DoesNotExist/MinGW/bin/mingw32-make.exe -f CMakeFiles\cmTC_ab097.dir\build.make CMakeFiles/cmTC_ab097.dir/build
+mingw32-make.exe[1]: Entering directory 'C:/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_ab097.dir/CMakeCCompilerABI.c.obj
+C:\DoesNotExist\MinGW\bin\gcc.exe -v -o CMakeFiles\cmTC_ab097.dir\CMakeCCompilerABI.c.obj -c "C:\CMake\Modules\CMakeCCompilerABI.c"
+Using built-in specs.
+COLLECT_GCC=C:\DoesNotExist\MinGW\bin\gcc.exe
+Target: mingw32
+Configured with: ../src/gcc-4.9.3/configure --build=x86_64-pc-linux-gnu --host=mingw32 --prefix=/mingw --disable-win32-registry --target=mingw32 --with-arch=i586 --enable-languages=c,c++,objc,obj-c++,fortran,ada --enable-static --enable-shared --enable-threads --with-dwarf2 --disable-sjlj-exceptions --enable-version-specific-runtime-libs --enable-libstdcxx-debug --with-tune=generic --enable-nls
+Thread model: win32
+gcc version 4.9.3 (GCC)
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles\cmTC_ab097.dir\CMakeCCompilerABI.c.obj' '-c' '-mtune=generic' '-march=i586'
+ c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/cc1.exe -quiet -v -iprefix c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/ C:\CMake\Modules\CMakeCCompilerABI.c -quiet -dumpbase CMakeCCompilerABI.c -mtune=generic -march=i586 -auxbase-strip CMakeFiles\cmTC_ab097.dir\CMakeCCompilerABI.c.obj -version -o C:\Users\DASHBO~1\AppData\Local\Temp\ccKRBU4I.s
+GNU C (GCC) version 4.9.3 (mingw32)
+ compiled by GNU C version 4.9.3, GMP version 5.1.2, MPFR version 3.1.2, MPC version 1.0.2
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+ignoring nonexistent directory "c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/../../../../mingw32/include"
+ignoring duplicate directory "c:/DoesNotExist/mingw/lib/gcc/../../lib/gcc/mingw32/4.9.3/include"
+ignoring duplicate directory "/mingw/lib/gcc/mingw32/4.9.3/../../../../include"
+ignoring duplicate directory "c:/DoesNotExist/mingw/lib/gcc/../../include"
+ignoring duplicate directory "c:/DoesNotExist/mingw/lib/gcc/../../lib/gcc/mingw32/4.9.3/include-fixed"
+ignoring nonexistent directory "c:/DoesNotExist/mingw/lib/gcc/../../lib/gcc/mingw32/4.9.3/../../../../mingw32/include"
+ignoring duplicate directory "/mingw/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/include
+ c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/../../../../include
+ c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/include-fixed
+End of search list.
+GNU C (GCC) version 4.9.3 (mingw32)
+ compiled by GNU C version 4.9.3, GMP version 5.1.2, MPFR version 3.1.2, MPC version 1.0.2
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+Compiler executable checksum: 32bccaa1a45d39107471fe656e1c3cd5
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles\cmTC_ab097.dir\CMakeCCompilerABI.c.obj' '-c' '-mtune=generic' '-march=i586'
+ c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/as.exe -v -o CMakeFiles\cmTC_ab097.dir\CMakeCCompilerABI.c.obj C:\Users\DASHBO~1\AppData\Local\Temp\ccKRBU4I.s
+GNU assembler version 2.25.1 (mingw32) using BFD version (GNU Binutils) 2.25.1
+COMPILER_PATH=c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/;c:/DoesNotExist/mingw/bin/../libexec/gcc/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/
+LIBRARY_PATH=c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/;c:/DoesNotExist/mingw/bin/../lib/gcc/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/lib/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles\cmTC_ab097.dir\CMakeCCompilerABI.c.obj' '-c' '-mtune=generic' '-march=i586'
+Linking C executable cmTC_ab097.exe
+"C:\CMake\bin\cmake.exe" -E cmake_link_script CMakeFiles\cmTC_ab097.dir\link.txt --verbose=1
+"C:\CMake\bin\cmake.exe" -E remove -f CMakeFiles\cmTC_ab097.dir/objects.a
+C:\DoesNotExist\MinGW\bin\ar.exe cr CMakeFiles\cmTC_ab097.dir/objects.a @CMakeFiles\cmTC_ab097.dir\objects1.rsp
+C:\DoesNotExist\MinGW\bin\gcc.exe -v -Wl,--whole-archive CMakeFiles\cmTC_ab097.dir/objects.a -Wl,--no-whole-archive -o cmTC_ab097.exe -Wl,--out-implib,libcmTC_ab097.dll.a -Wl,--major-image-version,0,--minor-image-version,0
+Using built-in specs.
+COLLECT_GCC=C:\DoesNotExist\MinGW\bin\gcc.exe
+COLLECT_LTO_WRAPPER=c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/lto-wrapper.exe
+Target: mingw32
+Configured with: ../src/gcc-4.9.3/configure --build=x86_64-pc-linux-gnu --host=mingw32 --prefix=/mingw --disable-win32-registry --target=mingw32 --with-arch=i586 --enable-languages=c,c++,objc,obj-c++,fortran,ada --enable-static --enable-shared --enable-threads --with-dwarf2 --disable-sjlj-exceptions --enable-version-specific-runtime-libs --enable-libstdcxx-debug --with-tune=generic --enable-nls
+Thread model: win32
+gcc version 4.9.3 (GCC)
+COMPILER_PATH=c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/;c:/DoesNotExist/mingw/bin/../libexec/gcc/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/
+LIBRARY_PATH=c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/;c:/DoesNotExist/mingw/bin/../lib/gcc/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/lib/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../
+COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_ab097.exe' '-mtune=generic' '-march=i586'
+ c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/collect2.exe -plugin c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/liblto_plugin-0.dll -plugin-opt=c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/lto-wrapper.exe -plugin-opt=-fresolution=C:\Users\DASHBO~1\AppData\Local\Temp\ccEGcsW8.res -plugin-opt=-pass-through=-lmingw32 -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_eh -plugin-opt=-pass-through=-lmoldname -plugin-opt=-pass-through=-lmingwex -plugin-opt=-pass-through=-lmsvcrt -plugin-opt=-pass-through=-ladvapi32 -plugin-opt=-pass-through=-lshell32 -plugin-opt=-pass-through=-luser32 -plugin-opt=-pass-through=-lkernel32 -plugin-opt=-pass-through=-lmingw32 -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_eh -plugin-opt=-pass-through=-lmoldname -plugin-opt=-pass-through=-lmingwex -plugin-opt=-pass-through=-lmsvcrt -Bdynamic -o cmTC_ab097.exe c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../crt2.o c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/crtbegin.o -Lc:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3 -Lc:/DoesNotExist/mingw/bin/../lib/gcc -Lc:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/lib -Lc:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../.. --whole-archive CMakeFiles\cmTC_ab097.dir/objects.a --no-whole-archive --out-implib libcmTC_ab097.dll.a --major-image-version 0 --minor-image-version 0 -lmingw32 -lgcc -lgcc_eh -lmoldname -lmingwex -lmsvcrt -ladvapi32 -lshell32 -luser32 -lkernel32 -lmingw32 -lgcc -lgcc_eh -lmoldname -lmingwex -lmsvcrt c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/crtend.o
+mingw32-make.exe[1]: Leaving directory 'C:/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-C-GNU-4.9.3.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-C-GNU-4.9.3.output
new file mode 100644
index 000000000..d23e7fe7c
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-C-GNU-4.9.3.output
@@ -0,0 +1 @@
+C:/DoesNotExist/mingw/lib/gcc/mingw32/4.9.3/include;C:/DoesNotExist/mingw/include;C:/DoesNotExist/mingw/lib/gcc/mingw32/4.9.3/include-fixed
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-CXX-GNU-4.9.3.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-CXX-GNU-4.9.3.input
new file mode 100644
index 000000000..cd773402c
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-CXX-GNU-4.9.3.input
@@ -0,0 +1,76 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=C:/DoesNotExist/MinGW/bin/gcc-ar.exe
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=GNU
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=C:/DoesNotExist/MinGW/bin/gcc-ranlib.exe
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=4.9.3
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: C:/tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"C:/DoesNotExist/MinGW/bin/mingw32-make.exe" "cmTC_2b790/fast"
+C:/DoesNotExist/MinGW/bin/mingw32-make.exe -f CMakeFiles\cmTC_2b790.dir\build.make CMakeFiles/cmTC_2b790.dir/build
+mingw32-make.exe[1]: Entering directory 'C:/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_2b790.dir/CMakeCXXCompilerABI.cpp.obj
+C:\DoesNotExist\MinGW\bin\g++.exe -v -o CMakeFiles\cmTC_2b790.dir\CMakeCXXCompilerABI.cpp.obj -c "C:\CMake\Modules\CMakeCXXCompilerABI.cpp"
+Using built-in specs.
+COLLECT_GCC=C:\DoesNotExist\MinGW\bin\g++.exe
+Target: mingw32
+Configured with: ../src/gcc-4.9.3/configure --build=x86_64-pc-linux-gnu --host=mingw32 --prefix=/mingw --disable-win32-registry --target=mingw32 --with-arch=i586 --enable-languages=c,c++,objc,obj-c++,fortran,ada --enable-static --enable-shared --enable-threads --with-dwarf2 --disable-sjlj-exceptions --enable-version-specific-runtime-libs --enable-libstdcxx-debug --with-tune=generic --enable-nls
+Thread model: win32
+gcc version 4.9.3 (GCC)
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles\cmTC_2b790.dir\CMakeCXXCompilerABI.cpp.obj' '-c' '-shared-libgcc' '-mtune=generic' '-march=i586'
+ c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/cc1plus.exe -quiet -v -iprefix c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/ C:\CMake\Modules\CMakeCXXCompilerABI.cpp -quiet -dumpbase CMakeCXXCompilerABI.cpp -mtune=generic -march=i586 -auxbase-strip CMakeFiles\cmTC_2b790.dir\CMakeCXXCompilerABI.cpp.obj -version -o C:\Users\DASHBO~1\AppData\Local\Temp\cceEHFvQ.s
+GNU C++ (GCC) version 4.9.3 (mingw32)
+ compiled by GNU C version 4.9.3, GMP version 5.1.2, MPFR version 3.1.2, MPC version 1.0.2
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+ignoring nonexistent directory "c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/../../../../mingw32/include"
+ignoring duplicate directory "c:/DoesNotExist/mingw/lib/gcc/../../lib/gcc/mingw32/4.9.3/include/c++"
+ignoring duplicate directory "c:/DoesNotExist/mingw/lib/gcc/../../lib/gcc/mingw32/4.9.3/include/c++/mingw32"
+ignoring duplicate directory "c:/DoesNotExist/mingw/lib/gcc/../../lib/gcc/mingw32/4.9.3/include/c++/backward"
+ignoring duplicate directory "c:/DoesNotExist/mingw/lib/gcc/../../lib/gcc/mingw32/4.9.3/include"
+ignoring duplicate directory "/mingw/lib/gcc/mingw32/4.9.3/../../../../include"
+ignoring duplicate directory "c:/DoesNotExist/mingw/lib/gcc/../../include"
+ignoring duplicate directory "c:/DoesNotExist/mingw/lib/gcc/../../lib/gcc/mingw32/4.9.3/include-fixed"
+ignoring nonexistent directory "c:/DoesNotExist/mingw/lib/gcc/../../lib/gcc/mingw32/4.9.3/../../../../mingw32/include"
+ignoring duplicate directory "/mingw/include"
+#include "..." search starts here:
+#include <...> search starts here:
+ c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/include/c++
+ c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/include/c++/mingw32
+ c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/include/c++/backward
+ c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/include
+ c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/../../../../include
+ c:\DoesNotExist\mingw\bin\../lib/gcc/mingw32/4.9.3/include-fixed
+End of search list.
+GNU C++ (GCC) version 4.9.3 (mingw32)
+ compiled by GNU C version 4.9.3, GMP version 5.1.2, MPFR version 3.1.2, MPC version 1.0.2
+GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072
+Compiler executable checksum: 5086496b116ea21cdc0e479568243b88
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles\cmTC_2b790.dir\CMakeCXXCompilerABI.cpp.obj' '-c' '-shared-libgcc' '-mtune=generic' '-march=i586'
+ c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/as.exe -v -o CMakeFiles\cmTC_2b790.dir\CMakeCXXCompilerABI.cpp.obj C:\Users\DASHBO~1\AppData\Local\Temp\cceEHFvQ.s
+GNU assembler version 2.25.1 (mingw32) using BFD version (GNU Binutils) 2.25.1
+COMPILER_PATH=c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/;c:/DoesNotExist/mingw/bin/../libexec/gcc/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/
+LIBRARY_PATH=c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/;c:/DoesNotExist/mingw/bin/../lib/gcc/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/lib/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles\cmTC_2b790.dir\CMakeCXXCompilerABI.cpp.obj' '-c' '-shared-libgcc' '-mtune=generic' '-march=i586'
+Linking CXX executable cmTC_2b790.exe
+"C:\CMake\bin\cmake.exe" -E cmake_link_script CMakeFiles\cmTC_2b790.dir\link.txt --verbose=1
+"C:\CMake\bin\cmake.exe" -E remove -f CMakeFiles\cmTC_2b790.dir/objects.a
+C:\DoesNotExist\MinGW\bin\ar.exe cr CMakeFiles\cmTC_2b790.dir/objects.a @CMakeFiles\cmTC_2b790.dir\objects1.rsp
+C:\DoesNotExist\MinGW\bin\g++.exe -v -Wl,--whole-archive CMakeFiles\cmTC_2b790.dir/objects.a -Wl,--no-whole-archive -o cmTC_2b790.exe -Wl,--out-implib,libcmTC_2b790.dll.a -Wl,--major-image-version,0,--minor-image-version,0
+Using built-in specs.
+COLLECT_GCC=C:\DoesNotExist\MinGW\bin\g++.exe
+COLLECT_LTO_WRAPPER=c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/lto-wrapper.exe
+Target: mingw32
+Configured with: ../src/gcc-4.9.3/configure --build=x86_64-pc-linux-gnu --host=mingw32 --prefix=/mingw --disable-win32-registry --target=mingw32 --with-arch=i586 --enable-languages=c,c++,objc,obj-c++,fortran,ada --enable-static --enable-shared --enable-threads --with-dwarf2 --disable-sjlj-exceptions --enable-version-specific-runtime-libs --enable-libstdcxx-debug --with-tune=generic --enable-nls
+Thread model: win32
+gcc version 4.9.3 (GCC)
+COMPILER_PATH=c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/;c:/DoesNotExist/mingw/bin/../libexec/gcc/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/bin/
+LIBRARY_PATH=c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/;c:/DoesNotExist/mingw/bin/../lib/gcc/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/lib/;c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../
+COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_2b790.exe' '-shared-libgcc' '-mtune=generic' '-march=i586'
+ c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/collect2.exe -plugin c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/liblto_plugin-0.dll -plugin-opt=c:/DoesNotExist/mingw/bin/../libexec/gcc/mingw32/4.9.3/lto-wrapper.exe -plugin-opt=-fresolution=C:\Users\DASHBO~1\AppData\Local\Temp\ccYpt7zh.res -plugin-opt=-pass-through=-lmingw32 -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lmoldname -plugin-opt=-pass-through=-lmingwex -plugin-opt=-pass-through=-lmsvcrt -plugin-opt=-pass-through=-ladvapi32 -plugin-opt=-pass-through=-lshell32 -plugin-opt=-pass-through=-luser32 -plugin-opt=-pass-through=-lkernel32 -plugin-opt=-pass-through=-lmingw32 -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lmoldname -plugin-opt=-pass-through=-lmingwex -plugin-opt=-pass-through=-lmsvcrt -Bdynamic -u ___register_frame_info -u ___deregister_frame_info -o cmTC_2b790.exe c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../crt2.o c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/crtbegin.o -Lc:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3 -Lc:/DoesNotExist/mingw/bin/../lib/gcc -Lc:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../../../mingw32/lib -Lc:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/../../.. --whole-archive CMakeFiles\cmTC_2b790.dir/objects.a --no-whole-archive --out-implib libcmTC_2b790.dll.a --major-image-version 0 --minor-image-version 0 -lstdc++ -lmingw32 -lgcc_s -lgcc -lmoldname -lmingwex -lmsvcrt -ladvapi32 -lshell32 -luser32 -lkernel32 -lmingw32 -lgcc_s -lgcc -lmoldname -lmingwex -lmsvcrt c:/DoesNotExist/mingw/bin/../lib/gcc/mingw32/4.9.3/crtend.o
+mingw32-make.exe[1]: Leaving directory 'C:/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-CXX-GNU-4.9.3.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-CXX-GNU-4.9.3.output
new file mode 100644
index 000000000..999694050
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/mingw.org-CXX-GNU-4.9.3.output
@@ -0,0 +1 @@
+C:/DoesNotExist/mingw/lib/gcc/mingw32/4.9.3/include/c\+\+;C:/DoesNotExist/mingw/lib/gcc/mingw32/4.9.3/include/c\+\+/mingw32;C:/DoesNotExist/mingw/lib/gcc/mingw32/4.9.3/include/c\+\+/backward;C:/DoesNotExist/mingw/lib/gcc/mingw32/4.9.3/include;C:/DoesNotExist/mingw/include;C:/DoesNotExist/mingw/lib/gcc/mingw32/4.9.3/include-fixed
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-C-GNU-4.8.5.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-C-GNU-4.8.5.input
new file mode 100644
index 000000000..b46848433
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-C-GNU-4.8.5.input
@@ -0,0 +1,60 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=CMAKE_C_COMPILER_AR-NOTFOUND
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=GNU
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=CMAKE_C_COMPILER_RANLIB-NOTFOUND
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=4.8.5
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/pkg/bin/gmake" "cmTC_9a517/fast"
+/usr/pkg/bin/gmake -f CMakeFiles/cmTC_9a517.dir/build.make CMakeFiles/cmTC_9a517.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_9a517.dir/CMakeCCompilerABI.c.o
+/usr/bin/cc -v -o CMakeFiles/cmTC_9a517.dir/CMakeCCompilerABI.c.o -c /usr/pkg/share/cmake-3.9/Modules/CMakeCCompilerABI.c
+Using built-in specs.
+COLLECT_GCC=/usr/bin/cc
+Target: i486--netbsdelf
+Configured with: /usr/7/src/tools/gcc/../../external/gpl3/gcc/dist/configure --target=i486--netbsdelf --enable-long-long --enable-threads --with-bugurl=http://www.NetBSD.org/Misc/send-pr.html --with-pkgversion='NetBSD nb2 20150115' --with-system-zlib --enable-__cxa_atexit --enable-libstdcxx-threads --with-arch=i486 --with-tune=nocona --enable-libstdcxx-time=rt --enable-lto --with-mpc-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpc/lib/libmpc --with-mpfr-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpfr/lib/libmpfr --with-gmp-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/gmp/lib/libgmp --with-mpc-include=/usr/7/src/external/lgpl3/mpc/dist/src --with-mpfr-include=/usr/7/src/external/lgpl3/mpfr/dist/src --with-gmp-include=/usr/7/src/external/lgpl3/gmp/lib/libgmp/arch/i386 --enable-tls --disable-multilib --disable-symvers --disable-libstdcxx-pch --build=x86_64-unknown-netbsd6.0. --host=i486--netbsdelf --with-sysroot=/var/obj/mknative/i386/usr/7/src/destdir.i386
+Thread model: posix
+gcc version 4.8.5 (nb2 20150115)
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_9a517.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=nocona' '-march=i486'
+ /usr/libexec/cc1 -quiet -v /usr/pkg/share/cmake-3.9/Modules/CMakeCCompilerABI.c -quiet -dumpbase CMakeCCompilerABI.c -mtune=nocona -march=i486 -auxbase-strip CMakeFiles/cmTC_9a517.dir/CMakeCCompilerABI.c.o -version -o /var/tmp//ccXQW9Zo.s
+GNU C (nb2 20150115) version 4.8.5 (i486--netbsdelf)
+ compiled by GNU C version 4.8.5, GMP version 5.1.3, MPFR version 3.1.2, MPC version 1.0.1
+GGC heuristics: --param ggc-min-expand=73 --param ggc-min-heapsize=81803
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/include/gcc-4.8
+ /usr/include
+End of search list.
+GNU C (nb2 20150115) version 4.8.5 (i486--netbsdelf)
+ compiled by GNU C version 4.8.5, GMP version 5.1.3, MPFR version 3.1.2, MPC version 1.0.1
+GGC heuristics: --param ggc-min-expand=73 --param ggc-min-heapsize=81803
+Compiler executable checksum: 468b91b49af5cfeb6bb696ad20c66c1c
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_9a517.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=nocona' '-march=i486'
+ as -v -o CMakeFiles/cmTC_9a517.dir/CMakeCCompilerABI.c.o /var/tmp//ccXQW9Zo.s
+GNU assembler version 2.23.2 (i486--netbsdelf) using BFD version (NetBSD Binutils nb1) 2.23.2
+COMPILER_PATH=/usr/libexec/
+LIBRARY_PATH=/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_9a517.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=nocona' '-march=i486'
+Linking C executable cmTC_9a517
+/usr/pkg/bin/cmake -E cmake_link_script CMakeFiles/cmTC_9a517.dir/link.txt --verbose=1
+/usr/bin/cc -v CMakeFiles/cmTC_9a517.dir/CMakeCCompilerABI.c.o -o cmTC_9a517
+Using built-in specs.
+COLLECT_GCC=/usr/bin/cc
+COLLECT_LTO_WRAPPER=/usr/libexec/lto-wrapper
+Target: i486--netbsdelf
+Configured with: /usr/7/src/tools/gcc/../../external/gpl3/gcc/dist/configure --target=i486--netbsdelf --enable-long-long --enable-threads --with-bugurl=http://www.NetBSD.org/Misc/send-pr.html --with-pkgversion='NetBSD nb2 20150115' --with-system-zlib --enable-__cxa_atexit --enable-libstdcxx-threads --with-arch=i486 --with-tune=nocona --enable-libstdcxx-time=rt --enable-lto --with-mpc-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpc/lib/libmpc --with-mpfr-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpfr/lib/libmpfr --with-gmp-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/gmp/lib/libgmp --with-mpc-include=/usr/7/src/external/lgpl3/mpc/dist/src --with-mpfr-include=/usr/7/src/external/lgpl3/mpfr/dist/src --with-gmp-include=/usr/7/src/external/lgpl3/gmp/lib/libgmp/arch/i386 --enable-tls --disable-multilib --disable-symvers --disable-libstdcxx-pch --build=x86_64-unknown-netbsd6.0. --host=i486--netbsdelf --with-sysroot=/var/obj/mknative/i386/usr/7/src/destdir.i386
+Thread model: posix
+gcc version 4.8.5 (nb2 20150115)
+COMPILER_PATH=/usr/libexec/
+LIBRARY_PATH=/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_9a517' '-mtune=nocona' '-march=i486'
+ ld --eh-frame-hdr -dc -dp -e __start -dynamic-linker /usr/libexec/ld.elf_so -o cmTC_9a517 /usr/lib/crt0.o /usr/lib/crti.o /usr/lib/crtbegin.o CMakeFiles/cmTC_9a517.dir/CMakeCCompilerABI.c.o -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /usr/lib/crtend.o /usr/lib/crtn.o
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-C-GNU-4.8.5.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-C-GNU-4.8.5.output
new file mode 100644
index 000000000..6b69b2d7c
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-C-GNU-4.8.5.output
@@ -0,0 +1 @@
+/usr/include/gcc-4.8;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-CXX-GNU-4.8.5.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-CXX-GNU-4.8.5.input
new file mode 100644
index 000000000..e3c5f72e9
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-CXX-GNU-4.8.5.input
@@ -0,0 +1,62 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=CMAKE_CXX_COMPILER_AR-NOTFOUND
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=GNU
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=CMAKE_CXX_COMPILER_RANLIB-NOTFOUND
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=4.8.5
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/pkg/bin/gmake" "cmTC_cca06/fast"
+/usr/pkg/bin/gmake -f CMakeFiles/cmTC_cca06.dir/build.make CMakeFiles/cmTC_cca06.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_cca06.dir/CMakeCXXCompilerABI.cpp.o
+/usr/bin/c++ -v -o CMakeFiles/cmTC_cca06.dir/CMakeCXXCompilerABI.cpp.o -c /usr/pkg/share/cmake-3.9/Modules/CMakeCXXCompilerABI.cpp
+Using built-in specs.
+COLLECT_GCC=/usr/bin/c++
+Target: i486--netbsdelf
+Configured with: /usr/7/src/tools/gcc/../../external/gpl3/gcc/dist/configure --target=i486--netbsdelf --enable-long-long --enable-threads --with-bugurl=http://www.NetBSD.org/Misc/send-pr.html --with-pkgversion='NetBSD nb2 20150115' --with-system-zlib --enable-__cxa_atexit --enable-libstdcxx-threads --with-arch=i486 --with-tune=nocona --enable-libstdcxx-time=rt --enable-lto --with-mpc-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpc/lib/libmpc --with-mpfr-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpfr/lib/libmpfr --with-gmp-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/gmp/lib/libgmp --with-mpc-include=/usr/7/src/external/lgpl3/mpc/dist/src --with-mpfr-include=/usr/7/src/external/lgpl3/mpfr/dist/src --with-gmp-include=/usr/7/src/external/lgpl3/gmp/lib/libgmp/arch/i386 --enable-tls --disable-multilib --disable-symvers --disable-libstdcxx-pch --build=x86_64-unknown-netbsd6.0. --host=i486--netbsdelf --with-sysroot=/var/obj/mknative/i386/usr/7/src/destdir.i386
+Thread model: posix
+gcc version 4.8.5 (nb2 20150115)
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_cca06.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=nocona' '-march=i486'
+ /usr/libexec/cc1plus -quiet -v /usr/pkg/share/cmake-3.9/Modules/CMakeCXXCompilerABI.cpp -quiet -dumpbase CMakeCXXCompilerABI.cpp -mtune=nocona -march=i486 -auxbase-strip CMakeFiles/cmTC_cca06.dir/CMakeCXXCompilerABI.cpp.o -version -o /var/tmp//ccqeRxzZ.s
+GNU C++ (nb2 20150115) version 4.8.5 (i486--netbsdelf)
+ compiled by GNU C version 4.8.5, GMP version 5.1.3, MPFR version 3.1.2, MPC version 1.0.1
+GGC heuristics: --param ggc-min-expand=73 --param ggc-min-heapsize=81803
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/include/g++
+ /usr/include/g++/backward
+ /usr/include/gcc-4.8
+ /usr/include
+End of search list.
+GNU C++ (nb2 20150115) version 4.8.5 (i486--netbsdelf)
+ compiled by GNU C version 4.8.5, GMP version 5.1.3, MPFR version 3.1.2, MPC version 1.0.1
+GGC heuristics: --param ggc-min-expand=73 --param ggc-min-heapsize=81803
+Compiler executable checksum: 961550adc452c84b614bf799df00d02b
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_cca06.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=nocona' '-march=i486'
+ as -v -o CMakeFiles/cmTC_cca06.dir/CMakeCXXCompilerABI.cpp.o /var/tmp//ccqeRxzZ.s
+GNU assembler version 2.23.2 (i486--netbsdelf) using BFD version (NetBSD Binutils nb1) 2.23.2
+COMPILER_PATH=/usr/libexec/
+LIBRARY_PATH=/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_cca06.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=nocona' '-march=i486'
+Linking CXX executable cmTC_cca06
+/usr/pkg/bin/cmake -E cmake_link_script CMakeFiles/cmTC_cca06.dir/link.txt --verbose=1
+/usr/bin/c++ -v CMakeFiles/cmTC_cca06.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_cca06
+Using built-in specs.
+COLLECT_GCC=/usr/bin/c++
+COLLECT_LTO_WRAPPER=/usr/libexec/lto-wrapper
+Target: i486--netbsdelf
+Configured with: /usr/7/src/tools/gcc/../../external/gpl3/gcc/dist/configure --target=i486--netbsdelf --enable-long-long --enable-threads --with-bugurl=http://www.NetBSD.org/Misc/send-pr.html --with-pkgversion='NetBSD nb2 20150115' --with-system-zlib --enable-__cxa_atexit --enable-libstdcxx-threads --with-arch=i486 --with-tune=nocona --enable-libstdcxx-time=rt --enable-lto --with-mpc-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpc/lib/libmpc --with-mpfr-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpfr/lib/libmpfr --with-gmp-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/gmp/lib/libgmp --with-mpc-include=/usr/7/src/external/lgpl3/mpc/dist/src --with-mpfr-include=/usr/7/src/external/lgpl3/mpfr/dist/src --with-gmp-include=/usr/7/src/external/lgpl3/gmp/lib/libgmp/arch/i386 --enable-tls --disable-multilib --disable-symvers --disable-libstdcxx-pch --build=x86_64-unknown-netbsd6.0. --host=i486--netbsdelf --with-sysroot=/var/obj/mknative/i386/usr/7/src/destdir.i386
+Thread model: posix
+gcc version 4.8.5 (nb2 20150115)
+COMPILER_PATH=/usr/libexec/
+LIBRARY_PATH=/usr/lib/
+COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_cca06' '-shared-libgcc' '-mtune=nocona' '-march=i486'
+ ld --eh-frame-hdr -dc -dp -e __start -dynamic-linker /usr/libexec/ld.elf_so -o cmTC_cca06 /usr/lib/crt0.o /usr/lib/crti.o /usr/lib/crtbegin.o CMakeFiles/cmTC_cca06.dir/CMakeCXXCompilerABI.cpp.o -lstdc++ -lm --as-needed -lgcc_s --no-as-needed -lgcc -lc --as-needed -lgcc_s --no-as-needed -lgcc /usr/lib/crtend.o /usr/lib/crtn.o
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-CXX-GNU-4.8.5.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-CXX-GNU-4.8.5.output
new file mode 100644
index 000000000..d2289eb81
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd-CXX-GNU-4.8.5.output
@@ -0,0 +1 @@
+/usr/include/g\+\+;/usr/include/g\+\+/backward;/usr/include/gcc-4.8;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-C-GNU-4.8.5.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-C-GNU-4.8.5.input
new file mode 100644
index 000000000..cd5845ae5
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-C-GNU-4.8.5.input
@@ -0,0 +1,58 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=CMAKE_C_COMPILER_AR-NOTFOUND
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=GNU
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=CMAKE_C_COMPILER_RANLIB-NOTFOUND
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=4.8.5
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/pkg/bin/gmake" "cmTC_b8d65/fast"
+/usr/pkg/bin/gmake -f CMakeFiles/cmTC_b8d65.dir/build.make CMakeFiles/cmTC_b8d65.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_b8d65.dir/CMakeCCompilerABI.c.o
+/usr/bin/cc -nostdinc -v -o CMakeFiles/cmTC_b8d65.dir/CMakeCCompilerABI.c.o -c /usr/pkg/share/cmake-3.9/Modules/CMakeCCompilerABI.c
+Using built-in specs.
+COLLECT_GCC=/usr/bin/cc
+Target: i486--netbsdelf
+Configured with: /usr/7/src/tools/gcc/../../external/gpl3/gcc/dist/configure --target=i486--netbsdelf --enable-long-long --enable-threads --with-bugurl=http://www.NetBSD.org/Misc/send-pr.html --with-pkgversion='NetBSD nb2 20150115' --with-system-zlib --enable-__cxa_atexit --enable-libstdcxx-threads --with-arch=i486 --with-tune=nocona --enable-libstdcxx-time=rt --enable-lto --with-mpc-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpc/lib/libmpc --with-mpfr-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpfr/lib/libmpfr --with-gmp-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/gmp/lib/libgmp --with-mpc-include=/usr/7/src/external/lgpl3/mpc/dist/src --with-mpfr-include=/usr/7/src/external/lgpl3/mpfr/dist/src --with-gmp-include=/usr/7/src/external/lgpl3/gmp/lib/libgmp/arch/i386 --enable-tls --disable-multilib --disable-symvers --disable-libstdcxx-pch --build=x86_64-unknown-netbsd6.0. --host=i486--netbsdelf --with-sysroot=/var/obj/mknative/i386/usr/7/src/destdir.i386
+Thread model: posix
+gcc version 4.8.5 (nb2 20150115)
+COLLECT_GCC_OPTIONS='-nostdinc' '-v' '-o' 'CMakeFiles/cmTC_b8d65.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=nocona' '-march=i486'
+ /usr/libexec/cc1 -quiet -nostdinc -v /usr/pkg/share/cmake-3.9/Modules/CMakeCCompilerABI.c -quiet -dumpbase CMakeCCompilerABI.c -mtune=nocona -march=i486 -auxbase-strip CMakeFiles/cmTC_b8d65.dir/CMakeCCompilerABI.c.o -version -o /var/tmp//ccPEfYnQ.s
+GNU C (nb2 20150115) version 4.8.5 (i486--netbsdelf)
+ compiled by GNU C version 4.8.5, GMP version 5.1.3, MPFR version 3.1.2, MPC version 1.0.1
+GGC heuristics: --param ggc-min-expand=73 --param ggc-min-heapsize=81803
+#include "..." search starts here:
+#include <...> search starts here:
+End of search list.
+GNU C (nb2 20150115) version 4.8.5 (i486--netbsdelf)
+ compiled by GNU C version 4.8.5, GMP version 5.1.3, MPFR version 3.1.2, MPC version 1.0.1
+GGC heuristics: --param ggc-min-expand=73 --param ggc-min-heapsize=81803
+Compiler executable checksum: 468b91b49af5cfeb6bb696ad20c66c1c
+COLLECT_GCC_OPTIONS='-nostdinc' '-v' '-o' 'CMakeFiles/cmTC_b8d65.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=nocona' '-march=i486'
+ as -v -o CMakeFiles/cmTC_b8d65.dir/CMakeCCompilerABI.c.o /var/tmp//ccPEfYnQ.s
+GNU assembler version 2.23.2 (i486--netbsdelf) using BFD version (NetBSD Binutils nb1) 2.23.2
+COMPILER_PATH=/usr/libexec/
+LIBRARY_PATH=/usr/lib/
+COLLECT_GCC_OPTIONS='-nostdinc' '-v' '-o' 'CMakeFiles/cmTC_b8d65.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=nocona' '-march=i486'
+Linking C executable cmTC_b8d65
+/usr/pkg/bin/cmake -E cmake_link_script CMakeFiles/cmTC_b8d65.dir/link.txt --verbose=1
+/usr/bin/cc -nostdinc -v CMakeFiles/cmTC_b8d65.dir/CMakeCCompilerABI.c.o -o cmTC_b8d65
+Using built-in specs.
+COLLECT_GCC=/usr/bin/cc
+COLLECT_LTO_WRAPPER=/usr/libexec/lto-wrapper
+Target: i486--netbsdelf
+Configured with: /usr/7/src/tools/gcc/../../external/gpl3/gcc/dist/configure --target=i486--netbsdelf --enable-long-long --enable-threads --with-bugurl=http://www.NetBSD.org/Misc/send-pr.html --with-pkgversion='NetBSD nb2 20150115' --with-system-zlib --enable-__cxa_atexit --enable-libstdcxx-threads --with-arch=i486 --with-tune=nocona --enable-libstdcxx-time=rt --enable-lto --with-mpc-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpc/lib/libmpc --with-mpfr-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpfr/lib/libmpfr --with-gmp-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/gmp/lib/libgmp --with-mpc-include=/usr/7/src/external/lgpl3/mpc/dist/src --with-mpfr-include=/usr/7/src/external/lgpl3/mpfr/dist/src --with-gmp-include=/usr/7/src/external/lgpl3/gmp/lib/libgmp/arch/i386 --enable-tls --disable-multilib --disable-symvers --disable-libstdcxx-pch --build=x86_64-unknown-netbsd6.0. --host=i486--netbsdelf --with-sysroot=/var/obj/mknative/i386/usr/7/src/destdir.i386
+Thread model: posix
+gcc version 4.8.5 (nb2 20150115)
+COMPILER_PATH=/usr/libexec/
+LIBRARY_PATH=/usr/lib/
+COLLECT_GCC_OPTIONS='-nostdinc' '-v' '-o' 'cmTC_b8d65' '-mtune=nocona' '-march=i486'
+ ld --eh-frame-hdr -dc -dp -e __start -dynamic-linker /usr/libexec/ld.elf_so -o cmTC_b8d65 /usr/lib/crt0.o /usr/lib/crti.o /usr/lib/crtbegin.o CMakeFiles/cmTC_b8d65.dir/CMakeCCompilerABI.c.o -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /usr/lib/crtend.o /usr/lib/crtn.o
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-C-GNU-4.8.5.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-C-GNU-4.8.5.output
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-C-GNU-4.8.5.output
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-CXX-GNU-4.8.5.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-CXX-GNU-4.8.5.input
new file mode 100644
index 000000000..b9a585cc1
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-CXX-GNU-4.8.5.input
@@ -0,0 +1,58 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=CMAKE_CXX_COMPILER_AR-NOTFOUND
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=GNU
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=CMAKE_CXX_COMPILER_RANLIB-NOTFOUND
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=4.8.5
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/pkg/bin/gmake" "cmTC_bbb1e/fast"
+/usr/pkg/bin/gmake -f CMakeFiles/cmTC_bbb1e.dir/build.make CMakeFiles/cmTC_bbb1e.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_bbb1e.dir/CMakeCXXCompilerABI.cpp.o
+/usr/bin/c++ -nostdinc -v -o CMakeFiles/cmTC_bbb1e.dir/CMakeCXXCompilerABI.cpp.o -c /usr/pkg/share/cmake-3.9/Modules/CMakeCXXCompilerABI.cpp
+Using built-in specs.
+COLLECT_GCC=/usr/bin/c++
+Target: i486--netbsdelf
+Configured with: /usr/7/src/tools/gcc/../../external/gpl3/gcc/dist/configure --target=i486--netbsdelf --enable-long-long --enable-threads --with-bugurl=http://www.NetBSD.org/Misc/send-pr.html --with-pkgversion='NetBSD nb2 20150115' --with-system-zlib --enable-__cxa_atexit --enable-libstdcxx-threads --with-arch=i486 --with-tune=nocona --enable-libstdcxx-time=rt --enable-lto --with-mpc-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpc/lib/libmpc --with-mpfr-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpfr/lib/libmpfr --with-gmp-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/gmp/lib/libgmp --with-mpc-include=/usr/7/src/external/lgpl3/mpc/dist/src --with-mpfr-include=/usr/7/src/external/lgpl3/mpfr/dist/src --with-gmp-include=/usr/7/src/external/lgpl3/gmp/lib/libgmp/arch/i386 --enable-tls --disable-multilib --disable-symvers --disable-libstdcxx-pch --build=x86_64-unknown-netbsd6.0. --host=i486--netbsdelf --with-sysroot=/var/obj/mknative/i386/usr/7/src/destdir.i386
+Thread model: posix
+gcc version 4.8.5 (nb2 20150115)
+COLLECT_GCC_OPTIONS='-nostdinc' '-v' '-o' 'CMakeFiles/cmTC_bbb1e.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=nocona' '-march=i486'
+ /usr/libexec/cc1plus -quiet -nostdinc -v /usr/pkg/share/cmake-3.9/Modules/CMakeCXXCompilerABI.cpp -quiet -dumpbase CMakeCXXCompilerABI.cpp -mtune=nocona -march=i486 -auxbase-strip CMakeFiles/cmTC_bbb1e.dir/CMakeCXXCompilerABI.cpp.o -version -o /var/tmp//cclVebp0.s
+GNU C++ (nb2 20150115) version 4.8.5 (i486--netbsdelf)
+ compiled by GNU C version 4.8.5, GMP version 5.1.3, MPFR version 3.1.2, MPC version 1.0.1
+GGC heuristics: --param ggc-min-expand=73 --param ggc-min-heapsize=81803
+#include "..." search starts here:
+#include <...> search starts here:
+End of search list.
+GNU C++ (nb2 20150115) version 4.8.5 (i486--netbsdelf)
+ compiled by GNU C version 4.8.5, GMP version 5.1.3, MPFR version 3.1.2, MPC version 1.0.1
+GGC heuristics: --param ggc-min-expand=73 --param ggc-min-heapsize=81803
+Compiler executable checksum: 961550adc452c84b614bf799df00d02b
+COLLECT_GCC_OPTIONS='-nostdinc' '-v' '-o' 'CMakeFiles/cmTC_bbb1e.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=nocona' '-march=i486'
+ as -v -o CMakeFiles/cmTC_bbb1e.dir/CMakeCXXCompilerABI.cpp.o /var/tmp//cclVebp0.s
+GNU assembler version 2.23.2 (i486--netbsdelf) using BFD version (NetBSD Binutils nb1) 2.23.2
+COMPILER_PATH=/usr/libexec/
+LIBRARY_PATH=/usr/lib/
+COLLECT_GCC_OPTIONS='-nostdinc' '-v' '-o' 'CMakeFiles/cmTC_bbb1e.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=nocona' '-march=i486'
+Linking CXX executable cmTC_bbb1e
+/usr/pkg/bin/cmake -E cmake_link_script CMakeFiles/cmTC_bbb1e.dir/link.txt --verbose=1
+/usr/bin/c++ -nostdinc -v CMakeFiles/cmTC_bbb1e.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_bbb1e
+Using built-in specs.
+COLLECT_GCC=/usr/bin/c++
+COLLECT_LTO_WRAPPER=/usr/libexec/lto-wrapper
+Target: i486--netbsdelf
+Configured with: /usr/7/src/tools/gcc/../../external/gpl3/gcc/dist/configure --target=i486--netbsdelf --enable-long-long --enable-threads --with-bugurl=http://www.NetBSD.org/Misc/send-pr.html --with-pkgversion='NetBSD nb2 20150115' --with-system-zlib --enable-__cxa_atexit --enable-libstdcxx-threads --with-arch=i486 --with-tune=nocona --enable-libstdcxx-time=rt --enable-lto --with-mpc-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpc/lib/libmpc --with-mpfr-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/mpfr/lib/libmpfr --with-gmp-lib=/var/obj/mknative/i386/usr/7/src/external/lgpl3/gmp/lib/libgmp --with-mpc-include=/usr/7/src/external/lgpl3/mpc/dist/src --with-mpfr-include=/usr/7/src/external/lgpl3/mpfr/dist/src --with-gmp-include=/usr/7/src/external/lgpl3/gmp/lib/libgmp/arch/i386 --enable-tls --disable-multilib --disable-symvers --disable-libstdcxx-pch --build=x86_64-unknown-netbsd6.0. --host=i486--netbsdelf --with-sysroot=/var/obj/mknative/i386/usr/7/src/destdir.i386
+Thread model: posix
+gcc version 4.8.5 (nb2 20150115)
+COMPILER_PATH=/usr/libexec/
+LIBRARY_PATH=/usr/lib/
+COLLECT_GCC_OPTIONS='-nostdinc' '-v' '-o' 'cmTC_bbb1e' '-shared-libgcc' '-mtune=nocona' '-march=i486'
+ ld --eh-frame-hdr -dc -dp -e __start -dynamic-linker /usr/libexec/ld.elf_so -o cmTC_bbb1e /usr/lib/crt0.o /usr/lib/crti.o /usr/lib/crtbegin.o CMakeFiles/cmTC_bbb1e.dir/CMakeCXXCompilerABI.cpp.o -lstdc++ -lm --as-needed -lgcc_s --no-as-needed -lgcc -lc --as-needed -lgcc_s --no-as-needed -lgcc /usr/lib/crtend.o /usr/lib/crtn.o
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-CXX-GNU-4.8.5.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-CXX-GNU-4.8.5.output
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/netbsd_nostdinc-CXX-GNU-4.8.5.output
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-C-Clang-5.0.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-C-Clang-5.0.1.input
new file mode 100644
index 000000000..9f34f3d41
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-C-Clang-5.0.1.input
@@ -0,0 +1,37 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=ELF
+CMAKE_C_COMPILER_AR=CMAKE_C_COMPILER_AR-NOTFOUND
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=Clang
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=CMAKE_C_COMPILER_RANLIB-NOTFOUND
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=5.0.1
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_f5360/fast"
+/usr/bin/make -f CMakeFiles/cmTC_f5360.dir/build.make CMakeFiles/cmTC_f5360.dir/build
+Building C object CMakeFiles/cmTC_f5360.dir/CMakeCCompilerABI.c.o
+/usr/bin/cc -v -o CMakeFiles/cmTC_f5360.dir/CMakeCCompilerABI.c.o -c /usr/local/share/cmake/Modules/CMakeCCompilerABI.c
+OpenBSD clang version 5.0.1 (tags/RELEASE_501/final) (based on LLVM 5.0.1)
+Target: amd64-unknown-openbsd6.3
+Thread model: posix
+InstalledDir: /usr/bin
+ "/usr/bin/cc" -cc1 -triple amd64-unknown-openbsd6.3 -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCCompilerABI.c -mrelocation-model pic -pic-level 1 -pic-is-pie -mthread-model posix -mdisable-fp-elim -relaxed-aliasing -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -v -dwarf-column-info -debugger-tuning=gdb -coverage-notes-file /tmp/ii/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_f5360.dir/CMakeCCompilerABI.c.gcno -resource-dir /usr/lib/clang/5.0.1 -fdebug-compilation-dir /tmp/ii/CMakeFiles/CMakeTmp -ferror-limit 19 -fmessage-length 0 -femulated-tls -fwrapv -stack-protector 2 -fobjc-runtime=gnustep -fdiagnostics-show-option -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -o CMakeFiles/cmTC_f5360.dir/CMakeCCompilerABI.c.o -x c /usr/local/share/cmake/Modules/CMakeCCompilerABI.c
+clang -cc1 version 5.0.1 based upon LLVM 5.0.1 default target amd64-unknown-openbsd6.3
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/lib/clang/5.0.1/include
+ /usr/include
+End of search list.
+Linking C executable cmTC_f5360
+/usr/local/bin/cmake -E cmake_link_script CMakeFiles/cmTC_f5360.dir/link.txt --verbose=1
+/usr/bin/cc -v CMakeFiles/cmTC_f5360.dir/CMakeCCompilerABI.c.o -o cmTC_f5360 -Wl,-rpath-link,/usr/X11R6/lib:/usr/local/lib
+OpenBSD clang version 5.0.1 (tags/RELEASE_501/final) (based on LLVM 5.0.1)
+Target: amd64-unknown-openbsd6.3
+Thread model: posix
+InstalledDir: /usr/bin
+ "/usr/bin/ld" -e __start --eh-frame-hdr -Bdynamic -dynamic-linker /usr/libexec/ld.so -o cmTC_f5360 /usr/bin/../lib/crt0.o /usr/bin/../lib/crtbegin.o -L/usr/bin/../lib -L/usr/lib CMakeFiles/cmTC_f5360.dir/CMakeCCompilerABI.c.o -rpath-link /usr/X11R6/lib:/usr/local/lib -lcompiler_rt -lc -lcompiler_rt /usr/bin/../lib/crtend.o
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-C-Clang-5.0.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-C-Clang-5.0.1.output
new file mode 100644
index 000000000..60dbe246a
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-C-Clang-5.0.1.output
@@ -0,0 +1 @@
+/usr/lib/clang/5.0.1/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-CXX-Clang-5.0.1.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-CXX-Clang-5.0.1.input
new file mode 100644
index 000000000..93f1a9570
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-CXX-Clang-5.0.1.input
@@ -0,0 +1,38 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=ELF
+CMAKE_CXX_COMPILER_AR=CMAKE_CXX_COMPILER_AR-NOTFOUND
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=Clang
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=CMAKE_CXX_COMPILER_RANLIB-NOTFOUND
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=5.0.1
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/usr/bin/make" "cmTC_a2bf8/fast"
+/usr/bin/make -f CMakeFiles/cmTC_a2bf8.dir/build.make CMakeFiles/cmTC_a2bf8.dir/build
+Building CXX object CMakeFiles/cmTC_a2bf8.dir/CMakeCXXCompilerABI.cpp.o
+/usr/bin/c++ -v -o CMakeFiles/cmTC_a2bf8.dir/CMakeCXXCompilerABI.cpp.o -c /usr/local/share/cmake/Modules/CMakeCXXCompilerABI.cpp
+OpenBSD clang version 5.0.1 (tags/RELEASE_501/final) (based on LLVM 5.0.1)
+Target: amd64-unknown-openbsd6.3
+Thread model: posix
+InstalledDir: /usr/bin
+ "/usr/bin/c++" -cc1 -triple amd64-unknown-openbsd6.3 -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CMakeCXXCompilerABI.cpp -mrelocation-model pic -pic-level 1 -pic-is-pie -mthread-model posix -mdisable-fp-elim -relaxed-aliasing -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -v -dwarf-column-info -debugger-tuning=gdb -coverage-notes-file /tmp/ii/CMakeFiles/CMakeTmp/CMakeFiles/cmTC_a2bf8.dir/CMakeCXXCompilerABI.cpp.gcno -resource-dir /usr/lib/clang/5.0.1 -internal-isystem /usr/include/c++/v1 -fdeprecated-macro -fdebug-compilation-dir /tmp/ii/CMakeFiles/CMakeTmp -ferror-limit 19 -fmessage-length 0 -femulated-tls -fwrapv -stack-protector 2 -fobjc-runtime=gnustep -fcxx-exceptions -fexceptions -fdiagnostics-show-option -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -o CMakeFiles/cmTC_a2bf8.dir/CMakeCXXCompilerABI.cpp.o -x c++ /usr/local/share/cmake/Modules/CMakeCXXCompilerABI.cpp
+clang -cc1 version 5.0.1 based upon LLVM 5.0.1 default target amd64-unknown-openbsd6.3
+#include "..." search starts here:
+#include <...> search starts here:
+ /usr/include/c++/v1
+ /usr/lib/clang/5.0.1/include
+ /usr/include
+End of search list.
+Linking CXX executable cmTC_a2bf8
+/usr/local/bin/cmake -E cmake_link_script CMakeFiles/cmTC_a2bf8.dir/link.txt --verbose=1
+/usr/bin/c++ -v CMakeFiles/cmTC_a2bf8.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_a2bf8 -Wl,-rpath-link,/usr/X11R6/lib:/usr/local/lib
+OpenBSD clang version 5.0.1 (tags/RELEASE_501/final) (based on LLVM 5.0.1)
+Target: amd64-unknown-openbsd6.3
+Thread model: posix
+InstalledDir: /usr/bin
+ "/usr/bin/ld" -e __start --eh-frame-hdr -Bdynamic -dynamic-linker /usr/libexec/ld.so -o cmTC_a2bf8 /usr/bin/../lib/crt0.o /usr/bin/../lib/crtbegin.o -L/usr/bin/../lib -L/usr/lib CMakeFiles/cmTC_a2bf8.dir/CMakeCXXCompilerABI.cpp.o -rpath-link /usr/X11R6/lib:/usr/local/lib -lc++ -lc++abi -lpthread -lm -lcompiler_rt -lc -lcompiler_rt /usr/bin/../lib/crtend.o
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-CXX-Clang-5.0.1.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-CXX-Clang-5.0.1.output
new file mode 100644
index 000000000..d77687b3c
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/openbsd-CXX-Clang-5.0.1.output
@@ -0,0 +1 @@
+/usr/include/c\+\+/v1;/usr/lib/clang/5.0.1/include;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-C-SunPro-5.13.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-C-SunPro-5.13.0.input
new file mode 100644
index 000000000..b0b504acb
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-C-SunPro-5.13.0.input
@@ -0,0 +1,35 @@
+CMAKE_LANG=C
+CMAKE_C_COMPILER_ABI=
+CMAKE_C_COMPILER_AR=
+CMAKE_C_COMPILER_ARCHITECTURE_ID=
+CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_C_COMPILER_ID=SunPro
+CMAKE_C_COMPILER_LAUNCHER=
+CMAKE_C_COMPILER_LOADED=1
+CMAKE_C_COMPILER_RANLIB=
+CMAKE_C_COMPILER_TARGET=
+CMAKE_C_COMPILER_VERSION=5.13.0
+CMAKE_C_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/opt/csw/bin/gmake" "cmTC_55079/fast"
+/opt/csw/bin/gmake -f CMakeFiles/cmTC_55079.dir/build.make CMakeFiles/cmTC_55079.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building C object CMakeFiles/cmTC_55079.dir/CMakeCCompilerABI.c.o
+/opt/solarisstudio12.4/bin/cc -# -o CMakeFiles/cmTC_55079.dir/CMakeCCompilerABI.c.o -c /tmp/CMake/Modules/CMakeCCompilerABI.c
+### cc: Note: NLSPATH = /opt/solarisstudio12.4/bin/../lib/locale/%L/LC_MESSAGES/%N.cat:/opt/solarisstudio12.4/bin/../../lib/locale/%L/LC_MESSAGES/%N.cat
+### command line files and options (expanded):
+### -# -oCMakeFiles/cmTC_55079.dir/CMakeCCompilerABI.c.o -c /tmp/CMake/Modules/CMakeCCompilerABI.c
+/opt/solarisstudio12.4/lib/compilers/acomp -Qy -std=c11 -i /tmp/CMake/Modules/CMakeCCompilerABI.c -D__SunOS_5_10 -D__SUNPRO_C=0x5130 -D__unix -D__SVR4 -D__sun -D__SunOS -D__sparcv8 -D__sparc -D__BUILTIN_VA_ARG_INCR -D__C11FEATURES__ -D__C99FEATURES__ -D__PRAGMA_REDEFINE_EXTNAME -Dunix -Dsun -Dsparc -D__RESTRICT -D__FLT_EVAL_METHOD__=0 -D__SUN_PREFETCH -D__NOVECTORSIZE__ -I-xbuiltin -I/opt/solarisstudio12.4/lib/compilers/include/cc -xbuiltin=%none -fsimple=0 -m32 -fparam_ir -fparam_ir -xdebuginfo=%none -xF=%none -xdbggen=dwarf+usedonly+incl -xldscope=global -xivdep=loop "-g/opt/solarisstudio12.4/bin/cc -c " -destination_ir=yabe -y-fbe -y/opt/solarisstudio12.4/bin/fbe -y-xmemalign=8i -y-verbose -y-comdat -y-xdebuginfo=%none -y-xarch=generic -y-m32 -y-comdat -y-xthreadvar=no%dynamic -y-xannotate=yes -y-o -yCMakeFiles/cmTC_55079.dir/CMakeCCompilerABI.c.o
+Linking C executable cmTC_55079
+/tmp/CMake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_55079.dir/link.txt --verbose=1
+/opt/solarisstudio12.4/bin/cc -# CMakeFiles/cmTC_55079.dir/CMakeCCompilerABI.c.o -o cmTC_55079
+### cc: Note: NLSPATH = /opt/solarisstudio12.4/bin/../lib/locale/%L/LC_MESSAGES/%N.cat:/opt/solarisstudio12.4/bin/../../lib/locale/%L/LC_MESSAGES/%N.cat
+### command line files and options (expanded):
+### -# CMakeFiles/cmTC_55079.dir/CMakeCCompilerABI.c.o -ocmTC_55079
+### cc: Note: LD_LIBRARY_PATH = (null)
+### cc: Note: LD_RUN_PATH = (null)
+### cc: Note: LD_OPTIONS = (null)
+ln -s /opt/solarisstudio12.4/lib/compilers /tmp/lib_link.1547820951.9061.01
+/usr/ccs/bin/ld -zld32=-S/tmp/lib_link.1547820951.9061.01/libldstab_ws.so -zld64=-S/tmp/lib_link.1547820951.9061.01/sparcv9/libldstab_ws.so -zld32=-S/tmp/lib_link.1547820951.9061.01/libld_annotate.so -zld64=-S/tmp/lib_link.1547820951.9061.01/sparcv9/libld_annotate.so /opt/solarisstudio12.4/lib/compilers/crti.o /opt/solarisstudio12.4/lib/compilers/crt1.o /opt/solarisstudio12.4/lib/compilers/misalign.o /opt/solarisstudio12.4/lib/compilers/values-xa.o CMakeFiles/cmTC_55079.dir/CMakeCCompilerABI.c.o -o cmTC_55079 -Y "P,/opt/solarisstudio12.4/lib/compilers/staticlib:/opt/solarisstudio12.4/lib/compilers/sparc:/opt/solarisstudio12.4/lib/compilers:/usr/ccs/lib:/lib:/usr/lib" -Qy -lc /opt/solarisstudio12.4/lib/compilers/crtn.o
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-C-SunPro-5.13.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-C-SunPro-5.13.0.output
new file mode 100644
index 000000000..27c452d26
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-C-SunPro-5.13.0.output
@@ -0,0 +1 @@
+/opt/solarisstudio12.4/lib/compilers/include/cc;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-CXX-SunPro-5.13.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-CXX-SunPro-5.13.0.input
new file mode 100644
index 000000000..9abd06a28
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-CXX-SunPro-5.13.0.input
@@ -0,0 +1,38 @@
+CMAKE_LANG=CXX
+CMAKE_CXX_COMPILER_ABI=
+CMAKE_CXX_COMPILER_AR=
+CMAKE_CXX_COMPILER_ARCHITECTURE_ID=
+CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_CXX_COMPILER_ID=SunPro
+CMAKE_CXX_COMPILER_LAUNCHER=
+CMAKE_CXX_COMPILER_LOADED=1
+CMAKE_CXX_COMPILER_RANLIB=
+CMAKE_CXX_COMPILER_TARGET=
+CMAKE_CXX_COMPILER_VERSION=5.13.0
+CMAKE_CXX_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/opt/csw/bin/gmake" "cmTC_cc4b2/fast"
+/opt/csw/bin/gmake -f CMakeFiles/cmTC_cc4b2.dir/build.make CMakeFiles/cmTC_cc4b2.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building CXX object CMakeFiles/cmTC_cc4b2.dir/CMakeCXXCompilerABI.cpp.o
+/opt/solarisstudio12.4/bin/CC -v -o CMakeFiles/cmTC_cc4b2.dir/CMakeCXXCompilerABI.cpp.o -c /tmp/CMake/Modules/CMakeCXXCompilerABI.cpp
+### CC: Note: NLSPATH = /opt/solarisstudio12.4/bin/../lib/locale/%L/LC_MESSAGES/%N.cat:/opt/solarisstudio12.4/bin/../../lib/locale/%L/LC_MESSAGES/%N.cat
+### command line files and options (expanded):
+### -v -oCMakeFiles/cmTC_cc4b2.dir/CMakeCXXCompilerABI.cpp.o -c /tmp/CMake/Modules/CMakeCXXCompilerABI.cpp
+/opt/solarisstudio12.4/lib/compilers/ccfe -D__SunOS_5_10 -D__SUNPRO_CC=0x5130 -D__unix -D__SVR4 -D__sun -D__SunOS -D__sparcv8 -D__sparc -D__BUILTIN_VA_ARG_INCR -Dunix -Dsun -Dsparc -D__SUN_PREFETCH -D__SUNPRO_CC_COMPAT=5 -D__NOVECTORSIZE__ -I-xbuiltin -I/opt/solarisstudio12.4/lib/compilers/include/CC/Cstd -I/opt/solarisstudio12.4/lib/compilers/include/CC -I/opt/solarisstudio12.4/lib/compilers/include/cc -ptf /tmp/ccfe.1547820952.9069.02.%1.%2 -ptx /opt/solarisstudio12.4/bin/CC -ptk "-v -c " -compat=5 -xdebuginfo=%none -instlib=/opt/solarisstudio12.4/lib/compilers/libCstd.a -xdbggen=dwarf+usedonly+incl -xF=%none -xbuiltin=%none -xldscope=global -xivdep=loop -O0 -xarrayloc /tmp/CMake/Modules/CMakeCXXCompilerABI.cpp -ptb CMakeFiles/cmTC_cc4b2.dir/CMakeCXXCompilerABI.cpp.o -y-fbe -y/opt/solarisstudio12.4/bin/fbe -y-xmemalign=8i -y-verbose -y-comdat -y-xdebuginfo=%none -y-xarch=generic -y-m32 -y-comdat -y-xthreadvar=no%dynamic -y-xannotate=yes -y-o -yCMakeFiles/cmTC_cc4b2.dir/CMakeCXXCompilerABI.cpp.o 2> /tmp/ccfe.1547820952.9069.01.err
+rm /tmp/ccfe.1547820952.9069.01.err
+Linking CXX executable cmTC_cc4b2
+/tmp/CMake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_cc4b2.dir/link.txt --verbose=1
+/opt/solarisstudio12.4/bin/CC -v CMakeFiles/cmTC_cc4b2.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_cc4b2
+### CC: Note: NLSPATH = /opt/solarisstudio12.4/bin/../lib/locale/%L/LC_MESSAGES/%N.cat:/opt/solarisstudio12.4/bin/../../lib/locale/%L/LC_MESSAGES/%N.cat
+### command line files and options (expanded):
+### -v CMakeFiles/cmTC_cc4b2.dir/CMakeCXXCompilerABI.cpp.o -ocmTC_cc4b2
+### CC: Note: LD_LIBRARY_PATH = (null)
+### CC: Note: LD_RUN_PATH = (null)
+### CC: Note: LD_OPTIONS = (null)
+ln -s /opt/solarisstudio12.4/lib/compilers /tmp/lib_link.1547820952.9076.01
+/usr/ccs/bin/ld -zld32=-S/tmp/lib_link.1547820952.9076.01/libldstab_ws.so -zld64=-S/tmp/lib_link.1547820952.9076.01/sparcv9/libldstab_ws.so -zld32=-S/tmp/lib_link.1547820952.9076.01/libld_annotate.so -zld64=-S/tmp/lib_link.1547820952.9076.01/sparcv9/libld_annotate.so -zld32=-S/tmp/lib_link.1547820952.9076.01/libCCexcept.so.1 -zld64=-S/tmp/lib_link.1547820952.9076.01/sparcv9/libCCexcept.so.1 /opt/solarisstudio12.4/lib/compilers/crti.o -u __1cH__CimplKcplus_init6F_v_ /opt/solarisstudio12.4/lib/compilers/CCrti.o /opt/solarisstudio12.4/lib/compilers/crt1.o /opt/solarisstudio12.4/lib/compilers/misalign.o /opt/solarisstudio12.4/lib/compilers/values-xa.o CMakeFiles/cmTC_cc4b2.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_cc4b2 -Y "P,/opt/solarisstudio12.4/lib/compilers/sparc:/opt/solarisstudio12.4/lib/compilers:/opt/solarisstudio12.4/lib/sparc:/opt/solarisstudio12.4/lib:/usr/ccs/lib:/lib:/usr/lib" -Qy "-R/opt/solarisstudio12.4/lib/sparc:/opt/solarisstudio12.4/lib" -lCstd -lCrun -lm -lc /opt/solarisstudio12.4/lib/compilers/CCrtn.o /opt/solarisstudio12.4/lib/compilers/crtn.o 2> /tmp/ld.1547820952.9076.02.err
+rm /tmp/lib_link.1547820952.9076.01
+rm /tmp/ld.1547820952.9076.02.err
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-CXX-SunPro-5.13.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-CXX-SunPro-5.13.0.output
new file mode 100644
index 000000000..be851c2ac
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-CXX-SunPro-5.13.0.output
@@ -0,0 +1 @@
+/opt/solarisstudio12.4/lib/compilers/include/CC/Cstd;/opt/solarisstudio12.4/lib/compilers/include/CC;/opt/solarisstudio12.4/lib/compilers/include/cc;/usr/include
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-Fortran-SunPro-8.8.0.input b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-Fortran-SunPro-8.8.0.input
new file mode 100644
index 000000000..4a2bedd87
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-Fortran-SunPro-8.8.0.input
@@ -0,0 +1,40 @@
+CMAKE_LANG=Fortran
+CMAKE_Fortran_COMPILER_ABI=
+CMAKE_Fortran_COMPILER_AR=
+CMAKE_Fortran_COMPILER_ARCHITECTURE_ID=
+CMAKE_Fortran_COMPILER_EXTERNAL_TOOLCHAIN=
+CMAKE_Fortran_COMPILER_ID=SunPro
+CMAKE_Fortran_COMPILER_LAUNCHER=
+CMAKE_Fortran_COMPILER_LOADED=1
+CMAKE_Fortran_COMPILER_RANLIB=
+CMAKE_Fortran_COMPILER_TARGET=
+CMAKE_Fortran_COMPILER_VERSION=8.8.0
+CMAKE_Fortran_COMPILER_VERSION_INTERAL=
+Change Dir: /tmp/ii/CMakeFiles/CMakeTmp
+
+Run Build Command:"/opt/csw/bin/gmake" "cmTC_adcec/fast"
+/opt/csw/bin/gmake -f CMakeFiles/cmTC_adcec.dir/build.make CMakeFiles/cmTC_adcec.dir/build
+gmake[1]: Entering directory '/tmp/ii/CMakeFiles/CMakeTmp'
+Building Fortran object CMakeFiles/cmTC_adcec.dir/CMakeFortranCompilerABI.F.o
+/opt/developerstudio12.6/bin/sunf95 -v -c /tmp/CMake/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_adcec.dir/CMakeFortranCompilerABI.F.o
+### f90: Note: NLSPATH = /opt/developerstudio12.6/bin/../lib/locale/%L/LC_MESSAGES/%N.cat:/opt/developerstudio12.6/bin/../../lib/locale/%L/LC_MESSAGES/%N.cat
+### command line files and options (expanded):
+### -v -c /tmp/CMake/Modules/CMakeFortranCompilerABI.F -o CMakeFiles/cmTC_adcec.dir/CMakeFortranCompilerABI.F.o
+/opt/developerstudio12.6/bin/fpp -undef -vax=bslash -Y/opt/developerstudio12.6/lib/compilers/include/f95 -D__SunOS_5_10 -D__SunOS_RELEASE=0x051000 -D__SUNPRO_F90=0x880 -D__SUNPRO_F95=0x880 -D__unix -D__SVR4__ -D__svr4__ -D__SVR4 -D__sun -D__sun__ -D__SunOS -D__sparcv8 -D__sparcv8plus -D__sparc -D__sparc__ -Dsun -Dunix -Dsparc -D__SUN_PREFETCH -I/opt/developerstudio12.6/lib/compilers/include/f95 /tmp/CMake/Modules/CMakeFortranCompilerABI.F /tmp/fpp.1548681160.26580.01.f
+/opt/developerstudio12.6/lib/compilers/bin/f90comp -E/tmp/CMake/Modules/CMakeFortranCompilerABI.F -m3 -ev -xall -xivdep=loop -H "/opt/developerstudio12.6/bin/f90 -v -c " -I/opt/developerstudio12.6/lib/compilers/include/f95 -p/opt/developerstudio12.6/lib/compilers/modules -m32 -y-m32 -xmemalign=8i -iorounding=processor-defined -xhasc=yes -xdebuginfo=%none -y-xdebuginfo=%none -y-xglobalize=no -xcache=generic -y-xcache=generic -y-xassume_control=optimize -xassume_control=optimize -y-xdbggen=dwarf+incl -keepmod=yes -y-ir -y/tmp/f90comp.1548681160.26580.02.ir /tmp/fpp.1548681160.26580.01.f
+/opt/developerstudio12.6/lib/compilers/bin/cg -Qy -fsimple=0 -xarch=sparcvis2 -m32 -xchip=generic -xcache=generic -comdat -ftrap=division,invalid,overflow -xdebuginfo=%none -xbuiltin=%none -xcode=abs32 -xannotate=yes -xmemalign=8i -xprefetch=auto,explicit -xprefetch_auto_type=no%indirect_array_access -xcheck=stkovf -xcheck=noreturn -xvector=no -oo CMakeFiles/cmTC_adcec.dir/CMakeFortranCompilerABI.F.o -ir /tmp/f90comp.1548681160.26580.02.ir
+rm /tmp/f90comp.1548681160.26580.02.ir
+rm /tmp/fpp.1548681160.26580.01.f
+Linking Fortran executable cmTC_adcec
+/tmp/CMake/bin/cmake -E cmake_link_script CMakeFiles/cmTC_adcec.dir/link.txt --verbose=1
+/opt/developerstudio12.6/bin/sunf95 -v CMakeFiles/cmTC_adcec.dir/CMakeFortranCompilerABI.F.o -o cmTC_adcec
+### f90: Note: NLSPATH = /opt/developerstudio12.6/bin/../lib/locale/%L/LC_MESSAGES/%N.cat:/opt/developerstudio12.6/bin/../../lib/locale/%L/LC_MESSAGES/%N.cat
+### command line files and options (expanded):
+### -v CMakeFiles/cmTC_adcec.dir/CMakeFortranCompilerABI.F.o -o cmTC_adcec
+### f90: Note: LD_LIBRARY_PATH = (null)
+### f90: Note: LD_RUN_PATH = (null)
+### f90: Note: LD_OPTIONS = (null)
+ln -s /opt/developerstudio12.6/lib/compilers /tmp/lib_link.1548681161.26655.01
+/usr/ccs/bin/ld -zld32=-S/tmp/lib_link.1548681161.26655.01/libldstab_ws.so -zld64=-S/tmp/lib_link.1548681161.26655.01/sparcv9/libldstab_ws.so -zld32=-S/tmp/lib_link.1548681161.26655.01/libld_annotate.so -zld64=-S/tmp/lib_link.1548681161.26655.01/sparcv9/libld_annotate.so /opt/developerstudio12.6/lib/compilers/crti.o /opt/developerstudio12.6/lib/compilers/crt1.o /opt/developerstudio12.6/lib/compilers/misalign.o /opt/developerstudio12.6/lib/compilers/values-xi.o CMakeFiles/cmTC_adcec.dir/CMakeFortranCompilerABI.F.o -o cmTC_adcec -Y "P,/opt/developerstudio12.6/lib/compilers/sparcvis2:/opt/developerstudio12.6/lib/compilers:/opt/developerstudio12.6/lib:/usr/ccs/lib:/lib:/usr/lib" -Qy -R/opt/developerstudio12.6/lib -t -lfsu -lsunmath -lmtsk -lm -lc /opt/developerstudio12.6/lib/compilers/crtn.o
+rm /tmp/lib_link.1548681161.26655.01
+gmake[1]: Leaving directory '/tmp/ii/CMakeFiles/CMakeTmp'
diff --git a/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-Fortran-SunPro-8.8.0.output b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-Fortran-SunPro-8.8.0.output
new file mode 100644
index 000000000..3c31e16c9
--- /dev/null
+++ b/Tests/RunCMake/ParseImplicitIncludeInfo/data/sunos-Fortran-SunPro-8.8.0.output
@@ -0,0 +1 @@
+/opt/developerstudio12.6/lib/compilers/include/f95
diff --git a/Tests/RunCMake/PositionIndependentCode/CMP0083-cmp0083_new-check.cmake b/Tests/RunCMake/PositionIndependentCode/CMP0083-cmp0083_new-check.cmake
new file mode 100644
index 000000000..255e63de4
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/CMP0083-cmp0083_new-check.cmake
@@ -0,0 +1,22 @@
+
+include ("${RunCMake_TEST_BINARY_DIR}/${RunCMake_TEST_CONFIG}/CMP0083_config.cmake")
+
+
+# retrieve default type of executable
+check_executable ("${cmp0083_ref}" ref)
+
+if (ref STREQUAL "PIE")
+ # check no_pie executable is really no position independent
+ check_executable ("${cmp0083_new_no_pie}" new_no_pie)
+ if (NOT new_no_pie STREQUAL "NO_PIE")
+ set (RunCMake_TEST_FAILED "CMP0083(NEW) do not produce expected executable.")
+ endif()
+elseif (ref STREQUAL "NO_PIE")
+ # check pie executable is really position independent
+ check_executable ("${cmp0083_new_pie}" new_pie)
+ if (NOT new_pie MATCHES "PIE")
+ set (RunCMake_TEST_FAILED "CMP0083(NEW) do not produce expected executable.")
+ endif()
+else()
+ set (RunCMake_TEST_FAILED "CMP0083(NEW) unexpected result.")
+endif()
diff --git a/Tests/RunCMake/PositionIndependentCode/CMP0083-cmp0083_old-check.cmake b/Tests/RunCMake/PositionIndependentCode/CMP0083-cmp0083_old-check.cmake
new file mode 100644
index 000000000..b66b67286
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/CMP0083-cmp0083_old-check.cmake
@@ -0,0 +1,20 @@
+
+include ("${RunCMake_TEST_BINARY_DIR}/${RunCMake_TEST_CONFIG}/CMP0083_config.cmake")
+
+
+# retrieve default type of executable
+check_executable ("${cmp0083_ref}" ref)
+
+# POSITION_INDEPENDENT_CODE must not have influence on executable
+# pie and no_pie executable must have same type as reference
+check_executable ("${cmp0083_old_pie}" old_pie)
+if (NOT old_pie STREQUAL ref)
+ set (RunCMake_TEST_FAILED "CMP0083(OLD) do not produce expected executable.")
+ return()
+endif()
+
+check_executable ("${cmp0083_old_no_pie}" old_no_pie)
+if (NOT old_no_pie STREQUAL ref)
+ set (RunCMake_TEST_FAILED "CMP0083(OLD) do not produce expected executable.")
+ return()
+endif()
diff --git a/Tests/RunCMake/PositionIndependentCode/CMP0083.cmake b/Tests/RunCMake/PositionIndependentCode/CMP0083.cmake
new file mode 100644
index 000000000..749ac793e
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/CMP0083.cmake
@@ -0,0 +1,47 @@
+
+# create reference to detect default : PIE or not
+add_executable (cmp0083_ref main.cpp)
+
+
+set (CMAKE_POSITION_INDEPENDENT_CODE ON)
+
+cmake_policy(SET CMP0083 NEW)
+include(CheckPIESupported)
+check_pie_supported()
+add_executable (cmp0083_new_pie main.cpp)
+
+
+cmake_policy(SET CMP0083 OLD)
+add_executable (cmp0083_old_pie main.cpp)
+
+
+set (CMAKE_POSITION_INDEPENDENT_CODE OFF)
+
+cmake_policy(SET CMP0083 NEW)
+add_executable (cmp0083_new_no_pie main.cpp)
+
+
+cmake_policy(SET CMP0083 OLD)
+add_executable (cmp0083_old_no_pie main.cpp)
+
+# high-level targets
+add_custom_target(cmp0083_new)
+add_dependencies(cmp0083_new cmp0083_ref cmp0083_new_pie cmp0083_new_no_pie)
+
+# high-level targets
+add_custom_target(cmp0083_old)
+add_dependencies(cmp0083_old cmp0083_ref cmp0083_old_pie cmp0083_old_no_pie)
+
+
+# generate file holding paths to executables
+file (GENERATE OUTPUT "${CMAKE_BINARY_DIR}/$<CONFIG>/CMP0083_config.cmake"
+ CONTENT
+[==[
+include ("${RunCMake_TEST_SOURCE_DIR}/PIE_validator.cmake")
+
+set (cmp0083_ref "$<TARGET_FILE:cmp0083_ref>")
+set (cmp0083_new_pie "$<TARGET_FILE:cmp0083_new_pie>")
+set (cmp0083_old_pie "$<TARGET_FILE:cmp0083_old_pie>")
+set (cmp0083_new_no_pie "$<TARGET_FILE:cmp0083_new_no_pie>")
+set (cmp0083_old_no_pie "$<TARGET_FILE:cmp0083_old_no_pie>")
+]==])
diff --git a/Tests/RunCMake/PositionIndependentCode/CheckPIESupported.cmake b/Tests/RunCMake/PositionIndependentCode/CheckPIESupported.cmake
new file mode 100644
index 000000000..61e1b6d3e
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/CheckPIESupported.cmake
@@ -0,0 +1,18 @@
+
+cmake_policy(SET CMP0083 NEW)
+
+include (CheckPIESupported)
+
+check_pie_supported()
+
+if (CMAKE_CXX_LINK_PIE_SUPPORTED)
+ file(WRITE "${PIE_SUPPORTED}" "\nset(PIE_SUPPORTED TRUE)\n")
+else()
+ file(WRITE "${PIE_SUPPORTED}" "\nset(PIE_SUPPORTED FALSE)\n")
+endif()
+
+if (CMAKE_CXX_LINK_NO_PIE_SUPPORTED)
+ file(APPEND "${PIE_SUPPORTED}" "\nset(NO_PIE_SUPPORTED TRUE)\n")
+else()
+ file(APPEND "${PIE_SUPPORTED}" "\nset(NO_PIE_SUPPORTED FALSE)\n")
+endif()
diff --git a/Tests/RunCMake/PositionIndependentCode/Genex1-result.txt b/Tests/RunCMake/PositionIndependentCode/Genex1-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/Genex1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/PositionIndependentCode/Genex1-stderr.txt b/Tests/RunCMake/PositionIndependentCode/Genex1-stderr.txt
new file mode 100644
index 000000000..c242a05cb
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/Genex1-stderr.txt
@@ -0,0 +1,3 @@
+CMake Error: Property POSITION_INDEPENDENT_CODE on target "conflict1" does
+not match the INTERFACE_POSITION_INDEPENDENT_CODE property requirement
+of dependency "genex_pic".
diff --git a/Tests/RunCMake/PositionIndependentCode/Genex1.cmake b/Tests/RunCMake/PositionIndependentCode/Genex1.cmake
new file mode 100644
index 000000000..a91be3eec
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/Genex1.cmake
@@ -0,0 +1,9 @@
+
+add_library(genex_pic UNKNOWN IMPORTED)
+# PIC is ON if sibling target is a library, OFF if it is an executable
+set_property(TARGET genex_pic PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE $<NOT:$<STREQUAL:$<TARGET_PROPERTY:TYPE>,EXECUTABLE>>)
+
+
+add_library(conflict1 STATIC main.cpp)
+set_property(TARGET conflict1 PROPERTY POSITION_INDEPENDENT_CODE OFF)
+target_link_libraries(conflict1 PRIVATE genex_pic)
diff --git a/Tests/RunCMake/PositionIndependentCode/Genex2-result.txt b/Tests/RunCMake/PositionIndependentCode/Genex2-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/Genex2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/PositionIndependentCode/Genex2-stderr.txt b/Tests/RunCMake/PositionIndependentCode/Genex2-stderr.txt
new file mode 100644
index 000000000..735a926ed
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/Genex2-stderr.txt
@@ -0,0 +1,3 @@
+CMake Error: Property POSITION_INDEPENDENT_CODE on target "conflict2" does
+not match the INTERFACE_POSITION_INDEPENDENT_CODE property requirement
+of dependency "genex_pic".
diff --git a/Tests/RunCMake/PositionIndependentCode/Genex2.cmake b/Tests/RunCMake/PositionIndependentCode/Genex2.cmake
new file mode 100644
index 000000000..fb0a5dbda
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/Genex2.cmake
@@ -0,0 +1,9 @@
+
+add_library(genex_pic UNKNOWN IMPORTED)
+# PIC is ON if sibling target is a library, OFF if it is an executable
+set_property(TARGET genex_pic PROPERTY INTERFACE_POSITION_INDEPENDENT_CODE $<NOT:$<STREQUAL:$<TARGET_PROPERTY:TYPE>,EXECUTABLE>>)
+
+
+add_executable(conflict2 main.cpp)
+set_property(TARGET conflict2 PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_link_libraries(conflict2 PRIVATE genex_pic)
diff --git a/Tests/RunCMake/PositionIndependentCode/PIE-pie_off-check.cmake b/Tests/RunCMake/PositionIndependentCode/PIE-pie_off-check.cmake
new file mode 100644
index 000000000..096395c08
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/PIE-pie_off-check.cmake
@@ -0,0 +1,7 @@
+
+include ("${RunCMake_TEST_BINARY_DIR}/${RunCMake_TEST_CONFIG}/PIE_config.cmake")
+
+check_executable ("${pie_off}" status)
+if (NOT status STREQUAL "NO_PIE")
+ set (RunCMake_TEST_FAILED "Executable is NOT 'no PIE' (${status}).")
+endif()
diff --git a/Tests/RunCMake/PositionIndependentCode/PIE-pie_on-check.cmake b/Tests/RunCMake/PositionIndependentCode/PIE-pie_on-check.cmake
new file mode 100644
index 000000000..bf3d0186d
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/PIE-pie_on-check.cmake
@@ -0,0 +1,7 @@
+
+include ("${RunCMake_TEST_BINARY_DIR}/${RunCMake_TEST_CONFIG}/PIE_config.cmake")
+
+check_executable ("${pie_on}" status)
+if (NOT status STREQUAL "PIE")
+ set (RunCMake_TEST_FAILED "Executable is NOT 'PIE' (${status}).")
+endif()
diff --git a/Tests/RunCMake/PositionIndependentCode/PIE.cmake b/Tests/RunCMake/PositionIndependentCode/PIE.cmake
new file mode 100644
index 000000000..16ed89ce6
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/PIE.cmake
@@ -0,0 +1,22 @@
+
+cmake_policy(SET CMP0083 NEW)
+
+include(CheckPIESupported)
+check_pie_supported()
+
+add_executable (pie_on main.cpp)
+set_property(TARGET pie_on PROPERTY POSITION_INDEPENDENT_CODE ON)
+
+add_executable (pie_off main.cpp)
+set_property(TARGET pie_off PROPERTY POSITION_INDEPENDENT_CODE OFF)
+
+
+# generate file holding paths to executables
+file (GENERATE OUTPUT "${CMAKE_BINARY_DIR}/$<CONFIG>/PIE_config.cmake"
+ CONTENT
+[==[
+include ("${RunCMake_TEST_SOURCE_DIR}/PIE_validator.cmake")
+
+set (pie_on "$<TARGET_FILE:pie_on>")
+set (pie_off "$<TARGET_FILE:pie_off>")
+]==])
diff --git a/Tests/RunCMake/PositionIndependentCode/PIE_validator.cmake b/Tests/RunCMake/PositionIndependentCode/PIE_validator.cmake
new file mode 100644
index 000000000..7be35db6a
--- /dev/null
+++ b/Tests/RunCMake/PositionIndependentCode/PIE_validator.cmake
@@ -0,0 +1,32 @@
+
+include_guard(GLOBAL)
+
+function (CHECK_EXECUTABLE executable result)
+ set (${result} "UNKNOWN" PARENT_SCOPE)
+
+ if (CMAKE_SYSTEM_NAME STREQUAL "Darwin")
+ set (tool otool -hv)
+ else()
+ set (tool "${CMAKE_COMMAND}" -E env LANG=C LC_ALL=C readelf -lW)
+ endif()
+
+ execute_process(COMMAND ${tool} "${executable}"
+ OUTPUT_VARIABLE output
+ ERROR_VARIABLE output)
+
+ if (CMAKE_SYSTEM_NAME STREQUAL "Darwin")
+ if (output MATCHES "( |\t)PIE( |\n|$)")
+ set (${result} "PIE" PARENT_SCOPE)
+ else()
+ set (${result} "NO_PIE" PARENT_SCOPE)
+ endif()
+ else()
+ if (output MATCHES "Elf file type is DYN")
+ set (${result} "PIE" PARENT_SCOPE)
+ elseif (output MATCHES "Elf file type is EXEC")
+ set (${result} "NO_PIE" PARENT_SCOPE)
+ else()
+ message(SEND_ERROR "Did not find a known file type")
+ endif()
+ endif()
+endfunction()
diff --git a/Tests/RunCMake/RuntimePath/Relative.cmake b/Tests/RunCMake/RuntimePath/Relative.cmake
new file mode 100644
index 000000000..203241ff0
--- /dev/null
+++ b/Tests/RunCMake/RuntimePath/Relative.cmake
@@ -0,0 +1,69 @@
+enable_language(C)
+
+if(NOT CMAKE_SHARED_LIBRARY_RPATH_ORIGIN_TOKEN)
+ if(CMAKE_C_PLATFORM_ID STREQUAL "Linux")
+ # Sanity check for platform that is definitely known to support $ORIGIN.
+ message(FATAL_ERROR "Platform fails to report relative RPATH support")
+ else()
+ message(STATUS "Platform does not support relative RPATHs, skipping")
+ endif()
+ return()
+endif()
+set(CMAKE_BUILD_RPATH_USE_ORIGIN ON)
+
+function(CheckRpath target rpath)
+ add_custom_command(
+ TARGET ${target}
+ POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -Dfile=$<TARGET_FILE:${target}> -Drpath=${rpath}
+ -P "${CMAKE_CURRENT_SOURCE_DIR}/RelativeCheck.cmake"
+ VERBATIM
+ )
+endfunction()
+
+if(CMAKE_C_COMPILER_ID STREQUAL "XL" AND CMAKE_BINARY_DIR MATCHES " ")
+ # XL 16.1.0.0 fails building the library if the output path contains a space.
+ set(externDir)
+ message(STATUS "Skipping external library test because of a toolchain bug")
+else()
+ get_filename_component(externDir "${CMAKE_BINARY_DIR}" DIRECTORY)
+ set(externDir "${externDir}/Relative-extern")
+endif()
+
+add_library(utils SHARED A.c)
+add_library(utils-sub SHARED A.c)
+set_property(TARGET utils-sub PROPERTY LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/libs)
+if(externDir)
+ add_library(utils-extern SHARED A.c)
+ set_property(TARGET utils-extern PROPERTY LIBRARY_OUTPUT_DIRECTORY ${externDir})
+endif()
+
+add_executable(main main.c)
+target_link_libraries(main utils)
+CheckRpath(main "\$ORIGIN")
+
+add_executable(main-norel main.c)
+target_link_libraries(main-norel utils)
+set_property(TARGET main-norel PROPERTY BUILD_RPATH_USE_ORIGIN OFF)
+CheckRpath(main-norel "${CMAKE_CURRENT_BINARY_DIR}")
+
+add_executable(mainsub main.c)
+target_link_libraries(mainsub utils)
+set_property(TARGET mainsub PROPERTY RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin)
+CheckRpath(mainsub "\$ORIGIN/../")
+
+add_executable(main-sub main.c)
+target_link_libraries(main-sub utils-sub)
+CheckRpath(main-sub "\$ORIGIN/libs")
+
+add_executable(mainsub-sub main.c)
+target_link_libraries(mainsub-sub utils-sub)
+set_property(TARGET mainsub-sub PROPERTY RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin)
+CheckRpath(mainsub-sub "\$ORIGIN/../libs")
+
+if(externDir)
+ # Binaries linking to libraries outside the build tree should have an absolute RPATH.
+ add_executable(main-extern main.c)
+ target_link_libraries(main-extern utils-extern)
+ CheckRpath(main-extern "${externDir}")
+endif()
diff --git a/Tests/RunCMake/RuntimePath/RelativeCheck.cmake b/Tests/RunCMake/RuntimePath/RelativeCheck.cmake
new file mode 100644
index 000000000..9ee403ff9
--- /dev/null
+++ b/Tests/RunCMake/RuntimePath/RelativeCheck.cmake
@@ -0,0 +1,4 @@
+file(RPATH_CHECK FILE "${file}" RPATH "${rpath}")
+if(NOT EXISTS "${file}")
+ message(FATAL_ERROR "RPATH for ${file} did not contain the expected value")
+endif()
diff --git a/Tests/RunCMake/ScriptMode/RunCMakeTest.cmake b/Tests/RunCMake/ScriptMode/RunCMakeTest.cmake
new file mode 100644
index 000000000..4c44ffb09
--- /dev/null
+++ b/Tests/RunCMake/ScriptMode/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake_command(set_directory_properties ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/set_directory_properties.cmake)
diff --git a/Tests/RunCMake/ScriptMode/set_directory_properties.cmake b/Tests/RunCMake/ScriptMode/set_directory_properties.cmake
new file mode 100644
index 000000000..bf793172f
--- /dev/null
+++ b/Tests/RunCMake/ScriptMode/set_directory_properties.cmake
@@ -0,0 +1 @@
+set_directory_properties(PROPERTIES SOME_PROPERTY FALSE)
diff --git a/Tests/RunCMake/SourceProperties/CMakeLists.txt b/Tests/RunCMake/SourceProperties/CMakeLists.txt
new file mode 100644
index 000000000..a17c8cd13
--- /dev/null
+++ b/Tests/RunCMake/SourceProperties/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 2.8.4)
+project(${RunCMake_TEST} C)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/SourceProperties/RelativeIncludeDir-result.txt b/Tests/RunCMake/SourceProperties/RelativeIncludeDir-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/SourceProperties/RelativeIncludeDir-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/SourceProperties/RelativeIncludeDir-stderr.txt b/Tests/RunCMake/SourceProperties/RelativeIncludeDir-stderr.txt
new file mode 100644
index 000000000..cf146c25d
--- /dev/null
+++ b/Tests/RunCMake/SourceProperties/RelativeIncludeDir-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error in CMakeLists.txt:
+ Found relative path while evaluating include directories of "empty.c":
+
+ "relative"
diff --git a/Tests/RunCMake/SourceProperties/RelativeIncludeDir.cmake b/Tests/RunCMake/SourceProperties/RelativeIncludeDir.cmake
new file mode 100644
index 000000000..08dffa81e
--- /dev/null
+++ b/Tests/RunCMake/SourceProperties/RelativeIncludeDir.cmake
@@ -0,0 +1,4 @@
+
+set_property (SOURCE empty.c PROPERTY INCLUDE_DIRECTORIES "relative")
+
+add_library (somelib empty.c)
diff --git a/Tests/RunCMake/SourceProperties/RunCMakeTest.cmake b/Tests/RunCMake/SourceProperties/RunCMakeTest.cmake
new file mode 100644
index 000000000..098215317
--- /dev/null
+++ b/Tests/RunCMake/SourceProperties/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(RelativeIncludeDir)
diff --git a/Tests/RunCMake/SourceProperties/empty.c b/Tests/RunCMake/SourceProperties/empty.c
new file mode 100644
index 000000000..a9ec1021d
--- /dev/null
+++ b/Tests/RunCMake/SourceProperties/empty.c
@@ -0,0 +1,5 @@
+
+int empty()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/Swift/E.swift b/Tests/RunCMake/Swift/E.swift
new file mode 100644
index 000000000..a41546787
--- /dev/null
+++ b/Tests/RunCMake/Swift/E.swift
@@ -0,0 +1,2 @@
+func f() {
+}
diff --git a/Tests/RunCMake/Swift/Win32ExecutableDisallowed-result.txt b/Tests/RunCMake/Swift/Win32ExecutableDisallowed-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/Swift/Win32ExecutableDisallowed-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Swift/Win32ExecutableDisallowed-stderr.txt b/Tests/RunCMake/Swift/Win32ExecutableDisallowed-stderr.txt
new file mode 100644
index 000000000..d78101a91
--- /dev/null
+++ b/Tests/RunCMake/Swift/Win32ExecutableDisallowed-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at Win32ExecutableDisallowed.cmake:[0-9]+ \(add_executable\):
+ WIN32_EXECUTABLE property is not supported on Swift executables
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/Swift/Win32ExecutableDisallowed.cmake b/Tests/RunCMake/Swift/Win32ExecutableDisallowed.cmake
new file mode 100644
index 000000000..02d544749
--- /dev/null
+++ b/Tests/RunCMake/Swift/Win32ExecutableDisallowed.cmake
@@ -0,0 +1,4 @@
+enable_language(Swift)
+add_executable(E E.swift)
+set_target_properties(E PROPERTIES
+ WIN32_EXECUTABLE TRUE)
diff --git a/Tests/RunCMake/Syntax/CMP0053-Dollar-NEW-stderr.txt b/Tests/RunCMake/Syntax/CMP0053-Dollar-NEW-stderr.txt
new file mode 100644
index 000000000..7f248ae17
--- /dev/null
+++ b/Tests/RunCMake/Syntax/CMP0053-Dollar-NEW-stderr.txt
@@ -0,0 +1,2 @@
+^-->value<--
+-->value<--$
diff --git a/Tests/RunCMake/Syntax/CMP0053-Dollar-NEW.cmake b/Tests/RunCMake/Syntax/CMP0053-Dollar-NEW.cmake
new file mode 100644
index 000000000..b81fd56eb
--- /dev/null
+++ b/Tests/RunCMake/Syntax/CMP0053-Dollar-NEW.cmake
@@ -0,0 +1,6 @@
+cmake_policy(SET CMP0053 NEW)
+
+set($ value)
+set(dollar $)
+message("-->${${dollar}}<--")
+message("-->${$}<--")
diff --git a/Tests/RunCMake/Syntax/CMP0053-Dollar-OLD-result.txt b/Tests/RunCMake/Syntax/CMP0053-Dollar-OLD-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/Syntax/CMP0053-Dollar-OLD-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Syntax/CMP0053-Dollar-OLD-stderr.txt b/Tests/RunCMake/Syntax/CMP0053-Dollar-OLD-stderr.txt
new file mode 100644
index 000000000..aecd4d333
--- /dev/null
+++ b/Tests/RunCMake/Syntax/CMP0053-Dollar-OLD-stderr.txt
@@ -0,0 +1,24 @@
+^CMake Deprecation Warning at CMP0053-Dollar-OLD.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0053 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+-->value<--
+CMake Error at CMP0053-Dollar-OLD.cmake:6 \(message\):
+ Syntax error in cmake code at
+
+ .*CMP0053-Dollar-OLD.cmake:6
+
+ when parsing string
+
+ -->\${\$}<--
+
+ syntax error, unexpected \$, expecting } \(7\)
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/Syntax/CMP0053-Dollar-OLD.cmake b/Tests/RunCMake/Syntax/CMP0053-Dollar-OLD.cmake
new file mode 100644
index 000000000..647f4648b
--- /dev/null
+++ b/Tests/RunCMake/Syntax/CMP0053-Dollar-OLD.cmake
@@ -0,0 +1,6 @@
+cmake_policy(SET CMP0053 OLD)
+
+set($ value)
+set(dollar $)
+message("-->${${dollar}}<--")
+message("-->${$}<--")
diff --git a/Tests/RunCMake/Syntax/NullAfterBackslash-result.txt b/Tests/RunCMake/Syntax/NullAfterBackslash-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/Syntax/NullAfterBackslash-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Syntax/NullAfterBackslash-stderr.txt b/Tests/RunCMake/Syntax/NullAfterBackslash-stderr.txt
new file mode 100644
index 000000000..e7ba44072
--- /dev/null
+++ b/Tests/RunCMake/Syntax/NullAfterBackslash-stderr.txt
@@ -0,0 +1,5 @@
+CMake Error at NullAfterBackslash.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/NullAfterBackslash.cmake b/Tests/RunCMake/Syntax/NullAfterBackslash.cmake
new file mode 100644
index 000000000..ed96904dc
--- /dev/null
+++ b/Tests/RunCMake/Syntax/NullAfterBackslash.cmake
Binary files differ
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/QueryCache-stderr.txt b/Tests/RunCMake/Syntax/QueryCache-stderr.txt
new file mode 100644
index 000000000..db6b2b7d6
--- /dev/null
+++ b/Tests/RunCMake/Syntax/QueryCache-stderr.txt
@@ -0,0 +1,2 @@
+-->cache value<--
+-->local value<--
diff --git a/Tests/RunCMake/Syntax/QueryCache.cmake b/Tests/RunCMake/Syntax/QueryCache.cmake
new file mode 100644
index 000000000..20c648e60
--- /dev/null
+++ b/Tests/RunCMake/Syntax/QueryCache.cmake
@@ -0,0 +1,6 @@
+
+set(query_var "cache value" CACHE STRING "")
+set(query_var "local value")
+
+message("-->$CACHE{query_var}<--")
+message("-->${query_var}<--")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName-result.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName-stderr.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName-stderr.txt
new file mode 100644
index 000000000..6da79b7d5
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName-stderr.txt
@@ -0,0 +1,52 @@
+^(CMake Error at BadInvalidName1/CMakeLists\.txt:[0-9]+ \(include_directories\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:Invali/dTarget,INCLUDE_DIRECTORIES>
+
+ Target name not supported.
++)+(CMake Error at BadInvalidName2/CMakeLists\.txt:[0-9]+ \(include_directories\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:Invali/dTarget,Invali/dProperty>
+
+ Target name and property name not supported.
++)+(CMake Error at BadInvalidName3/CMakeLists\.txt:[0-9]+ \(include_directories\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:Invali/dProperty>
+
+ Property name not supported.
++)+(CMake Error at BadInvalidName4/CMakeLists\.txt:[0-9]+ \(include_directories\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:BadInvalidName4,Invali/dProperty>
+
+ Property name not supported.
++)+(CMake Error at BadInvalidName5/CMakeLists\.txt:[0-9]+ \(include_directories\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:,>
+
+ \$<TARGET_PROPERTY:tgt,prop> expression requires a non-empty target name and
+ property name.
++)+(CMake Error at BadInvalidName6/CMakeLists\.txt:[0-9]+ \(include_directories\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:,ValidProperty>
+
+ \$<TARGET_PROPERTY:tgt,prop> expression requires a non-empty target name.
++)+(CMake Error at BadInvalidName7/CMakeLists\.txt:[0-9]+ \(include_directories\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:BadInvalidName7,>
+
+ \$<TARGET_PROPERTY:...> expression requires a non-empty property name.
++)+(CMake Error at BadInvalidName8/CMakeLists\.txt:[0-9]+ \(include_directories\):
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:>
+
+ \$<TARGET_PROPERTY:...> expression requires a non-empty property name.
+*)+
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName.cmake b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName.cmake
new file mode 100644
index 000000000..5f083e2a6
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName.cmake
@@ -0,0 +1,8 @@
+add_subdirectory(BadInvalidName1)
+add_subdirectory(BadInvalidName2)
+add_subdirectory(BadInvalidName3)
+add_subdirectory(BadInvalidName4)
+add_subdirectory(BadInvalidName5)
+add_subdirectory(BadInvalidName6)
+add_subdirectory(BadInvalidName7)
+add_subdirectory(BadInvalidName8)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName1/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName1/CMakeLists.txt
new file mode 100644
index 000000000..13e1de7d6
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName1/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadInvalidName1 ../main.cpp)
+include_directories("$<TARGET_PROPERTY:Invali/dTarget,INCLUDE_DIRECTORIES>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName2/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName2/CMakeLists.txt
new file mode 100644
index 000000000..4b784729e
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName2/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadInvalidName2 ../main.cpp)
+include_directories("$<TARGET_PROPERTY:Invali/dTarget,Invali/dProperty>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName3/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName3/CMakeLists.txt
new file mode 100644
index 000000000..516a049a8
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName3/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadInvalidName3 ../main.cpp)
+include_directories("$<TARGET_PROPERTY:Invali/dProperty>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName4/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName4/CMakeLists.txt
new file mode 100644
index 000000000..02f2a1a8a
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName4/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadInvalidName4 ../main.cpp)
+include_directories("$<TARGET_PROPERTY:BadInvalidName4,Invali/dProperty>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName5/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName5/CMakeLists.txt
new file mode 100644
index 000000000..a653583b5
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName5/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadInvalidName5 ../main.cpp)
+include_directories("$<TARGET_PROPERTY:,>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName6/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName6/CMakeLists.txt
new file mode 100644
index 000000000..614458ef2
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName6/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadInvalidName6 ../main.cpp)
+include_directories("$<TARGET_PROPERTY:,ValidProperty>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName7/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName7/CMakeLists.txt
new file mode 100644
index 000000000..8a9fe8018
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName7/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadInvalidName7 ../main.cpp)
+include_directories("$<TARGET_PROPERTY:BadInvalidName7,>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName8/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName8/CMakeLists.txt
new file mode 100644
index 000000000..b228159f0
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadInvalidName8/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadInvalidName8 ../main.cpp)
+include_directories("$<TARGET_PROPERTY:>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference-result.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference-stderr.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference-stderr.txt
new file mode 100644
index 000000000..fa2686193
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference-stderr.txt
@@ -0,0 +1,39 @@
+^(CMake Error:
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>
+
+ Self reference on target "BadSelfReference1".
++)+(CMake Error:
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>
+
+ Self reference on target "BadSelfReference2".
++)+(CMake Error:
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:BadSelfReference3,INCLUDE_DIRECTORIES>
+
+ Self reference on target "BadSelfReference3".
++)+(CMake Error:
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:BadSelfReference4,INCLUDE_DIRECTORIES>
+
+ Self reference on target "BadSelfReference4".
++)+(CMake Error:
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:COMPILE_DEFINITIONS>
+
+ Self reference on target "BadSelfReference5".
++)+(CMake Error:
+ Error evaluating generator expression:
+
+ \$<TARGET_PROPERTY:BadSelfReference6,COMPILE_DEFINITIONS>
+
+ Self reference on target "BadSelfReference6".
+*)+
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference.cmake b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference.cmake
new file mode 100644
index 000000000..5a99f7afa
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference.cmake
@@ -0,0 +1,6 @@
+add_subdirectory(BadSelfReference1)
+add_subdirectory(BadSelfReference2)
+add_subdirectory(BadSelfReference3)
+add_subdirectory(BadSelfReference4)
+add_subdirectory(BadSelfReference5)
+add_subdirectory(BadSelfReference6)
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference1/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference1/CMakeLists.txt
new file mode 100644
index 000000000..30c27f51b
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference1/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadSelfReference1 ../main.cpp)
+include_directories("$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference2/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference2/CMakeLists.txt
new file mode 100644
index 000000000..c2322f43b
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference2/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadSelfReference2 ../main.cpp)
+set_property(TARGET BadSelfReference2 PROPERTY INCLUDE_DIRECTORIES "$<TARGET_PROPERTY:INCLUDE_DIRECTORIES>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference3/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference3/CMakeLists.txt
new file mode 100644
index 000000000..3e6c30a74
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference3/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadSelfReference3 ../main.cpp)
+include_directories("$<TARGET_PROPERTY:BadSelfReference3,INCLUDE_DIRECTORIES>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference4/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference4/CMakeLists.txt
new file mode 100644
index 000000000..f79727a9c
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference4/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadSelfReference4 ../main.cpp)
+set_property(TARGET BadSelfReference4 PROPERTY INCLUDE_DIRECTORIES "$<TARGET_PROPERTY:BadSelfReference4,INCLUDE_DIRECTORIES>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference5/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference5/CMakeLists.txt
new file mode 100644
index 000000000..c0badbfed
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference5/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadSelfReference5 ../main.cpp)
+set_property(TARGET BadSelfReference5 PROPERTY COMPILE_DEFINITIONS "$<TARGET_PROPERTY:COMPILE_DEFINITIONS>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference6/CMakeLists.txt b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference6/CMakeLists.txt
new file mode 100644
index 000000000..fcb6b3c3e
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/BadSelfReference6/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_executable(BadSelfReference6 ../main.cpp)
+set_property(TARGET BadSelfReference6 PROPERTY COMPILE_DEFINITIONS "$<TARGET_PROPERTY:BadSelfReference6,COMPILE_DEFINITIONS>")
diff --git a/Tests/RunCMake/TargetPropertyGeneratorExpressions/main.cpp b/Tests/RunCMake/TargetPropertyGeneratorExpressions/main.cpp
new file mode 100644
index 000000000..f8b643afb
--- /dev/null
+++ b/Tests/RunCMake/TargetPropertyGeneratorExpressions/main.cpp
@@ -0,0 +1,4 @@
+int main()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/TargetSources/CMP0076-OLD-result.txt b/Tests/RunCMake/TargetSources/CMP0076-OLD-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/CMP0076-OLD-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/TargetSources/CMP0076-OLD-stderr.txt b/Tests/RunCMake/TargetSources/CMP0076-OLD-stderr.txt
new file mode 100644
index 000000000..d47dd4de3
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/CMP0076-OLD-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error in CMakeLists.txt:
+ Target "iface" contains relative path in its INTERFACE_SOURCES:
+
+ "empty_1.cpp"
diff --git a/Tests/RunCMake/TargetSources/CMP0076-OLD.cmake b/Tests/RunCMake/TargetSources/CMP0076-OLD.cmake
new file mode 100644
index 000000000..4d8c268ef
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/CMP0076-OLD.cmake
@@ -0,0 +1,10 @@
+cmake_policy(SET CMP0076 OLD)
+
+add_library(iface INTERFACE)
+target_sources(iface INTERFACE empty_1.cpp)
+
+get_property(iface_sources TARGET iface PROPERTY INTERFACE_SOURCES)
+message(STATUS "iface: ${iface_sources}")
+
+add_executable(main main.cpp)
+target_link_libraries(main iface)
diff --git a/Tests/RunCMake/TargetSources/CMP0076-WARN-result.txt b/Tests/RunCMake/TargetSources/CMP0076-WARN-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/CMP0076-WARN-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/TargetSources/CMP0076-WARN-stderr.txt b/Tests/RunCMake/TargetSources/CMP0076-WARN-stderr.txt
new file mode 100644
index 000000000..bd888eed5
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/CMP0076-WARN-stderr.txt
@@ -0,0 +1,21 @@
+CMake Warning \(dev\) at CMP0076-WARN/CMakeLists\.txt:[0-9]+ \(target_sources\):
+ Policy CMP0076 is not set: target_sources\(\) command converts relative paths
+ to absolute. Run "cmake --help-policy CMP0076" for policy details. Use
+ the cmake_policy command to set the policy and suppress this warning.
+
+ An interface source of target "publiclib" has a relative path.
+This warning is for project developers. Use -Wno-dev to suppress it.
+
+CMake Warning \(dev\) at CMP0076-WARN/CMakeLists\.txt:[0-9]+ \(target_sources\):
+ Policy CMP0076 is not set: target_sources\(\) command converts relative paths
+ to absolute. Run "cmake --help-policy CMP0076" for policy details. Use
+ the cmake_policy command to set the policy and suppress this warning.
+
+ A private source from a directory other than that of target "publiclib" has
+ a relative path.
+This warning is for project developers. Use -Wno-dev to suppress it.
+
+CMake Error in CMakeLists.txt:
+ Target "publiclib" contains relative path in its INTERFACE_SOURCES:
+
+ "CMP0076-WARN/subdir_empty_1.cpp"
diff --git a/Tests/RunCMake/TargetSources/CMP0076-WARN.cmake b/Tests/RunCMake/TargetSources/CMP0076-WARN.cmake
new file mode 100644
index 000000000..2e0733112
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/CMP0076-WARN.cmake
@@ -0,0 +1,8 @@
+cmake_minimum_required(VERSION 3.12)
+
+add_library(publiclib)
+
+add_subdirectory(CMP0076-WARN)
+
+add_executable(main main.cpp)
+target_link_libraries(main publiclib)
diff --git a/Tests/RunCMake/TargetSources/CMP0076-WARN/CMakeLists.txt b/Tests/RunCMake/TargetSources/CMP0076-WARN/CMakeLists.txt
new file mode 100644
index 000000000..f9c7d6d5e
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/CMP0076-WARN/CMakeLists.txt
@@ -0,0 +1,3 @@
+
+target_sources(publiclib INTERFACE CMP0076-WARN/subdir_empty_1.cpp
+ PRIVATE empty_1.cpp)
diff --git a/Tests/RunCMake/TargetSources/CMP0076-WARN/subdir_empty_1.cpp b/Tests/RunCMake/TargetSources/CMP0076-WARN/subdir_empty_1.cpp
new file mode 100644
index 000000000..11ec041d1
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/CMP0076-WARN/subdir_empty_1.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/TargetSources/RelativePathInInterface-stdout.txt b/Tests/RunCMake/TargetSources/RelativePathInInterface-stdout.txt
new file mode 100644
index 000000000..4581d8a88
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInInterface-stdout.txt
@@ -0,0 +1 @@
+-- iface: .*Tests/RunCMake/TargetSources/empty_1.cpp
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx-stdout.txt b/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx-stdout.txt
new file mode 100644
index 000000000..7f480829f
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx-stdout.txt
@@ -0,0 +1 @@
+-- genexlib: \$<1:.*Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx/subdir_empty_1.cpp>;\$<1:.*Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx/../empty_1.cpp>;\$<1:empty_2.cpp>
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx.cmake b/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx.cmake
new file mode 100644
index 000000000..1cdc2a785
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx.cmake
@@ -0,0 +1,10 @@
+cmake_policy(SET CMP0076 NEW)
+
+add_library(genexlib)
+add_subdirectory(RelativePathInSubdirGenEx)
+
+get_property(genexlib_sources TARGET genexlib PROPERTY SOURCES)
+message(STATUS "genexlib: ${genexlib_sources}")
+
+add_executable(genexmain main.cpp)
+target_link_libraries(genexmain genexlib)
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx/CMakeLists.txt b/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx/CMakeLists.txt
new file mode 100644
index 000000000..3bcf454da
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx/CMakeLists.txt
@@ -0,0 +1,4 @@
+
+target_sources(genexlib PUBLIC $<1:${CMAKE_CURRENT_LIST_DIR}/subdir_empty_1.cpp>
+ $<1:${CMAKE_CURRENT_LIST_DIR}/../empty_1.cpp>
+ PRIVATE $<1:empty_2.cpp>)
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx/subdir_empty_1.cpp b/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx/subdir_empty_1.cpp
new file mode 100644
index 000000000..11ec041d1
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirGenEx/subdir_empty_1.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude-stdout.txt b/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude-stdout.txt
new file mode 100644
index 000000000..aa4851ffa
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude-stdout.txt
@@ -0,0 +1 @@
+-- privatelib: .*Tests/RunCMake/TargetSources/RelativePathInSubdirInclude/subdir_empty_1.cpp;empty_1.cpp
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude.cmake b/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude.cmake
new file mode 100644
index 000000000..4acbecacc
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude.cmake
@@ -0,0 +1,8 @@
+cmake_policy(SET CMP0076 NEW)
+
+add_library(privatelib)
+
+include("RelativePathInSubdirInclude/CMakeLists.txt")
+
+get_property(privatelib_sources TARGET privatelib PROPERTY SOURCES)
+message(STATUS "privatelib: ${privatelib_sources}")
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude/CMakeLists.txt b/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude/CMakeLists.txt
new file mode 100644
index 000000000..3dcb13545
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude/CMakeLists.txt
@@ -0,0 +1,3 @@
+
+target_sources(privatelib PRIVATE "${CMAKE_CURRENT_LIST_DIR}/subdir_empty_1.cpp"
+ empty_1.cpp)
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude/subdir_empty_1.cpp b/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude/subdir_empty_1.cpp
new file mode 100644
index 000000000..11ec041d1
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirInclude/subdir_empty_1.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface-stdout.txt b/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface-stdout.txt
new file mode 100644
index 000000000..5990a0599
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface-stdout.txt
@@ -0,0 +1 @@
+-- iface: .*Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/subdir_empty_1.cpp;.*Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/subdir_empty_2.cpp;.*Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/../empty_1.cpp;.*Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/../empty_2.cpp
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface.cmake b/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface.cmake
new file mode 100644
index 000000000..3652b4f64
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface.cmake
@@ -0,0 +1,11 @@
+cmake_policy(SET CMP0076 NEW)
+
+add_library(iface INTERFACE)
+
+add_subdirectory(RelativePathInSubdirInterface)
+
+get_property(iface_sources TARGET iface PROPERTY INTERFACE_SOURCES)
+message(STATUS "iface: ${iface_sources}")
+
+add_executable(main main.cpp)
+target_link_libraries(main iface)
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/CMakeLists.txt b/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/CMakeLists.txt
new file mode 100644
index 000000000..02e69669e
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/CMakeLists.txt
@@ -0,0 +1,5 @@
+
+target_sources(iface INTERFACE subdir_empty_1.cpp
+ "${CMAKE_CURRENT_LIST_DIR}/subdir_empty_2.cpp"
+ ../empty_1.cpp
+ "${CMAKE_CURRENT_LIST_DIR}/../empty_2.cpp")
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/subdir_empty_1.cpp b/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/subdir_empty_1.cpp
new file mode 100644
index 000000000..11ec041d1
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/subdir_empty_1.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/subdir_empty_2.cpp b/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/subdir_empty_2.cpp
new file mode 100644
index 000000000..11ec041d1
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirInterface/subdir_empty_2.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate-stdout.txt b/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate-stdout.txt
new file mode 100644
index 000000000..fa5bcbfee
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate-stdout.txt
@@ -0,0 +1 @@
+-- privatelib: .*Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/subdir_empty_1.cpp;.*Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/subdir_empty_2.cpp;.*Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/../empty_1.cpp;.*Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/../empty_2.cpp
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate.cmake b/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate.cmake
new file mode 100644
index 000000000..d0d3dc441
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate.cmake
@@ -0,0 +1,8 @@
+cmake_policy(SET CMP0076 NEW)
+
+add_library(privatelib)
+
+add_subdirectory(RelativePathInSubdirPrivate)
+
+get_property(privatelib_sources TARGET privatelib PROPERTY SOURCES)
+message(STATUS "privatelib: ${privatelib_sources}")
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/CMakeLists.txt b/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/CMakeLists.txt
new file mode 100644
index 000000000..56ee853e1
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/CMakeLists.txt
@@ -0,0 +1,5 @@
+
+target_sources(privatelib PRIVATE subdir_empty_1.cpp
+ "${CMAKE_CURRENT_LIST_DIR}/subdir_empty_2.cpp"
+ ../empty_1.cpp
+ "${CMAKE_CURRENT_LIST_DIR}/../empty_2.cpp")
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/subdir_empty_1.cpp b/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/subdir_empty_1.cpp
new file mode 100644
index 000000000..11ec041d1
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/subdir_empty_1.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/subdir_empty_2.cpp b/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/subdir_empty_2.cpp
new file mode 100644
index 000000000..11ec041d1
--- /dev/null
+++ b/Tests/RunCMake/TargetSources/RelativePathInSubdirPrivate/subdir_empty_2.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/ToolchainFile/IncludeDirectories-toolchain.cmake b/Tests/RunCMake/ToolchainFile/IncludeDirectories-toolchain.cmake
new file mode 100644
index 000000000..e77e9fe10
--- /dev/null
+++ b/Tests/RunCMake/ToolchainFile/IncludeDirectories-toolchain.cmake
@@ -0,0 +1 @@
+include_directories(${CMAKE_CURRENT_LIST_DIR}/IncludeDirectories)
diff --git a/Tests/RunCMake/ToolchainFile/IncludeDirectories.c b/Tests/RunCMake/ToolchainFile/IncludeDirectories.c
new file mode 100644
index 000000000..81b2465a1
--- /dev/null
+++ b/Tests/RunCMake/ToolchainFile/IncludeDirectories.c
@@ -0,0 +1,5 @@
+#include <IncDir.h>
+
+void IncDir(void)
+{
+}
diff --git a/Tests/RunCMake/ToolchainFile/IncludeDirectories.cmake b/Tests/RunCMake/ToolchainFile/IncludeDirectories.cmake
new file mode 100644
index 000000000..616cff4c3
--- /dev/null
+++ b/Tests/RunCMake/ToolchainFile/IncludeDirectories.cmake
@@ -0,0 +1,2 @@
+enable_language(C)
+add_library(IncDir STATIC IncludeDirectories.c)
diff --git a/Tests/RunCMake/ToolchainFile/IncludeDirectories/IncDir.h b/Tests/RunCMake/ToolchainFile/IncludeDirectories/IncDir.h
new file mode 100644
index 000000000..bca9c2c6f
--- /dev/null
+++ b/Tests/RunCMake/ToolchainFile/IncludeDirectories/IncDir.h
@@ -0,0 +1 @@
+/* IncDir.h */
diff --git a/Tests/RunCMake/UseSWIG/CMP0078-NEW-stdout.txt b/Tests/RunCMake/UseSWIG/CMP0078-NEW-stdout.txt
new file mode 100644
index 000000000..d4fa6e4b8
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0078-NEW-stdout.txt
@@ -0,0 +1,2 @@
+-- PREFIX='_'
+-- TARGET NAME='example'
diff --git a/Tests/RunCMake/UseSWIG/CMP0078-NEW.cmake b/Tests/RunCMake/UseSWIG/CMP0078-NEW.cmake
new file mode 100644
index 000000000..ce77218c8
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0078-NEW.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0078 NEW)
+include(CMP0078-common.cmake)
diff --git a/Tests/RunCMake/UseSWIG/CMP0078-OLD-stdout.txt b/Tests/RunCMake/UseSWIG/CMP0078-OLD-stdout.txt
new file mode 100644
index 000000000..62f5371e1
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0078-OLD-stdout.txt
@@ -0,0 +1,2 @@
+-- PREFIX=''
+-- TARGET NAME='_example'
diff --git a/Tests/RunCMake/UseSWIG/CMP0078-OLD.cmake b/Tests/RunCMake/UseSWIG/CMP0078-OLD.cmake
new file mode 100644
index 000000000..2c4d142d5
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0078-OLD.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0078 OLD)
+include(CMP0078-common.cmake)
diff --git a/Tests/RunCMake/UseSWIG/CMP0078-WARN-stderr.txt b/Tests/RunCMake/UseSWIG/CMP0078-WARN-stderr.txt
new file mode 100644
index 000000000..d89d1744d
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0078-WARN-stderr.txt
@@ -0,0 +1,10 @@
+CMake Warning \(dev\) at .*/Modules/UseSWIG\.cmake:[0-9]+ \(message\):
+ Policy CMP0078 is not set: UseSWIG generates standard target names\. Run
+ "cmake --help-policy CMP0078" for policy details\. Use the cmake_policy
+ command to set the policy and suppress this warning\.
+
+Call Stack \(most recent call first\):
+ CMP0078-common\.cmake:8 \(swig_add_library\)
+ CMP0078-WARN\.cmake:1 \(include\)
+ CMakeLists\.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/UseSWIG/CMP0078-WARN-stdout.txt b/Tests/RunCMake/UseSWIG/CMP0078-WARN-stdout.txt
new file mode 100644
index 000000000..62f5371e1
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0078-WARN-stdout.txt
@@ -0,0 +1,2 @@
+-- PREFIX=''
+-- TARGET NAME='_example'
diff --git a/Tests/RunCMake/UseSWIG/CMP0078-WARN.cmake b/Tests/RunCMake/UseSWIG/CMP0078-WARN.cmake
new file mode 100644
index 000000000..86b21a585
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0078-WARN.cmake
@@ -0,0 +1 @@
+include(CMP0078-common.cmake)
diff --git a/Tests/RunCMake/UseSWIG/CMP0078-common.cmake b/Tests/RunCMake/UseSWIG/CMP0078-common.cmake
new file mode 100644
index 000000000..b13796b55
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0078-common.cmake
@@ -0,0 +1,12 @@
+
+cmake_policy(SET CMP0086 NEW)
+
+set(SWIG_EXECUTABLE "swig")
+set(SWIG_DIR "/swig")
+include(UseSWIG)
+
+swig_add_library(example LANGUAGE python TYPE MODULE SOURCES example.i)
+
+get_property(prefix TARGET ${SWIG_MODULE_example_REAL_NAME} PROPERTY PREFIX)
+message(STATUS "PREFIX='${prefix}'")
+message(STATUS "TARGET NAME='${SWIG_MODULE_example_REAL_NAME}'")
diff --git a/Tests/RunCMake/UseSWIG/CMP0086-NEW-nuild-check.cmake b/Tests/RunCMake/UseSWIG/CMP0086-NEW-nuild-check.cmake
new file mode 100644
index 000000000..ea8b2cdcb
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0086-NEW-nuild-check.cmake
@@ -0,0 +1,4 @@
+
+if (NOT EXISTS "${RunCMake_TEST_BINARY_DIR}/new_example.py")
+ set (RunCMake_TEST_FAILED "Not found expected file: '${RunCMake_TEST_BINARY_DIR}/new_example.py'.")
+endif()
diff --git a/Tests/RunCMake/UseSWIG/CMP0086-NEW.cmake b/Tests/RunCMake/UseSWIG/CMP0086-NEW.cmake
new file mode 100644
index 000000000..b54338d6a
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0086-NEW.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0086 NEW)
+include(CMP0086-common.cmake)
diff --git a/Tests/RunCMake/UseSWIG/CMP0086-OLD-build-check.cmake b/Tests/RunCMake/UseSWIG/CMP0086-OLD-build-check.cmake
new file mode 100644
index 000000000..96b5295a3
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0086-OLD-build-check.cmake
@@ -0,0 +1,4 @@
+
+if (NOT EXISTS "${RunCMake_TEST_BINARY_DIR}/example.py")
+ set (RunCMake_TEST_FAILED "Not found expected file: '${RunCMake_TEST_BINARY_DIR}/example.py'.")
+endif()
diff --git a/Tests/RunCMake/UseSWIG/CMP0086-OLD.cmake b/Tests/RunCMake/UseSWIG/CMP0086-OLD.cmake
new file mode 100644
index 000000000..6a63d4cd0
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0086-OLD.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0086 OLD)
+include(CMP0086-common.cmake)
diff --git a/Tests/RunCMake/UseSWIG/CMP0086-WARN-stderr.txt b/Tests/RunCMake/UseSWIG/CMP0086-WARN-stderr.txt
new file mode 100644
index 000000000..af4102144
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0086-WARN-stderr.txt
@@ -0,0 +1,11 @@
+CMake Warning \(dev\) at .*/Modules/UseSWIG.cmake:[0-9]+ \(message\):
+ Policy CMP0086 is not set: UseSWIG honors SWIG_MODULE_NAME via -module
+ flag. Run "cmake --help-policy CMP0086" for policy details\. Use the
+ cmake_policy command to set the policy and suppress this warning\.
+
+Call Stack \(most recent call first\):
+ .*/Modules/UseSWIG.cmake:[0-9]+ \(SWIG_ADD_SOURCE_TO_MODULE\)
+ CMP0086-common\.cmake:[0-9]+ \(swig_add_library\)
+ CMP0086-WARN\.cmake:1 \(include\)
+ CMakeLists\.txt:3 \(include\)
+This warning is for project developers\. Use -Wno-dev to suppress it\.$
diff --git a/Tests/RunCMake/UseSWIG/CMP0086-WARN.cmake b/Tests/RunCMake/UseSWIG/CMP0086-WARN.cmake
new file mode 100644
index 000000000..69c2d9db7
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0086-WARN.cmake
@@ -0,0 +1 @@
+include(CMP0086-common.cmake)
diff --git a/Tests/RunCMake/UseSWIG/CMP0086-common.cmake b/Tests/RunCMake/UseSWIG/CMP0086-common.cmake
new file mode 100644
index 000000000..ef9021813
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMP0086-common.cmake
@@ -0,0 +1,11 @@
+
+cmake_policy(SET CMP0078 NEW)
+
+find_package(Python REQUIRED COMPONENTS Development)
+find_package (SWIG REQUIRED)
+include(UseSWIG)
+
+set_property (SOURCE example.i PROPERTY SWIG_MODULE_NAME "new_example")
+
+swig_add_library(example LANGUAGE python TYPE MODULE SOURCES example.i)
+target_link_libraries(example PRIVATE Python::Module)
diff --git a/Tests/RunCMake/UseSWIG/CMakeLists.txt b/Tests/RunCMake/UseSWIG/CMakeLists.txt
new file mode 100644
index 000000000..d1b0d2c3e
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.10)
+project(${RunCMake_TEST} C)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/UseSWIG/RunCMakeTest.cmake b/Tests/RunCMake/UseSWIG/RunCMakeTest.cmake
new file mode 100644
index 000000000..6acf7199c
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/RunCMakeTest.cmake
@@ -0,0 +1,25 @@
+include(RunCMake)
+
+run_cmake(CMP0078-WARN)
+run_cmake(CMP0078-OLD)
+run_cmake(CMP0078-NEW)
+
+run_cmake(CMP0086-WARN)
+
+if (CMake_TEST_FindPython)
+
+ macro(run_cmake_target test subtest target)
+ set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${test}-build)
+ set(RunCMake_TEST_NO_CLEAN 1)
+ run_cmake_command(${test}-${subtest} ${CMAKE_COMMAND} --build . --target ${target} ${ARGN})
+
+ unset(RunCMake_TEST_BINARY_DIR)
+ unset(RunCMake_TEST_NO_CLEAN)
+ endmacro()
+
+ run_cmake(CMP0086-OLD)
+ run_cmake_target(CMP0086-OLD build example)
+ run_cmake(CMP0086-NEW)
+ run_cmake_target(CMP0086-NEW build example)
+
+endif()
diff --git a/Tests/RunCMake/UseSWIG/example.i b/Tests/RunCMake/UseSWIG/example.i
new file mode 100644
index 000000000..86625aa3a
--- /dev/null
+++ b/Tests/RunCMake/UseSWIG/example.i
@@ -0,0 +1,2 @@
+/* File : example.i */
+%module example
diff --git a/Tests/RunCMake/VS10Project/ExplicitCMakeLists-check.cmake b/Tests/RunCMake/VS10Project/ExplicitCMakeLists-check.cmake
new file mode 100644
index 000000000..b671e3580
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/ExplicitCMakeLists-check.cmake
@@ -0,0 +1,25 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+endif()
+
+set(foundCMakeLists 0)
+file(STRINGS "${vcProjectFile}" lines)
+foreach(line IN LISTS lines)
+ if(line MATCHES "<([A-Za-z0-9_]+) +Include=.*CMakeLists.txt")
+ set(rule "${CMAKE_MATCH_1}")
+ if(NOT rule STREQUAL "CustomBuild")
+ set(RunCMake_TEST_FAILED "CMakeLists.txt referenced as ${rule} instead of CustomBuild")
+ return()
+ endif()
+ if(foundCMakeLists)
+ set(RunCMake_TEST_FAILED "CMakeLists.txt referenced multiple times")
+ return()
+ endif()
+ set(foundCMakeLists 1)
+ endif()
+endforeach()
+if(NOT foundCMakeLists)
+ set(RunCMake_TEST_FAILED "CMakeLists.txt not referenced")
+endif()
diff --git a/Tests/RunCMake/VS10Project/ExplicitCMakeLists.cmake b/Tests/RunCMake/VS10Project/ExplicitCMakeLists.cmake
new file mode 100644
index 000000000..c9e44561b
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/ExplicitCMakeLists.cmake
@@ -0,0 +1,3 @@
+set(CMAKE_CONFIGURATION_TYPES Debug)
+enable_language(CXX)
+add_executable(foo foo.cpp ${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt)
diff --git a/Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake b/Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake
new file mode 100644
index 000000000..689b35f4c
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/RuntimeLibrary-check.cmake
@@ -0,0 +1,36 @@
+macro(RuntimeLibrary_check tgt rtl_expect)
+ set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/${tgt}.vcxproj")
+ if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not exist.")
+ return()
+ endif()
+
+ set(HAVE_Runtimelibrary 0)
+
+ file(STRINGS "${vcProjectFile}" lines)
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<RuntimeLibrary>([^<>]+)</RuntimeLibrary>")
+ set(rtl_actual "${CMAKE_MATCH_1}")
+ if(NOT "${rtl_actual}" STREQUAL "${rtl_expect}")
+ set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj has RuntimeLibrary '${rtl_actual}', not '${rtl_expect}'.")
+ return()
+ endif()
+ set(HAVE_Runtimelibrary 1)
+ break()
+ endif()
+ endforeach()
+
+ if(NOT HAVE_Runtimelibrary AND NOT "${rtl_expect}" STREQUAL "")
+ set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not have a RuntimeLibrary field.")
+ return()
+ endif()
+endmacro()
+
+RuntimeLibrary_check(default-C MultiThreadedDebugDLL)
+RuntimeLibrary_check(default-CXX MultiThreadedDebugDLL)
+RuntimeLibrary_check(empty-C "")
+RuntimeLibrary_check(empty-CXX "")
+RuntimeLibrary_check(MTd-C MultiThreadedDebug)
+RuntimeLibrary_check(MTd-CXX MultiThreadedDebug)
+RuntimeLibrary_check(MT-C MultiThreaded)
+RuntimeLibrary_check(MT-CXX MultiThreaded)
diff --git a/Tests/RunCMake/VS10Project/RuntimeLibrary.cmake b/Tests/RunCMake/VS10Project/RuntimeLibrary.cmake
new file mode 100644
index 000000000..d7787c8f8
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/RuntimeLibrary.cmake
@@ -0,0 +1,20 @@
+set(CMAKE_CONFIGURATION_TYPES Debug)
+cmake_policy(SET CMP0091 NEW)
+enable_language(C)
+enable_language(CXX)
+
+add_library(default-C empty.c)
+add_library(default-CXX empty.cxx)
+
+set(CMAKE_MSVC_RUNTIME_LIBRARY "")
+add_library(empty-C empty.c)
+add_library(empty-CXX empty.cxx)
+
+set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreadedDebug")
+add_library(MTd-C empty.c)
+add_library(MTd-CXX empty.cxx)
+
+add_library(MT-C empty.c)
+set_property(TARGET MT-C PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded")
+add_library(MT-CXX empty.cxx)
+set_property(TARGET MT-CXX PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded")
diff --git a/Tests/RunCMake/VS10Project/SourceGroupCMakeLists-check.cmake b/Tests/RunCMake/VS10Project/SourceGroupCMakeLists-check.cmake
new file mode 100644
index 000000000..c2a94bbbe
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/SourceGroupCMakeLists-check.cmake
@@ -0,0 +1,33 @@
+set(vcFiltersFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj.filters")
+if(NOT EXISTS "${vcFiltersFile}")
+ set(RunCMake_TEST_FAILED "Filters file ${vcFiltersFile} does not exist.")
+ return()
+endif()
+
+set(foundFileFilter 0)
+set(foundFilter 0)
+file(STRINGS "${vcFiltersFile}" lines)
+foreach(line IN LISTS lines)
+ if(line MATCHES "<Filter>CMakeListsSourceGroup</Filter>")
+ set(rule "${CMAKE_MATCH_1}")
+ if(foundFileFilter)
+ set(RunCMake_TEST_FAILED "Multiple files listed with filter for CMakeListsSourceGroup.")
+ return()
+ endif()
+ set(foundFileFilter 1)
+ endif()
+ if(line MATCHES "<Filter.*Include=\"CMakeListsSourceGroup\"")
+ set(rule "${CMAKE_MATCH_1}")
+ if(foundFilter)
+ set(RunCMake_TEST_FAILED "Multiple copies of CMakeListsSourceGroup filter listed.")
+ return()
+ endif()
+ set(foundFilter 1)
+ endif()
+endforeach()
+if(NOT foundFileFilter)
+ set(RunCMake_TEST_FAILED "File filter for CMakeListsSourceGroup not found.")
+endif()
+if(NOT foundFilter)
+ set(RunCMake_TEST_FAILED "Filter CMakeListsSourceGroup not found.")
+endif()
diff --git a/Tests/RunCMake/VS10Project/SourceGroupCMakeLists.cmake b/Tests/RunCMake/VS10Project/SourceGroupCMakeLists.cmake
new file mode 100644
index 000000000..4ad87ec8d
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/SourceGroupCMakeLists.cmake
@@ -0,0 +1,3 @@
+set(CMAKE_CONFIGURATION_TYPES Debug)
+add_custom_target(foo)
+source_group("CMakeListsSourceGroup" FILES CMakeLists.txt)
diff --git a/Tests/RunCMake/VS10Project/VsCSharpCompilerOpts-check.cmake b/Tests/RunCMake/VS10Project/VsCSharpCompilerOpts-check.cmake
new file mode 100644
index 000000000..3e418c34b
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpCompilerOpts-check.cmake
@@ -0,0 +1,64 @@
+#
+# Check C# VS project for required elements.
+#
+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(inDebug FALSE)
+set(inRelease FALSE)
+set(debugOK FALSE)
+set(releaseOK FALSE)
+
+
+file(STRINGS "${csProjectFile}" lines)
+foreach(line IN LISTS lines)
+ #message(STATUS ${line})
+ if(line MATCHES "^ *<PropertyGroup .*Debug\\|(Win32|x64).*")
+ set(inDebug TRUE)
+ elseif(line MATCHES "^ *<PropertyGroup .*Release\\|(Win32|x64).*")
+ set(inRelease TRUE)
+ elseif(line MATCHES "^ *</PropertyGroup> *$")
+ set(inRelease FALSE)
+ set(inDebug FALSE)
+ elseif(inDebug AND
+ (line MATCHES "^ *<NoWarn>.*505.*</NoWarn> *$") AND
+ (line MATCHES "^ *<NoWarn>.*707.*</NoWarn> *$") AND
+ (line MATCHES "^ *<NoWarn>.*808.*</NoWarn> *$") AND
+ (line MATCHES "^ *<NoWarn>.*909.*</NoWarn> *$")
+ )
+ set(debugOK TRUE)
+ elseif(inRelease AND
+ (NOT (line MATCHES "^ *<NoWarn>.*505.*</NoWarn> *$")) AND
+ (line MATCHES "^ *<NoWarn>.*707.*</NoWarn> *$") AND
+ (line MATCHES "^ *<NoWarn>.*808.*</NoWarn> *$") AND
+ (line MATCHES "^ *<NoWarn>.*909.*</NoWarn> *$")
+ )
+ set(releaseOK TRUE)
+ endif()
+endforeach()
+
+function(print_csprojfile)
+ file(STRINGS "${csProjectFile}" lines)
+ foreach(line IN LISTS lines)
+ message(STATUS ${line})
+ endforeach()
+endfunction()
+
+
+if(NOT debugOK)
+ message(STATUS "Failed to set Debug configuration warning config correctly.")
+ set(RunCMake_TEST_FAILED "Failed to set Debug configuration defines correctly.")
+ print_csprojfile()
+ return()
+endif()
+
+if(NOT releaseOK)
+ message(STATUS "Failed to set Release configuration warning config correctly.")
+ set(RunCMake_TEST_FAILED "Failed to set Release configuration defines correctly.")
+ print_csprojfile()
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsCSharpCompilerOpts.cmake b/Tests/RunCMake/VS10Project/VsCSharpCompilerOpts.cmake
new file mode 100644
index 000000000..85af38be9
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpCompilerOpts.cmake
@@ -0,0 +1,14 @@
+enable_language(CSharp)
+
+add_library(foo SHARED
+ foo.cs)
+
+set_target_properties(foo PROPERTIES
+ LINKER_LANGUAGE CSharp)
+
+
+# Issue 18878
+target_compile_options(foo PRIVATE "/platform:anycpu" "/nowarn:707,808" "/nowarn:909" )
+
+# Debug only warning disable
+set(CMAKE_CSharp_FLAGS_DEBUG "${CMAKE_CSharp_FLAGS_DEBUG} /nowarn:505")
diff --git a/Tests/RunCMake/VS10Project/VsCSharpCustomTags-stderr.txt b/Tests/RunCMake/VS10Project/VsCSharpCustomTags-stderr.txt
new file mode 100644
index 000000000..1ea3b510b
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpCustomTags-stderr.txt
@@ -0,0 +1,3 @@
+^CMake Deprecation Warning in CMakeLists.txt:
+ The C# target "foo" is of type STATIC_LIBRARY. This is discouraged \(and
+ may be disabled in future\). Make it a SHARED library instead.$
diff --git a/Tests/RunCMake/VS10Project/VsCSharpDefines-check.cmake b/Tests/RunCMake/VS10Project/VsCSharpDefines-check.cmake
new file mode 100644
index 000000000..152bf9c93
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpDefines-check.cmake
@@ -0,0 +1,64 @@
+#
+# Check C# VS project for required elements.
+#
+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(inDebug FALSE)
+set(inRelease FALSE)
+set(debugOK FALSE)
+set(releaseOK FALSE)
+
+
+file(STRINGS "${csProjectFile}" lines)
+foreach(line IN LISTS lines)
+ #message(STATUS ${line})
+ if(line MATCHES "^ *<PropertyGroup .*Debug\\|(Win32|x64).*")
+ set(inDebug TRUE)
+ elseif(line MATCHES "^ *<PropertyGroup .*Release\\|(Win32|x64).*")
+ set(inRelease TRUE)
+ elseif(line MATCHES "^ *</PropertyGroup> *$")
+ set(inRelease FALSE)
+ set(inDebug FALSE)
+ elseif(inDebug AND
+ (line MATCHES "^ *<DefineConstants>.*MY_FOO_DEFINE.*</DefineConstants> *$") AND
+ (line MATCHES "^ *<DefineConstants>.*DEFINE_ONLY_FOR_DEBUG.*</DefineConstants> *$") AND
+ (line MATCHES "^ *<DefineConstants>.*MY_BAR_ASSIGNMENT=bar.*</DefineConstants> *$") AND
+ (NOT (line MATCHES "^ *<DefineConstants>.*DEFINE_ONLY_FOR_RELEASE.*</DefineConstants> *$"))
+ )
+ set(debugOK TRUE)
+ elseif(inRelease AND
+ (line MATCHES "^ *<DefineConstants>.*MY_FOO_DEFINE.*</DefineConstants> *$") AND
+ (line MATCHES "^ *<DefineConstants>.*DEFINE_ONLY_FOR_RELEASE.*</DefineConstants> *$") AND
+ (line MATCHES "^ *<DefineConstants>.*MY_BAR_ASSIGNMENT=bar.*</DefineConstants> *$") AND
+ (NOT (line MATCHES "^ *<DefineConstants>.*DEFINE_ONLY_FOR_DEBUG.*</DefineConstants> *$"))
+ )
+ set(releaseOK TRUE)
+ endif()
+endforeach()
+
+function(print_csprojfile)
+ file(STRINGS "${csProjectFile}" lines)
+ foreach(line IN LISTS lines)
+ message(STATUS ${line})
+ endforeach()
+endfunction()
+
+
+if(NOT debugOK)
+ message(STATUS "Failed to set Debug configuration defines correctly.")
+ set(RunCMake_TEST_FAILED "Failed to set Debug configuration defines correctly.")
+ print_csprojfile()
+ return()
+endif()
+
+if(NOT releaseOK)
+ message(STATUS "Failed to set Release configuration defines correctly.")
+ set(RunCMake_TEST_FAILED "Failed to set Release configuration defines correctly.")
+ print_csprojfile()
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsCSharpDefines.cmake b/Tests/RunCMake/VS10Project/VsCSharpDefines.cmake
new file mode 100644
index 000000000..62c19c521
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpDefines.cmake
@@ -0,0 +1,18 @@
+enable_language(CSharp)
+
+add_library(foo SHARED
+ foo.cs)
+
+set_target_properties(foo PROPERTIES
+ LINKER_LANGUAGE CSharp)
+
+
+# Issue 18698
+target_compile_definitions(
+ foo
+ PUBLIC
+ MY_FOO_DEFINE
+ "MY_BAR_ASSIGNMENT=bar"
+ $<$<CONFIG:Debug>:DEFINE_ONLY_FOR_DEBUG>
+ $<$<CONFIG:Release>:DEFINE_ONLY_FOR_RELEASE>
+)
diff --git a/Tests/RunCMake/VS10Project/VsCSharpDeployFiles-check.cmake b/Tests/RunCMake/VS10Project/VsCSharpDeployFiles-check.cmake
new file mode 100644
index 000000000..c29f2ae42
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpDeployFiles-check.cmake
@@ -0,0 +1,67 @@
+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(inNode1 FALSE)
+set(foundNode1 FALSE)
+set(foundCopyDirective1 FALSE)
+
+set(inNode2 FALSE)
+set(foundNode2 FALSE)
+set(foundCopyDirective2 FALSE)
+
+set(foundNode3 FALSE)
+
+file(STRINGS "${csProjectFile}" lines)
+
+foreach(line IN LISTS lines)
+ if( inNode1 )
+ if(line MATCHES " *<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> *$")
+ set(foundCopyDirective1 TRUE)
+ elseif( line MATCHES " *</Content> *$")
+ set(inNode1 FALSE)
+ endif()
+ elseif( inNode2 )
+ if(line MATCHES " *<CopyToOutputDirectory>Always</CopyToOutputDirectory> *$")
+ set(foundCopyDirective2 TRUE)
+ elseif( line MATCHES " *</Content> *$")
+ set(inNode2 FALSE)
+ endif()
+ elseif(line MATCHES "^ *<Content *Include *= *\".*content1\\.txt\"> *")
+ set(foundNode1 TRUE)
+ set(inNode1 TRUE)
+ elseif(line MATCHES "^ *<Content *Include *= *\".*content2\\.txt\"> *")
+ set(foundNode2 TRUE)
+ set(inNode2 TRUE)
+ elseif(line MATCHES "^ *<None *Include *= *\".*content3\\.txt\"> *")
+ set(foundNode3 TRUE)
+ endif()
+endforeach()
+
+if(NOT foundNode1)
+ set(RunCMake_TEST_FAILED "Did not find <Content> item content1.txt.")
+ return()
+endif()
+
+if(NOT foundCopyDirective1)
+ set(RunCMake_TEST_FAILED "Did not find PreserveNewest for <Content> item content1.txt.")
+ return()
+endif()
+
+if(NOT foundNode2)
+ set(RunCMake_TEST_FAILED "Did not find <Content> item content2.txt.")
+ return()
+endif()
+
+if(NOT foundCopyDirective2)
+ set(RunCMake_TEST_FAILED "Did not find Always for <Content> item content2.txt.")
+ return()
+endif()
+
+if(NOT foundNode3)
+ set(RunCMake_TEST_FAILED "Did not find <None> item content3.txt.")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsCSharpDeployFiles.cmake b/Tests/RunCMake/VS10Project/VsCSharpDeployFiles.cmake
new file mode 100644
index 000000000..cb77fa7dd
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpDeployFiles.cmake
@@ -0,0 +1,27 @@
+enable_language(CSharp)
+
+set(fileNames
+ "${CMAKE_CURRENT_BINARY_DIR}/content1.txt"
+ "${CMAKE_CURRENT_BINARY_DIR}/content2.txt"
+ "${CMAKE_CURRENT_BINARY_DIR}/content3.txt")
+
+foreach(f ${fileNames})
+ message(STATUS "touch ${f}")
+ file(TOUCH ${f})
+endforeach()
+
+set_source_files_properties( "${CMAKE_CURRENT_BINARY_DIR}/content1.txt"
+ PROPERTIES
+ VS_COPY_TO_OUT_DIR PreserveNewest
+)
+
+set_source_files_properties( "${CMAKE_CURRENT_BINARY_DIR}/content2.txt"
+ PROPERTIES
+ VS_COPY_TO_OUT_DIR Always
+)
+
+
+add_library(foo SHARED
+ foo.cs
+ ${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-stderr.txt b/Tests/RunCMake/VS10Project/VsCSharpReferenceProps-stderr.txt
new file mode 100644
index 000000000..4402b8f57
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpReferenceProps-stderr.txt
@@ -0,0 +1,8 @@
+^CMake Deprecation Warning in CMakeLists.txt:
+ The C# target "foo2" is of type STATIC_LIBRARY. This is discouraged \(and
+ may be disabled in future\). Make it a SHARED library instead.
+
+
+CMake Deprecation Warning in CMakeLists.txt:
+ The C# target "foo" is of type STATIC_LIBRARY. This is discouraged \(and
+ may be disabled in future\). Make it a SHARED library instead.$
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/VS10Project/VsCSharpWithoutSources-check.cmake b/Tests/RunCMake/VS10Project/VsCSharpWithoutSources-check.cmake
new file mode 100644
index 000000000..90ae7c3c0
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpWithoutSources-check.cmake
@@ -0,0 +1,5 @@
+set(csProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.csproj")
+if(NOT EXISTS "${csProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${csProjectFile} does not exist.")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsCSharpWithoutSources.cmake b/Tests/RunCMake/VS10Project/VsCSharpWithoutSources.cmake
new file mode 100644
index 000000000..5fdeaa0a2
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpWithoutSources.cmake
@@ -0,0 +1,7 @@
+enable_language(CSharp)
+
+add_library(foo SHARED
+ "${CMAKE_CURRENT_LIST_FILE}")
+
+set_target_properties(foo PROPERTIES
+ LINKER_LANGUAGE CSharp)
diff --git a/Tests/RunCMake/VS10Project/VsDebuggerCommand-check.cmake b/Tests/RunCMake/VS10Project/VsDebuggerCommand-check.cmake
new file mode 100644
index 000000000..00288d483
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsDebuggerCommand-check.cmake
@@ -0,0 +1,24 @@
+foreach(target foo bar)
+ set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/${target}.vcxproj")
+ if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+ endif()
+
+ set(debuggerCommandSet FALSE)
+
+ file(STRINGS "${vcProjectFile}" lines)
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<LocalDebuggerCommand[^>]*>([^<>]+)</LocalDebuggerCommand>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "my-debugger-command foo")
+ message(STATUS "${target}.vcxproj has debugger command set")
+ set(debuggerCommandSet TRUE)
+ endif()
+ endif()
+ endforeach()
+
+ if(NOT debuggerCommandSet)
+ set(RunCMake_TEST_FAILED "LocalDebuggerCommand not found or not set correctly.")
+ return()
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/VS10Project/VsDebuggerCommand.cmake b/Tests/RunCMake/VS10Project/VsDebuggerCommand.cmake
new file mode 100644
index 000000000..54f91549f
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsDebuggerCommand.cmake
@@ -0,0 +1,6 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+add_custom_target(bar)
+
+set_target_properties(foo bar PROPERTIES
+ VS_DEBUGGER_COMMAND "my-debugger-command $<TARGET_PROPERTY:foo,NAME>")
diff --git a/Tests/RunCMake/VS10Project/VsDebuggerCommandArguments-check.cmake b/Tests/RunCMake/VS10Project/VsDebuggerCommandArguments-check.cmake
new file mode 100644
index 000000000..87555d1f5
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsDebuggerCommandArguments-check.cmake
@@ -0,0 +1,24 @@
+foreach(target foo bar)
+ set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/${target}.vcxproj")
+ if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+ endif()
+
+ set(debuggerCommandArgumentsSet FALSE)
+
+ file(STRINGS "${vcProjectFile}" lines)
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<LocalDebuggerCommandArguments[^>]*>([^<>]+)</LocalDebuggerCommandArguments>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "my-debugger-command-arguments foo")
+ message(STATUS "${target}.vcxproj has debugger command arguments set")
+ set(debuggerCommandArgumentsSet TRUE)
+ endif()
+ endif()
+ endforeach()
+
+ if(NOT debuggerCommandArgumentsSet)
+ set(RunCMake_TEST_FAILED "LocalDebuggerCommandArguments not found or not set correctly.")
+ return()
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/VS10Project/VsDebuggerCommandArguments.cmake b/Tests/RunCMake/VS10Project/VsDebuggerCommandArguments.cmake
new file mode 100644
index 000000000..1f7d0be49
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsDebuggerCommandArguments.cmake
@@ -0,0 +1,6 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+add_custom_target(bar)
+
+set_target_properties(foo bar PROPERTIES
+ VS_DEBUGGER_COMMAND_ARGUMENTS "my-debugger-command-arguments $<TARGET_PROPERTY:foo,NAME>")
diff --git a/Tests/RunCMake/VS10Project/VsDebuggerEnvironment-check.cmake b/Tests/RunCMake/VS10Project/VsDebuggerEnvironment-check.cmake
new file mode 100644
index 000000000..fee121a5e
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsDebuggerEnvironment-check.cmake
@@ -0,0 +1,24 @@
+foreach(target foo bar)
+ set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/${target}.vcxproj")
+ if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+ endif()
+
+ set(debuggerEnvironmentSet FALSE)
+
+ file(STRINGS "${vcProjectFile}" lines)
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<LocalDebuggerEnvironment[^>]*>([^<>]+)</LocalDebuggerEnvironment>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "my-debugger-environment foo")
+ message(STATUS "${target}.vcxproj has debugger environment set")
+ set(debuggerEnvironmentSet TRUE)
+ endif()
+ endif()
+ endforeach()
+
+ if(NOT debuggerEnvironmentSet)
+ set(RunCMake_TEST_FAILED "LocalDebuggerEnvironment not found or not set correctly.")
+ return()
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/VS10Project/VsDebuggerEnvironment.cmake b/Tests/RunCMake/VS10Project/VsDebuggerEnvironment.cmake
new file mode 100644
index 000000000..c594f3532
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsDebuggerEnvironment.cmake
@@ -0,0 +1,6 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+add_custom_target(bar)
+
+set_target_properties(foo bar PROPERTIES
+ VS_DEBUGGER_ENVIRONMENT "my-debugger-environment $<TARGET_PROPERTY:foo,NAME>")
diff --git a/Tests/RunCMake/VS10Project/VsGlobals-check.cmake b/Tests/RunCMake/VS10Project/VsGlobals-check.cmake
new file mode 100644
index 000000000..0e7fd45c1
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsGlobals-check.cmake
@@ -0,0 +1,44 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+endif()
+
+set(InsideGlobals FALSE)
+set(DefaultLanguageSet FALSE)
+set(MinimumVisualStudioVersionSet FALSE)
+
+file(STRINGS "${vcProjectFile}" lines)
+foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<PropertyGroup Label=\"Globals\"> *$")
+ set(InsideGlobals TRUE)
+ elseif(line MATCHES "^ *<DefaultLanguage>([a-zA-Z\\-]+)</DefaultLanguage> *$")
+ if("${CMAKE_MATCH_1}" STREQUAL "en-US")
+ if(InsideGlobals)
+ message(STATUS "foo.vcxproj has correct DefaultLanguage global property")
+ set(DefaultLanguageSet TRUE)
+ else()
+ message(STATUS "DefaultLanguage is set but not within \"Globals\" property group")
+ endif()
+ endif()
+ elseif(line MATCHES "^ *<MinimumVisualStudioVersion>([0-9\\.]+)</MinimumVisualStudioVersion> *$")
+ if("${CMAKE_MATCH_1}" STREQUAL "14.0")
+ if(InsideGlobals)
+ message(STATUS "foo.vcxproj has correct MinimumVisualStudioVersion global property")
+ set(MinimumVisualStudioVersionSet TRUE)
+ else()
+ message(STATUS "MinimumVisualStudioVersion is set but not within \"Globals\" property group")
+ endif()
+ endif()
+ endif()
+endforeach()
+
+if(NOT DefaultLanguageSet)
+ set(RunCMake_TEST_FAILED "DefaultLanguageSet not found or not set correctly.")
+ return()
+endif()
+
+if(NOT MinimumVisualStudioVersionSet)
+ set(RunCMake_TEST_FAILED "MinimumVisualStudioVersionSet not found or not set correctly.")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsGlobals.cmake b/Tests/RunCMake/VS10Project/VsGlobals.cmake
new file mode 100644
index 000000000..a3ed5afa9
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsGlobals.cmake
@@ -0,0 +1,8 @@
+enable_language(CXX)
+
+set(CMAKE_VS_GLOBALS
+ "DefaultLanguage=en-US"
+ "MinimumVisualStudioVersion=14.0"
+)
+
+add_library(foo foo.cpp)
diff --git a/Tests/RunCMake/VS10Project/VsJustMyCode-check.cmake b/Tests/RunCMake/VS10Project/VsJustMyCode-check.cmake
new file mode 100644
index 000000000..7119976f0
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsJustMyCode-check.cmake
@@ -0,0 +1,38 @@
+macro(VsJustMyCode_check tgt jmc_expect)
+ set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/${tgt}.vcxproj")
+ if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not exist.")
+ return()
+ endif()
+
+ set(HAVE_JMC 0)
+
+ file(STRINGS "${vcProjectFile}" lines)
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<SupportJustMyCode>([^<>]+)</SupportJustMyCode>")
+ set(jmc_actual "${CMAKE_MATCH_1}")
+ if(NOT "${jmc_actual}" STREQUAL "${jmc_expect}")
+ set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj has <SupportJustMyCode> '${jmc_actual}', not '${jmc_expect}'.")
+ return()
+ endif()
+ set(HAVE_JMC 1)
+ break()
+ endif()
+ endforeach()
+
+ if(NOT HAVE_JMC AND NOT "${jmc_expect}" STREQUAL "")
+ set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not have a <SupportJustMyCode> property group.")
+ return()
+ endif()
+endmacro()
+
+VsJustMyCode_check(JMC-default-C "")
+VsJustMyCode_check(JMC-default-CXX "")
+VsJustMyCode_check(JMC-ON-C true)
+VsJustMyCode_check(JMC-ON-CXX true)
+VsJustMyCode_check(JMC-OFF-C "")
+VsJustMyCode_check(JMC-OFF-CXX "")
+VsJustMyCode_check(JMC-TGT-ON-C true)
+VsJustMyCode_check(JMC-TGT-ON-CXX true)
+VsJustMyCode_check(JMC-TGT-OFF-C "")
+VsJustMyCode_check(JMC-TGT-OFF-CXX "")
diff --git a/Tests/RunCMake/VS10Project/VsJustMyCode.cmake b/Tests/RunCMake/VS10Project/VsJustMyCode.cmake
new file mode 100644
index 000000000..b39f30f6c
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsJustMyCode.cmake
@@ -0,0 +1,24 @@
+set(CMAKE_CONFIGURATION_TYPES Debug)
+enable_language(C)
+enable_language(CXX)
+
+add_library(JMC-default-C empty.c)
+add_library(JMC-default-CXX empty.cxx)
+
+set(CMAKE_VS_JUST_MY_CODE_DEBUGGING OFF)
+add_library(JMC-OFF-C empty.c)
+add_library(JMC-OFF-CXX empty.cxx)
+
+set(CMAKE_VS_JUST_MY_CODE_DEBUGGING ON)
+add_library(JMC-ON-C empty.c)
+add_library(JMC-ON-CXX empty.cxx)
+
+set(CMAKE_VS_JUST_MY_CODE_DEBUGGING OFF)
+add_library(JMC-TGT-ON-C empty.c)
+set_property(TARGET JMC-TGT-ON-C PROPERTY VS_JUST_MY_CODE_DEBUGGING ON)
+add_library(JMC-TGT-ON-CXX empty.cxx)
+set_property(TARGET JMC-TGT-ON-CXX PROPERTY VS_JUST_MY_CODE_DEBUGGING ON)
+add_library(JMC-TGT-OFF-C empty.c)
+set_property(TARGET JMC-TGT-OFF-C PROPERTY VS_JUST_MY_CODE_DEBUGGING OFF)
+add_library(JMC-TGT-OFF-CXX empty.cxx)
+set_property(TARGET JMC-TGT-OFF-CXX PROPERTY VS_JUST_MY_CODE_DEBUGGING OFF)
diff --git a/Tests/RunCMake/VS10Project/VsPackageReferences-check.cmake b/Tests/RunCMake/VS10Project/VsPackageReferences-check.cmake
new file mode 100644
index 000000000..4ff5327a9
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsPackageReferences-check.cmake
@@ -0,0 +1,39 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file foo.vcxproj does not exist.")
+ return()
+endif()
+
+
+set(test1Library "boost")
+set(test1Version "1.7.0")
+
+
+set(test2Library "SFML")
+set(test2Version "2.2.0")
+
+set(Library1Found FALSE)
+set(Library2Found FALSE)
+
+file(STRINGS "${vcProjectFile}" lines)
+
+foreach(i 1 2)
+ set(testLibrary "${test${i}Library}")
+ set(testVersion "${test${i}Version}")
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<PackageReference Include=\"${testLibrary}\".*>$")
+ if(line MATCHES "^ *<PackageReference .* Version=\"${testVersion}\".*>$")
+ set(Library${i}Found TRUE)
+ message(STATUS "foo.vcxproj is using package reference ${testLibrary} with version ${testVersion}")
+ elseif()
+ message(STATUS "foo.vcxproj failed to define reference ${testLibrary} with version ${testVersion}")
+ set(Library${i}Found FALSE)
+ endif()
+ endif()
+ endforeach()
+endforeach()
+
+if(NOT Library1Found OR NOT Library2Found)
+ set(RunCMake_TEST_FAILED "Failed to find package references")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsPackageReferences.cmake b/Tests/RunCMake/VS10Project/VsPackageReferences.cmake
new file mode 100644
index 000000000..224ab18d7
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsPackageReferences.cmake
@@ -0,0 +1,4 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+
+set_property(TARGET foo PROPERTY VS_PACKAGE_REFERENCES "boost_1.7.0;SFML_2.2.0")
diff --git a/Tests/RunCMake/VS10Project/VsProjectImport-check.cmake b/Tests/RunCMake/VS10Project/VsProjectImport-check.cmake
new file mode 100644
index 000000000..e438bf46d
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsProjectImport-check.cmake
@@ -0,0 +1,28 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+endif()
+
+set(test1Import "path\\\\to\\\\nuget_packages\\\\Foo.1.0.0\\\\build\\\\Foo.props")
+set(test2Import "path\\\\to\\\\nuget_packages\\\\Bar.1.0.0\\\\build\\\\Bar.props")
+
+set(import1Found FALSE)
+set(import2Found FALSE)
+
+file(STRINGS "${vcProjectFile}" lines)
+
+foreach(i 1 2)
+ set(testImport "${test${i}Import}")
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<Import Project=\".*${test1Import}\" />$")
+ message(STATUS "foo.vcxproj is using project import ${testImport}")
+ set(import${i}Found TRUE)
+ endif()
+ endforeach()
+endforeach()
+
+if(NOT import1Found OR NOT import2Found)
+ set(RunCMake_TEST_FAILED "Imported project not found.")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsProjectImport.cmake b/Tests/RunCMake/VS10Project/VsProjectImport.cmake
new file mode 100644
index 000000000..70bddedf8
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsProjectImport.cmake
@@ -0,0 +1,11 @@
+enable_language(CXX)
+add_library(foo foo.cpp)
+
+set(test1Import "path/to/nuget_packages/Foo.1.0.0/build/Foo.props")
+set(test2Import "path/to/nuget_packages/Bar.1.0.0/build/Bar.props")
+
+set_property(TARGET foo PROPERTY
+ VS_PROJECT_IMPORT
+ ${test1Import}
+ ${test2Import}
+ )
diff --git a/Tests/RunCMake/VS10Project/VsSdkDirectories-check.cmake b/Tests/RunCMake/VS10Project/VsSdkDirectories-check.cmake
new file mode 100644
index 000000000..c21afb642
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsSdkDirectories-check.cmake
@@ -0,0 +1,88 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+endif()
+
+set(ExecutablePathSet FALSE)
+set(IncludePathSet FALSE)
+set(ReferencePathSet FALSE)
+set(LibraryPathSet FALSE)
+set(LibraryWPathSet FALSE)
+set(SourcePathSet FALSE)
+set(ExcludePathSet FALSE)
+
+file(STRINGS "${vcProjectFile}" lines)
+foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<ExecutablePath[^>]*>([^<>]+)</ExecutablePath>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "$(VC_ExecutablePath_x86);C:\\Program Files\\Custom-SDK\\;")
+ message(STATUS "foo.vcxproj has executable path set")
+ set(ExecutablePathSet TRUE)
+ endif()
+ elseif(line MATCHES "^ *<IncludePath[^>]*>([^<>]+)</IncludePath>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "$(VC_IncludePath);C:\\Program Files\\Custom-SDK\\;")
+ message(STATUS "foo.vcxproj has include path set")
+ set(IncludePathSet TRUE)
+ endif()
+ elseif(line MATCHES "^ *<ReferencePath[^>]*>([^<>]+)</ReferencePath>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "$(VC_ReferencesPath_x86);C:\\Program Files\\Custom-SDK\\;")
+ message(STATUS "foo.vcxproj has reference path set")
+ set(ReferencePathSet TRUE)
+ endif()
+ elseif(line MATCHES "^ *<LibraryPath[^>]*>([^<>]+)</LibraryPath>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "$(VC_LibraryPath_x86);C:\\Program Files\\Custom-SDK\\;")
+ message(STATUS "foo.vcxproj has library path set")
+ set(LibraryPathSet TRUE)
+ endif()
+ elseif(line MATCHES "^ *<LibraryWPath[^>]*>([^<>]+)</LibraryWPath>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "$(WindowsSDK_MetadataPath);C:\\Program Files\\Custom-SDK\\;")
+ message(STATUS "foo.vcxproj has library WinRT path set")
+ set(LibraryWPathSet TRUE)
+ endif()
+ elseif(line MATCHES "^ *<SourcePath[^>]*>([^<>]+)</SourcePath>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "$(VC_SourcePath);C:\\Program Files\\Custom-SDK\\;")
+ message(STATUS "foo.vcxproj has source path set")
+ set(SourcePathSet TRUE)
+ endif()
+ elseif(line MATCHES "^ *<ExcludePath[^>]*>([^<>]+)</ExcludePath>$")
+ if("${CMAKE_MATCH_1}" STREQUAL "$(VC_IncludePath);C:\\Program Files\\Custom-SDK\\;")
+ message(STATUS "foo.vcxproj has exclude path set")
+ set(ExcludePathSet TRUE)
+ endif()
+ endif()
+endforeach()
+
+if(NOT ExecutablePathSet)
+ set(RunCMake_TEST_FAILED "ExecutablePath not found or not set correctly.")
+ return()
+endif()
+
+if(NOT IncludePathSet)
+ set(RunCMake_TEST_FAILED "IncludePath not found or not set correctly.")
+ return()
+endif()
+
+if(NOT ReferencePathSet)
+ set(RunCMake_TEST_FAILED "ReferencePath not found or not set correctly.")
+ return()
+endif()
+
+if(NOT LibraryPathSet)
+ set(RunCMake_TEST_FAILED "LibraryPath not found or not set correctly.")
+ return()
+endif()
+
+if(NOT LibraryWPathSet)
+ set(RunCMake_TEST_FAILED "LibraryWPath not found or not set correctly.")
+ return()
+endif()
+
+if(NOT SourcePathSet)
+ set(RunCMake_TEST_FAILED "SourcePath not found or not set correctly.")
+ return()
+endif()
+
+if(NOT ExcludePathSet)
+ set(RunCMake_TEST_FAILED "ExcludePath not found or not set correctly.")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsSdkDirectories.cmake b/Tests/RunCMake/VS10Project/VsSdkDirectories.cmake
new file mode 100644
index 000000000..c8f2a5a27
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsSdkDirectories.cmake
@@ -0,0 +1,11 @@
+enable_language(CXX)
+
+set(CMAKE_VS_SDK_EXECUTABLE_DIRECTORIES "$(VC_ExecutablePath_x86);C:\\Program Files\\Custom-SDK\\;")
+set(CMAKE_VS_SDK_INCLUDE_DIRECTORIES "$(VC_IncludePath);C:\\Program Files\\Custom-SDK\\;")
+set(CMAKE_VS_SDK_REFERENCE_DIRECTORIES "$(VC_ReferencesPath_x86);C:\\Program Files\\Custom-SDK\\;")
+set(CMAKE_VS_SDK_LIBRARY_DIRECTORIES "$(VC_LibraryPath_x86);C:\\Program Files\\Custom-SDK\\;")
+set(CMAKE_VS_SDK_LIBRARY_WINRT_DIRECTORIES "$(WindowsSDK_MetadataPath);C:\\Program Files\\Custom-SDK\\;")
+set(CMAKE_VS_SDK_SOURCE_DIRECTORIES "$(VC_SourcePath);C:\\Program Files\\Custom-SDK\\;")
+set(CMAKE_VS_SDK_EXCLUDE_DIRECTORIES "$(VC_IncludePath);C:\\Program Files\\Custom-SDK\\;")
+
+add_library(foo foo.cpp)
diff --git a/Tests/RunCMake/VS10Project/VsSpectreMitigation-check.cmake b/Tests/RunCMake/VS10Project/VsSpectreMitigation-check.cmake
new file mode 100644
index 000000000..611776316
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsSpectreMitigation-check.cmake
@@ -0,0 +1,30 @@
+macro(VsSpectreMitigation_check tgt spectre_expect)
+ set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/${tgt}.vcxproj")
+ if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not exist.")
+ return()
+ endif()
+
+ set(HAVE_SpectreMitigation 0)
+
+ file(STRINGS "${vcProjectFile}" lines)
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<SpectreMitigation>([^<>]+)</SpectreMitigation>")
+ set(spectre_actual "${CMAKE_MATCH_1}")
+ if(NOT "${spectre_actual}" STREQUAL "${spectre_expect}")
+ set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj has <SpectreMitigation> '${spectre_actual}', not '${spectre_expect}'.")
+ return()
+ endif()
+ set(HAVE_SpectreMitigation 1)
+ break()
+ endif()
+ endforeach()
+
+ if(NOT HAVE_SpectreMitigation AND NOT "${spectre_expect}" STREQUAL "")
+ set(RunCMake_TEST_FAILED "Project file ${tgt}.vcxproj does not have a <SpectreMitigation> field.")
+ return()
+ endif()
+endmacro()
+
+VsSpectreMitigation_check(SpectreMitigationOn-C "Spectre")
+VsSpectreMitigation_check(SpectreMitigationOff-C "false")
diff --git a/Tests/RunCMake/VS10Project/VsSpectreMitigation.cmake b/Tests/RunCMake/VS10Project/VsSpectreMitigation.cmake
new file mode 100644
index 000000000..b3779d7cc
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsSpectreMitigation.cmake
@@ -0,0 +1,8 @@
+set(CMAKE_CONFIGURATION_TYPES Debug)
+enable_language(C)
+
+add_library(SpectreMitigationOn-C empty.c)
+target_compile_options(SpectreMitigationOn-C PRIVATE -Qspectre)
+
+add_library(SpectreMitigationOff-C empty.c)
+target_compile_options(SpectreMitigationOff-C PRIVATE -Qspectre-)
diff --git a/Tests/RunCMake/VS10Project/empty.c b/Tests/RunCMake/VS10Project/empty.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/empty.c
diff --git a/Tests/RunCMake/VS10Project/empty.cxx b/Tests/RunCMake/VS10Project/empty.cxx
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/empty.cxx
diff --git a/Tests/RunCMake/VS10ProjectWinCE/CMakeLists.txt b/Tests/RunCMake/VS10ProjectWinCE/CMakeLists.txt
new file mode 100644
index 000000000..91baae7eb
--- /dev/null
+++ b/Tests/RunCMake/VS10ProjectWinCE/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.5.0)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/VS10ProjectWinCE/RunCMakeTest.cmake b/Tests/RunCMake/VS10ProjectWinCE/RunCMakeTest.cmake
new file mode 100644
index 000000000..2c9067f75
--- /dev/null
+++ b/Tests/RunCMake/VS10ProjectWinCE/RunCMakeTest.cmake
@@ -0,0 +1,9 @@
+include(RunCMake)
+
+set(RunCMake_GENERATOR "Visual Studio 12 2013")
+set(RunCMake_GENERATOR_TOOLSET CE800)
+set(RunCMake_GENERATOR_INSTANCE "")
+set(RunCMake_TEST_OPTIONS -DCMAKE_SYSTEM_NAME=WindowsCE )
+
+run_cmake(VsCEDebuggerDeploy)
+run_cmake(VSCSharpCFProject)
diff --git a/Tests/RunCMake/VS10ProjectWinCE/VsCEDebuggerDeploy-check.cmake b/Tests/RunCMake/VS10ProjectWinCE/VsCEDebuggerDeploy-check.cmake
new file mode 100644
index 000000000..dab1c33a3
--- /dev/null
+++ b/Tests/RunCMake/VS10ProjectWinCE/VsCEDebuggerDeploy-check.cmake
@@ -0,0 +1,101 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+endif()
+
+
+if( NOT ${CMAKE_SYSTEM_NAME} STREQUAL "WindowsCE" )
+ set(RunCMake_TEST_FAILED "Test only valid for WindowsCE")
+ return()
+endif()
+
+
+set(FoundCEAdditionalFiles FALSE)
+set(FoundRemoteDirectory FALSE)
+set(FoundToolsVersion4 FALSE)
+
+file(STRINGS "${vcProjectFile}" lines)
+foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<CEAdditionalFiles> *foo\\.dll\\|\\\\foo\\\\src\\\\dir\\\\on\\\\host\\|\\$\\(RemoteDirectory\\)\\|0;bar\\.dll\\|\\\\bar\\\\src\\\\dir\\|\\$\\(RemoteDirectory\\)bardir\\|0.*</CEAdditionalFiles> *$")
+ set(FoundCEAdditionalFiles TRUE)
+ elseif(line MATCHES " *<RemoteDirectory>[A-Za-z0-9\\]+</RemoteDirectory> *$")
+ set(FoundRemoteDirectory TRUE)
+ elseif(line MATCHES " *<Project +.*ToolsVersion=\"4.0\".*> *$")
+ set(FoundToolsVersion4 TRUE)
+ endif()
+endforeach()
+
+if(NOT FoundCEAdditionalFiles)
+ set(RunCMake_TEST_FAILED "CEAddionalFiles not found or not set correctly.")
+ return()
+endif()
+
+if(NOT FoundRemoteDirectory)
+ set(RunCMake_TEST_FAILED "RemoteDirectory not found or not set correctly.")
+ return()
+endif()
+
+if(NOT FoundToolsVersion4)
+ set(RunCMake_TEST_FAILED "Failed to find correct ToolsVersion=\"4.0\" .")
+ return()
+endif()
+
+#
+# Test solution file deployment items.
+#
+
+set(vcSlnFile "${RunCMake_TEST_BINARY_DIR}/VsCEDebuggerDeploy.sln")
+if(NOT EXISTS "${vcSlnFile}")
+ set(RunCMake_TEST_FAILED "Solution file ${vcSlnFile} does not exist.")
+ return()
+endif()
+
+
+if( NOT ${CMAKE_SYSTEM_NAME} STREQUAL "WindowsCE" )
+ set(RunCMake_TEST_FAILED "Test only valid for WindowsCE")
+ return()
+endif()
+
+
+set(FooProjGUID "")
+set(FoundFooProj FALSE)
+set(InFooProj FALSE)
+set(FoundReleaseDeploy FALSE)
+set(DeployConfigs Debug MinSizeRel RelWithDebInfo )
+
+file(STRINGS "${vcSlnFile}" lines)
+foreach(line IN LISTS lines)
+#message(STATUS "${line}")
+ if( (NOT InFooProj ) AND (line MATCHES "^[ \\t]*Project\\(\"{[A-F0-9-]+}\"\\) = \"foo\", \"foo.vcxproj\", \"({[A-F0-9-]+})\"[ \\t]*$"))
+ # First, identify the GUID for the foo project, and record it.
+ set(FoundFooProj TRUE)
+ set(InFooProj TRUE)
+ set(FooProjGUID ${CMAKE_MATCH_1})
+ elseif(InFooProj AND line MATCHES "EndProject")
+ set(InFooProj FALSE)
+ elseif((NOT InFooProj) AND line MATCHES "${FooProjGUID}\\.Release.*\\.Deploy\\.0")
+ # If foo's Release configuration is set to deploy, this is the error.
+ set(FoundReleaseDeploy TRUE)
+ endif()
+ if( line MATCHES "{[A-F0-9-]+}\\.([^\\|]+).*\\.Deploy\\.0" )
+ # Check that the other configurations ARE set to deploy.
+ list( REMOVE_ITEM DeployConfigs ${CMAKE_MATCH_1})
+ endif()
+endforeach()
+
+if(FoundReleaseDeploy)
+ set(RunCMake_TEST_FAILED "Release deployment not inhibited by VS_NO_SOLUTION_DEPLOY_Release.")
+ return()
+endif()
+
+if(NOT FoundFooProj)
+ set(RunCMake_TEST_FAILED "Failed to find foo project in the solution.")
+ return()
+endif()
+
+list(LENGTH DeployConfigs length)
+if( length GREATER 0 )
+ set(RunCMake_TEST_FAILED "Failed to find Deploy lines for non-Release configurations. (${length})")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10ProjectWinCE/VsCEDebuggerDeploy.cmake b/Tests/RunCMake/VS10ProjectWinCE/VsCEDebuggerDeploy.cmake
new file mode 100644
index 000000000..611db0adb
--- /dev/null
+++ b/Tests/RunCMake/VS10ProjectWinCE/VsCEDebuggerDeploy.cmake
@@ -0,0 +1,14 @@
+enable_language(CXX)
+
+set(DEPLOY_DIR
+ "temp\\foodir"
+)
+
+add_library(foo SHARED foo.cpp)
+
+set_target_properties(foo
+ PROPERTIES
+ DEPLOYMENT_ADDITIONAL_FILES "foo.dll|\\foo\\src\\dir\\on\\host|$(RemoteDirectory)|0;bar.dll|\\bar\\src\\dir|$(RemoteDirectory)bardir|0"
+ DEPLOYMENT_REMOTE_DIRECTORY ${DEPLOY_DIR}
+ VS_NO_SOLUTION_DEPLOY $<CONFIG:Release>
+)
diff --git a/Tests/RunCMake/VS10ProjectWinCE/VsCSharpCFProject-check.cmake b/Tests/RunCMake/VS10ProjectWinCE/VsCSharpCFProject-check.cmake
new file mode 100644
index 000000000..618896ec0
--- /dev/null
+++ b/Tests/RunCMake/VS10ProjectWinCE/VsCSharpCFProject-check.cmake
@@ -0,0 +1,54 @@
+#
+# Check C# Compact Framework project for required elements.
+#
+set(csProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.csproj")
+if(NOT EXISTS "${csProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${csProjectFile} does not exist.")
+ return()
+endif()
+
+if( NOT ${CMAKE_SYSTEM_NAME} STREQUAL "WindowsCE" )
+ set(RunCMake_TEST_FAILED "Test only valid for WindowsCE")
+ return()
+endif()
+
+set(FoundTargetFrameworkTargetsVersion FALSE)
+set(FoundDotNetFrameworkVersion FALSE)
+set(FoundTargetFrameworkIdentifier FALSE)
+set(FoundCFTargetsImport FALSE)
+
+
+file(STRINGS "${csProjectFile}" lines)
+foreach(line IN LISTS lines)
+ #message(STATUS ${line})
+ if(line MATCHES "^ *<TargetFrameworkIdentifier>WindowsEmbeddedCompact</TargetFrameworkIdentifier> *$")
+ set(FoundTargetFrameworkIdentifier TRUE)
+ elseif(line MATCHES " *<TargetFrameworkVersion>v3.9</TargetFrameworkVersion> *$")
+ set(FoundDotNetFrameworkVersion TRUE)
+ elseif(line MATCHES " *<TargetFrameworkTargetsVersion>v8.0</TargetFrameworkTargetsVersion> *$")
+ set(FoundTargetFrameworkTargetsVersion TRUE)
+ elseif( line MATCHES " *<Import Project=\"\\$\\(MSBuildExtensionsPath\\)\\\\Microsoft\\\\\\$\\(TargetFrameworkIdentifier\\)\\\\\\$\\(TargetFrameworkTargetsVersion\\)\\\\Microsoft\\.\\$\\(TargetFrameworkIdentifier\\)\\.CSharp\\.targets\" */> *" )
+ set(FoundCFTargetsImport TRUE)
+ endif()
+endforeach()
+
+
+if(NOT FoundTargetFrameworkTargetsVersion)
+ set(RunCMake_TEST_FAILED "TargetFrameworkIdentifier not found or not set correctly.")
+ return()
+endif()
+
+if(NOT FoundDotNetFrameworkVersion)
+ set(RunCMake_TEST_FAILED "TargetFrameworkVersion not found or not set correctly.")
+ return()
+endif()
+
+if(NOT FoundTargetFrameworkIdentifier)
+ set(RunCMake_TEST_FAILED "TargetFrameworkTargetsVersion not found or not set correctly.")
+ return()
+endif()
+
+if(NOT FoundCFTargetsImport)
+ set(RunCMake_TEST_FAILED "Import of Compact Framework targets file not found or not set correctly.")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10ProjectWinCE/VsCSharpCFProject.cmake b/Tests/RunCMake/VS10ProjectWinCE/VsCSharpCFProject.cmake
new file mode 100644
index 000000000..fb2acbbe6
--- /dev/null
+++ b/Tests/RunCMake/VS10ProjectWinCE/VsCSharpCFProject.cmake
@@ -0,0 +1,8 @@
+enable_language(CSharp)
+
+add_library(foo SHARED foo.cs )
+
+set_target_properties(foo
+ PROPERTIES
+ DOTNET_TARGET_FRAMEWORK_VERSION "v3.9"
+)
diff --git a/Tests/RunCMake/VS10ProjectWinCE/foo.cpp b/Tests/RunCMake/VS10ProjectWinCE/foo.cpp
new file mode 100644
index 000000000..3695dc91e
--- /dev/null
+++ b/Tests/RunCMake/VS10ProjectWinCE/foo.cpp
@@ -0,0 +1,3 @@
+void foo()
+{
+}
diff --git a/Tests/RunCMake/VS10ProjectWinCE/foo.cs b/Tests/RunCMake/VS10ProjectWinCE/foo.cs
new file mode 100644
index 000000000..3695dc91e
--- /dev/null
+++ b/Tests/RunCMake/VS10ProjectWinCE/foo.cs
@@ -0,0 +1,3 @@
+void foo()
+{
+}
diff --git a/Tests/RunCMake/VisibilityPreset/CMP0063-OLD-stderr.txt b/Tests/RunCMake/VisibilityPreset/CMP0063-OLD-stderr.txt
new file mode 100644
index 000000000..34ac57d20
--- /dev/null
+++ b/Tests/RunCMake/VisibilityPreset/CMP0063-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0063-OLD.cmake:[0-9]+ \(cmake_policy\):
+ The OLD behavior for policy CMP0063 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/WorkingDirectory/CMakeLists.txt.in b/Tests/RunCMake/WorkingDirectory/CMakeLists.txt.in
new file mode 100644
index 000000000..46047b8dd
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/CMakeLists.txt.in
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.11)
+project(@CASE_NAME@ NONE)
+include("@RunCMake_SOURCE_DIR@/@CASE_NAME@.cmake")
diff --git a/Tests/RunCMake/WorkingDirectory/RunCMakeTest.cmake b/Tests/RunCMake/WorkingDirectory/RunCMakeTest.cmake
new file mode 100644
index 000000000..a7685aeed
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/RunCMakeTest.cmake
@@ -0,0 +1,9 @@
+include(RunCTest)
+
+run_ctest(dirNotExist)
+run_ctest(buildAndTestNoBuildDir
+ --build-and-test
+ ${RunCMake_BINARY_DIR}/buildAndTestNoBuildDir
+ ${RunCMake_BINARY_DIR}/buildAndTestNoBuildDir/CMakeLists.txt # Deliberately a file
+ --build-generator "${RunCMake_GENERATOR}"
+)
diff --git a/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-check.cmake b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-check.cmake
new file mode 100644
index 000000000..fcfe4619b
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-check.cmake
@@ -0,0 +1,3 @@
+if(EXISTS ${RunCMake_TEST_BINARY_DIR}/CMakeCache.txt)
+ set(RunCMake_TEST_FAILED "Default build dir ${RunCMake_TEST_BINARY_DIR} was used, should not have been")
+endif()
diff --git a/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-result.txt b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-result.txt
new file mode 100644
index 000000000..0617a38a5
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-result.txt
@@ -0,0 +1 @@
+^[^0][0-9]*$
diff --git a/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-stdout.txt b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-stdout.txt
new file mode 100644
index 000000000..da893176c
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir-stdout.txt
@@ -0,0 +1 @@
+Failed to change working directory to .*[/\\]buildAndTestNoBuildDir[/\\]CMakeLists.txt :
diff --git a/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir.cmake b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir.cmake
new file mode 100644
index 000000000..ad795c472
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/buildAndTestNoBuildDir.cmake
@@ -0,0 +1,7 @@
+# We want a single test that always passes. We should never actually get to
+# configure with this file, so we use a successful configure-build-test
+# sequence to denote failure of the test case.
+include(CTest)
+add_test(NAME willPass
+ COMMAND ${CMAKE_COMMAND} -E touch someFile.txt
+)
diff --git a/Tests/RunCMake/WorkingDirectory/dirNotExist-result.txt b/Tests/RunCMake/WorkingDirectory/dirNotExist-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/dirNotExist-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/WorkingDirectory/dirNotExist-stderr.txt b/Tests/RunCMake/WorkingDirectory/dirNotExist-stderr.txt
new file mode 100644
index 000000000..3cea8906d
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/dirNotExist-stderr.txt
@@ -0,0 +1 @@
+Failed to change working directory to .*[/\\]dirNotExist-build[/\\]thisDirWillNotExist :
diff --git a/Tests/RunCMake/WorkingDirectory/dirNotExist-stdout.txt b/Tests/RunCMake/WorkingDirectory/dirNotExist-stdout.txt
new file mode 100644
index 000000000..58aa6e4b8
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/dirNotExist-stdout.txt
@@ -0,0 +1,10 @@
+Test project .*/Tests/RunCMake/WorkingDirectory/dirNotExist-build
+.* +Start 1: dirNotExist
+1/1 Test #1: dirNotExist +\.+\*\*\*Not Run +[0-9.]+ sec
++
+0% tests passed, 1 tests failed out of 1
++
+Total Test time \(real\) = +[0-9.]+ sec
++
+The following tests FAILED:
+.* +1 - dirNotExist \(Not Run\)$
diff --git a/Tests/RunCMake/WorkingDirectory/dirNotExist.cmake b/Tests/RunCMake/WorkingDirectory/dirNotExist.cmake
new file mode 100644
index 000000000..642386e85
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/dirNotExist.cmake
@@ -0,0 +1,6 @@
+include(CTest)
+
+add_test(NAME dirNotExist
+ COMMAND ${CMAKE_COMMAND} -E touch someFile.txt
+ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/thisDirWillNotExist
+)
diff --git a/Tests/RunCMake/WorkingDirectory/test.cmake.in b/Tests/RunCMake/WorkingDirectory/test.cmake.in
new file mode 100644
index 000000000..8eccd799c
--- /dev/null
+++ b/Tests/RunCMake/WorkingDirectory/test.cmake.in
@@ -0,0 +1,15 @@
+cmake_minimum_required(VERSION 3.11)
+
+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}")
+
+ctest_start(Experimental)
+ctest_configure()
+ctest_build()
+ctest_test()
diff --git a/Tests/RunCMake/WriteBasicConfigVersionFile/All.cmake b/Tests/RunCMake/WriteBasicConfigVersionFile/All.cmake
new file mode 100644
index 000000000..425365239
--- /dev/null
+++ b/Tests/RunCMake/WriteBasicConfigVersionFile/All.cmake
@@ -0,0 +1,884 @@
+# Hard-code architecture for test without a real compiler.
+set(CMAKE_SIZEOF_VOID_P 4)
+
+include(WriteBasicConfigVersionFile)
+
+set(_compatibilities AnyNewerVersion
+ SameMajorVersion
+ SameMinorVersion
+ ExactVersion)
+
+function(TEST_WRITE_BASIC_CONFIG_VERSION_FILE_PREPARE _version_installed)
+ set(_same_CMAKE_SIZEOF_VOID_P ${CMAKE_SIZEOF_VOID_P})
+ set(_no_CMAKE_SIZEOF_VOID_P "")
+ math(EXPR _diff_CMAKE_SIZEOF_VOID_P "${CMAKE_SIZEOF_VOID_P} + 1")
+ foreach(_compat ${_compatibilities})
+ set(_pkg ${_compat}${_version_installed})
+ string(REPLACE "." "" _pkg ${_pkg})
+ set(_filename "${CMAKE_CURRENT_BINARY_DIR}/${_pkg}ConfigVersion.cmake")
+ set(_filename_novoid "${CMAKE_CURRENT_BINARY_DIR}/${_pkg}NoVoidConfigVersion.cmake")
+ set(_filename_diffvoid "${CMAKE_CURRENT_BINARY_DIR}/${_pkg}DiffVoidConfigVersion.cmake")
+
+ set(CMAKE_SIZEOF_VOID_P ${_same_CMAKE_SIZEOF_VOID_P})
+ write_basic_config_version_file("${_filename}"
+ VERSION ${_version_installed}
+ COMPATIBILITY ${_compat})
+
+ # Test that an empty CMAKE_SIZEOF_VOID_P is accepted:
+ set(CMAKE_SIZEOF_VOID_P ${_no_CMAKE_SIZEOF_VOID_P})
+ write_basic_config_version_file("${_filename_novoid}"
+ VERSION ${_version_installed}
+ COMPATIBILITY ${_compat})
+
+ # Test that a different CMAKE_SIZEOF_VOID_P results in
+ # PACKAGE_VERSION_UNSUITABLE
+ set(CMAKE_SIZEOF_VOID_P ${_diff_CMAKE_SIZEOF_VOID_P})
+ write_basic_config_version_file("${_filename_diffvoid}"
+ VERSION ${_version_installed}
+ COMPATIBILITY ${_compat})
+ endforeach()
+endfunction()
+
+macro(TEST_WRITE_BASIC_CONFIG_VERSION_FILE_CHECK _filename)
+ include("${_filename}")
+
+ if(_expected_compatible AND NOT PACKAGE_VERSION_COMPATIBLE)
+ message(SEND_ERROR "Did not find package with version ${_version_installed} (${_version_requested} was requested)!")
+ elseif(NOT _expected_compatible AND PACKAGE_VERSION_COMPATIBLE)
+ message(SEND_ERROR "Found package with version ${_version_installed}, but ${_version_requested} was requested!")
+ endif()
+
+ if(${_expected_exact} AND NOT PACKAGE_VERSION_EXACT)
+ message(SEND_ERROR "PACKAGE_VERSION_EXACT not set, although it should be!")
+ elseif(NOT ${_expected_exact} AND PACKAGE_VERSION_EXACT)
+ message(SEND_ERROR "PACKAGE_VERSION_EXACT set, although it should not be!")
+ endif()
+
+ if(${_expected_unsuitable} AND NOT PACKAGE_VERSION_UNSUITABLE)
+ message(SEND_ERROR "PACKAGE_VERSION_UNSUITABLE set, although it should not be!")
+ elseif(NOT ${_expected_unsuitable} AND PACKAGE_VERSION_UNSUITABLE)
+ message(SEND_ERROR "PACKAGE_VERSION_UNSUITABLE not set, although it should be!")
+ endif()
+
+ unset(PACKAGE_VERSION_COMPATIBLE)
+ unset(PACKAGE_VERSION_EXACT)
+ unset(PACKAGE_VERSION_UNSUITABLE)
+endmacro()
+
+function(TEST_WRITE_BASIC_CONFIG_VERSION_FILE _version_installed
+ _version_requested
+ _expected_compatible_AnyNewerVersion
+ _expected_compatible_SameMajorVersion
+ _expected_compatible_SameMinorVersion
+ _expected_compatible_ExactVersion)
+ set(PACKAGE_FIND_VERSION ${_version_requested})
+ if("${PACKAGE_FIND_VERSION}" MATCHES [[(^([0-9]+)(\.([0-9]+)(\.([0-9]+)(\.([0-9]+))?)?)?)?$]])
+ set(PACKAGE_FIND_VERSION_MAJOR "${CMAKE_MATCH_2}")
+ set(PACKAGE_FIND_VERSION_MINOR "${CMAKE_MATCH_4}")
+ set(PACKAGE_FIND_VERSION_PATCH "${CMAKE_MATCH_6}")
+ set(PACKAGE_FIND_VERSION_TWEAK "${CMAKE_MATCH_8}")
+ else()
+ message(FATAL_ERROR "_version_requested (${_version_requested}) should be a version number")
+ endif()
+
+ if ("${_version_installed}" STREQUAL "${_version_requested}")
+ set(_expected_exact 1)
+ else()
+ set(_expected_exact 0)
+ endif()
+
+ unset(PACKAGE_VERSION_COMPATIBLE)
+ unset(PACKAGE_VERSION_EXACT)
+ unset(PACKAGE_VERSION_UNSUITABLE)
+
+ foreach(_compat ${_compatibilities})
+ set(_pkg ${_compat}${_version_installed})
+ string(REPLACE "." "" _pkg ${_pkg})
+ set(_filename "${CMAKE_CURRENT_BINARY_DIR}/${_pkg}ConfigVersion.cmake")
+ set(_filename_novoid "${CMAKE_CURRENT_BINARY_DIR}/${_pkg}NoVoidConfigVersion.cmake")
+ set(_filename_diffvoid "${CMAKE_CURRENT_BINARY_DIR}/${_pkg}DiffVoidConfigVersion.cmake")
+
+ set(_expected_compatible ${_expected_compatible_${_compat}})
+
+ # Test "normal" version
+ set(_expected_unsuitable 0)
+ message(STATUS "TEST write_basic_config_version_file(VERSION ${_version_installed} \
+COMPATIBILITY ${_compat}) vs. ${_version_requested} \
+(expected compatible = ${_expected_compatible}, exact = ${_expected_exact}, unsuitable = ${_expected_unsuitable})")
+ test_write_basic_config_version_file_check("${_filename}")
+
+ # test empty CMAKE_SIZEOF_VOID_P version:
+ set(_expected_unsuitable 0)
+ message(STATUS "TEST write_basic_config_version_file(VERSION ${_version_installed} \
+COMPATIBILITY ${_compat}) vs. ${_version_requested} (no CMAKE_SIZEOF_VOID_P) \
+(expected compatible = ${_expected_compatible}, exact = ${_expected_exact}, unsuitable = ${_expected_unsuitable})")
+ test_write_basic_config_version_file_check("${_filename_novoid}")
+
+ # test different CMAKE_SIZEOF_VOID_P version:
+ set(_expected_unsuitable 1)
+ message(STATUS "TEST write_basic_config_version_file(VERSION ${_version_installed} \
+COMPATIBILITY ${_compat}) vs. ${_version_requested} (different CMAKE_SIZEOF_VOID_P) \
+(expected compatible = ${_expected_compatible}, exact = ${_expected_exact}, unsuitable = ${_expected_unsuitable})")
+ test_write_basic_config_version_file_check("${_filename_diffvoid}")
+
+ endforeach()
+endfunction()
+
+
+test_write_basic_config_version_file_prepare(4)
+test_write_basic_config_version_file_prepare(4.5)
+test_write_basic_config_version_file_prepare(4.5.6)
+test_write_basic_config_version_file_prepare(4.5.6.7)
+
+# AnyNewerVersion
+# | SameMajorVersion
+# | | SameMinorVersion
+# | | | ExactVersion
+# | | | |
+test_write_basic_config_version_file(4 0 1 0 0 0) # Request 0
+test_write_basic_config_version_file(4 2 1 0 0 0) # Request [older major]
+test_write_basic_config_version_file(4 4 1 1 1 1) # Request [same major]
+test_write_basic_config_version_file(4 9 0 0 0 0) # Request [newer major]
+
+test_write_basic_config_version_file(4 0.0 1 0 0 0) # Request 0.0
+test_write_basic_config_version_file(4 0.9 1 0 0 0) # Request 0.[newer minor]
+test_write_basic_config_version_file(4 2.0 1 0 0 0) # Request [older major].0
+test_write_basic_config_version_file(4 2.9 1 0 0 0) # Request [older major].[newer minor]
+test_write_basic_config_version_file(4 4.0 1 1 0 0) # Request [same major].0
+test_write_basic_config_version_file(4 4.9 0 0 0 0) # Request [same major].[newer minor]
+test_write_basic_config_version_file(4 9.0 0 0 0 0) # Request [newer major].0
+test_write_basic_config_version_file(4 9.9 0 0 0 0) # Request [newer major].[newer minor]
+
+test_write_basic_config_version_file(4 0.0.0 1 0 0 0) # Request 0.0.0
+test_write_basic_config_version_file(4 0.0.9 1 0 0 0) # Request 0.0.[newer patch]
+test_write_basic_config_version_file(4 0.9.0 1 0 0 0) # Request 0.[newer minor].0
+test_write_basic_config_version_file(4 0.9.9 1 0 0 0) # Request 0.[newer minor].[newer patch]
+test_write_basic_config_version_file(4 2.0.0 1 0 0 0) # Request [older major].0.0
+test_write_basic_config_version_file(4 2.0.9 1 0 0 0) # Request [older major].0.[newer patch]
+test_write_basic_config_version_file(4 2.9.0 1 0 0 0) # Request [older major].[newer minor].0
+test_write_basic_config_version_file(4 2.9.9 1 0 0 0) # Request [older major].[newer minor].[newer patch]
+test_write_basic_config_version_file(4 4.0.0 1 1 0 0) # Request [same major].0.0
+test_write_basic_config_version_file(4 4.0.9 0 0 0 0) # Request [same major].0.[newer patch]
+test_write_basic_config_version_file(4 4.9.0 0 0 0 0) # Request [same major].[newer minor].0
+test_write_basic_config_version_file(4 4.9.9 0 0 0 0) # Request [same major].[newer minor].[newer patch]
+test_write_basic_config_version_file(4 9.0.0 0 0 0 0) # Request [newer major].0.0
+test_write_basic_config_version_file(4 9.0.9 0 0 0 0) # Request [newer major].0.[newer patch]
+test_write_basic_config_version_file(4 9.9.0 0 0 0 0) # Request [newer major].[newer minor].0
+test_write_basic_config_version_file(4 9.9.9 0 0 0 0) # Request [newer major].[newer minor].[newer patch]
+
+test_write_basic_config_version_file(4 0.0.0.0 1 0 0 0) # Request 0.0.0.0
+test_write_basic_config_version_file(4 0.0.0.9 1 0 0 0) # Request 0.0.0.[newer tweak]
+test_write_basic_config_version_file(4 0.0.9.0 1 0 0 0) # Request 0.0.[newer patch].0
+test_write_basic_config_version_file(4 0.0.9.9 1 0 0 0) # Request 0.0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4 0.9.0.0 1 0 0 0) # Request 0.[newer minor].0.0
+test_write_basic_config_version_file(4 0.9.0.9 1 0 0 0) # Request 0.[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4 0.9.9.0 1 0 0 0) # Request 0.[newer minor].[newer patch].0
+test_write_basic_config_version_file(4 0.9.9.9 1 0 0 0) # Request 0.[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4 2.0.0.0 1 0 0 0) # Request [older major].0.0.0
+test_write_basic_config_version_file(4 2.0.0.9 1 0 0 0) # Request [older major].0.0.[newer tweak]
+test_write_basic_config_version_file(4 2.0.9.0 1 0 0 0) # Request [older major].0.[newer patch].0
+test_write_basic_config_version_file(4 2.0.9.9 1 0 0 0) # Request [older major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4 2.9.0.0 1 0 0 0) # Request [older major].[newer minor].0.0
+test_write_basic_config_version_file(4 2.9.0.9 1 0 0 0) # Request [older major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4 2.9.9.0 1 0 0 0) # Request [older major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4 2.9.9.9 1 0 0 0) # Request [older major].[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4 4.0.0.0 1 1 0 0) # Request [same major].0.0.0
+test_write_basic_config_version_file(4 4.0.0.9 0 0 0 0) # Request [same major].0.0.[newer tweak]
+test_write_basic_config_version_file(4 4.0.9.0 0 0 0 0) # Request [same major].0.[newer patch].0
+test_write_basic_config_version_file(4 4.0.9.9 0 0 0 0) # Request [same major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4 4.9.0.0 0 0 0 0) # Request [same major].[newer minor].0.0
+test_write_basic_config_version_file(4 4.9.0.9 0 0 0 0) # Request [same major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4 4.9.9.0 0 0 0 0) # Request [same major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4 4.9.9.9 0 0 0 0) # Request [same major].[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4 9.0.0.0 0 0 0 0) # Request [newer major].0.0.0
+test_write_basic_config_version_file(4 9.0.0.9 0 0 0 0) # Request [newer major].0.0.[newer tweak]
+test_write_basic_config_version_file(4 9.0.9.0 0 0 0 0) # Request [newer major].0.[newer patch].0
+test_write_basic_config_version_file(4 9.0.9.9 0 0 0 0) # Request [newer major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4 9.9.0.0 0 0 0 0) # Request [newer major].[newer minor].0.0
+test_write_basic_config_version_file(4 9.9.0.9 0 0 0 0) # Request [newer major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4 9.9.9.0 0 0 0 0) # Request [newer major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4 9.9.9.9 0 0 0 0) # Request [newer major].[newer minor].[newer patch].[newer tweak]
+
+
+
+test_write_basic_config_version_file(4.5 0 1 0 0 0) # Request 0
+test_write_basic_config_version_file(4.5 2 1 0 0 0) # Request [older major]
+test_write_basic_config_version_file(4.5 4 1 1 0 0) # Request [same major]
+test_write_basic_config_version_file(4.5 9 0 0 0 0) # Request [newer major]
+
+test_write_basic_config_version_file(4.5 0.0 1 0 0 0) # Request 0.0
+test_write_basic_config_version_file(4.5 0.2 1 0 0 0) # Request 0.[older minor]
+test_write_basic_config_version_file(4.5 0.5 1 0 0 0) # Request 0.[same minor]
+test_write_basic_config_version_file(4.5 0.9 1 0 0 0) # Request 0.[newer minor]
+test_write_basic_config_version_file(4.5 2.0 1 0 0 0) # Request [older major].0
+test_write_basic_config_version_file(4.5 2.2 1 0 0 0) # Request [older major].[older minor]
+test_write_basic_config_version_file(4.5 2.5 1 0 0 0) # Request [older major].[same minor]
+test_write_basic_config_version_file(4.5 2.9 1 0 0 0) # Request [older major].[newer minor]
+test_write_basic_config_version_file(4.5 4.0 1 1 0 0) # Request [same major].0
+test_write_basic_config_version_file(4.5 4.2 1 1 0 0) # Request [same major].[older minor]
+test_write_basic_config_version_file(4.5 4.5 1 1 1 1) # Request [same major].[same minor]
+test_write_basic_config_version_file(4.5 4.9 0 0 0 0) # Request [same major].[newer minor]
+test_write_basic_config_version_file(4.5 9.0 0 0 0 0) # Request [newer major].0
+test_write_basic_config_version_file(4.5 9.1 0 0 0 0) # Request [newer major].[older minor]
+test_write_basic_config_version_file(4.5 9.5 0 0 0 0) # Request [newer major].[same minor]
+test_write_basic_config_version_file(4.5 9.9 0 0 0 0) # Request [newer major].[newer minor]
+
+test_write_basic_config_version_file(4.5 0.0.0 1 0 0 0) # Request 0.0.0
+test_write_basic_config_version_file(4.5 0.0.9 1 0 0 0) # Request 0.0.[newer patch]
+test_write_basic_config_version_file(4.5 0.2.0 1 0 0 0) # Request 0.[older minor].0
+test_write_basic_config_version_file(4.5 0.2.9 1 0 0 0) # Request 0.[older minor].[newer patch]
+test_write_basic_config_version_file(4.5 0.5.0 1 0 0 0) # Request 0.[same minor].0
+test_write_basic_config_version_file(4.5 0.5.9 1 0 0 0) # Request 0.[same minor].[newer patch]
+test_write_basic_config_version_file(4.5 0.9.0 1 0 0 0) # Request 0.[newer minor].0
+test_write_basic_config_version_file(4.5 0.9.9 1 0 0 0) # Request 0.[newer minor].[newer patch]
+test_write_basic_config_version_file(4.5 2.0.0 1 0 0 0) # Request [older major].0.0
+test_write_basic_config_version_file(4.5 2.0.9 1 0 0 0) # Request [older major].0.[newer patch]
+test_write_basic_config_version_file(4.5 2.2.0 1 0 0 0) # Request [older major].[older minor].0
+test_write_basic_config_version_file(4.5 2.2.9 1 0 0 0) # Request [older major].[older minor].[newer patch]
+test_write_basic_config_version_file(4.5 2.5.0 1 0 0 0) # Request [older major].[same minor].0
+test_write_basic_config_version_file(4.5 2.5.9 1 0 0 0) # Request [older major].[same minor].[newer patch]
+test_write_basic_config_version_file(4.5 2.9.0 1 0 0 0) # Request [older major].[newer minor].0
+test_write_basic_config_version_file(4.5 2.9.9 1 0 0 0) # Request [older major].[newer minor].[newer patch]
+test_write_basic_config_version_file(4.5 4.0.0 1 1 0 0) # Request [same major].0.0
+test_write_basic_config_version_file(4.5 4.0.9 1 1 0 0) # Request [same major].0.[newer patch]
+test_write_basic_config_version_file(4.5 4.2.0 1 1 0 0) # Request [same major].[older minor].0
+test_write_basic_config_version_file(4.5 4.2.9 1 1 0 0) # Request [same major].[older minor].[newer patch]
+test_write_basic_config_version_file(4.5 4.5.0 1 1 1 0) # Request [same major].[same minor].0
+test_write_basic_config_version_file(4.5 4.5.9 0 0 0 0) # Request [same major].[same minor].[newer patch]
+test_write_basic_config_version_file(4.5 4.9.0 0 0 0 0) # Request [same major].[newer minor].0
+test_write_basic_config_version_file(4.5 4.9.9 0 0 0 0) # Request [same major].[newer minor].[newer patch]
+test_write_basic_config_version_file(4.5 9.0.0 0 0 0 0) # Request [newer major].0.0
+test_write_basic_config_version_file(4.5 9.0.9 0 0 0 0) # Request [newer major].0.[newer patch]
+test_write_basic_config_version_file(4.5 9.2.0 0 0 0 0) # Request [newer major].[older minor].0
+test_write_basic_config_version_file(4.5 9.2.9 0 0 0 0) # Request [newer major].[older minor].[newer patch]
+test_write_basic_config_version_file(4.5 9.5.0 0 0 0 0) # Request [newer major].[same minor].0
+test_write_basic_config_version_file(4.5 9.5.9 0 0 0 0) # Request [newer major].[same minor].[newer patch]
+test_write_basic_config_version_file(4.5 9.9.0 0 0 0 0) # Request [newer major].[newer minor].0
+test_write_basic_config_version_file(4.5 9.9.9 0 0 0 0) # Request [newer major].[newer minor].[newer patch]
+
+test_write_basic_config_version_file(4.5 0.0.0.0 1 0 0 0) # Request 0.0.0.0
+test_write_basic_config_version_file(4.5 0.0.0.9 1 0 0 0) # Request 0.0.0.[newer tweak]
+test_write_basic_config_version_file(4.5 0.0.9.0 1 0 0 0) # Request 0.0.[newer patch].0
+test_write_basic_config_version_file(4.5 0.0.9.9 1 0 0 0) # Request 0.0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 0.2.0.0 1 0 0 0) # Request 0.[older minor].0.0
+test_write_basic_config_version_file(4.5 0.2.0.9 1 0 0 0) # Request 0.[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 0.2.9.0 1 0 0 0) # Request 0.[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5 0.2.9.9 1 0 0 0) # Request 0.[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 0.5.0.0 1 0 0 0) # Request 0.[same minor].0.0
+test_write_basic_config_version_file(4.5 0.5.0.9 1 0 0 0) # Request 0.[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 0.5.9.0 1 0 0 0) # Request 0.[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5 0.5.9.9 1 0 0 0) # Request 0.[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 0.9.0.0 1 0 0 0) # Request 0.[newer minor].0.0
+test_write_basic_config_version_file(4.5 0.9.0.9 1 0 0 0) # Request 0.[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 0.9.9.0 1 0 0 0) # Request 0.[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5 0.9.9.9 1 0 0 0) # Request 0.[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 2.0.0.0 1 0 0 0) # Request [older major].0.0.0
+test_write_basic_config_version_file(4.5 2.0.0.9 1 0 0 0) # Request [older major].0.0.[newer tweak]
+test_write_basic_config_version_file(4.5 2.0.9.0 1 0 0 0) # Request [older major].0.[newer patch].0
+test_write_basic_config_version_file(4.5 2.0.9.9 1 0 0 0) # Request [older major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 2.2.0.0 1 0 0 0) # Request [older major].[older minor].0.0
+test_write_basic_config_version_file(4.5 2.2.0.9 1 0 0 0) # Request [older major].[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 2.2.9.0 1 0 0 0) # Request [older major].[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5 2.2.9.9 1 0 0 0) # Request [older major].[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 2.5.0.0 1 0 0 0) # Request [older major].[same minor].0.0
+test_write_basic_config_version_file(4.5 2.5.0.9 1 0 0 0) # Request [older major].[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 2.5.9.0 1 0 0 0) # Request [older major].[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5 2.5.9.9 1 0 0 0) # Request [older major].[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 2.9.0.0 1 0 0 0) # Request [older major].[newer minor].0.0
+test_write_basic_config_version_file(4.5 2.9.0.9 1 0 0 0) # Request [older major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 2.9.9.0 1 0 0 0) # Request [older major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5 2.9.9.9 1 0 0 0) # Request [older major].[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 4.0.0.0 1 1 0 0) # Request [same major].0.0.0
+test_write_basic_config_version_file(4.5 4.0.0.9 1 1 0 0) # Request [same major].0.0.[newer tweak]
+test_write_basic_config_version_file(4.5 4.0.9.0 1 1 0 0) # Request [same major].0.[newer patch].0
+test_write_basic_config_version_file(4.5 4.0.9.9 1 1 0 0) # Request [same major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 4.2.0.0 1 1 0 0) # Request [same major].[older minor].0.0
+test_write_basic_config_version_file(4.5 4.2.0.9 1 1 0 0) # Request [same major].[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 4.2.9.0 1 1 0 0) # Request [same major].[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5 4.2.9.9 1 1 0 0) # Request [same major].[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 4.5.0.0 1 1 1 0) # Request [same major].[same minor].0.0
+test_write_basic_config_version_file(4.5 4.5.0.9 0 0 0 0) # Request [same major].[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 4.5.9.0 0 0 0 0) # Request [same major].[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5 4.5.9.9 0 0 0 0) # Request [same major].[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 4.9.0.0 0 0 0 0) # Request [same major].[newer minor].0.0
+test_write_basic_config_version_file(4.5 4.9.0.9 0 0 0 0) # Request [same major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 4.9.9.0 0 0 0 0) # Request [same major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5 4.9.9.9 0 0 0 0) # Request [same major].[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 9.0.0.0 0 0 0 0) # Request [newer major].0.0.0
+test_write_basic_config_version_file(4.5 9.0.0.9 0 0 0 0) # Request [newer major].0.0.[newer tweak]
+test_write_basic_config_version_file(4.5 9.0.9.0 0 0 0 0) # Request [newer major].0.[newer patch].0
+test_write_basic_config_version_file(4.5 9.0.9.9 0 0 0 0) # Request [newer major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 9.2.0.0 0 0 0 0) # Request [newer major].[older minor].0.0
+test_write_basic_config_version_file(4.5 9.2.0.9 0 0 0 0) # Request [newer major].[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 9.2.9.0 0 0 0 0) # Request [newer major].[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5 9.2.9.9 0 0 0 0) # Request [newer major].[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 9.5.0.0 0 0 0 0) # Request [newer major].[same minor].0.0
+test_write_basic_config_version_file(4.5 9.5.0.9 0 0 0 0) # Request [newer major].[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 9.5.9.0 0 0 0 0) # Request [newer major].[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5 9.5.9.9 0 0 0 0) # Request [newer major].[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5 9.9.0.0 0 0 0 0) # Request [newer major].[newer minor].0.0
+test_write_basic_config_version_file(4.5 9.9.0.9 0 0 0 0) # Request [newer major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5 9.9.9.0 0 0 0 0) # Request [newer major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5 9.9.9.9 0 0 0 0) # Request [newer major].[newer minor].[newer patch].[newer tweak]
+
+
+test_write_basic_config_version_file(4.5.6 0 1 0 0 0) # Request 0
+test_write_basic_config_version_file(4.5.6 2 1 0 0 0) # Request [older major]
+test_write_basic_config_version_file(4.5.6 4 1 1 0 0) # Request [same major]
+test_write_basic_config_version_file(4.5.6 9 0 0 0 0) # Request [newer major]
+
+test_write_basic_config_version_file(4.5.6 0.0 1 0 0 0) # Request 0.0
+test_write_basic_config_version_file(4.5.6 0.2 1 0 0 0) # Request 0.[older minor]
+test_write_basic_config_version_file(4.5.6 0.5 1 0 0 0) # Request 0.[same minor]
+test_write_basic_config_version_file(4.5.6 0.9 1 0 0 0) # Request 0.[newer minor]
+test_write_basic_config_version_file(4.5.6 2.0 1 0 0 0) # Request [older major].0
+test_write_basic_config_version_file(4.5.6 2.2 1 0 0 0) # Request [older major].[older minor]
+test_write_basic_config_version_file(4.5.6 2.5 1 0 0 0) # Request [older major].[same minor]
+test_write_basic_config_version_file(4.5.6 2.9 1 0 0 0) # Request [older major].[newer minor]
+test_write_basic_config_version_file(4.5.6 4.0 1 1 0 0) # Request [same major].0
+test_write_basic_config_version_file(4.5.6 4.2 1 1 0 0) # Request [same major].[older minor]
+test_write_basic_config_version_file(4.5.6 4.5 1 1 1 0) # Request [same major].[same minor]
+test_write_basic_config_version_file(4.5.6 4.9 0 0 0 0) # Request [same major].[newer minor]
+test_write_basic_config_version_file(4.5.6 9.0 0 0 0 0) # Request [newer major].0
+test_write_basic_config_version_file(4.5.6 9.1 0 0 0 0) # Request [newer major].[older minor]
+test_write_basic_config_version_file(4.5.6 9.5 0 0 0 0) # Request [newer major].[same minor]
+test_write_basic_config_version_file(4.5.6 9.9 0 0 0 0) # Request [newer major].[newer minor]
+
+test_write_basic_config_version_file(4.5.6 0.0.0 1 0 0 0) # Request 0.0.0
+test_write_basic_config_version_file(4.5.6 0.0.2 1 0 0 0) # Request 0.0.[older patch]
+test_write_basic_config_version_file(4.5.6 0.0.6 1 0 0 0) # Request 0.0.[same patch]
+test_write_basic_config_version_file(4.5.6 0.0.9 1 0 0 0) # Request 0.0.[newer patch]
+test_write_basic_config_version_file(4.5.6 0.2.0 1 0 0 0) # Request 0.[older minor].0
+test_write_basic_config_version_file(4.5.6 0.2.2 1 0 0 0) # Request 0.[older minor].[older patch]
+test_write_basic_config_version_file(4.5.6 0.2.6 1 0 0 0) # Request 0.[older minor].[same patch]
+test_write_basic_config_version_file(4.5.6 0.2.9 1 0 0 0) # Request 0.[older minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 0.5.0 1 0 0 0) # Request 0.[same minor].0
+test_write_basic_config_version_file(4.5.6 0.5.2 1 0 0 0) # Request 0.[same minor].[older patch]
+test_write_basic_config_version_file(4.5.6 0.5.6 1 0 0 0) # Request 0.[same minor].[same patch]
+test_write_basic_config_version_file(4.5.6 0.5.9 1 0 0 0) # Request 0.[same minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 0.9.0 1 0 0 0) # Request 0.[newer minor].0
+test_write_basic_config_version_file(4.5.6 0.9.2 1 0 0 0) # Request 0.[newer minor].[older patch]
+test_write_basic_config_version_file(4.5.6 0.9.6 1 0 0 0) # Request 0.[newer minor].[same patch]
+test_write_basic_config_version_file(4.5.6 0.9.9 1 0 0 0) # Request 0.[newer minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 2.0.0 1 0 0 0) # Request [older major].0.0
+test_write_basic_config_version_file(4.5.6 2.0.2 1 0 0 0) # Request [older major].0.[older patch]
+test_write_basic_config_version_file(4.5.6 2.0.6 1 0 0 0) # Request [older major].0.[same patch]
+test_write_basic_config_version_file(4.5.6 2.0.9 1 0 0 0) # Request [older major].0.[newer patch]
+test_write_basic_config_version_file(4.5.6 2.2.0 1 0 0 0) # Request [older major].[older minor].0
+test_write_basic_config_version_file(4.5.6 2.2.2 1 0 0 0) # Request [older major].[older minor].[older patch]
+test_write_basic_config_version_file(4.5.6 2.2.6 1 0 0 0) # Request [older major].[older minor].[same patch]
+test_write_basic_config_version_file(4.5.6 2.2.9 1 0 0 0) # Request [older major].[older minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 2.5.0 1 0 0 0) # Request [older major].[same minor].0
+test_write_basic_config_version_file(4.5.6 2.5.2 1 0 0 0) # Request [older major].[same minor].[older patch]
+test_write_basic_config_version_file(4.5.6 2.5.6 1 0 0 0) # Request [older major].[same minor].[same patch]
+test_write_basic_config_version_file(4.5.6 2.5.9 1 0 0 0) # Request [older major].[same minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 2.9.0 1 0 0 0) # Request [older major].[newer minor].0
+test_write_basic_config_version_file(4.5.6 2.9.2 1 0 0 0) # Request [older major].[newer minor].[older patch]
+test_write_basic_config_version_file(4.5.6 2.9.6 1 0 0 0) # Request [older major].[newer minor].[same patch]
+test_write_basic_config_version_file(4.5.6 2.9.9 1 0 0 0) # Request [older major].[newer minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 4.0.0 1 1 0 0) # Request [same major].0.0
+test_write_basic_config_version_file(4.5.6 4.0.2 1 1 0 0) # Request [same major].0.[older patch]
+test_write_basic_config_version_file(4.5.6 4.0.6 1 1 0 0) # Request [same major].0.[same patch]
+test_write_basic_config_version_file(4.5.6 4.0.9 1 1 0 0) # Request [same major].0.[newer patch]
+test_write_basic_config_version_file(4.5.6 4.2.0 1 1 0 0) # Request [same major].[older minor].0
+test_write_basic_config_version_file(4.5.6 4.2.2 1 1 0 0) # Request [same major].[older minor].[older patch]
+test_write_basic_config_version_file(4.5.6 4.2.6 1 1 0 0) # Request [same major].[older minor].[same patch]
+test_write_basic_config_version_file(4.5.6 4.2.9 1 1 0 0) # Request [same major].[older minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 4.5.0 1 1 1 0) # Request [same major].[same minor].0
+test_write_basic_config_version_file(4.5.6 4.5.2 1 1 1 0) # Request [same major].[same minor].[older patch]
+test_write_basic_config_version_file(4.5.6 4.5.6 1 1 1 1) # Request [same major].[same minor].[same patch]
+test_write_basic_config_version_file(4.5.6 4.5.9 0 0 0 0) # Request [same major].[same minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 4.9.0 0 0 0 0) # Request [same major].[newer minor].0
+test_write_basic_config_version_file(4.5.6 4.9.2 0 0 0 0) # Request [same major].[newer minor].[older patch]
+test_write_basic_config_version_file(4.5.6 4.9.6 0 0 0 0) # Request [same major].[newer minor].[same patch]
+test_write_basic_config_version_file(4.5.6 4.9.9 0 0 0 0) # Request [same major].[newer minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 9.0.0 0 0 0 0) # Request [newer major].0.0
+test_write_basic_config_version_file(4.5.6 9.0.2 0 0 0 0) # Request [newer major].0.[older patch]
+test_write_basic_config_version_file(4.5.6 9.0.6 0 0 0 0) # Request [newer major].0.[same patch]
+test_write_basic_config_version_file(4.5.6 9.0.9 0 0 0 0) # Request [newer major].0.[newer patch]
+test_write_basic_config_version_file(4.5.6 9.2.0 0 0 0 0) # Request [newer major].[older minor].0
+test_write_basic_config_version_file(4.5.6 9.2.2 0 0 0 0) # Request [newer major].[older minor].[older patch]
+test_write_basic_config_version_file(4.5.6 9.2.6 0 0 0 0) # Request [newer major].[older minor].[same patch]
+test_write_basic_config_version_file(4.5.6 9.2.9 0 0 0 0) # Request [newer major].[older minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 9.5.0 0 0 0 0) # Request [newer major].[same minor].0
+test_write_basic_config_version_file(4.5.6 9.5.2 0 0 0 0) # Request [newer major].[same minor].[older patch]
+test_write_basic_config_version_file(4.5.6 9.5.6 0 0 0 0) # Request [newer major].[same minor].[same patch]
+test_write_basic_config_version_file(4.5.6 9.5.9 0 0 0 0) # Request [newer major].[same minor].[newer patch]
+test_write_basic_config_version_file(4.5.6 9.9.0 0 0 0 0) # Request [newer major].[newer minor].0
+test_write_basic_config_version_file(4.5.6 9.9.2 0 0 0 0) # Request [newer major].[newer minor].[older patch]
+test_write_basic_config_version_file(4.5.6 9.9.6 0 0 0 0) # Request [newer major].[newer minor].[same patch]
+test_write_basic_config_version_file(4.5.6 9.9.9 0 0 0 0) # Request [newer major].[newer minor].[newer patch]
+
+test_write_basic_config_version_file(4.5.6 0.0.0.0 1 0 0 0) # Request 0.0.0.0
+test_write_basic_config_version_file(4.5.6 0.0.0.9 1 0 0 0) # Request 0.0.0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.0.2.0 1 0 0 0) # Request 0.0.[older patch].0
+test_write_basic_config_version_file(4.5.6 0.0.2.9 1 0 0 0) # Request 0.0.[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.0.6.0 1 0 0 0) # Request 0.0.[same patch].0
+test_write_basic_config_version_file(4.5.6 0.0.6.9 1 0 0 0) # Request 0.0.[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.0.9.0 1 0 0 0) # Request 0.0.[newer patch].0
+test_write_basic_config_version_file(4.5.6 0.0.9.9 1 0 0 0) # Request 0.0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.2.0.0 1 0 0 0) # Request 0.[older minor].0.0
+test_write_basic_config_version_file(4.5.6 0.2.0.9 1 0 0 0) # Request 0.[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.2.2.0 1 0 0 0) # Request 0.[older minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 0.2.2.9 1 0 0 0) # Request 0.[older minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.2.6.0 1 0 0 0) # Request 0.[older minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 0.2.6.9 1 0 0 0) # Request 0.[older minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.2.9.0 1 0 0 0) # Request 0.[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 0.2.9.9 1 0 0 0) # Request 0.[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.5.0.0 1 0 0 0) # Request 0.[same minor].0.0
+test_write_basic_config_version_file(4.5.6 0.5.0.9 1 0 0 0) # Request 0.[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.5.2.0 1 0 0 0) # Request 0.[same minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 0.5.2.9 1 0 0 0) # Request 0.[same minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.5.6.0 1 0 0 0) # Request 0.[same minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 0.5.6.9 1 0 0 0) # Request 0.[same minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.5.9.0 1 0 0 0) # Request 0.[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 0.5.9.9 1 0 0 0) # Request 0.[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.9.0.0 1 0 0 0) # Request 0.[newer minor].0.0
+test_write_basic_config_version_file(4.5.6 0.9.0.9 1 0 0 0) # Request 0.[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.9.2.0 1 0 0 0) # Request 0.[newer minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 0.9.2.9 1 0 0 0) # Request 0.[newer minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.9.6.0 1 0 0 0) # Request 0.[newer minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 0.9.6.9 1 0 0 0) # Request 0.[newer minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 0.9.9.0 1 0 0 0) # Request 0.[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 0.9.9.9 1 0 0 0) # Request 0.[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.0.0.0 1 0 0 0) # Request [older major].0.0.0
+test_write_basic_config_version_file(4.5.6 2.0.0.9 1 0 0 0) # Request [older major].0.0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.0.2.0 1 0 0 0) # Request [older major].0.[older patch].0
+test_write_basic_config_version_file(4.5.6 2.0.2.9 1 0 0 0) # Request [older major].0.[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.0.6.0 1 0 0 0) # Request [older major].0.[same patch].0
+test_write_basic_config_version_file(4.5.6 2.0.6.9 1 0 0 0) # Request [older major].0.[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.0.9.0 1 0 0 0) # Request [older major].0.[newer patch].0
+test_write_basic_config_version_file(4.5.6 2.0.9.9 1 0 0 0) # Request [older major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.2.0.0 1 0 0 0) # Request [older major].[older minor].0.0
+test_write_basic_config_version_file(4.5.6 2.2.0.9 1 0 0 0) # Request [older major].[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.2.2.0 1 0 0 0) # Request [older major].[older minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 2.2.2.9 1 0 0 0) # Request [older major].[older minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.2.6.0 1 0 0 0) # Request [older major].[older minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 2.2.6.9 1 0 0 0) # Request [older major].[older minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.2.9.0 1 0 0 0) # Request [older major].[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 2.2.9.9 1 0 0 0) # Request [older major].[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.5.0.0 1 0 0 0) # Request [older major].[same minor].0.0
+test_write_basic_config_version_file(4.5.6 2.5.0.9 1 0 0 0) # Request [older major].[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.5.2.0 1 0 0 0) # Request [older major].[same minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 2.5.2.9 1 0 0 0) # Request [older major].[same minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.5.6.0 1 0 0 0) # Request [older major].[same minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 2.5.6.9 1 0 0 0) # Request [older major].[same minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.5.9.0 1 0 0 0) # Request [older major].[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 2.5.9.9 1 0 0 0) # Request [older major].[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.9.0.0 1 0 0 0) # Request [older major].[newer minor].0.0
+test_write_basic_config_version_file(4.5.6 2.9.0.9 1 0 0 0) # Request [older major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.9.2.0 1 0 0 0) # Request [older major].[newer minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 2.9.2.9 1 0 0 0) # Request [older major].[newer minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.9.6.0 1 0 0 0) # Request [older major].[newer minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 2.9.6.9 1 0 0 0) # Request [older major].[newer minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 2.9.9.0 1 0 0 0) # Request [older major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 2.9.9.9 1 0 0 0) # Request [older major].[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.0.0.0 1 1 0 0) # Request [same major].0.0.0
+test_write_basic_config_version_file(4.5.6 4.0.0.9 1 1 0 0) # Request [same major].0.0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.0.2.0 1 1 0 0) # Request [same major].0.[older patch].0
+test_write_basic_config_version_file(4.5.6 4.0.2.9 1 1 0 0) # Request [same major].0.[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.0.6.0 1 1 0 0) # Request [same major].0.[same patch].0
+test_write_basic_config_version_file(4.5.6 4.0.6.9 1 1 0 0) # Request [same major].0.[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.0.9.0 1 1 0 0) # Request [same major].0.[newer patch].0
+test_write_basic_config_version_file(4.5.6 4.0.9.9 1 1 0 0) # Request [same major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.2.0.0 1 1 0 0) # Request [same major].[older minor].0.0
+test_write_basic_config_version_file(4.5.6 4.2.0.9 1 1 0 0) # Request [same major].[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.2.2.0 1 1 0 0) # Request [same major].[older minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 4.2.2.9 1 1 0 0) # Request [same major].[older minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.2.6.0 1 1 0 0) # Request [same major].[older minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 4.2.6.9 1 1 0 0) # Request [same major].[older minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.2.9.0 1 1 0 0) # Request [same major].[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 4.2.9.9 1 1 0 0) # Request [same major].[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.5.0.0 1 1 1 0) # Request [same major].[same minor].0.0
+test_write_basic_config_version_file(4.5.6 4.5.0.9 1 1 1 0) # Request [same major].[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.5.2.0 1 1 1 0) # Request [same major].[same minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 4.5.2.9 1 1 1 0) # Request [same major].[same minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.5.6.0 1 1 1 1) # Request [same major].[same minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 4.5.6.9 0 0 0 1) # Request [same major].[same minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.5.9.0 0 0 0 0) # Request [same major].[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 4.5.9.9 0 0 0 0) # Request [same major].[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.9.0.0 0 0 0 0) # Request [same major].[newer minor].0.0
+test_write_basic_config_version_file(4.5.6 4.9.0.9 0 0 0 0) # Request [same major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.9.2.0 0 0 0 0) # Request [same major].[newer minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 4.9.2.9 0 0 0 0) # Request [same major].[newer minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.9.6.0 0 0 0 0) # Request [same major].[newer minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 4.9.6.9 0 0 0 0) # Request [same major].[newer minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 4.9.9.0 0 0 0 0) # Request [same major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 4.9.9.9 0 0 0 0) # Request [same major].[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.0.0.0 0 0 0 0) # Request [newer major].0.0.0
+test_write_basic_config_version_file(4.5.6 9.0.0.9 0 0 0 0) # Request [newer major].0.0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.0.2.0 0 0 0 0) # Request [newer major].0.[older patch].0
+test_write_basic_config_version_file(4.5.6 9.0.2.9 0 0 0 0) # Request [newer major].0.[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.0.6.0 0 0 0 0) # Request [newer major].0.[same patch].0
+test_write_basic_config_version_file(4.5.6 9.0.6.9 0 0 0 0) # Request [newer major].0.[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.0.9.0 0 0 0 0) # Request [newer major].0.[newer patch].0
+test_write_basic_config_version_file(4.5.6 9.0.9.9 0 0 0 0) # Request [newer major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.2.0.0 0 0 0 0) # Request [newer major].[older minor].0.0
+test_write_basic_config_version_file(4.5.6 9.2.0.9 0 0 0 0) # Request [newer major].[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.2.2.0 0 0 0 0) # Request [newer major].[older minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 9.2.2.9 0 0 0 0) # Request [newer major].[older minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.2.6.0 0 0 0 0) # Request [newer major].[older minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 9.2.6.9 0 0 0 0) # Request [newer major].[older minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.2.9.0 0 0 0 0) # Request [newer major].[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 9.2.9.9 0 0 0 0) # Request [newer major].[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.5.0.0 0 0 0 0) # Request [newer major].[same minor].0.0
+test_write_basic_config_version_file(4.5.6 9.5.0.9 0 0 0 0) # Request [newer major].[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.5.2.0 0 0 0 0) # Request [newer major].[same minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 9.5.2.9 0 0 0 0) # Request [newer major].[same minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.5.6.0 0 0 0 0) # Request [newer major].[same minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 9.5.6.9 0 0 0 0) # Request [newer major].[same minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.5.9.0 0 0 0 0) # Request [newer major].[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 9.5.9.9 0 0 0 0) # Request [newer major].[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.9.0.0 0 0 0 0) # Request [newer major].[newer minor].0.0
+test_write_basic_config_version_file(4.5.6 9.9.0.9 0 0 0 0) # Request [newer major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.9.2.0 0 0 0 0) # Request [newer major].[newer minor].[older patch].0
+test_write_basic_config_version_file(4.5.6 9.9.2.9 0 0 0 0) # Request [newer major].[newer minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.9.6.0 0 0 0 0) # Request [newer major].[newer minor].[same patch].0
+test_write_basic_config_version_file(4.5.6 9.9.6.9 0 0 0 0) # Request [newer major].[newer minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6 9.9.9.0 0 0 0 0) # Request [newer major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6 9.9.9.9 0 0 0 0) # Request [newer major].[newer minor].[newer patch].[newer tweak]
+
+
+test_write_basic_config_version_file(4.5.6.7 0 1 0 0 0) # Request 0
+test_write_basic_config_version_file(4.5.6.7 2 1 0 0 0) # Request [older major]
+test_write_basic_config_version_file(4.5.6.7 4 1 1 0 0) # Request [same major]
+test_write_basic_config_version_file(4.5.6.7 9 0 0 0 0) # Request [newer major]
+
+test_write_basic_config_version_file(4.5.6.7 0.0 1 0 0 0) # Request 0.0
+test_write_basic_config_version_file(4.5.6.7 0.2 1 0 0 0) # Request 0.[older minor]
+test_write_basic_config_version_file(4.5.6.7 0.5 1 0 0 0) # Request 0.[same minor]
+test_write_basic_config_version_file(4.5.6.7 0.9 1 0 0 0) # Request 0.[newer minor]
+test_write_basic_config_version_file(4.5.6.7 2.0 1 0 0 0) # Request [older major].0
+test_write_basic_config_version_file(4.5.6.7 2.2 1 0 0 0) # Request [older major].[older minor]
+test_write_basic_config_version_file(4.5.6.7 2.5 1 0 0 0) # Request [older major].[same minor]
+test_write_basic_config_version_file(4.5.6.7 2.9 1 0 0 0) # Request [older major].[newer minor]
+test_write_basic_config_version_file(4.5.6.7 4.0 1 1 0 0) # Request [same major].0
+test_write_basic_config_version_file(4.5.6.7 4.2 1 1 0 0) # Request [same major].[older minor]
+test_write_basic_config_version_file(4.5.6.7 4.5 1 1 1 0) # Request [same major].[same minor]
+test_write_basic_config_version_file(4.5.6.7 4.9 0 0 0 0) # Request [same major].[newer minor]
+test_write_basic_config_version_file(4.5.6.7 9.0 0 0 0 0) # Request [newer major].0
+test_write_basic_config_version_file(4.5.6.7 9.1 0 0 0 0) # Request [newer major].[older minor]
+test_write_basic_config_version_file(4.5.6.7 9.5 0 0 0 0) # Request [newer major].[same minor]
+test_write_basic_config_version_file(4.5.6.7 9.9 0 0 0 0) # Request [newer major].[newer minor]
+
+test_write_basic_config_version_file(4.5.6.7 0.0.0 1 0 0 0) # Request 0.0.0
+test_write_basic_config_version_file(4.5.6.7 0.0.2 1 0 0 0) # Request 0.0.[older patch]
+test_write_basic_config_version_file(4.5.6.7 0.0.6 1 0 0 0) # Request 0.0.[same patch]
+test_write_basic_config_version_file(4.5.6.7 0.0.9 1 0 0 0) # Request 0.0.[newer patch]
+test_write_basic_config_version_file(4.5.6.7 0.2.0 1 0 0 0) # Request 0.[older minor].0
+test_write_basic_config_version_file(4.5.6.7 0.2.2 1 0 0 0) # Request 0.[older minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 0.2.6 1 0 0 0) # Request 0.[older minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 0.2.9 1 0 0 0) # Request 0.[older minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 0.5.0 1 0 0 0) # Request 0.[same minor].0
+test_write_basic_config_version_file(4.5.6.7 0.5.2 1 0 0 0) # Request 0.[same minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 0.5.6 1 0 0 0) # Request 0.[same minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 0.5.9 1 0 0 0) # Request 0.[same minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 0.9.0 1 0 0 0) # Request 0.[newer minor].0
+test_write_basic_config_version_file(4.5.6.7 0.9.2 1 0 0 0) # Request 0.[newer minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 0.9.6 1 0 0 0) # Request 0.[newer minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 0.9.9 1 0 0 0) # Request 0.[newer minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 2.0.0 1 0 0 0) # Request [older major].0.0
+test_write_basic_config_version_file(4.5.6.7 2.0.2 1 0 0 0) # Request [older major].0.[older patch]
+test_write_basic_config_version_file(4.5.6.7 2.0.6 1 0 0 0) # Request [older major].0.[same patch]
+test_write_basic_config_version_file(4.5.6.7 2.0.9 1 0 0 0) # Request [older major].0.[newer patch]
+test_write_basic_config_version_file(4.5.6.7 2.2.0 1 0 0 0) # Request [older major].[older minor].0
+test_write_basic_config_version_file(4.5.6.7 2.2.2 1 0 0 0) # Request [older major].[older minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 2.2.6 1 0 0 0) # Request [older major].[older minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 2.2.9 1 0 0 0) # Request [older major].[older minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 2.5.0 1 0 0 0) # Request [older major].[same minor].0
+test_write_basic_config_version_file(4.5.6.7 2.5.2 1 0 0 0) # Request [older major].[same minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 2.5.6 1 0 0 0) # Request [older major].[same minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 2.5.9 1 0 0 0) # Request [older major].[same minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 2.9.0 1 0 0 0) # Request [older major].[newer minor].0
+test_write_basic_config_version_file(4.5.6.7 2.9.2 1 0 0 0) # Request [older major].[newer minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 2.9.6 1 0 0 0) # Request [older major].[newer minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 2.9.9 1 0 0 0) # Request [older major].[newer minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 4.0.0 1 1 0 0) # Request [same major].0.0
+test_write_basic_config_version_file(4.5.6.7 4.0.2 1 1 0 0) # Request [same major].0.[older patch]
+test_write_basic_config_version_file(4.5.6.7 4.0.6 1 1 0 0) # Request [same major].0.[same patch]
+test_write_basic_config_version_file(4.5.6.7 4.0.9 1 1 0 0) # Request [same major].0.[newer patch]
+test_write_basic_config_version_file(4.5.6.7 4.2.0 1 1 0 0) # Request [same major].[older minor].0
+test_write_basic_config_version_file(4.5.6.7 4.2.2 1 1 0 0) # Request [same major].[older minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 4.2.6 1 1 0 0) # Request [same major].[older minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 4.2.9 1 1 0 0) # Request [same major].[older minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 4.5.0 1 1 1 0) # Request [same major].[same minor].0
+test_write_basic_config_version_file(4.5.6.7 4.5.2 1 1 1 0) # Request [same major].[same minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 4.5.6 1 1 1 1) # Request [same major].[same minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 4.5.9 0 0 0 0) # Request [same major].[same minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 4.9.0 0 0 0 0) # Request [same major].[newer minor].0
+test_write_basic_config_version_file(4.5.6.7 4.9.2 0 0 0 0) # Request [same major].[newer minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 4.9.6 0 0 0 0) # Request [same major].[newer minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 4.9.9 0 0 0 0) # Request [same major].[newer minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 9.0.0 0 0 0 0) # Request [newer major].0.0
+test_write_basic_config_version_file(4.5.6.7 9.0.2 0 0 0 0) # Request [newer major].0.[older patch]
+test_write_basic_config_version_file(4.5.6.7 9.0.6 0 0 0 0) # Request [newer major].0.[same patch]
+test_write_basic_config_version_file(4.5.6.7 9.0.9 0 0 0 0) # Request [newer major].0.[newer patch]
+test_write_basic_config_version_file(4.5.6.7 9.2.0 0 0 0 0) # Request [newer major].[older minor].0
+test_write_basic_config_version_file(4.5.6.7 9.2.2 0 0 0 0) # Request [newer major].[older minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 9.2.6 0 0 0 0) # Request [newer major].[older minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 9.2.9 0 0 0 0) # Request [newer major].[older minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 9.5.0 0 0 0 0) # Request [newer major].[same minor].0
+test_write_basic_config_version_file(4.5.6.7 9.5.2 0 0 0 0) # Request [newer major].[same minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 9.5.6 0 0 0 0) # Request [newer major].[same minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 9.5.9 0 0 0 0) # Request [newer major].[same minor].[newer patch]
+test_write_basic_config_version_file(4.5.6.7 9.9.0 0 0 0 0) # Request [newer major].[newer minor].0
+test_write_basic_config_version_file(4.5.6.7 9.9.2 0 0 0 0) # Request [newer major].[newer minor].[older patch]
+test_write_basic_config_version_file(4.5.6.7 9.9.6 0 0 0 0) # Request [newer major].[newer minor].[same patch]
+test_write_basic_config_version_file(4.5.6.7 9.9.9 0 0 0 0) # Request [newer major].[newer minor].[newer patch]
+
+test_write_basic_config_version_file(4.5.6.7 0.0.0.0 1 0 0 0) # Request 0.0.0.0
+test_write_basic_config_version_file(4.5.6.7 0.0.0.2 1 0 0 0) # Request 0.0.0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.0.7 1 0 0 0) # Request 0.0.0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.0.9 1 0 0 0) # Request 0.0.0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.2.0 1 0 0 0) # Request 0.0.[older patch].0
+test_write_basic_config_version_file(4.5.6.7 0.0.2.2 1 0 0 0) # Request 0.0.[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.2.7 1 0 0 0) # Request 0.0.[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.2.9 1 0 0 0) # Request 0.0.[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.6.0 1 0 0 0) # Request 0.0.[same patch].0
+test_write_basic_config_version_file(4.5.6.7 0.0.6.2 1 0 0 0) # Request 0.0.[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.6.7 1 0 0 0) # Request 0.0.[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.6.9 1 0 0 0) # Request 0.0.[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.9.0 1 0 0 0) # Request 0.0.[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 0.0.9.2 1 0 0 0) # Request 0.0.[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.9.7 1 0 0 0) # Request 0.0.[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.0.9.9 1 0 0 0) # Request 0.0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.0.0 1 0 0 0) # Request 0.[older minor].0.0
+test_write_basic_config_version_file(4.5.6.7 0.2.0.2 1 0 0 0) # Request 0.[older minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.0.7 1 0 0 0) # Request 0.[older minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.0.9 1 0 0 0) # Request 0.[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.2.0 1 0 0 0) # Request 0.[older minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 0.2.2.2 1 0 0 0) # Request 0.[older minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.2.7 1 0 0 0) # Request 0.[older minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.2.9 1 0 0 0) # Request 0.[older minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.6.0 1 0 0 0) # Request 0.[older minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 0.2.6.2 1 0 0 0) # Request 0.[older minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.6.7 1 0 0 0) # Request 0.[older minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.6.9 1 0 0 0) # Request 0.[older minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.9.0 1 0 0 0) # Request 0.[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 0.2.9.2 1 0 0 0) # Request 0.[older minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.9.7 1 0 0 0) # Request 0.[older minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.2.9.9 1 0 0 0) # Request 0.[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.0.0 1 0 0 0) # Request 0.[same minor].0.0
+test_write_basic_config_version_file(4.5.6.7 0.5.0.2 1 0 0 0) # Request 0.[same minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.0.7 1 0 0 0) # Request 0.[same minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.0.9 1 0 0 0) # Request 0.[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.2.0 1 0 0 0) # Request 0.[same minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 0.5.2.2 1 0 0 0) # Request 0.[same minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.2.7 1 0 0 0) # Request 0.[same minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.2.9 1 0 0 0) # Request 0.[same minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.6.0 1 0 0 0) # Request 0.[same minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 0.5.6.2 1 0 0 0) # Request 0.[same minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.6.7 1 0 0 0) # Request 0.[same minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.6.9 1 0 0 0) # Request 0.[same minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.9.0 1 0 0 0) # Request 0.[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 0.5.9.2 1 0 0 0) # Request 0.[same minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.9.7 1 0 0 0) # Request 0.[same minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.5.9.9 1 0 0 0) # Request 0.[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.0.0 1 0 0 0) # Request 0.[newer minor].0.0
+test_write_basic_config_version_file(4.5.6.7 0.9.0.2 1 0 0 0) # Request 0.[newer minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.0.7 1 0 0 0) # Request 0.[newer minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.0.9 1 0 0 0) # Request 0.[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.2.0 1 0 0 0) # Request 0.[newer minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 0.9.2.2 1 0 0 0) # Request 0.[newer minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.2.7 1 0 0 0) # Request 0.[newer minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.2.9 1 0 0 0) # Request 0.[newer minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.6.0 1 0 0 0) # Request 0.[newer minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 0.9.6.2 1 0 0 0) # Request 0.[newer minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.6.7 1 0 0 0) # Request 0.[newer minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.6.9 1 0 0 0) # Request 0.[newer minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.9.0 1 0 0 0) # Request 0.[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 0.9.9.2 1 0 0 0) # Request 0.[newer minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.9.7 1 0 0 0) # Request 0.[newer minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 0.9.9.9 1 0 0 0) # Request 0.[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.0.0 1 0 0 0) # Request [older major].0.0.0
+test_write_basic_config_version_file(4.5.6.7 2.0.0.2 1 0 0 0) # Request [older major].0.0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.0.7 1 0 0 0) # Request [older major].0.0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.0.9 1 0 0 0) # Request [older major].0.0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.2.0 1 0 0 0) # Request [older major].0.[older patch].0
+test_write_basic_config_version_file(4.5.6.7 2.0.2.2 1 0 0 0) # Request [older major].0.[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.2.7 1 0 0 0) # Request [older major].0.[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.2.9 1 0 0 0) # Request [older major].0.[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.6.0 1 0 0 0) # Request [older major].0.[same patch].0
+test_write_basic_config_version_file(4.5.6.7 2.0.6.2 1 0 0 0) # Request [older major].0.[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.6.7 1 0 0 0) # Request [older major].0.[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.6.9 1 0 0 0) # Request [older major].0.[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.9.0 1 0 0 0) # Request [older major].0.[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 2.0.9.2 1 0 0 0) # Request [older major].0.[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.9.7 1 0 0 0) # Request [older major].0.[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.0.9.9 1 0 0 0) # Request [older major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.0.0 1 0 0 0) # Request [older major].[older minor].0.0
+test_write_basic_config_version_file(4.5.6.7 2.2.0.2 1 0 0 0) # Request [older major].[older minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.0.7 1 0 0 0) # Request [older major].[older minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.0.9 1 0 0 0) # Request [older major].[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.2.0 1 0 0 0) # Request [older major].[older minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 2.2.2.2 1 0 0 0) # Request [older major].[older minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.2.7 1 0 0 0) # Request [older major].[older minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.2.9 1 0 0 0) # Request [older major].[older minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.6.0 1 0 0 0) # Request [older major].[older minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 2.2.6.2 1 0 0 0) # Request [older major].[older minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.6.7 1 0 0 0) # Request [older major].[older minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.6.9 1 0 0 0) # Request [older major].[older minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.9.0 1 0 0 0) # Request [older major].[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 2.2.9.2 1 0 0 0) # Request [older major].[older minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.9.7 1 0 0 0) # Request [older major].[older minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.2.9.9 1 0 0 0) # Request [older major].[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.0.0 1 0 0 0) # Request [older major].[same minor].0.0
+test_write_basic_config_version_file(4.5.6.7 2.5.0.2 1 0 0 0) # Request [older major].[same minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.0.7 1 0 0 0) # Request [older major].[same minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.0.9 1 0 0 0) # Request [older major].[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.2.0 1 0 0 0) # Request [older major].[same minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 2.5.2.2 1 0 0 0) # Request [older major].[same minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.2.7 1 0 0 0) # Request [older major].[same minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.2.9 1 0 0 0) # Request [older major].[same minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.6.0 1 0 0 0) # Request [older major].[same minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 2.5.6.2 1 0 0 0) # Request [older major].[same minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.6.7 1 0 0 0) # Request [older major].[same minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.6.9 1 0 0 0) # Request [older major].[same minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.9.0 1 0 0 0) # Request [older major].[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 2.5.9.2 1 0 0 0) # Request [older major].[same minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.9.7 1 0 0 0) # Request [older major].[same minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.5.9.9 1 0 0 0) # Request [older major].[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.0.0 1 0 0 0) # Request [older major].[newer minor].0.0
+test_write_basic_config_version_file(4.5.6.7 2.9.0.2 1 0 0 0) # Request [older major].[newer minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.0.7 1 0 0 0) # Request [older major].[newer minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.0.9 1 0 0 0) # Request [older major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.2.0 1 0 0 0) # Request [older major].[newer minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 2.9.2.2 1 0 0 0) # Request [older major].[newer minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.2.7 1 0 0 0) # Request [older major].[newer minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.2.9 1 0 0 0) # Request [older major].[newer minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.6.0 1 0 0 0) # Request [older major].[newer minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 2.9.6.2 1 0 0 0) # Request [older major].[newer minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.6.7 1 0 0 0) # Request [older major].[newer minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.6.9 1 0 0 0) # Request [older major].[newer minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.9.0 1 0 0 0) # Request [older major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 2.9.9.2 1 0 0 0) # Request [older major].[newer minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.9.7 1 0 0 0) # Request [older major].[newer minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 2.9.9.9 1 0 0 0) # Request [older major].[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.0.0 1 1 0 0) # Request [same major].0.0.0
+test_write_basic_config_version_file(4.5.6.7 4.0.0.2 1 1 0 0) # Request [same major].0.0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.0.7 1 1 0 0) # Request [same major].0.0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.0.9 1 1 0 0) # Request [same major].0.0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.2.0 1 1 0 0) # Request [same major].0.[older patch].0
+test_write_basic_config_version_file(4.5.6.7 4.0.2.2 1 1 0 0) # Request [same major].0.[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.2.7 1 1 0 0) # Request [same major].0.[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.2.9 1 1 0 0) # Request [same major].0.[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.6.0 1 1 0 0) # Request [same major].0.[same patch].0
+test_write_basic_config_version_file(4.5.6.7 4.0.6.2 1 1 0 0) # Request [same major].0.[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.6.7 1 1 0 0) # Request [same major].0.[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.6.9 1 1 0 0) # Request [same major].0.[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.9.0 1 1 0 0) # Request [same major].0.[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 4.0.9.2 1 1 0 0) # Request [same major].0.[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.9.7 1 1 0 0) # Request [same major].0.[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.0.9.9 1 1 0 0) # Request [same major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.0.0 1 1 0 0) # Request [same major].[older minor].0.0
+test_write_basic_config_version_file(4.5.6.7 4.2.0.2 1 1 0 0) # Request [same major].[older minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.0.7 1 1 0 0) # Request [same major].[older minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.0.9 1 1 0 0) # Request [same major].[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.2.0 1 1 0 0) # Request [same major].[older minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 4.2.2.2 1 1 0 0) # Request [same major].[older minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.2.7 1 1 0 0) # Request [same major].[older minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.2.9 1 1 0 0) # Request [same major].[older minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.6.0 1 1 0 0) # Request [same major].[older minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 4.2.6.2 1 1 0 0) # Request [same major].[older minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.6.7 1 1 0 0) # Request [same major].[older minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.6.9 1 1 0 0) # Request [same major].[older minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.9.0 1 1 0 0) # Request [same major].[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 4.2.9.2 1 1 0 0) # Request [same major].[older minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.9.7 1 1 0 0) # Request [same major].[older minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.2.9.9 1 1 0 0) # Request [same major].[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.0.0 1 1 1 0) # Request [same major].[same minor].0.0
+test_write_basic_config_version_file(4.5.6.7 4.5.0.2 1 1 1 0) # Request [same major].[same minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.0.7 1 1 1 0) # Request [same major].[same minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.0.9 1 1 1 0) # Request [same major].[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.2.0 1 1 1 0) # Request [same major].[same minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 4.5.2.2 1 1 1 0) # Request [same major].[same minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.2.7 1 1 1 0) # Request [same major].[same minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.2.9 1 1 1 0) # Request [same major].[same minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.6.0 1 1 1 1) # Request [same major].[same minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 4.5.6.2 1 1 1 1) # Request [same major].[same minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.6.7 1 1 1 1) # Request [same major].[same minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.6.9 0 0 0 1) # Request [same major].[same minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.9.0 0 0 0 0) # Request [same major].[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 4.5.9.2 0 0 0 0) # Request [same major].[same minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.9.7 0 0 0 0) # Request [same major].[same minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.5.9.9 0 0 0 0) # Request [same major].[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.0.0 0 0 0 0) # Request [same major].[newer minor].0.0
+test_write_basic_config_version_file(4.5.6.7 4.9.0.2 0 0 0 0) # Request [same major].[newer minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.0.7 0 0 0 0) # Request [same major].[newer minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.0.9 0 0 0 0) # Request [same major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.2.0 0 0 0 0) # Request [same major].[newer minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 4.9.2.2 0 0 0 0) # Request [same major].[newer minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.2.7 0 0 0 0) # Request [same major].[newer minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.2.9 0 0 0 0) # Request [same major].[newer minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.6.0 0 0 0 0) # Request [same major].[newer minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 4.9.6.2 0 0 0 0) # Request [same major].[newer minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.6.7 0 0 0 0) # Request [same major].[newer minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.6.9 0 0 0 0) # Request [same major].[newer minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.9.0 0 0 0 0) # Request [same major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 4.9.9.2 0 0 0 0) # Request [same major].[newer minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.9.7 0 0 0 0) # Request [same major].[newer minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 4.9.9.9 0 0 0 0) # Request [same major].[newer minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.0.0 0 0 0 0) # Request [newer major].0.0.0
+test_write_basic_config_version_file(4.5.6.7 9.0.0.2 0 0 0 0) # Request [newer major].0.0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.0.7 0 0 0 0) # Request [newer major].0.0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.0.9 0 0 0 0) # Request [newer major].0.0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.2.0 0 0 0 0) # Request [newer major].0.[older patch].0
+test_write_basic_config_version_file(4.5.6.7 9.0.2.2 0 0 0 0) # Request [newer major].0.[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.2.7 0 0 0 0) # Request [newer major].0.[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.2.9 0 0 0 0) # Request [newer major].0.[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.6.0 0 0 0 0) # Request [newer major].0.[same patch].0
+test_write_basic_config_version_file(4.5.6.7 9.0.6.2 0 0 0 0) # Request [newer major].0.[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.6.7 0 0 0 0) # Request [newer major].0.[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.6.9 0 0 0 0) # Request [newer major].0.[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.9.0 0 0 0 0) # Request [newer major].0.[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 9.0.9.2 0 0 0 0) # Request [newer major].0.[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.9.7 0 0 0 0) # Request [newer major].0.[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.0.9.9 0 0 0 0) # Request [newer major].0.[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.0.0 0 0 0 0) # Request [newer major].[older minor].0.0
+test_write_basic_config_version_file(4.5.6.7 9.2.0.2 0 0 0 0) # Request [newer major].[older minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.0.7 0 0 0 0) # Request [newer major].[older minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.0.9 0 0 0 0) # Request [newer major].[older minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.2.0 0 0 0 0) # Request [newer major].[older minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 9.2.2.2 0 0 0 0) # Request [newer major].[older minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.2.7 0 0 0 0) # Request [newer major].[older minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.2.9 0 0 0 0) # Request [newer major].[older minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.6.0 0 0 0 0) # Request [newer major].[older minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 9.2.6.2 0 0 0 0) # Request [newer major].[older minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.6.7 0 0 0 0) # Request [newer major].[older minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.6.9 0 0 0 0) # Request [newer major].[older minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.9.0 0 0 0 0) # Request [newer major].[older minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 9.2.9.2 0 0 0 0) # Request [newer major].[older minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.9.7 0 0 0 0) # Request [newer major].[older minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.2.9.9 0 0 0 0) # Request [newer major].[older minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.0.0 0 0 0 0) # Request [newer major].[same minor].0.0
+test_write_basic_config_version_file(4.5.6.7 9.5.0.2 0 0 0 0) # Request [newer major].[same minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.0.7 0 0 0 0) # Request [newer major].[same minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.0.9 0 0 0 0) # Request [newer major].[same minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.2.0 0 0 0 0) # Request [newer major].[same minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 9.5.2.2 0 0 0 0) # Request [newer major].[same minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.2.7 0 0 0 0) # Request [newer major].[same minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.2.9 0 0 0 0) # Request [newer major].[same minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.6.0 0 0 0 0) # Request [newer major].[same minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 9.5.6.2 0 0 0 0) # Request [newer major].[same minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.6.7 0 0 0 0) # Request [newer major].[same minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.6.9 0 0 0 0) # Request [newer major].[same minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.9.0 0 0 0 0) # Request [newer major].[same minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 9.5.9.2 0 0 0 0) # Request [newer major].[same minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.9.7 0 0 0 0) # Request [newer major].[same minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.5.9.9 0 0 0 0) # Request [newer major].[same minor].[newer patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.0.0 0 0 0 0) # Request [newer major].[newer minor].0.0
+test_write_basic_config_version_file(4.5.6.7 9.9.0.2 0 0 0 0) # Request [newer major].[newer minor].0.[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.0.7 0 0 0 0) # Request [newer major].[newer minor].0.[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.0.9 0 0 0 0) # Request [newer major].[newer minor].0.[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.2.0 0 0 0 0) # Request [newer major].[newer minor].[older patch].0
+test_write_basic_config_version_file(4.5.6.7 9.9.2.2 0 0 0 0) # Request [newer major].[newer minor].[older patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.2.7 0 0 0 0) # Request [newer major].[newer minor].[older patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.2.9 0 0 0 0) # Request [newer major].[newer minor].[older patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.6.0 0 0 0 0) # Request [newer major].[newer minor].[same patch].0
+test_write_basic_config_version_file(4.5.6.7 9.9.6.2 0 0 0 0) # Request [newer major].[newer minor].[same patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.6.7 0 0 0 0) # Request [newer major].[newer minor].[same patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.6.9 0 0 0 0) # Request [newer major].[newer minor].[same patch].[newer tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.9.0 0 0 0 0) # Request [newer major].[newer minor].[newer patch].0
+test_write_basic_config_version_file(4.5.6.7 9.9.9.2 0 0 0 0) # Request [newer major].[newer minor].[newer patch].[older tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.9.7 0 0 0 0) # Request [newer major].[newer minor].[newer patch].[same tweak]
+test_write_basic_config_version_file(4.5.6.7 9.9.9.9 0 0 0 0) # Request [newer major].[newer minor].[newer patch].[newer tweak]
diff --git a/Tests/RunCMake/WriteBasicConfigVersionFile/ArchIndependent.cmake b/Tests/RunCMake/WriteBasicConfigVersionFile/ArchIndependent.cmake
new file mode 100644
index 000000000..13ec5d1dd
--- /dev/null
+++ b/Tests/RunCMake/WriteBasicConfigVersionFile/ArchIndependent.cmake
@@ -0,0 +1,63 @@
+# Hard-code architecture for test without a real compiler.
+set(CMAKE_SIZEOF_VOID_P 4)
+
+include(WriteBasicConfigVersionFile)
+
+set(_dummy_version 1.0.0)
+
+set(_compatibilities AnyNewerVersion
+ SameMajorVersion
+ SameMinorVersion
+ ExactVersion)
+
+function(test_write_basic_config_version_file_arch_prepare filename_out compat arch_independent arch)
+ if(arch_independent)
+ set(arch_arg ARCH_INDEPENDENT)
+ else()
+ set(arch_arg )
+ endif()
+
+ set(filename "${CMAKE_CURRENT_BINARY_DIR}/${compat}Arch${arch_arg}ConfigVersion.cmake")
+
+ set(CMAKE_SIZEOF_VOID_P "${arch}")
+
+ write_basic_config_version_file("${filename}"
+ VERSION "${_dummy_version}"
+ COMPATIBILITY "${compat}"
+ ${arch_arg})
+
+ set("${filename_out}" "${filename}" PARENT_SCOPE)
+endfunction()
+
+function(test_write_basic_config_version_file_arch_check unsuitable_out filename arch)
+ set(CMAKE_SIZEOF_VOID_P "${arch}")
+ set(PACKAGE_FIND_VERSION "${_dummy_version}")
+
+ include("${filename}")
+
+ set("${unsuitable_out}" "${PACKAGE_VERSION_UNSUITABLE}" PARENT_SCOPE)
+endfunction()
+
+function(test_write_basic_config_version_file_arch_test expected_unsuitable compat arch_independent source_arch user_arch)
+ test_write_basic_config_version_file_arch_prepare(filename "${compat}" "${arch_independent}" "${source_arch}")
+ test_write_basic_config_version_file_arch_check(unsuitable "${filename}" "${user_arch}")
+ if(unsuitable AND NOT expected_unsuitable)
+ message(SEND_ERROR "Architecture was checked when it shouldn't have been. Compatibility: ${compat} ARCH_INDEPENDENT: ${arch_independent}.")
+ elseif(expected_unsuitable AND NOT unsuitable)
+ message(SEND_ERROR "Requested architecture check not performed. Compatibility: ${compat} ARCH_INDEPENDENT: ${arch_independent}.")
+ endif()
+endfunction()
+
+set(_unsuitable TRUE)
+set(_suitable FALSE)
+
+foreach(compat ${_compatibilities})
+ test_write_basic_config_version_file_arch_test("${_suitable}" "${compat}" TRUE 4 4)
+ test_write_basic_config_version_file_arch_test("${_suitable}" "${compat}" FALSE 4 4)
+ test_write_basic_config_version_file_arch_test("${_suitable}" "${compat}" TRUE 4 8)
+ test_write_basic_config_version_file_arch_test("${_unsuitable}" "${compat}" FALSE 4 8)
+ test_write_basic_config_version_file_arch_test("${_suitable}" "${compat}" TRUE 8 4)
+ test_write_basic_config_version_file_arch_test("${_unsuitable}" "${compat}" FALSE 8 4)
+ test_write_basic_config_version_file_arch_test("${_suitable}" "${compat}" TRUE 8 8)
+ test_write_basic_config_version_file_arch_test("${_suitable}" "${compat}" FALSE 8 8)
+endforeach()
diff --git a/Tests/RunCMake/WriteBasicConfigVersionFile/CMakeLists.txt b/Tests/RunCMake/WriteBasicConfigVersionFile/CMakeLists.txt
new file mode 100644
index 000000000..44025d3bd
--- /dev/null
+++ b/Tests/RunCMake/WriteBasicConfigVersionFile/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.12)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/WriteBasicConfigVersionFile/RunCMakeTest.cmake b/Tests/RunCMake/WriteBasicConfigVersionFile/RunCMakeTest.cmake
new file mode 100644
index 000000000..5db33f7f2
--- /dev/null
+++ b/Tests/RunCMake/WriteBasicConfigVersionFile/RunCMakeTest.cmake
@@ -0,0 +1,4 @@
+include(RunCMake)
+
+run_cmake(All)
+run_cmake(ArchIndependent)
diff --git a/Tests/RunCMake/XcodeProject/DeploymentTarget.c b/Tests/RunCMake/XcodeProject/DeploymentTarget.c
new file mode 100644
index 000000000..5e0f40fed
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/DeploymentTarget.c
@@ -0,0 +1,26 @@
+#include <Availability.h>
+#include <TargetConditionals.h>
+
+#if TARGET_OS_OSX
+# if __MAC_OS_X_VERSION_MIN_REQUIRED != __MAC_10_11
+# error macOS deployment version mismatch
+# endif
+#elif TARGET_OS_IOS
+# if __IPHONE_OS_VERSION_MIN_REQUIRED != __IPHONE_9_1
+# error iOS deployment version mismatch
+# endif
+#elif TARGET_OS_WATCH
+# if __WATCH_OS_VERSION_MIN_REQUIRED != __WATCHOS_2_0
+# error watchOS deployment version mismatch
+# endif
+#elif TARGET_OS_TV
+# if __TV_OS_VERSION_MIN_REQUIRED != __TVOS_9_0
+# error tvOS deployment version mismatch
+# endif
+#else
+# error unknown OS
+#endif
+
+void foo()
+{
+}
diff --git a/Tests/RunCMake/XcodeProject/DeploymentTarget.cmake b/Tests/RunCMake/XcodeProject/DeploymentTarget.cmake
new file mode 100644
index 000000000..288735e87
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/DeploymentTarget.cmake
@@ -0,0 +1,25 @@
+cmake_minimum_required(VERSION 3.10)
+project(DeploymentTarget C)
+
+# using Xcode 7.1 SDK versions for deployment targets
+
+if(CMAKE_SYSTEM_NAME STREQUAL "iOS")
+ set(CMAKE_OSX_DEPLOYMENT_TARGET "9.1")
+ set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO")
+ set(CMAKE_XCODE_ATTRIBUTE_ENABLE_BITCODE "NO")
+elseif(CMAKE_SYSTEM_NAME STREQUAL "watchOS")
+ set(CMAKE_OSX_DEPLOYMENT_TARGET "2.0")
+ set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO")
+ set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "")
+ set(CMAKE_XCODE_ATTRIBUTE_ENABLE_BITCODE "YES")
+elseif(CMAKE_SYSTEM_NAME STREQUAL "tvOS")
+ set(CMAKE_OSX_DEPLOYMENT_TARGET "9.0")
+ set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO")
+ set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "")
+ set(CMAKE_XCODE_ATTRIBUTE_ENABLE_BITCODE "YES")
+else()
+ set(CMAKE_OSX_DEPLOYMENT_TARGET "10.11")
+endif()
+
+add_library(myFramework STATIC DeploymentTarget.c)
+set_target_properties(myFramework PROPERTIES FRAMEWORK TRUE)
diff --git a/Tests/RunCMake/XcodeProject/ExplicitCMakeLists-check.cmake b/Tests/RunCMake/XcodeProject/ExplicitCMakeLists-check.cmake
new file mode 100644
index 000000000..3073e0b87
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/ExplicitCMakeLists-check.cmake
@@ -0,0 +1,20 @@
+set(xcProjectFile "${RunCMake_TEST_BINARY_DIR}/ExplicitCMakeLists.xcodeproj/project.pbxproj")
+if(NOT EXISTS "${xcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${xcProjectFile} does not exist.")
+ return()
+endif()
+
+set(foundCMakeLists 0)
+file(STRINGS "${xcProjectFile}" lines)
+foreach(line IN LISTS lines)
+ if(line MATCHES "PBXBuildFile.*fileRef.*CMakeLists.txt")
+ if(foundCMakeLists)
+ set(RunCMake_TEST_FAILED "CMakeLists.txt referenced multiple times")
+ return()
+ endif()
+ set(foundCMakeLists 1)
+ endif()
+endforeach()
+if(NOT foundCMakeLists)
+ set(RunCMake_TEST_FAILED "CMakeLists.txt not referenced")
+endif()
diff --git a/Tests/RunCMake/XcodeProject/ExplicitCMakeLists.cmake b/Tests/RunCMake/XcodeProject/ExplicitCMakeLists.cmake
new file mode 100644
index 000000000..678b0ea9d
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/ExplicitCMakeLists.cmake
@@ -0,0 +1,2 @@
+enable_language(CXX)
+add_executable(foo foo.cpp ${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt)
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions-result.txt b/Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions-stderr.txt b/Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions-stderr.txt
new file mode 100644
index 000000000..69c61e698
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Error in CMakeLists.txt:
+ Xcode does not support per-config per-source COMPILE_DEFINITIONS:
+
+ \$<\$<CONFIG:Debug>:MYDEBUG>
+
+ specified for source:
+
+ .*/Tests/RunCMake/XcodeProject/main.c
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions.cmake b/Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions.cmake
new file mode 100644
index 000000000..f9df55fe9
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceDefinitions.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+add_executable(main main.c)
+set_property(SOURCE main.c PROPERTY COMPILE_DEFINITIONS "$<$<CONFIG:Debug>:MYDEBUG>")
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs-result.txt b/Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs-stderr.txt b/Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs-stderr.txt
new file mode 100644
index 000000000..ff70b95a3
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Error in CMakeLists.txt:
+ Xcode does not support per-config per-source INCLUDE_DIRECTORIES:
+
+ \$<\$<CONFIG:Debug>:MYDEBUG>
+
+ specified for source:
+
+ .*/Tests/RunCMake/XcodeProject/main.c
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs.cmake b/Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs.cmake
new file mode 100644
index 000000000..4476c39fc
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceIncludeDirs.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+add_executable(main main.c)
+set_property(SOURCE main.c PROPERTY INCLUDE_DIRECTORIES "$<$<CONFIG:Debug>:MYDEBUG>")
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions-result.txt b/Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions-stderr.txt b/Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions-stderr.txt
new file mode 100644
index 000000000..100008a44
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Error in CMakeLists.txt:
+ Xcode does not support per-config per-source COMPILE_OPTIONS:
+
+ \$<\$<CONFIG:Debug>:-DMYDEBUG>
+
+ specified for source:
+
+ .*/Tests/RunCMake/XcodeProject/main.c
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
diff --git a/Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions.cmake b/Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions.cmake
new file mode 100644
index 000000000..f8e803083
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/PerConfigPerSourceOptions.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+add_executable(main main.c)
+set_property(SOURCE main.c PROPERTY COMPILE_OPTIONS $<$<CONFIG:Debug>:-DMYDEBUG>)
diff --git a/Tests/RunCMake/XcodeProject/XCTestLookup.cmake b/Tests/RunCMake/XcodeProject/XCTestLookup.cmake
new file mode 100644
index 000000000..77676e5bd
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XCTestLookup.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+
+find_package(XCTest REQUIRED)
diff --git a/Tests/RunCMake/XcodeProject/XcodeDependOnZeroCheck-build-stdout.txt b/Tests/RunCMake/XcodeProject/XcodeDependOnZeroCheck-build-stdout.txt
new file mode 100644
index 000000000..92c9a2948
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XcodeDependOnZeroCheck-build-stdout.txt
@@ -0,0 +1 @@
+BUILD AGGREGATE TARGET ZERO_CHECK
diff --git a/Tests/RunCMake/XcodeProject/XcodeDependOnZeroCheck.cmake b/Tests/RunCMake/XcodeProject/XcodeDependOnZeroCheck.cmake
new file mode 100644
index 000000000..d759a6545
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XcodeDependOnZeroCheck.cmake
@@ -0,0 +1,4 @@
+set(CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY TRUE)
+project(XcodeDependOnZeroCheck CXX)
+add_subdirectory(zerocheck)
+add_library(parentdirlib foo.cpp)
diff --git a/Tests/RunCMake/XcodeProject/XcodeGenerateTopLevelProjectOnly-check.cmake b/Tests/RunCMake/XcodeProject/XcodeGenerateTopLevelProjectOnly-check.cmake
new file mode 100644
index 000000000..64654af5e
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XcodeGenerateTopLevelProjectOnly-check.cmake
@@ -0,0 +1,3 @@
+if(EXISTS "${RunCMake_TEST_BINARY_DIR}/subproject/subproject.xcodeproj")
+ message(SEND_ERROR "Unexpected project file for subproject found.")
+endif()
diff --git a/Tests/RunCMake/XcodeProject/XcodeGenerateTopLevelProjectOnly.cmake b/Tests/RunCMake/XcodeProject/XcodeGenerateTopLevelProjectOnly.cmake
new file mode 100644
index 000000000..7e53c494e
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XcodeGenerateTopLevelProjectOnly.cmake
@@ -0,0 +1,3 @@
+set(CMAKE_XCODE_GENERATE_TOP_LEVEL_PROJECT_ONLY TRUE)
+project(XcodeGenerateTopLevelProjectOnly NONE)
+add_subdirectory(subproject)
diff --git a/Tests/RunCMake/XcodeProject/XcodeSchemaProperty-check.cmake b/Tests/RunCMake/XcodeProject/XcodeSchemaProperty-check.cmake
new file mode 100644
index 000000000..7d83a7034
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XcodeSchemaProperty-check.cmake
@@ -0,0 +1,52 @@
+function(check_property property matcher)
+ set(schema "${RunCMake_TEST_BINARY_DIR}/XcodeSchemaProperty.xcodeproj/xcshareddata/xcschemes/${property}.xcscheme")
+ file(STRINGS ${schema} actual-${property}
+ REGEX "${matcher}" LIMIT_COUNT 1)
+ if(NOT actual-${property})
+ message(SEND_ERROR "Xcode schema property ${property}: Could not find ${matcher} in schema ${schema}")
+ endif()
+endfunction()
+
+function(expect_schema target)
+ set(schema "${RunCMake_TEST_BINARY_DIR}/XcodeSchemaProperty.xcodeproj/xcshareddata/xcschemes/${target}.xcscheme")
+ if(NOT EXISTS ${schema})
+ message(SEND_ERROR "Missing schema for target ${target}")
+ endif()
+endfunction()
+
+function(expect_no_schema target)
+ set(schema "${RunCMake_TEST_BINARY_DIR}/XcodeSchemaProperty.xcodeproj/xcshareddata/xcschemes/${target}.xcscheme")
+ if(EXISTS ${schema})
+ message(SEND_ERROR "Found unexpected schema ${schema}")
+ endif()
+endfunction()
+
+check_property("ADDRESS_SANITIZER" "enableAddressSanitizer")
+check_property("ADDRESS_SANITIZER_USE_AFTER_RETURN" "enableASanStackUseAfterReturn")
+check_property("THREAD_SANITIZER" "enableThreadSanitizer")
+check_property("THREAD_SANITIZER_STOP" "stopOnEveryThreadSanitizerIssue")
+check_property("UNDEFINED_BEHAVIOUR_SANITIZER" "enableUBSanitizer")
+check_property("UNDEFINED_BEHAVIOUR_SANITIZER_STOP" "stopOnEveryUBSanitizerIssue")
+check_property("DISABLE_MAIN_THREAD_CHECKER" "disableMainThreadChecker")
+check_property("MAIN_THREAD_CHECKER_STOP" "stopOnEveryMainThreadCheckerIssue")
+
+check_property("MALLOC_SCRIBBLE" "MallocScribble")
+check_property("MALLOC_GUARD_EDGES" "MallocGuardEdges")
+check_property("GUARD_MALLOC" "DYLD_INSERT_LIBRARIES")
+check_property("ZOMBIE_OBJECTS" "NSZombieEnabled")
+check_property("MALLOC_STACK" "MallocStackLogging")
+check_property("DYNAMIC_LINKER_API_USAGE" "DYLD_PRINT_APIS")
+check_property("DYNAMIC_LIBRARY_LOADS" "DYLD_PRINT_LIBRARIES")
+
+check_property("EXECUTABLE" "myExecutable")
+check_property("ARGUMENTS" [=["--foo"]=])
+check_property("ARGUMENTS" [=["--bar=baz"]=])
+check_property("ENVIRONMENT" [=[key="FOO"]=])
+check_property("ENVIRONMENT" [=[value="foo"]=])
+check_property("ENVIRONMENT" [=[key="BAR"]=])
+check_property("ENVIRONMENT" [=[value="bar"]=])
+
+expect_no_schema("NoSchema")
+
+expect_schema("CustomTarget")
+expect_schema("ALL_BUILD")
diff --git a/Tests/RunCMake/XcodeProject/XcodeSchemaProperty.cmake b/Tests/RunCMake/XcodeProject/XcodeSchemaProperty.cmake
new file mode 100644
index 000000000..be219f411
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/XcodeSchemaProperty.cmake
@@ -0,0 +1,42 @@
+cmake_minimum_required(VERSION 3.7)
+
+set(CMAKE_XCODE_GENERATE_SCHEME ON)
+
+project(XcodeSchemaProperty CXX)
+
+function(create_scheme_for_variable variable)
+ set(CMAKE_XCODE_SCHEME_${variable} ON)
+ add_executable(${variable} main.cpp)
+endfunction()
+
+create_scheme_for_variable(ADDRESS_SANITIZER)
+create_scheme_for_variable(ADDRESS_SANITIZER_USE_AFTER_RETURN)
+create_scheme_for_variable(THREAD_SANITIZER)
+create_scheme_for_variable(THREAD_SANITIZER_STOP)
+create_scheme_for_variable(UNDEFINED_BEHAVIOUR_SANITIZER)
+create_scheme_for_variable(UNDEFINED_BEHAVIOUR_SANITIZER_STOP)
+create_scheme_for_variable(DISABLE_MAIN_THREAD_CHECKER)
+create_scheme_for_variable(MAIN_THREAD_CHECKER_STOP)
+
+create_scheme_for_variable(MALLOC_SCRIBBLE)
+create_scheme_for_variable(MALLOC_GUARD_EDGES)
+create_scheme_for_variable(GUARD_MALLOC)
+create_scheme_for_variable(ZOMBIE_OBJECTS)
+create_scheme_for_variable(MALLOC_STACK)
+create_scheme_for_variable(DYNAMIC_LINKER_API_USAGE)
+create_scheme_for_variable(DYNAMIC_LIBRARY_LOADS)
+
+function(create_scheme_for_property property value)
+ set(XCODE_SCHEME_${property} ON)
+ add_executable(${property} main.cpp)
+ set_target_properties(${property} PROPERTIES XCODE_SCHEME_${property} "${value}")
+endfunction()
+
+create_scheme_for_property(EXECUTABLE myExecutable)
+create_scheme_for_property(ARGUMENTS "--foo;--bar=baz")
+create_scheme_for_property(ENVIRONMENT "FOO=foo;BAR=bar")
+
+add_executable(NoSchema main.cpp)
+set_target_properties(NoSchema PROPERTIES XCODE_GENERATE_SCHEME OFF)
+
+add_custom_target(CustomTarget)
diff --git a/Tests/RunCMake/XcodeProject/subproject/CMakeLists.txt b/Tests/RunCMake/XcodeProject/subproject/CMakeLists.txt
new file mode 100644
index 000000000..20e12b17c
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/subproject/CMakeLists.txt
@@ -0,0 +1 @@
+project(subproject)
diff --git a/Tests/RunCMake/XcodeProject/zerocheck/CMakeLists.txt b/Tests/RunCMake/XcodeProject/zerocheck/CMakeLists.txt
new file mode 100644
index 000000000..4adde99d7
--- /dev/null
+++ b/Tests/RunCMake/XcodeProject/zerocheck/CMakeLists.txt
@@ -0,0 +1,2 @@
+project(subproject)
+add_library(subdirlib ../foo.cpp)
diff --git a/Tests/RunCMake/add_custom_command/AssigningMultipleTargets.cmake b/Tests/RunCMake/add_custom_command/AssigningMultipleTargets.cmake
new file mode 100644
index 000000000..fe1cceb9a
--- /dev/null
+++ b/Tests/RunCMake/add_custom_command/AssigningMultipleTargets.cmake
@@ -0,0 +1,13 @@
+enable_language(CXX)
+
+add_custom_command(OUTPUT generated.cpp
+ MAIN_DEPENDENCY a.c
+ COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/generate-once.cmake ${CMAKE_CURRENT_BINARY_DIR}/generated.cpp
+ VERBATIM)
+
+add_executable(exe1 ${CMAKE_CURRENT_BINARY_DIR}/generated.cpp)
+add_executable(exe2 ${CMAKE_CURRENT_BINARY_DIR}/generated.cpp)
+add_executable(exe3 ${CMAKE_CURRENT_BINARY_DIR}/generated.cpp)
+
+add_dependencies(exe1 exe2)
+add_dependencies(exe3 exe1)
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/a.c b/Tests/RunCMake/add_custom_command/a.c
new file mode 100644
index 000000000..707c1c380
--- /dev/null
+++ b/Tests/RunCMake/add_custom_command/a.c
@@ -0,0 +1,3 @@
+void a()
+{
+}
diff --git a/Tests/RunCMake/add_custom_command/generate-once.cmake b/Tests/RunCMake/add_custom_command/generate-once.cmake
new file mode 100644
index 000000000..2a8e8433e
--- /dev/null
+++ b/Tests/RunCMake/add_custom_command/generate-once.cmake
@@ -0,0 +1,8 @@
+if (${CMAKE_ARGC} LESS 4)
+ message(FATAL_ERROR "Too few arguments")
+endif()
+set(output "${CMAKE_ARGV3}")
+if(EXISTS ${output})
+ message(FATAL_ERROR "${output} already exists")
+endif()
+file(WRITE ${output} "int main() { return 0; }\n")
diff --git a/Tests/RunCMake/add_custom_target/CommandExpandsEmpty.cmake b/Tests/RunCMake/add_custom_target/CommandExpandsEmpty.cmake
new file mode 100644
index 000000000..bc899a4d2
--- /dev/null
+++ b/Tests/RunCMake/add_custom_target/CommandExpandsEmpty.cmake
@@ -0,0 +1 @@
+add_custom_target(EmptyCustom COMMAND "" COMMAND_EXPAND_LISTS)
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..abefc6d12
--- /dev/null
+++ b/Tests/RunCMake/add_executable/NoSources-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at NoSources.cmake:[0-9]+ \(add_executable\):
+ No SOURCES given to target: TestExeWithoutSources
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
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..80026bfca
--- /dev/null
+++ b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at NoSourcesButLinkObjects.cmake:[0-9]+ \(add_executable\):
+ No SOURCES given to target: TestExeWithoutSources
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
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.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..88916b71f
--- /dev/null
+++ b/Tests/RunCMake/add_executable/RunCMakeTest.cmake
@@ -0,0 +1,7 @@
+include(RunCMake)
+
+run_cmake(NoSources)
+run_cmake(OnlyObjectSources)
+if(NOT RunCMake_GENERATOR STREQUAL "Xcode" OR NOT "$ENV{CMAKE_OSX_ARCHITECTURES}" MATCHES "[;$]")
+ run_cmake(NoSourcesButLinkObjects)
+endif()
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/CMP0073-stdout.txt b/Tests/RunCMake/add_library/CMP0073-stdout.txt
new file mode 100644
index 000000000..84645b8f3
--- /dev/null
+++ b/Tests/RunCMake/add_library/CMP0073-stdout.txt
@@ -0,0 +1,3 @@
+-- warn_LIB_DEPENDS='general;bar;'
+-- old_LIB_DEPENDS='general;bar;'
+-- new_LIB_DEPENDS=''
diff --git a/Tests/RunCMake/add_library/CMP0073.cmake b/Tests/RunCMake/add_library/CMP0073.cmake
new file mode 100644
index 000000000..b34f5dccd
--- /dev/null
+++ b/Tests/RunCMake/add_library/CMP0073.cmake
@@ -0,0 +1,18 @@
+enable_language(C)
+
+add_library(warn empty.c)
+target_link_libraries(warn bar)
+message(STATUS "warn_LIB_DEPENDS='${warn_LIB_DEPENDS}'")
+
+cmake_policy(SET CMP0073 OLD)
+add_library(old empty.c)
+target_link_libraries(old bar)
+message(STATUS "old_LIB_DEPENDS='${old_LIB_DEPENDS}'")
+
+cmake_policy(SET CMP0073 NEW)
+add_library(new empty.c)
+target_link_libraries(new bar)
+message(STATUS "new_LIB_DEPENDS='${new_LIB_DEPENDS}'")
+if(DEFINED new_LIB_DEPENDS)
+ message(FATAL_ERROR "new_LIB_DEPENDS set but should not be")
+endif()
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..72b92ced8
--- /dev/null
+++ b/Tests/RunCMake/add_library/MODULEwithNoSources-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at MODULEwithNoSources.cmake:[0-9]+ \(add_library\):
+ No SOURCES given to target: TestModuleLibWithoutSources
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
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..1490524e0
--- /dev/null
+++ b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at MODULEwithNoSourcesButLinkObjects.cmake:[0-9]+ \(add_library\):
+ No SOURCES given to target: TestModuleLibWithoutSources
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
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.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..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithNoSources-result.txt
@@ -0,0 +1 @@
+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..be7634c87
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithNoSources-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at OBJECTwithNoSources.cmake:[0-9]+ \(add_library\):
+ No SOURCES given to target: TestObjectLibWithoutSources
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
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..3f8591666
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at OBJECTwithNoSourcesButLinkObjects.cmake:[0-9]+ \(add_library\):
+ No SOURCES given to target: TestObjectLibWithoutSources
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
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.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..dfadb8fc1
--- /dev/null
+++ b/Tests/RunCMake/add_library/RunCMakeTest.cmake
@@ -0,0 +1,26 @@
+include(RunCMake)
+
+run_cmake(CMP0073)
+
+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..471eda12a
--- /dev/null
+++ b/Tests/RunCMake/add_library/SHAREDwithNoSources-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at SHAREDwithNoSources.cmake:[0-9]+ \(add_library\):
+ No SOURCES given to target: TestSharedLibWithoutSources
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
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..4bec7ae89
--- /dev/null
+++ b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at SHAREDwithNoSourcesButLinkObjects.cmake:[0-9]+ \(add_library\):
+ No SOURCES given to target: TestSharedLibWithoutSources
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
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.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..f65522116
--- /dev/null
+++ b/Tests/RunCMake/add_library/STATICwithNoSources-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at STATICwithNoSources.cmake:[0-9]+ \(add_library\):
+ No SOURCES given to target: TestStaticLibWithoutSources
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
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..185aad801
--- /dev/null
+++ b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at STATICwithNoSourcesButLinkObjects.cmake:[0-9]+ \(add_library\):
+ No SOURCES given to target: TestStaticLibWithoutSources
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
++
+CMake Generate step failed\. Build files cannot be regenerated correctly\.$
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.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.cmake b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects.cmake
new file mode 100644
index 000000000..a977d42fc
--- /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 INTERFACE $<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/empty.c b/Tests/RunCMake/add_library/empty.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/add_library/empty.c
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/add_link_options/CMakeLists.txt b/Tests/RunCMake/add_link_options/CMakeLists.txt
new file mode 100644
index 000000000..14ef56e8e
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/CMakeLists.txt
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.11)
+
+project(${RunCMake_TEST} LANGUAGES NONE)
+
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/add_link_options/LINKER_SHELL_expansion-build-check.cmake b/Tests/RunCMake/add_link_options/LINKER_SHELL_expansion-build-check.cmake
new file mode 100644
index 000000000..d0ef8de85
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINKER_SHELL_expansion-build-check.cmake
@@ -0,0 +1,2 @@
+
+include ("${CMAKE_CURRENT_LIST_DIR}/LINKER_expansion-validation.cmake")
diff --git a/Tests/RunCMake/add_link_options/LINKER_SHELL_expansion.cmake b/Tests/RunCMake/add_link_options/LINKER_SHELL_expansion.cmake
new file mode 100644
index 000000000..7316ef52b
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINKER_SHELL_expansion.cmake
@@ -0,0 +1,4 @@
+
+set (LINKER_OPTION "LINKER:SHELL:-foo bar")
+
+include ("LINKER_expansion-list.cmake")
diff --git a/Tests/RunCMake/add_link_options/LINKER_expansion-build-check.cmake b/Tests/RunCMake/add_link_options/LINKER_expansion-build-check.cmake
new file mode 100644
index 000000000..d0ef8de85
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINKER_expansion-build-check.cmake
@@ -0,0 +1,2 @@
+
+include ("${CMAKE_CURRENT_LIST_DIR}/LINKER_expansion-validation.cmake")
diff --git a/Tests/RunCMake/add_link_options/LINKER_expansion-list.cmake b/Tests/RunCMake/add_link_options/LINKER_expansion-list.cmake
new file mode 100644
index 000000000..34dcc6756
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINKER_expansion-list.cmake
@@ -0,0 +1,36 @@
+
+enable_language(C)
+
+add_executable(dump dump.c)
+
+add_link_options("${LINKER_OPTION}")
+
+# ensure no temp file will be used
+string(REPLACE "${CMAKE_START_TEMP_FILE}" "" CMAKE_C_CREATE_SHARED_LIBRARY "${CMAKE_C_CREATE_SHARED_LIBRARY}")
+string(REPLACE "${CMAKE_END_TEMP_FILE}" "" CMAKE_C_CREATE_SHARED_LIBRARY "${CMAKE_C_CREATE_SHARED_LIBRARY}")
+
+add_library(example SHARED LinkOptionsLib.c)
+# use LAUNCH facility to dump linker command
+set_property(TARGET example PROPERTY RULE_LAUNCH_LINK "\"${CMAKE_CURRENT_BINARY_DIR}/dump${CMAKE_EXECUTABLE_SUFFIX}\"")
+
+add_dependencies (example dump)
+
+# generate reference for LINKER flag
+if (CMAKE_C_LINKER_WRAPPER_FLAG)
+ set(linker_flag ${CMAKE_C_LINKER_WRAPPER_FLAG})
+ list(GET linker_flag -1 linker_space)
+ if (linker_space STREQUAL " ")
+ list(REMOVE_AT linker_flag -1)
+ else()
+ set(linker_space)
+ endif()
+ list (JOIN linker_flag " " linker_flag)
+ if (CMAKE_C_LINKER_WRAPPER_FLAG_SEP)
+ string (APPEND linker_flag "${linker_space}" "-foo${CMAKE_C_LINKER_WRAPPER_FLAG_SEP}bar")
+ else()
+ set (linker_flag "${linker_flag}${linker_space}-foo ${linker_flag}${linker_space}bar")
+ endif()
+else()
+ set(linker_flag "-foo bar")
+endif()
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/LINKER.txt" "${linker_flag}")
diff --git a/Tests/RunCMake/add_link_options/LINKER_expansion-validation.cmake b/Tests/RunCMake/add_link_options/LINKER_expansion-validation.cmake
new file mode 100644
index 000000000..bebd6c736
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINKER_expansion-validation.cmake
@@ -0,0 +1,15 @@
+
+if (actual_stdout MATCHES "(LINKER|SHELL):")
+ set (RunCMake_TEST_FAILED "LINKER: prefix was not expanded.")
+ return()
+endif()
+
+if (NOT EXISTS "${RunCMake_TEST_BINARY_DIR}/LINKER.txt")
+ set (RunCMake_TEST_FAILED "${RunCMake_TEST_BINARY_DIR}/LINKER.txt: Reference file not found.")
+ return()
+endif()
+file(READ "${RunCMake_TEST_BINARY_DIR}/LINKER.txt" linker_flag)
+
+if (NOT actual_stdout MATCHES "${linker_flag}")
+ set (RunCMake_TEST_FAILED "LINKER: was not expanded correctly.")
+endif()
diff --git a/Tests/RunCMake/add_link_options/LINKER_expansion.cmake b/Tests/RunCMake/add_link_options/LINKER_expansion.cmake
new file mode 100644
index 000000000..42b286d2d
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINKER_expansion.cmake
@@ -0,0 +1,4 @@
+
+set (LINKER_OPTION "LINKER:-foo,bar")
+
+include ("LINKER_expansion-list.cmake")
diff --git a/Tests/RunCMake/add_link_options/LINK_OPTIONS-exe-check.cmake b/Tests/RunCMake/add_link_options/LINK_OPTIONS-exe-check.cmake
new file mode 100644
index 000000000..4a22d7e6d
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINK_OPTIONS-exe-check.cmake
@@ -0,0 +1,7 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG_EXECUTABLE_RELEASE")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG_EXECUTABLE_RELEASE'.")
+endif()
+if (actual_stdout MATCHES "BADFLAG_(SHARED|MODULE)_RELEASE")
+ set (RunCMake_TEST_FAILED "Found unexpected 'BADFLAG_(SHARED|MODULE)_RELEASE'.")
+endif()
diff --git a/Tests/RunCMake/add_link_options/LINK_OPTIONS-exe-result.txt b/Tests/RunCMake/add_link_options/LINK_OPTIONS-exe-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINK_OPTIONS-exe-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/add_link_options/LINK_OPTIONS-mod-check.cmake b/Tests/RunCMake/add_link_options/LINK_OPTIONS-mod-check.cmake
new file mode 100644
index 000000000..d695761c9
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINK_OPTIONS-mod-check.cmake
@@ -0,0 +1,7 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG_MODULE_RELEASE")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG_MODULE_RELEASE'.")
+endif()
+if (actual_stdout MATCHES "BADFLAG_(SHARED|EXECUTABLE)_RELEASE")
+ set (RunCMake_TEST_FAILED "Found unexpected 'BADFLAG_(SHARED|EXECUTABLE)_RELEASE'.")
+endif()
diff --git a/Tests/RunCMake/add_link_options/LINK_OPTIONS-mod-result.txt b/Tests/RunCMake/add_link_options/LINK_OPTIONS-mod-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINK_OPTIONS-mod-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/add_link_options/LINK_OPTIONS-shared-check.cmake b/Tests/RunCMake/add_link_options/LINK_OPTIONS-shared-check.cmake
new file mode 100644
index 000000000..eaac8e372
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINK_OPTIONS-shared-check.cmake
@@ -0,0 +1,7 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG_SHARED_RELEASE")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG_SHARED_RELEASE'.")
+endif()
+if (actual_stdout MATCHES "BADFLAG_(MODULE|EXECUTABLE)_RELEASE")
+ set (RunCMake_TEST_FAILED "Found unexpected 'BADFLAG_(MODULE|EXECUTABLE)_RELEASE'.")
+endif()
diff --git a/Tests/RunCMake/add_link_options/LINK_OPTIONS-shared-result.txt b/Tests/RunCMake/add_link_options/LINK_OPTIONS-shared-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINK_OPTIONS-shared-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/add_link_options/LINK_OPTIONS.cmake b/Tests/RunCMake/add_link_options/LINK_OPTIONS.cmake
new file mode 100644
index 000000000..802ff4f42
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LINK_OPTIONS.cmake
@@ -0,0 +1,17 @@
+
+enable_language(C)
+
+set(obj "${CMAKE_C_OUTPUT_EXTENSION}")
+if(BORLAND)
+ set(pre -)
+endif()
+
+add_link_options($<$<AND:$<STREQUAL:$<TARGET_PROPERTY:TYPE>,SHARED_LIBRARY>,$<CONFIG:Release>>:${pre}BADFLAG_SHARED_RELEASE${obj}>)
+add_link_options($<$<AND:$<STREQUAL:$<TARGET_PROPERTY:TYPE>,MODULE_LIBRARY>,$<CONFIG:Release>>:${pre}BADFLAG_MODULE_RELEASE${obj}>)
+add_link_options($<$<AND:$<STREQUAL:$<TARGET_PROPERTY:TYPE>,EXECUTABLE>,$<CONFIG:Release>>:${pre}BADFLAG_EXECUTABLE_RELEASE${obj}>)
+
+add_library(LinkOptions_shared SHARED LinkOptionsLib.c)
+
+add_library(LinkOptions_mod MODULE LinkOptionsLib.c)
+
+add_executable(LinkOptions_exe LinkOptionsExe.c)
diff --git a/Tests/RunCMake/add_link_options/LinkOptionsExe.c b/Tests/RunCMake/add_link_options/LinkOptionsExe.c
new file mode 100644
index 000000000..8488f4e58
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LinkOptionsExe.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/add_link_options/LinkOptionsLib.c b/Tests/RunCMake/add_link_options/LinkOptionsLib.c
new file mode 100644
index 000000000..9bbd24cd8
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/LinkOptionsLib.c
@@ -0,0 +1,7 @@
+#if defined(_WIN32)
+__declspec(dllexport)
+#endif
+ int flags_lib(void)
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/add_link_options/RunCMakeTest.cmake b/Tests/RunCMake/add_link_options/RunCMakeTest.cmake
new file mode 100644
index 000000000..4f5df724e
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/RunCMakeTest.cmake
@@ -0,0 +1,38 @@
+
+include(RunCMake)
+
+macro(run_cmake_target test subtest target)
+ set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${test}-build)
+ set(RunCMake_TEST_NO_CLEAN 1)
+ run_cmake_command(${test}-${subtest} ${CMAKE_COMMAND} --build . --target ${target} ${ARGN})
+
+ unset(RunCMake_TEST_BINARY_DIR)
+ unset(RunCMake_TEST_NO_CLEAN)
+endmacro()
+
+if (NOT CMAKE_C_COMPILER_ID STREQUAL "Intel")
+ # Intel compiler does not reject bad flags or objects!
+ set(RunCMake_TEST_OUTPUT_MERGE TRUE)
+ if (NOT RunCMake_GENERATOR_IS_MULTI_CONFIG)
+ set(RunCMake_TEST_OPTIONS -DCMAKE_BUILD_TYPE=Release)
+ endif()
+
+ run_cmake(LINK_OPTIONS)
+
+ run_cmake_target(LINK_OPTIONS shared LinkOptions_shared --config Release)
+ run_cmake_target(LINK_OPTIONS mod LinkOptions_mod --config Release)
+ run_cmake_target(LINK_OPTIONS exe LinkOptions_exe --config Release)
+
+ unset(RunCMake_TEST_OPTIONS)
+ unset(RunCMake_TEST_OUTPUT_MERGE)
+endif()
+
+run_cmake(bad_SHELL_usage)
+
+if(RunCMake_GENERATOR MATCHES "(Ninja|Makefile)")
+ run_cmake(LINKER_expansion)
+ run_cmake_target(LINKER_expansion build all)
+
+ run_cmake(LINKER_SHELL_expansion)
+ run_cmake_target(LINKER_SHELL_expansion build all)
+endif()
diff --git a/Tests/RunCMake/add_link_options/bad_SHELL_usage-result.txt b/Tests/RunCMake/add_link_options/bad_SHELL_usage-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/bad_SHELL_usage-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_link_options/bad_SHELL_usage-stderr.txt b/Tests/RunCMake/add_link_options/bad_SHELL_usage-stderr.txt
new file mode 100644
index 000000000..02d09f316
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/bad_SHELL_usage-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at bad_SHELL_usage.cmake:6 \(add_library\):
+ 'SHELL:' prefix is not supported as part of 'LINKER:' arguments.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:5 \(include\)
diff --git a/Tests/RunCMake/add_link_options/bad_SHELL_usage.cmake b/Tests/RunCMake/add_link_options/bad_SHELL_usage.cmake
new file mode 100644
index 000000000..324893ddf
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/bad_SHELL_usage.cmake
@@ -0,0 +1,6 @@
+
+enable_language(C)
+
+add_link_options("LINKER:-foo,SHELL:-bar")
+
+add_library(example SHARED LinkOptionsLib.c)
diff --git a/Tests/RunCMake/add_link_options/dump.c b/Tests/RunCMake/add_link_options/dump.c
new file mode 100644
index 000000000..8baa313fd
--- /dev/null
+++ b/Tests/RunCMake/add_link_options/dump.c
@@ -0,0 +1,13 @@
+
+#include "stdio.h"
+
+int main(int argc, char* argv[])
+{
+ int i;
+
+ for (i = 1; i < argc; i++)
+ printf("%s ", argv[i]);
+ printf("\n");
+
+ return 0;
+}
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-ExcludeFromAll/CMakeLists.txt b/Tests/RunCMake/add_subdirectory/CMP0082-ExcludeFromAll/CMakeLists.txt
new file mode 100644
index 000000000..1bd7f495b
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-ExcludeFromAll/CMakeLists.txt
@@ -0,0 +1 @@
+install(CODE "message(STATUS \"exclude\")")
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-NEW-install-component-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-NEW-install-component-stdout.txt
new file mode 100644
index 000000000..7d76ed959
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-NEW-install-component-stdout.txt
@@ -0,0 +1,4 @@
+^-- Install configuration: "[^\n]*"
+-- Install component: "Unspecified"
+-- sub
+-- top$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-NEW-install-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-NEW-install-stdout.txt
new file mode 100644
index 000000000..35b0bb5e1
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-NEW-install-stdout.txt
@@ -0,0 +1,3 @@
+^-- Install configuration: "[^\n]*"
+-- sub
+-- top$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-NEW.cmake b/Tests/RunCMake/add_subdirectory/CMP0082-NEW.cmake
new file mode 100644
index 000000000..56c1b81f7
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-NEW.cmake
@@ -0,0 +1,3 @@
+add_subdirectory(CMP0082)
+add_subdirectory(CMP0082-ExcludeFromAll EXCLUDE_FROM_ALL)
+install(CODE "message(STATUS \"top\")")
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-Nested/CMakeLists.txt b/Tests/RunCMake/add_subdirectory/CMP0082-Nested/CMakeLists.txt
new file mode 100644
index 000000000..8f26c248e
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-Nested/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(sub)
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-Nested/sub/CMakeLists.txt b/Tests/RunCMake/add_subdirectory/CMP0082-Nested/sub/CMakeLists.txt
new file mode 100644
index 000000000..91a8936dc
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-Nested/sub/CMakeLists.txt
@@ -0,0 +1 @@
+install(CODE "message(STATUS \"sub\")")
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-NestedSub/CMakeLists.txt b/Tests/RunCMake/add_subdirectory/CMP0082-NestedSub/CMakeLists.txt
new file mode 100644
index 000000000..52a066504
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-NestedSub/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_subdirectory(sub)
+install(CODE "message(STATUS \"top\")")
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-NestedSub/sub/CMakeLists.txt b/Tests/RunCMake/add_subdirectory/CMP0082-NestedSub/sub/CMakeLists.txt
new file mode 100644
index 000000000..91a8936dc
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-NestedSub/sub/CMakeLists.txt
@@ -0,0 +1 @@
+install(CODE "message(STATUS \"sub\")")
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-None/CMakeLists.txt b/Tests/RunCMake/add_subdirectory/CMP0082-None/CMakeLists.txt
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-None/CMakeLists.txt
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-OLD-install-component-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-OLD-install-component-stdout.txt
new file mode 100644
index 000000000..4b39789f7
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-OLD-install-component-stdout.txt
@@ -0,0 +1,4 @@
+^-- Install configuration: "[^\n]*"
+-- Install component: "Unspecified"
+-- top
+-- sub$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-OLD-install-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-OLD-install-stdout.txt
new file mode 100644
index 000000000..8f3a5f71d
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-OLD-install-stdout.txt
@@ -0,0 +1,3 @@
+^-- Install configuration: "[^\n]*"
+-- top
+-- sub$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-OLD.cmake b/Tests/RunCMake/add_subdirectory/CMP0082-OLD.cmake
new file mode 100644
index 000000000..56c1b81f7
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-OLD.cmake
@@ -0,0 +1,3 @@
+add_subdirectory(CMP0082)
+add_subdirectory(CMP0082-ExcludeFromAll EXCLUDE_FROM_ALL)
+install(CODE "message(STATUS \"top\")")
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-install-component-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-install-component-stdout.txt
new file mode 100644
index 000000000..4b39789f7
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-install-component-stdout.txt
@@ -0,0 +1,4 @@
+^-- Install configuration: "[^\n]*"
+-- Install component: "Unspecified"
+-- top
+-- sub$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-install-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-install-stdout.txt
new file mode 100644
index 000000000..8f3a5f71d
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-install-stdout.txt
@@ -0,0 +1,3 @@
+^-- Install configuration: "[^\n]*"
+-- top
+-- sub$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-stderr.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-stderr.txt
new file mode 100644
index 000000000..3624c43a4
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested-stderr.txt
@@ -0,0 +1,7 @@
+CMake Warning \(dev\) in CMakeLists\.txt:
+ Policy CMP0082 is not set: Install rules from add_subdirectory\(\) are
+ interleaved with those in caller\. Run "cmake --help-policy CMP0082" for
+ policy details\. Use the cmake_policy command to set the policy and
+ suppress this warning\.
+
+This warning is for project developers\. Use -Wno-dev to suppress it\.
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested.cmake b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested.cmake
new file mode 100644
index 000000000..df5688af3
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-Nested.cmake
@@ -0,0 +1,2 @@
+add_subdirectory(CMP0082-Nested)
+install(CODE "message(STATUS \"top\")")
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-install-component-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-install-component-stdout.txt
new file mode 100644
index 000000000..4b39789f7
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-install-component-stdout.txt
@@ -0,0 +1,4 @@
+^-- Install configuration: "[^\n]*"
+-- Install component: "Unspecified"
+-- top
+-- sub$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-install-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-install-stdout.txt
new file mode 100644
index 000000000..8f3a5f71d
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-install-stdout.txt
@@ -0,0 +1,3 @@
+^-- Install configuration: "[^\n]*"
+-- top
+-- sub$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-stderr.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-stderr.txt
new file mode 100644
index 000000000..93629053b
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub-stderr.txt
@@ -0,0 +1,7 @@
+CMake Warning \(dev\) in CMP0082-NestedSub/CMakeLists\.txt:
+ Policy CMP0082 is not set: Install rules from add_subdirectory\(\) are
+ interleaved with those in caller\. Run "cmake --help-policy CMP0082" for
+ policy details\. Use the cmake_policy command to set the policy and
+ suppress this warning\.
+
+This warning is for project developers\. Use -Wno-dev to suppress it\.
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub.cmake b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub.cmake
new file mode 100644
index 000000000..88a0856a6
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NestedSub.cmake
@@ -0,0 +1 @@
+add_subdirectory(CMP0082-NestedSub)
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall-install-component-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall-install-component-stdout.txt
new file mode 100644
index 000000000..f7a331df2
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall-install-component-stdout.txt
@@ -0,0 +1,3 @@
+^-- Install configuration: "[^\n]*"
+-- Install component: "Unspecified"
+-- sub$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall-install-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall-install-stdout.txt
new file mode 100644
index 000000000..6f22ae24d
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall-install-stdout.txt
@@ -0,0 +1,2 @@
+^-- Install configuration: "[^\n]*"
+-- sub$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall.cmake b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall.cmake
new file mode 100644
index 000000000..70bc9edf1
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-NoTopInstall.cmake
@@ -0,0 +1 @@
+add_subdirectory(CMP0082)
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-None-install-component-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-None-install-component-stdout.txt
new file mode 100644
index 000000000..157ab37e2
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-None-install-component-stdout.txt
@@ -0,0 +1,3 @@
+^-- Install configuration: "[^\n]*"
+-- Install component: "Unspecified"
+-- top$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-None-install-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-None-install-stdout.txt
new file mode 100644
index 000000000..9e15872bd
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-None-install-stdout.txt
@@ -0,0 +1,2 @@
+^-- Install configuration: "[^\n]*"
+-- top$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-None.cmake b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-None.cmake
new file mode 100644
index 000000000..670f89b04
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-None.cmake
@@ -0,0 +1,2 @@
+add_subdirectory(CMP0082-None)
+install(CODE "message(STATUS \"top\")")
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-install-component-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-install-component-stdout.txt
new file mode 100644
index 000000000..4b39789f7
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-install-component-stdout.txt
@@ -0,0 +1,4 @@
+^-- Install configuration: "[^\n]*"
+-- Install component: "Unspecified"
+-- top
+-- sub$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-install-stdout.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-install-stdout.txt
new file mode 100644
index 000000000..8f3a5f71d
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-install-stdout.txt
@@ -0,0 +1,3 @@
+^-- Install configuration: "[^\n]*"
+-- top
+-- sub$
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN-stderr.txt b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-stderr.txt
new file mode 100644
index 000000000..3624c43a4
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN-stderr.txt
@@ -0,0 +1,7 @@
+CMake Warning \(dev\) in CMakeLists\.txt:
+ Policy CMP0082 is not set: Install rules from add_subdirectory\(\) are
+ interleaved with those in caller\. Run "cmake --help-policy CMP0082" for
+ policy details\. Use the cmake_policy command to set the policy and
+ suppress this warning\.
+
+This warning is for project developers\. Use -Wno-dev to suppress it\.
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082-WARN.cmake b/Tests/RunCMake/add_subdirectory/CMP0082-WARN.cmake
new file mode 100644
index 000000000..56c1b81f7
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082-WARN.cmake
@@ -0,0 +1,3 @@
+add_subdirectory(CMP0082)
+add_subdirectory(CMP0082-ExcludeFromAll EXCLUDE_FROM_ALL)
+install(CODE "message(STATUS \"top\")")
diff --git a/Tests/RunCMake/add_subdirectory/CMP0082/CMakeLists.txt b/Tests/RunCMake/add_subdirectory/CMP0082/CMakeLists.txt
new file mode 100644
index 000000000..91a8936dc
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/CMP0082/CMakeLists.txt
@@ -0,0 +1 @@
+install(CODE "message(STATUS \"sub\")")
diff --git a/Tests/RunCMake/add_subdirectory/ExcludeFromAll-build-sub-stderr.txt b/Tests/RunCMake/add_subdirectory/ExcludeFromAll-build-sub-stderr.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/ExcludeFromAll-build-sub-stderr.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/add_subdirectory/ExcludeFromAll/check-sub.cmake b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/check-sub.cmake
new file mode 100644
index 000000000..297ad1e22
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/check-sub.cmake
@@ -0,0 +1,32 @@
+if(EXISTS ${RunCMake_TEST_BINARY_DIR}/check-debug.cmake)
+ include(${RunCMake_TEST_BINARY_DIR}/check-debug.cmake)
+ if(RunCMake_TEST_FAILED)
+ return()
+ endif()
+
+ foreach(file
+ "${foo_lib}"
+ "${subinc_lib}"
+ "${zot_lib}"
+ )
+ if(NOT EXISTS "${file}")
+ set(RunCMake_TEST_FAILED
+ "Artifact should exist but is missing:\n ${file}")
+ return()
+ endif()
+ endforeach()
+ foreach(file
+ "${main_exe}"
+ "${bar_lib}"
+ )
+ if(EXISTS "${file}")
+ set(RunCMake_TEST_FAILED
+ "Artifact should be missing but exists:\n ${file}")
+ return()
+ endif()
+ endforeach()
+else()
+ set(RunCMake_TEST_FAILED "
+ '${RunCMake_TEST_BINARY_DIR}/check-debug.cmake' missing
+")
+endif()
diff --git a/Tests/RunCMake/add_subdirectory/ExcludeFromAll/check.cmake b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/check.cmake
new file mode 100644
index 000000000..433c03208
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/check.cmake
@@ -0,0 +1,35 @@
+if(EXISTS ${RunCMake_TEST_BINARY_DIR}/check-debug.cmake)
+ include(${RunCMake_TEST_BINARY_DIR}/check-debug.cmake)
+ if(RunCMake_TEST_FAILED)
+ return()
+ endif()
+
+ foreach(file
+ "${foo_lib}"
+ "${subinc_lib}"
+ "${main_exe}"
+ )
+ if(EXISTS "${file}")
+ # Remove for next step of test.
+ file(REMOVE "${file}")
+ else()
+ set(RunCMake_TEST_FAILED
+ "Artifact should exist but is missing:\n ${file}")
+ return()
+ endif()
+ endforeach()
+ foreach(file
+ "${zot_lib}"
+ "${bar_lib}"
+ )
+ if(EXISTS "${file}")
+ set(RunCMake_TEST_FAILED
+ "Artifact should be missing but exists:\n ${file}")
+ return()
+ endif()
+ endforeach()
+else()
+ set(RunCMake_TEST_FAILED "
+ '${RunCMake_TEST_BINARY_DIR}/check-debug.cmake' missing
+")
+endif()
diff --git a/Tests/RunCMake/add_subdirectory/ExcludeFromAll/subinc.cpp b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/subinc.cpp
new file mode 100644
index 000000000..e9faacdba
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/subinc.cpp
@@ -0,0 +1,4 @@
+int subinc()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/add_subdirectory/ExcludeFromAll/zot.cpp b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/zot.cpp
new file mode 100644
index 000000000..ba7e9661c
--- /dev/null
+++ b/Tests/RunCMake/add_subdirectory/ExcludeFromAll/zot.cpp
@@ -0,0 +1,4 @@
+int zot()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/alias_targets/imported-global-target-stderr.txt b/Tests/RunCMake/alias_targets/imported-global-target-stderr.txt
new file mode 100644
index 000000000..8259c8059
--- /dev/null
+++ b/Tests/RunCMake/alias_targets/imported-global-target-stderr.txt
@@ -0,0 +1,2 @@
+^'alias-test-exe' is an alias for 'test-exe' and its name-property contains 'test-exe'.
+'alias-test-lib' is an alias for 'test-lib' and its name-property contains 'test-lib'.$
diff --git a/Tests/RunCMake/alias_targets/imported-global-target.cmake b/Tests/RunCMake/alias_targets/imported-global-target.cmake
new file mode 100644
index 000000000..12c4e0a61
--- /dev/null
+++ b/Tests/RunCMake/alias_targets/imported-global-target.cmake
@@ -0,0 +1,46 @@
+
+enable_language(CXX)
+
+
+add_executable(test-exe IMPORTED GLOBAL)
+add_executable(alias-test-exe ALIAS test-exe)
+
+if(TARGET alias-test-exe)
+ get_target_property(aliased-target alias-test-exe ALIASED_TARGET)
+ if("${aliased-target}" STREQUAL "test-exe")
+ get_target_property(aliased-name alias-test-exe NAME)
+ if("${aliased-name}" STREQUAL "test-exe")
+ message("'alias-test-exe' is an alias for '${aliased-target}'"
+ " and its name-property contains '${aliased-name}'.")
+ else()
+ message("'alias-test-exe' is an alias for '${aliased-target}'"
+ " but its name-property contains '${aliased-name}'!?")
+ endif()
+ else()
+ message("'alias-test-exe' is something but not a real target!?")
+ endif()
+else()
+ message("'alias-test-exe' does not exist!?")
+endif()
+
+
+add_library(test-lib SHARED IMPORTED GLOBAL)
+add_library(alias-test-lib ALIAS test-lib)
+
+if(TARGET alias-test-lib)
+ get_target_property(aliased-target alias-test-lib ALIASED_TARGET)
+ if("${aliased-target}" STREQUAL "test-lib")
+ get_target_property(aliased-name alias-test-lib NAME)
+ if("${aliased-name}" STREQUAL "test-lib")
+ message("'alias-test-lib' is an alias for '${aliased-target}'"
+ " and its name-property contains '${aliased-name}'.")
+ else()
+ message("'alias-test-lib' is an alias for '${aliased-target}'"
+ " but its name-property contains '${aliased-name}'!?")
+ endif()
+ else()
+ message("'alias-test-lib' is something but not a real target!?")
+ endif()
+else()
+ message("'alias-test-lib' does not exist!?")
+endif()
diff --git a/Tests/RunCMake/cmake_minimum_required/Future.cmake b/Tests/RunCMake/cmake_minimum_required/Future.cmake
new file mode 100644
index 000000000..2b5c44517
--- /dev/null
+++ b/Tests/RunCMake/cmake_minimum_required/Future.cmake
@@ -0,0 +1 @@
+cmake_minimum_required(VERSION 3.11...99.0 SOME_FUTURE_OPTION)
diff --git a/Tests/RunCMake/cmake_minimum_required/Range-stderr.txt b/Tests/RunCMake/cmake_minimum_required/Range-stderr.txt
new file mode 100644
index 000000000..7d2bdae3b
--- /dev/null
+++ b/Tests/RunCMake/cmake_minimum_required/Range-stderr.txt
@@ -0,0 +1,4 @@
+^CMAKE_MINIMUM_REQUIRED_VERSION='3\.10'
+CMP0071='NEW'
+CMP0072='NEW'
+CMP0073=''$
diff --git a/Tests/RunCMake/cmake_minimum_required/Range.cmake b/Tests/RunCMake/cmake_minimum_required/Range.cmake
new file mode 100644
index 000000000..008009269
--- /dev/null
+++ b/Tests/RunCMake/cmake_minimum_required/Range.cmake
@@ -0,0 +1,6 @@
+cmake_minimum_required(VERSION 3.10...3.11)
+message("CMAKE_MINIMUM_REQUIRED_VERSION='${CMAKE_MINIMUM_REQUIRED_VERSION}'")
+foreach(policy CMP0071 CMP0072 CMP0073)
+ cmake_policy(GET ${policy} status)
+ message("${policy}='${status}'")
+endforeach()
diff --git a/Tests/RunCMake/cmake_minimum_required/RangeBad-result.txt b/Tests/RunCMake/cmake_minimum_required/RangeBad-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/cmake_minimum_required/RangeBad-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/cmake_minimum_required/RangeBad-stderr.txt b/Tests/RunCMake/cmake_minimum_required/RangeBad-stderr.txt
new file mode 100644
index 000000000..b2c62fbfc
--- /dev/null
+++ b/Tests/RunCMake/cmake_minimum_required/RangeBad-stderr.txt
@@ -0,0 +1,56 @@
+^CMake Error at RangeBad.cmake:1 \(cmake_minimum_required\):
+ cmake_minimum_required VERSION "3.11..." does not have a version on both
+ sides of "...".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+CMake Error at RangeBad.cmake:2 \(cmake_minimum_required\):
+ cmake_minimum_required VERSION "...3.11" does not have a version on both
+ sides of "...".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+CMake Error at RangeBad.cmake:3 \(cmake_minimum_required\):
+ cmake_minimum_required VERSION "..." does not have a version on both sides
+ of "...".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+CMake Error at RangeBad.cmake:4 \(cmake_minimum_required\):
+ Invalid policy max version value "4". A numeric
+ major.minor\[.patch\[.tweak\]\] must be given.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+CMake Error at RangeBad.cmake:5 \(cmake_minimum_required\):
+ Policy VERSION range "3.11...3.10" specifies a larger minimum than maximum.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+CMake Error at RangeBad.cmake:6 \(cmake_policy\):
+ cmake_policy VERSION "3.11..." does not have a version on both sides of
+ "...".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+CMake Error at RangeBad.cmake:7 \(cmake_policy\):
+ cmake_policy VERSION "...3.11" does not have a version on both sides of
+ "...".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+CMake Error at RangeBad.cmake:8 \(cmake_policy\):
+ cmake_policy VERSION "..." does not have a version on both sides of "...".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+CMake Error at RangeBad.cmake:9 \(cmake_policy\):
+ Invalid policy max version value "4". A numeric
+ major.minor\[.patch\[.tweak\]\] must be given.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
++
+CMake Error at RangeBad.cmake:10 \(cmake_policy\):
+ Policy VERSION range "3.11...3.10" specifies a larger minimum than maximum.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/cmake_minimum_required/RangeBad.cmake b/Tests/RunCMake/cmake_minimum_required/RangeBad.cmake
new file mode 100644
index 000000000..2a2dade2c
--- /dev/null
+++ b/Tests/RunCMake/cmake_minimum_required/RangeBad.cmake
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 3.11...)
+cmake_minimum_required(VERSION ...3.11)
+cmake_minimum_required(VERSION ...)
+cmake_minimum_required(VERSION 3.11...4)
+cmake_minimum_required(VERSION 3.11...3.10)
+cmake_policy(VERSION 3.11...)
+cmake_policy(VERSION ...3.11)
+cmake_policy(VERSION ...)
+cmake_policy(VERSION 3.11...4)
+cmake_policy(VERSION 3.11...3.10)
diff --git a/Tests/RunCMake/cmake_minimum_required/Unknown-result.txt b/Tests/RunCMake/cmake_minimum_required/Unknown-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/cmake_minimum_required/Unknown-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/cmake_minimum_required/Unknown-stderr.txt b/Tests/RunCMake/cmake_minimum_required/Unknown-stderr.txt
new file mode 100644
index 000000000..d698642b4
--- /dev/null
+++ b/Tests/RunCMake/cmake_minimum_required/Unknown-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at Unknown.cmake:1 \(cmake_minimum_required\):
+ cmake_minimum_required called with unknown argument "SOME_UNKNOWN_OPTION".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/cmake_minimum_required/Unknown.cmake b/Tests/RunCMake/cmake_minimum_required/Unknown.cmake
new file mode 100644
index 000000000..6c70f917c
--- /dev/null
+++ b/Tests/RunCMake/cmake_minimum_required/Unknown.cmake
@@ -0,0 +1 @@
+cmake_minimum_required(VERSION 3.11 SOME_UNKNOWN_OPTION)
diff --git a/Tests/RunCMake/cmake_parse_arguments/KeyWordsMissingValues.cmake b/Tests/RunCMake/cmake_parse_arguments/KeyWordsMissingValues.cmake
new file mode 100644
index 000000000..561f9c03b
--- /dev/null
+++ b/Tests/RunCMake/cmake_parse_arguments/KeyWordsMissingValues.cmake
@@ -0,0 +1,133 @@
+include(${CMAKE_CURRENT_LIST_DIR}/test_utils.cmake)
+
+# No keywords that miss any values, _KEYWORDS_MISSING_VALUES should not be defined
+cmake_parse_arguments(PREF "" "P1" "P2" P1 p1 P2 p2_a p2_b)
+
+TEST(PREF_KEYWORDS_MISSING_VALUES "UNDEFINED")
+
+# Keyword should even be deleted from the actual scope
+set(PREF_KEYWORDS_MISSING_VALUES "What ever")
+cmake_parse_arguments(PREF "" "" "")
+
+TEST(PREF_KEYWORDS_MISSING_VALUES "UNDEFINED")
+
+# Given missing keywords as only option
+cmake_parse_arguments(PREF "" "P1" "P2" P1)
+
+TEST(PREF_KEYWORDS_MISSING_VALUES "P1")
+TEST(PREF_P1 "UNDEFINED")
+TEST(PREF_UNPARSED_ARGUMENTS "UNDEFINED")
+
+# Mixed with unparsed arguments
+cmake_parse_arguments(UPREF "" "P1" "P2" A B P2 C P1)
+TEST(UPREF_KEYWORDS_MISSING_VALUES "P1")
+TEST(UPREF_UNPARSED_ARGUMENTS A B)
+
+# one_value_keyword followed by option
+cmake_parse_arguments(REF "OP" "P1" "" P1 OP)
+TEST(REF_KEYWORDS_MISSING_VALUES "P1")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_OP "TRUE")
+
+# Counter Test
+cmake_parse_arguments(REF "OP" "P1" "" P1 p1 OP)
+TEST(REF_KEYWORDS_MISSING_VALUES "UNDEFINED")
+TEST(REF_P1 "p1")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_OP "TRUE")
+
+# one_value_keyword followed by a one_value_keyword
+cmake_parse_arguments(REF "" "P1;P2" "" P1 P2 p2)
+TEST(REF_KEYWORDS_MISSING_VALUES "P1")
+TEST(REF_P1 "UNDEFINED")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_P2 "p2")
+
+# Counter Test
+cmake_parse_arguments(REF "" "P1;P2" "" P1 p1 P2 p2)
+TEST(REF_KEYWORDS_MISSING_VALUES "UNDEFINED")
+TEST(REF_P1 "p1")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_P2 "p2")
+
+# one_value_keyword followed by a multi_value_keywords
+cmake_parse_arguments(REF "" "P1" "P2" P1 P2 p1 p2)
+TEST(REF_KEYWORDS_MISSING_VALUES "P1")
+TEST(REF_P1 "UNDEFINED")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_P2 p1 p2)
+
+# Counter Examples
+cmake_parse_arguments(REF "" "P1" "P2" P1 p1 P2 p1 p2)
+TEST(REF_KEYWORDS_MISSING_VALUES "UNDEFINED")
+TEST(REF_P1 "p1")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_P2 p1 p2)
+
+# multi_value_keywords as only option
+cmake_parse_arguments(REF "" "P1" "P2" P2)
+TEST(REF_KEYWORDS_MISSING_VALUES "P2")
+TEST(REF_P1 "UNDEFINED")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_P2 "UNDEFINED")
+
+# multi_value_keywords followed by option
+cmake_parse_arguments(REF "O1" "" "P1" P1 O1)
+TEST(REF_KEYWORDS_MISSING_VALUES "P1")
+TEST(REF_P1 "UNDEFINED")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_O1 "TRUE")
+
+# counter test
+cmake_parse_arguments(REF "O1" "" "P1" P1 p1 p2 O1)
+TEST(REF_KEYWORDS_MISSING_VALUES "UNDEFINED")
+TEST(REF_P1 "p1;p2")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_O1 "TRUE")
+
+# multi_value_keywords followed by one_value_keyword
+cmake_parse_arguments(REF "" "P1" "P2" P2 P1 p1)
+TEST(REF_KEYWORDS_MISSING_VALUES "P2")
+TEST(REF_P1 "p1")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_P2 "UNDEFINED")
+
+# counter test
+cmake_parse_arguments(REF "" "P1" "P2" P2 p2 P1 p1)
+TEST(REF_KEYWORDS_MISSING_VALUES "UNDEFINED")
+TEST(REF_P1 "p1")
+TEST(REF_UNPARSED_ARGUMENTS "UNDEFINED")
+TEST(REF_P2 "p2")
+
+# one_value_keyword as last argument
+cmake_parse_arguments(REF "" "P1" "P2" A P2 p2 P1)
+TEST(REF_KEYWORDS_MISSING_VALUES "P1")
+TEST(REF_P1 "UNDEFINED")
+TEST(REF_UNPARSED_ARGUMENTS "A")
+TEST(REF_P2 "p2")
+
+# multi_value_keywords as last argument
+cmake_parse_arguments(REF "" "P1" "P2" P1 p1 P2)
+TEST(REF_KEYWORDS_MISSING_VALUES "P2")
+TEST(REF_P1 "p1")
+TEST(REF_P2 "UNDEFINED")
+
+# Multiple one_value_keyword and multi_value_keywords at different places
+cmake_parse_arguments(REF "O1;O2" "P1" "P2" P1 O1 P2 O2)
+TEST(REF_KEYWORDS_MISSING_VALUES P1 P2)
+TEST(REF_P1 "UNDEFINED")
+TEST(REF_P2 "UNDEFINED")
+
+# Duplicated missing keywords
+cmake_parse_arguments(REF "O1;O2" "P1" "P2" P1 O1 P2 O2 P1 P2)
+TEST(REF_KEYWORDS_MISSING_VALUES P1 P2)
+TEST(REF_P1 "UNDEFINED")
+TEST(REF_P2 "UNDEFINED")
+
+# make sure keywords that are never used, don't get added to KEYWORDS_MISSING_VALUES
+cmake_parse_arguments(REF "O1;O2" "P1" "P2")
+TEST(REF_KEYWORDS_MISSING_VALUES "UNDEFINED")
+TEST(REF_O1 FALSE)
+TEST(REF_O2 FALSE)
+TEST(REF_P1 UNDEFINED)
+TEST(REF_P2 UNDEFINED)
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..5d8353068
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfig.cmake.in
@@ -0,0 +1 @@
+@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_start/AppendDifferentModel-check.cmake b/Tests/RunCMake/ctest_start/AppendDifferentModel-check.cmake
new file mode 100644
index 000000000..d71b1cf01
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendDifferentModel-check.cmake
@@ -0,0 +1 @@
+check_tag_contents("^19551112-2204\nContinuousTrack\nContinuous\n$")
diff --git a/Tests/RunCMake/ctest_start/AppendDifferentModel-stderr.txt b/Tests/RunCMake/ctest_start/AppendDifferentModel-stderr.txt
new file mode 100644
index 000000000..a523f3ff0
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendDifferentModel-stderr.txt
@@ -0,0 +1 @@
+^Model given in TAG does not match model given in ctest_start\(\)$
diff --git a/Tests/RunCMake/ctest_start/AppendDifferentModel-stdout.txt b/Tests/RunCMake/ctest_start/AppendDifferentModel-stdout.txt
new file mode 100644
index 000000000..78f36a1a5
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendDifferentModel-stdout.txt
@@ -0,0 +1,7 @@
+Run dashboard with model Experimental
+ Source directory: .*/Tests/RunCMake/ctest_start/AppendDifferentModel
+ Build directory: .*/Tests/RunCMake/ctest_start/AppendDifferentModel-build
+ Site: test-site
+ Build name: test-build-name
+ Use existing tag: 19551112-2204 - ContinuousTrack
+ Use ContinuousTrack tag: [0-9-]+
diff --git a/Tests/RunCMake/ctest_start/AppendDifferentTrack-stderr.txt b/Tests/RunCMake/ctest_start/AppendDifferentTrack-stderr.txt
new file mode 100644
index 000000000..0d6d19d73
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendDifferentTrack-stderr.txt
@@ -0,0 +1 @@
+^Track given in TAG does not match track given in ctest_start\(\)$
diff --git a/Tests/RunCMake/ctest_start/AppendDifferentTrack-stdout.txt b/Tests/RunCMake/ctest_start/AppendDifferentTrack-stdout.txt
new file mode 100644
index 000000000..25085ef26
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendDifferentTrack-stdout.txt
@@ -0,0 +1,8 @@
+Run dashboard with to-be-determined model
+ Source directory: .*/Tests/RunCMake/ctest_start/AppendDifferentTrack
+ Build directory: .*/Tests/RunCMake/ctest_start/AppendDifferentTrack-build
+ Track: ExperimentalDifferent
+ Site: test-site
+ Build name: test-build-name
+ Use existing tag: 19551112-2204 - ExperimentalDifferent
+ Use ExperimentalDifferent tag: [0-9-]+
diff --git a/Tests/RunCMake/ctest_start/AppendNoMatchingTrack-stdout.txt b/Tests/RunCMake/ctest_start/AppendNoMatchingTrack-stdout.txt
new file mode 100644
index 000000000..578062959
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendNoMatchingTrack-stdout.txt
@@ -0,0 +1,7 @@
+Run dashboard with model Continuous
+ Source directory: .*/Tests/RunCMake/ctest_start/AppendNoMatchingTrack
+ Build directory: .*/Tests/RunCMake/ctest_start/AppendNoMatchingTrack-build
+ Site: test-site
+ Build name: test-build-name
+ Use existing tag: 19551112-2204 - SomeWeirdTrackName
+ Use SomeWeirdTrackName tag: [0-9-]+
diff --git a/Tests/RunCMake/ctest_start/AppendNoModel-check.cmake b/Tests/RunCMake/ctest_start/AppendNoModel-check.cmake
new file mode 100644
index 000000000..d71b1cf01
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendNoModel-check.cmake
@@ -0,0 +1 @@
+check_tag_contents("^19551112-2204\nContinuousTrack\nContinuous\n$")
diff --git a/Tests/RunCMake/ctest_start/AppendNoModel-stdout.txt b/Tests/RunCMake/ctest_start/AppendNoModel-stdout.txt
new file mode 100644
index 000000000..bcd01256b
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendNoModel-stdout.txt
@@ -0,0 +1,7 @@
+Run dashboard with to-be-determined model
+ Source directory: .*/Tests/RunCMake/ctest_start/AppendNoModel
+ Build directory: .*/Tests/RunCMake/ctest_start/AppendNoModel-build
+ Site: test-site
+ Build name: test-build-name
+ Use existing tag: 19551112-2204 - ContinuousTrack
+ Use ContinuousTrack tag: [0-9-]+
diff --git a/Tests/RunCMake/ctest_start/AppendOldContinuous-stdout.txt b/Tests/RunCMake/ctest_start/AppendOldContinuous-stdout.txt
new file mode 100644
index 000000000..e58cd9c66
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendOldContinuous-stdout.txt
@@ -0,0 +1,7 @@
+Run dashboard with model Continuous
+ Source directory: .*/Tests/RunCMake/ctest_start/AppendOldContinuous
+ Build directory: .*/Tests/RunCMake/ctest_start/AppendOldContinuous-build
+ Site: test-site
+ Build name: test-build-name
+ Use existing tag: 19551112-2204 - ContinuousTrack
+ Use ContinuousTrack tag: 19551112-2204
diff --git a/Tests/RunCMake/ctest_start/AppendOldNoModel-result.txt b/Tests/RunCMake/ctest_start/AppendOldNoModel-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendOldNoModel-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_start/AppendOldNoModel-stderr.txt b/Tests/RunCMake/ctest_start/AppendOldNoModel-stderr.txt
new file mode 100644
index 000000000..c7ca1e7d8
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendOldNoModel-stderr.txt
@@ -0,0 +1,3 @@
+^TAG file does not contain model and no model specified in start command
+CMake Error at .*/Tests/RunCMake/ctest_start/AppendOldNoModel/test.cmake:[0-9]+ \(ctest_start\):
+ ctest_start unknown error.$
diff --git a/Tests/RunCMake/ctest_start/AppendOldNoModel-stdout.txt b/Tests/RunCMake/ctest_start/AppendOldNoModel-stdout.txt
new file mode 100644
index 000000000..47331e637
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendOldNoModel-stdout.txt
@@ -0,0 +1,5 @@
+Run dashboard with to-be-determined model
+ Source directory: .*/Tests/RunCMake/ctest_start/AppendOldNoModel
+ Build directory: .*/Tests/RunCMake/ctest_start/AppendOldNoModel-build
+ Site: test-site
+ Build name: test-build-name
diff --git a/Tests/RunCMake/ctest_start/AppendSameModel-check.cmake b/Tests/RunCMake/ctest_start/AppendSameModel-check.cmake
new file mode 100644
index 000000000..d71b1cf01
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendSameModel-check.cmake
@@ -0,0 +1 @@
+check_tag_contents("^19551112-2204\nContinuousTrack\nContinuous\n$")
diff --git a/Tests/RunCMake/ctest_start/AppendSameModel-stdout.txt b/Tests/RunCMake/ctest_start/AppendSameModel-stdout.txt
new file mode 100644
index 000000000..3abd51e0f
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/AppendSameModel-stdout.txt
@@ -0,0 +1,7 @@
+Run dashboard with model Continuous
+ Source directory: .*/Tests/RunCMake/ctest_start/AppendSameModel
+ Build directory: .*/Tests/RunCMake/ctest_start/AppendSameModel-build
+ Site: test-site
+ Build name: test-build-name
+ Use existing tag: 19551112-2204 - ContinuousTrack
+ Use ContinuousTrack tag: [0-9-]+
diff --git a/Tests/RunCMake/ctest_start/FunctionScope-stdout.txt b/Tests/RunCMake/ctest_start/FunctionScope-stdout.txt
new file mode 100644
index 000000000..10f32932e
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/FunctionScope-stdout.txt
@@ -0,0 +1 @@
+^$
diff --git a/Tests/RunCMake/ctest_start/MissingTrackArg-result.txt b/Tests/RunCMake/ctest_start/MissingTrackArg-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/MissingTrackArg-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_start/MissingTrackArg-stderr.txt b/Tests/RunCMake/ctest_start/MissingTrackArg-stderr.txt
new file mode 100644
index 000000000..7b42bc9db
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/MissingTrackArg-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error at .*/Tests/RunCMake/ctest_start/MissingTrackArg/test\.cmake:[0-9]+ \(ctest_start\):
+ ctest_start TRACK argument missing track name$
diff --git a/Tests/RunCMake/ctest_start/MissingTrackArgAppend-result.txt b/Tests/RunCMake/ctest_start/MissingTrackArgAppend-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/MissingTrackArgAppend-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_start/MissingTrackArgAppend-stderr.txt b/Tests/RunCMake/ctest_start/MissingTrackArgAppend-stderr.txt
new file mode 100644
index 000000000..695bfad37
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/MissingTrackArgAppend-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error at .*/Tests/RunCMake/ctest_start/MissingTrackArgAppend/test\.cmake:[0-9]+ \(ctest_start\):
+ ctest_start TRACK argument missing track name$
diff --git a/Tests/RunCMake/ctest_start/MissingTrackArgQuiet-result.txt b/Tests/RunCMake/ctest_start/MissingTrackArgQuiet-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/MissingTrackArgQuiet-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_start/MissingTrackArgQuiet-stderr.txt b/Tests/RunCMake/ctest_start/MissingTrackArgQuiet-stderr.txt
new file mode 100644
index 000000000..943852206
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/MissingTrackArgQuiet-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error at .*/Tests/RunCMake/ctest_start/MissingTrackArgQuiet/test\.cmake:[0-9]+ \(ctest_start\):
+ ctest_start TRACK argument missing track name$
diff --git a/Tests/RunCMake/ctest_start/NoAppendDifferentTrack-stdout.txt b/Tests/RunCMake/ctest_start/NoAppendDifferentTrack-stdout.txt
new file mode 100644
index 000000000..20a29beb9
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/NoAppendDifferentTrack-stdout.txt
@@ -0,0 +1,7 @@
+Run dashboard with model Experimental
+ Source directory: .*/Tests/RunCMake/ctest_start/NoAppendDifferentTrack
+ Build directory: .*/Tests/RunCMake/ctest_start/NoAppendDifferentTrack-build
+ Track: ExperimentalDifferent
+ Site: test-site
+ Build name: test-build-name
+ Use ExperimentalDifferent tag: [0-9-]+
diff --git a/Tests/RunCMake/ctest_start/NoModel-result.txt b/Tests/RunCMake/ctest_start/NoModel-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/NoModel-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_start/NoModel-stderr.txt b/Tests/RunCMake/ctest_start/NoModel-stderr.txt
new file mode 100644
index 000000000..a516cf806
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/NoModel-stderr.txt
@@ -0,0 +1,3 @@
+^CMake Error at .*/Tests/RunCMake/ctest_start/NoModel/test\.cmake:[0-9]+ \(ctest_start\):
+ ctest_start no test model specified and APPEND not specified. Specify
+ either a test model or the APPEND argument$
diff --git a/Tests/RunCMake/ctest_start/TooManyArgs-result.txt b/Tests/RunCMake/ctest_start/TooManyArgs-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/TooManyArgs-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_start/TooManyArgs-stderr.txt b/Tests/RunCMake/ctest_start/TooManyArgs-stderr.txt
new file mode 100644
index 000000000..c1d5f2207
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/TooManyArgs-stderr.txt
@@ -0,0 +1,2 @@
+^CMake Error at .*/Tests/RunCMake/ctest_start/TooManyArgs/test\.cmake:[0-9]+ \(ctest_start\):
+ ctest_start Too many arguments$
diff --git a/Tests/RunCMake/ctest_start/WriteModelToTagContinuous-check.cmake b/Tests/RunCMake/ctest_start/WriteModelToTagContinuous-check.cmake
new file mode 100644
index 000000000..4e67bf555
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/WriteModelToTagContinuous-check.cmake
@@ -0,0 +1 @@
+check_tag_contents("^[0-9-]+\nContinuous\nContinuous\n$")
diff --git a/Tests/RunCMake/ctest_start/WriteModelToTagExperimental-check.cmake b/Tests/RunCMake/ctest_start/WriteModelToTagExperimental-check.cmake
new file mode 100644
index 000000000..b5bf2cfa4
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/WriteModelToTagExperimental-check.cmake
@@ -0,0 +1 @@
+check_tag_contents("^[0-9-]+\nExperimental\nExperimental\n$")
diff --git a/Tests/RunCMake/ctest_start/WriteModelToTagNightly-check.cmake b/Tests/RunCMake/ctest_start/WriteModelToTagNightly-check.cmake
new file mode 100644
index 000000000..35d056654
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/WriteModelToTagNightly-check.cmake
@@ -0,0 +1 @@
+check_tag_contents("^[0-9-]+\nNightly\nNightly\n$")
diff --git a/Tests/RunCMake/ctest_start/WriteModelToTagNoMatchingTrack-check.cmake b/Tests/RunCMake/ctest_start/WriteModelToTagNoMatchingTrack-check.cmake
new file mode 100644
index 000000000..bd2862deb
--- /dev/null
+++ b/Tests/RunCMake/ctest_start/WriteModelToTagNoMatchingTrack-check.cmake
@@ -0,0 +1 @@
+check_tag_contents("^[0-9-]+\nSomeWeirdTrackName\nContinuous\n$")
diff --git a/Tests/RunCMake/ctest_submit/CDashSubmitVerbose-result.txt b/Tests/RunCMake/ctest_submit/CDashSubmitVerbose-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/CDashSubmitVerbose-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_submit/CDashSubmitVerbose-stderr.txt b/Tests/RunCMake/ctest_submit/CDashSubmitVerbose-stderr.txt
new file mode 100644
index 000000000..a8f10b558
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/CDashSubmitVerbose-stderr.txt
@@ -0,0 +1 @@
+ *Error message was: ([Cc]ould *n.t resolve host:? '?-no-site-'?.*|The requested URL returned error:.*)
diff --git a/Tests/RunCMake/ctest_submit/CDashSubmitVerbose-stdout.txt b/Tests/RunCMake/ctest_submit/CDashSubmitVerbose-stdout.txt
new file mode 100644
index 000000000..11a4edf1a
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/CDashSubmitVerbose-stdout.txt
@@ -0,0 +1 @@
+Upload file: .* to http:\/\/-no-site-\?FileName=test-site___test-build-name___.*-Experimental___XML___Configure.xml&build=test-build-name&site=test-site&stamp=.*-Experimental&subproject=mysubproj&MD5=.* Size: .*
diff --git a/Tests/RunCMake/ctest_submit/FILESNoBuildId-result.txt b/Tests/RunCMake/ctest_submit/FILESNoBuildId-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/FILESNoBuildId-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_submit/FILESNoBuildId-stderr.txt b/Tests/RunCMake/ctest_submit/FILESNoBuildId-stderr.txt
new file mode 100644
index 000000000..a8f10b558
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/FILESNoBuildId-stderr.txt
@@ -0,0 +1 @@
+ *Error message was: ([Cc]ould *n.t resolve host:? '?-no-site-'?.*|The requested URL returned error:.*)
diff --git a/Tests/RunCMake/ctest_submit/FILESNoBuildId-stdout.txt b/Tests/RunCMake/ctest_submit/FILESNoBuildId-stdout.txt
new file mode 100644
index 000000000..929b2549c
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/FILESNoBuildId-stdout.txt
@@ -0,0 +1 @@
+Upload file: .* to http:\/\/-no-site-\?FileName=test-site___test-build-name___.*-Experimental___XML___RunCMakeTest.cmake&MD5=.* Size: .*
diff --git a/Tests/RunCMake/ctest_submit/PARTSDone-result.txt b/Tests/RunCMake/ctest_submit/PARTSDone-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/PARTSDone-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_submit/PARTSDone-stderr.txt b/Tests/RunCMake/ctest_submit/PARTSDone-stderr.txt
new file mode 100644
index 000000000..0020a0fe3
--- /dev/null
+++ b/Tests/RunCMake/ctest_submit/PARTSDone-stderr.txt
@@ -0,0 +1,3 @@
+ *Error when uploading file: .*/Done.xml
+ *Error message was: ([Cc]ould *n.t resolve host:? '?-no-site-'?.*|The requested URL returned error:.*)
+ *Problems when submitting via HTTP
diff --git a/Tests/RunCMake/ctest_test/CTestTestLoadWait-stdout.txt b/Tests/RunCMake/ctest_test/CTestTestLoadWait-stdout.txt
new file mode 100644
index 000000000..2af3838ed
--- /dev/null
+++ b/Tests/RunCMake/ctest_test/CTestTestLoadWait-stdout.txt
@@ -0,0 +1,8 @@
+Test project .*/Tests/RunCMake/ctest_test/CTestTestLoadWait-build
+\*\*\*\*\* WAITING, System Load: 5, Max Allowed Load: 4, Smallest test RunCMakeVersion requires 1\*\*\*\*\*
+ Start 1: RunCMakeVersion
+1/1 Test #1: RunCMakeVersion .................. Passed +[0-9.]+ sec
++
+100% tests passed, 0 tests failed out of 1
++
+Total Test time \(real\) = +[0-9.]+ sec$
diff --git a/Tests/RunCMake/ctest_test/TestLoadWait-stdout.txt b/Tests/RunCMake/ctest_test/TestLoadWait-stdout.txt
new file mode 100644
index 000000000..07f4ed361
--- /dev/null
+++ b/Tests/RunCMake/ctest_test/TestLoadWait-stdout.txt
@@ -0,0 +1,8 @@
+Test project .*/Tests/RunCMake/ctest_test/TestLoadWait-build
+\*\*\*\*\* WAITING, System Load: 5, Max Allowed Load: 2, Smallest test RunCMakeVersion requires 1\*\*\*\*\*
+ Start 1: RunCMakeVersion
+1/1 Test #1: RunCMakeVersion .................. Passed +[0-9.]+ sec
++
+100% tests passed, 0 tests failed out of 1
++
+Total Test time \(real\) = +[0-9.]+ sec$
diff --git a/Tests/RunCMake/ctest_update/CMakeLists.txt.in b/Tests/RunCMake/ctest_update/CMakeLists.txt.in
new file mode 100644
index 000000000..ecf0e54ea
--- /dev/null
+++ b/Tests/RunCMake/ctest_update/CMakeLists.txt.in
@@ -0,0 +1,4 @@
+cmake_minimum_required(VERSION 3.1)
+project(CTestTest@CASE_NAME@ NONE)
+include(CTest)
+@CASE_CMAKELISTS_SUFFIX_CODE@
diff --git a/Tests/RunCMake/ctest_update/RunCMakeTest.cmake b/Tests/RunCMake/ctest_update/RunCMakeTest.cmake
new file mode 100644
index 000000000..f8d7665ab
--- /dev/null
+++ b/Tests/RunCMake/ctest_update/RunCMakeTest.cmake
@@ -0,0 +1,25 @@
+include(RunCTest)
+set(CASE_CTEST_UPDATE_ARGS "")
+function(run_ctest_update CASE_NAME)
+ set(CASE_CTEST_UPDATE_ARGS "${ARGN}")
+ run_ctest(${CASE_NAME})
+endfunction()
+
+run_ctest_update(UpdateQuiet QUIET)
+
+function(run_UpdateChangeId)
+ set(CASE_TEST_PREFIX_CODE [[
+ set(CTEST_CHANGE_ID "<>1")
+ ]])
+
+ run_ctest(UpdateChangeId)
+endfunction()
+run_UpdateChangeId()
+
+function(run_UpdateVersionOverride)
+ set(CASE_TEST_PREFIX_CODE [[
+ set(CTEST_UPDATE_VERSION_OVERRIDE "qwertyuiop")
+ ]])
+ run_ctest(UpdateVersionOverride)
+endfunction()
+run_UpdateVersionOverride()
diff --git a/Tests/RunCMake/ctest_update/UpdateActualVersion-check.cmake b/Tests/RunCMake/ctest_update/UpdateActualVersion-check.cmake
new file mode 100644
index 000000000..12bd5a00d
--- /dev/null
+++ b/Tests/RunCMake/ctest_update/UpdateActualVersion-check.cmake
@@ -0,0 +1,12 @@
+file(GLOB update_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Update.xml")
+if(update_xml_file)
+ file(READ "${update_xml_file}" update_xml LIMIT 4096)
+ if(NOT update_xml MATCHES "qwertyuiop")
+ string(REPLACE "\n" "\n " update_xml " ${update_xml}")
+ set(RunCMake_TEST_FAILED
+ "Did not find 'qwertyuiop' in Update.xml:\n${update_xml}"
+ )
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "Update.xml not found")
+endif()
diff --git a/Tests/RunCMake/ctest_update/UpdateChangeId-check.cmake b/Tests/RunCMake/ctest_update/UpdateChangeId-check.cmake
new file mode 100644
index 000000000..382fbec6a
--- /dev/null
+++ b/Tests/RunCMake/ctest_update/UpdateChangeId-check.cmake
@@ -0,0 +1,12 @@
+file(GLOB update_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Update.xml")
+if(update_xml_file)
+ file(READ "${update_xml_file}" update_xml LIMIT 4096)
+ if(NOT update_xml MATCHES [[ChangeId>&lt;&gt;1]])
+ string(REPLACE "\n" "\n " update_xml " ${update_xml}")
+ set(RunCMake_TEST_FAILED
+ "Update.xml does not have expected ChangeId:\n${update_xml}"
+ )
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "Update.xml not found")
+endif()
diff --git a/Tests/RunCMake/ctest_update/test.cmake.in b/Tests/RunCMake/ctest_update/test.cmake.in
new file mode 100644
index 000000000..25b842324
--- /dev/null
+++ b/Tests/RunCMake/ctest_update/test.cmake.in
@@ -0,0 +1,18 @@
+cmake_minimum_required(VERSION 3.1)
+@CASE_TEST_PREFIX_CODE@
+
+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}")
+
+# FIXME: update test to do someting meaningful with this.
+set(CTEST_UPDATE_COMMAND "not-actually-used")
+
+set(ctest_test_args "@CASE_CTEST_UPDATE_ARGS@")
+ctest_start(Experimental)
+ctest_update(${ctest_update_args})
diff --git a/Tests/RunCMake/execute_process/EchoCommand-result.txt b/Tests/RunCMake/execute_process/EchoCommand-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EchoCommand-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/execute_process/EchoCommand-stderr.txt b/Tests/RunCMake/execute_process/EchoCommand-stderr.txt
new file mode 100644
index 000000000..f10ece8c4
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EchoCommand-stderr.txt
@@ -0,0 +1,5 @@
+.*cmake.*-E' 'echo' '-- 2 COMMAND_ECHO STDERR'
+.*cmake.*-E' 'echo' '-- 4 COMMAND_ECHO STDERR'
+.*cmake.*-E' 'echo' '-- 8 COMMAND_ECHO STDOUT COMMAND_ECHO STDERR'
+CMake Error at .*EchoCommand.cmake:.* \(execute_process\):
+ CMAKE_EXECUTE_PROCESS_COMMAND_ECHO set to 'BAD' expected STDERR|STDOUT|NONE$
diff --git a/Tests/RunCMake/execute_process/EchoCommand-stdout.txt b/Tests/RunCMake/execute_process/EchoCommand-stdout.txt
new file mode 100644
index 000000000..0954b3b3d
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EchoCommand-stdout.txt
@@ -0,0 +1,12 @@
+.*cmake.*-E' 'echo' '-- 1 COMMAND_ECHO STDOUT'
+-- 1 COMMAND_ECHO STDOUT
+-- 2 COMMAND_ECHO STDERR
+.*cmake.* '-E' 'echo' '-- 3 COMMAND_ECHO STDOUT'
+-- 3 COMMAND_ECHO STDOUT
+-- 4 COMMAND_ECHO STDERR
+.*cmake.* '-E' 'echo' '-- 5 COMMAND_ECHO STDOUT'
+-- 5 COMMAND_ECHO STDOUT
+-- 6 COMMAND_ECHO NONE
+.*cmake.* '-E' 'echo' '-- 7 COMMAND_ECHO STDERR COMMAND_ECHO STDOUT'
+-- 7 COMMAND_ECHO STDERR COMMAND_ECHO STDOUT
+-- 8 COMMAND_ECHO STDOUT COMMAND_ECHO STDERR$
diff --git a/Tests/RunCMake/execute_process/EchoCommand.cmake b/Tests/RunCMake/execute_process/EchoCommand.cmake
new file mode 100644
index 000000000..9c7d13db6
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EchoCommand.cmake
@@ -0,0 +1,41 @@
+if(CHECK_ERROR_OUTPUT_LOCATION)
+ execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 1 COMMAND_ECHO " COMMAND_ECHO )
+endif()
+# test COMMAND_ECHO STDOUT
+execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 1 COMMAND_ECHO STDOUT" COMMAND_ECHO STDOUT )
+# test COMMAND_ECHO STDERR
+execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 2 COMMAND_ECHO STDERR" COMMAND_ECHO STDERR )
+# test CMAKE_EXECUTE_PROCESS_COMMAND_ECHO STDOUT
+set(CMAKE_EXECUTE_PROCESS_COMMAND_ECHO STDOUT)
+execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 3 COMMAND_ECHO STDOUT" )
+# test CMAKE_EXECUTE_PROCESS_COMMAND_ECHO STDERR
+set(CMAKE_EXECUTE_PROCESS_COMMAND_ECHO STDERR)
+execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 4 COMMAND_ECHO STDERR" )
+# make sure local will override global settings
+execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 5 COMMAND_ECHO STDOUT" COMMAND_ECHO STDOUT )
+execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 6 COMMAND_ECHO NONE" COMMAND_ECHO NONE)
+# test both and make sure override works
+execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 7 COMMAND_ECHO STDERR COMMAND_ECHO STDOUT" COMMAND_ECHO STDERR
+ COMMAND_ECHO STDOUT)
+execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 8 COMMAND_ECHO STDOUT COMMAND_ECHO STDERR" COMMAND_ECHO STDOUT
+ COMMAND_ECHO STDERR)
+
+# check for bad arguments to global and local
+if(CHECK_GLOBAL)
+ # make sure a non STDERR or STDOUT value is an error
+ set(CMAKE_EXECUTE_PROCESS_COMMAND_ECHO BAD)
+ execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 9 - 1 CMAKE_EXECUTE_PROCESS_COMMAND_ECHO BAD" )
+else()
+ execute_process(COMMAND ${CMAKE_COMMAND} -E echo
+ "-- 9 - 2 COMMAND_ECHO BAD" COMMAND_ECHO BAD)
+endif()
diff --git a/Tests/RunCMake/execute_process/EchoCommand2-result.txt b/Tests/RunCMake/execute_process/EchoCommand2-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EchoCommand2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/execute_process/EchoCommand2-stderr.txt b/Tests/RunCMake/execute_process/EchoCommand2-stderr.txt
new file mode 100644
index 000000000..4ae01c4fb
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EchoCommand2-stderr.txt
@@ -0,0 +1,5 @@
+.*cmake.*-E' 'echo' '-- 2 COMMAND_ECHO STDERR'
+.*cmake.*-E' 'echo' '-- 4 COMMAND_ECHO STDERR'
+.*cmake.*-E' 'echo' '-- 8 COMMAND_ECHO STDOUT COMMAND_ECHO STDERR'
+CMake Error at .*EchoCommand.cmake:.* \(execute_process\):
+ called with 'BAD' expected STDERR|STDOUT|NONE for COMMAND_ECHO.$
diff --git a/Tests/RunCMake/execute_process/EchoCommand2-stdout.txt b/Tests/RunCMake/execute_process/EchoCommand2-stdout.txt
new file mode 100644
index 000000000..0954b3b3d
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EchoCommand2-stdout.txt
@@ -0,0 +1,12 @@
+.*cmake.*-E' 'echo' '-- 1 COMMAND_ECHO STDOUT'
+-- 1 COMMAND_ECHO STDOUT
+-- 2 COMMAND_ECHO STDERR
+.*cmake.* '-E' 'echo' '-- 3 COMMAND_ECHO STDOUT'
+-- 3 COMMAND_ECHO STDOUT
+-- 4 COMMAND_ECHO STDERR
+.*cmake.* '-E' 'echo' '-- 5 COMMAND_ECHO STDOUT'
+-- 5 COMMAND_ECHO STDOUT
+-- 6 COMMAND_ECHO NONE
+.*cmake.* '-E' 'echo' '-- 7 COMMAND_ECHO STDERR COMMAND_ECHO STDOUT'
+-- 7 COMMAND_ECHO STDERR COMMAND_ECHO STDOUT
+-- 8 COMMAND_ECHO STDOUT COMMAND_ECHO STDERR$
diff --git a/Tests/RunCMake/execute_process/EchoCommand3-result.txt b/Tests/RunCMake/execute_process/EchoCommand3-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EchoCommand3-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/execute_process/EchoCommand3-stderr.txt b/Tests/RunCMake/execute_process/EchoCommand3-stderr.txt
new file mode 100644
index 000000000..e27f1e6d2
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EchoCommand3-stderr.txt
@@ -0,0 +1,2 @@
+CMake Error at .*EchoCommand.cmake:.*\(execute_process\):
+ execute_process called with no value for COMMAND_ECHO.
diff --git a/Tests/RunCMake/execute_process/EncodingUTF-8-stderr.txt b/Tests/RunCMake/execute_process/EncodingUTF-8-stderr.txt
new file mode 100644
index 000000000..0ac68de83
--- /dev/null
+++ b/Tests/RunCMake/execute_process/EncodingUTF-8-stderr.txt
@@ -0,0 +1 @@
+यूनिकोड είναι very здорово!
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/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/export/Empty.cmake b/Tests/RunCMake/export/Empty.cmake
new file mode 100644
index 000000000..2198ddf75
--- /dev/null
+++ b/Tests/RunCMake/export/Empty.cmake
@@ -0,0 +1 @@
+export(TARGETS FILE targets.cmake)
diff --git a/Tests/RunCMake/export/ExportPropertiesUndefined.cmake b/Tests/RunCMake/export/ExportPropertiesUndefined.cmake
new file mode 100644
index 000000000..aa529f29a
--- /dev/null
+++ b/Tests/RunCMake/export/ExportPropertiesUndefined.cmake
@@ -0,0 +1,11 @@
+enable_language(CXX)
+add_library(foo empty.cpp)
+set_target_properties(foo PROPERTIES
+ EXPORT_PROPERTIES "NotDefinedProp"
+)
+export(TARGETS foo FILE "${CMAKE_CURRENT_BINARY_DIR}/foo.cmake")
+install(TARGETS foo EXPORT fooExport
+ RUNTIME DESTINATION bin
+ LIBRARY DESTINATION lib
+ ARCHIVE DESTINATION lib
+)
diff --git a/Tests/RunCMake/export/ForbiddenToExportImportedProperties-result.txt b/Tests/RunCMake/export/ForbiddenToExportImportedProperties-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/export/ForbiddenToExportImportedProperties-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/export/ForbiddenToExportImportedProperties-stderr.txt b/Tests/RunCMake/export/ForbiddenToExportImportedProperties-stderr.txt
new file mode 100644
index 000000000..ab0394316
--- /dev/null
+++ b/Tests/RunCMake/export/ForbiddenToExportImportedProperties-stderr.txt
@@ -0,0 +1,3 @@
+CMake Error in CMakeLists.txt:
+ Target \"foo\" contains property \"IMPORTED_FOOBAR\" in EXPORT_PROPERTIES but
+ IMPORTED_\* and INTERFACE_\* properties are reserved.
diff --git a/Tests/RunCMake/export/ForbiddenToExportImportedProperties.cmake b/Tests/RunCMake/export/ForbiddenToExportImportedProperties.cmake
new file mode 100644
index 000000000..9c8653d8d
--- /dev/null
+++ b/Tests/RunCMake/export/ForbiddenToExportImportedProperties.cmake
@@ -0,0 +1,12 @@
+enable_language(CXX)
+add_library(foo empty.cpp)
+set_target_properties(foo PROPERTIES
+ IMPORTED_FOOBAR "Some other string"
+ EXPORT_PROPERTIES "IMPORTED_FOOBAR"
+)
+export(TARGETS foo FILE "${CMAKE_CURRENT_BINARY_DIR}/foo.cmake")
+install(TARGETS foo EXPORT fooExport
+ RUNTIME DESTINATION bin
+ LIBRARY DESTINATION lib
+ ARCHIVE DESTINATION lib
+)
diff --git a/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-result.txt b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-stderr.txt b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-stderr.txt
new file mode 100644
index 000000000..577602b33
--- /dev/null
+++ b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties-stderr.txt
@@ -0,0 +1,3 @@
+CMake Error in CMakeLists.txt:
+ Target \"foo\" contains property \"INTERFACE_FOOBAR\" in EXPORT_PROPERTIES but
+ IMPORTED_\* and INTERFACE_\* properties are reserved.
diff --git a/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties.cmake b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties.cmake
new file mode 100644
index 000000000..bab8de0f3
--- /dev/null
+++ b/Tests/RunCMake/export/ForbiddenToExportInterfaceProperties.cmake
@@ -0,0 +1,12 @@
+enable_language(CXX)
+add_library(foo empty.cpp)
+set_target_properties(foo PROPERTIES
+ INTERFACE_FOOBAR "Some string"
+ EXPORT_PROPERTIES "INTERFACE_FOOBAR"
+)
+export(TARGETS foo FILE "${CMAKE_CURRENT_BINARY_DIR}/foo.cmake")
+install(TARGETS foo EXPORT fooExport
+ RUNTIME DESTINATION bin
+ LIBRARY DESTINATION lib
+ ARCHIVE DESTINATION lib
+)
diff --git a/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-result.txt b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-stderr.txt b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-stderr.txt
new file mode 100644
index 000000000..56488e69e
--- /dev/null
+++ b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp-stderr.txt
@@ -0,0 +1,3 @@
+CMake Error in CMakeLists.txt:
+ Target \"foo\" contains property \"JUST_A_PROPERTY\" in EXPORT_PROPERTIES but
+ this property contains a generator expression. This is not allowed.
diff --git a/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp.cmake b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp.cmake
new file mode 100644
index 000000000..065cdbcdb
--- /dev/null
+++ b/Tests/RunCMake/export/ForbiddenToExportPropertyWithGenExp.cmake
@@ -0,0 +1,12 @@
+enable_language(CXX)
+add_library(foo empty.cpp)
+set_target_properties(foo PROPERTIES
+ JUST_A_PROPERTY "$<C_COMPILER_VERSION:0>"
+ EXPORT_PROPERTIES "JUST_A_PROPERTY"
+)
+export(TARGETS foo FILE "${CMAKE_CURRENT_BINARY_DIR}/foo.cmake")
+install(TARGETS foo EXPORT fooExport
+ RUNTIME DESTINATION bin
+ LIBRARY DESTINATION lib
+ ARCHIVE DESTINATION lib
+)
diff --git a/Tests/RunCMake/export/empty.cpp b/Tests/RunCMake/export/empty.cpp
new file mode 100644
index 000000000..11ec041d1
--- /dev/null
+++ b/Tests/RunCMake/export/empty.cpp
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int empty()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/file/CREATE_LINK-COPY_ON_ERROR.cmake b/Tests/RunCMake/file/CREATE_LINK-COPY_ON_ERROR.cmake
new file mode 100644
index 000000000..777ef4e6c
--- /dev/null
+++ b/Tests/RunCMake/file/CREATE_LINK-COPY_ON_ERROR.cmake
@@ -0,0 +1,11 @@
+# Use COPY_ON_ERROR to handle the case where the source and destination
+# directory are on different devices. Cross-device links are not permitted
+# and the following command falls back to copying the file if link fails.
+file(CREATE_LINK
+ ${CMAKE_CURRENT_LIST_FILE} TestCreateLink.cmake
+ RESULT result
+ COPY_ON_ERROR
+ )
+if(NOT result STREQUAL "0")
+ message(SEND_ERROR "COPY_ON_ERROR failed: '${result}'")
+endif()
diff --git a/Tests/RunCMake/file/CREATE_LINK-SYMBOLIC-noexist.cmake b/Tests/RunCMake/file/CREATE_LINK-SYMBOLIC-noexist.cmake
new file mode 100644
index 000000000..61aaf388f
--- /dev/null
+++ b/Tests/RunCMake/file/CREATE_LINK-SYMBOLIC-noexist.cmake
@@ -0,0 +1,4 @@
+file(CREATE_LINK does_not_exist.txt TestSymLink.txt RESULT sym_result SYMBOLIC)
+if(NOT sym_result STREQUAL "0")
+ message("Symlink fail: ${sym_result}")
+endif()
diff --git a/Tests/RunCMake/file/CREATE_LINK-SYMBOLIC.cmake b/Tests/RunCMake/file/CREATE_LINK-SYMBOLIC.cmake
new file mode 100644
index 000000000..77b899cff
--- /dev/null
+++ b/Tests/RunCMake/file/CREATE_LINK-SYMBOLIC.cmake
@@ -0,0 +1,4 @@
+file(CREATE_LINK ${CMAKE_CURRENT_LIST_FILE} TestSymLink.cmake RESULT sym_result SYMBOLIC)
+if(NOT sym_result STREQUAL "0")
+ message(SEND_ERROR "Symlink result='${sym_result}'")
+endif()
diff --git a/Tests/RunCMake/file/CREATE_LINK-noarg-result.txt b/Tests/RunCMake/file/CREATE_LINK-noarg-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/CREATE_LINK-noarg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/CREATE_LINK-noarg-stderr.txt b/Tests/RunCMake/file/CREATE_LINK-noarg-stderr.txt
new file mode 100644
index 000000000..12494f845
--- /dev/null
+++ b/Tests/RunCMake/file/CREATE_LINK-noarg-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at CREATE_LINK-noarg\.cmake:[0-9]+ \(file\):
+ file CREATE_LINK must be called with at least two additional arguments
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/file/CREATE_LINK-noarg.cmake b/Tests/RunCMake/file/CREATE_LINK-noarg.cmake
new file mode 100644
index 000000000..65002fa77
--- /dev/null
+++ b/Tests/RunCMake/file/CREATE_LINK-noarg.cmake
@@ -0,0 +1 @@
+file(CREATE_LINK ${CMAKE_CURRENT_LIST_FILE})
diff --git a/Tests/RunCMake/file/CREATE_LINK-noexist-stderr.txt b/Tests/RunCMake/file/CREATE_LINK-noexist-stderr.txt
new file mode 100644
index 000000000..97eee4fef
--- /dev/null
+++ b/Tests/RunCMake/file/CREATE_LINK-noexist-stderr.txt
@@ -0,0 +1 @@
+Hard link error: Cannot hard link 'does_not_exist.txt' as it does not exist.
diff --git a/Tests/RunCMake/file/CREATE_LINK-noexist.cmake b/Tests/RunCMake/file/CREATE_LINK-noexist.cmake
new file mode 100644
index 000000000..5ee258017
--- /dev/null
+++ b/Tests/RunCMake/file/CREATE_LINK-noexist.cmake
@@ -0,0 +1,4 @@
+file(CREATE_LINK does_not_exist.txt TestLink.txt RESULT result)
+if(NOT result STREQUAL "0")
+ message("Hard link error: ${result}")
+endif()
diff --git a/Tests/RunCMake/file/CREATE_LINK.cmake b/Tests/RunCMake/file/CREATE_LINK.cmake
new file mode 100644
index 000000000..ca616468a
--- /dev/null
+++ b/Tests/RunCMake/file/CREATE_LINK.cmake
@@ -0,0 +1,11 @@
+# start with a file in the same directory to avoid cross-device links
+set(test_file ${CMAKE_CURRENT_BINARY_DIR}/CreateLinkTest.txt)
+file(TOUCH ${test_file})
+
+file(CREATE_LINK
+ ${test_file} ${CMAKE_CURRENT_BINARY_DIR}/TestCreateLink.txt
+ RESULT result
+ )
+if(NOT result STREQUAL "0")
+ message(SEND_ERROR "Hard link result='${result}'")
+endif()
diff --git a/Tests/RunCMake/file/DOWNLOAD-netrc-bad-result.txt b/Tests/RunCMake/file/DOWNLOAD-netrc-bad-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-netrc-bad-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/DOWNLOAD-netrc-bad-stderr.txt b/Tests/RunCMake/file/DOWNLOAD-netrc-bad-stderr.txt
new file mode 100644
index 000000000..96ce62ad0
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-netrc-bad-stderr.txt
@@ -0,0 +1,19 @@
+^CMake Error at DOWNLOAD-netrc-bad\.cmake:[0-9]+ \(file\):
+ file DOWNLOAD missing level value for NETRC\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
++
+CMake Error at DOWNLOAD-netrc-bad\.cmake:[0-9]+ \(file\):
+ file DOWNLOAD missing file value for NETRC_FILE\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
++
+CMake Error at DOWNLOAD-netrc-bad\.cmake:[0-9]+ \(file\):
+ file NETRC accepts OPTIONAL, IGNORED or REQUIRED but got: INVALID
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
++
+CMake Error at DOWNLOAD-netrc-bad\.cmake:[0-9]+ \(file\):
+ file NETRC accepts OPTIONAL, IGNORED or REQUIRED but got: FALSE
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/DOWNLOAD-netrc-bad.cmake b/Tests/RunCMake/file/DOWNLOAD-netrc-bad.cmake
new file mode 100644
index 000000000..6a62df94e
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-netrc-bad.cmake
@@ -0,0 +1,15 @@
+if(NOT "${CMAKE_CURRENT_SOURCE_DIR}" MATCHES "^/")
+ set(slash /)
+endif()
+file(DOWNLOAD "" "" NETRC)
+file(DOWNLOAD "" "" NETRC_FILE)
+set(CMAKE_NETRC FALSE)
+file(DOWNLOAD
+ "file://${slash}${CMAKE_CURRENT_SOURCE_DIR}/DOWNLOAD-netrc-bad.txt"
+ "${CMAKE_CURRENT_BINARY_DIR}/netrc-bad.txt"
+ NETRC INVALID
+ )
+file(DOWNLOAD
+ "file://${slash}${CMAKE_CURRENT_SOURCE_DIR}/DOWNLOAD-netrc-bad.txt"
+ "${CMAKE_CURRENT_BINARY_DIR}/netrc-bad.txt"
+ )
diff --git a/Tests/RunCMake/file/DOWNLOAD-netrc-bad.txt b/Tests/RunCMake/file/DOWNLOAD-netrc-bad.txt
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/file/DOWNLOAD-netrc-bad.txt
diff --git a/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-build-stdout.txt b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-build-stdout.txt
new file mode 100644
index 000000000..71ab721d7
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-build-stdout.txt
@@ -0,0 +1 @@
+.*b9fbdd8803c036dbe9f5ea6b74db4b9670c78a72
diff --git a/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_first-stdout.txt b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_first-stdout.txt
new file mode 100644
index 000000000..ff90f9c1d
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_first-stdout.txt
@@ -0,0 +1,2 @@
+.*Running CMake on GLOB-CONFIGURE_DEPENDS-RerunCMake
+.*6bc141b40c0f851d20fa9a1fe5fbdae94acc5de0
diff --git a/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_second-stdout.txt b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_second-stdout.txt
new file mode 100644
index 000000000..cf2a5afe6
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-rebuild_second-stdout.txt
@@ -0,0 +1,2 @@
+.*Running CMake on GLOB-CONFIGURE_DEPENDS-RerunCMake
+.*0c3ceab9daa7914fde7410c34cae4049e140aa51
diff --git a/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-stdout.txt b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-stdout.txt
new file mode 100644
index 000000000..66b6c449a
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake-stdout.txt
@@ -0,0 +1 @@
+.*Running CMake on GLOB-CONFIGURE_DEPENDS-RerunCMake
diff --git a/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake.cmake b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake.cmake
new file mode 100644
index 000000000..fe87c7849
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-CONFIGURE_DEPENDS-RerunCMake.cmake
@@ -0,0 +1,10 @@
+message(STATUS "Running CMake on GLOB-CONFIGURE_DEPENDS-RerunCMake")
+file(GLOB_RECURSE
+ CONTENT_LIST
+ CONFIGURE_DEPENDS
+ LIST_DIRECTORIES false
+ RELATIVE "${CMAKE_CURRENT_BINARY_DIR}"
+ "${CMAKE_CURRENT_BINARY_DIR}/test/*"
+ )
+string(SHA1 CONTENT_LIST_HASH "${CONTENT_LIST}")
+add_custom_target(CONTENT_ECHO ALL ${CMAKE_COMMAND} -E echo ${CONTENT_LIST_HASH})
diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-result.txt b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-stderr.txt b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-stderr.txt
new file mode 100644
index 000000000..40083c129
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE-stderr.txt
@@ -0,0 +1 @@
+.*CONFIGURE_DEPENDS is invalid for script and find package modes\.
diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE.cmake b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE.cmake
new file mode 100644
index 000000000..9dc0f0393
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-SCRIPT_MODE.cmake
@@ -0,0 +1 @@
+file(GLOB CONTENT_LIST CONFIGURE_DEPENDS)
diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-result.txt b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-stderr.txt b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-stderr.txt
new file mode 100644
index 000000000..d7b36eb67
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified-stderr.txt
@@ -0,0 +1,7 @@
+^CMake Error: The glob expression
+.* at GLOB-error-CONFIGURE_DEPENDS-modified\.cmake:[0-9]+ \(file\)
+was already present in the glob cache but the directory
+contents have changed during the configuration run.
+Matching glob expressions:
+ CONTENT_LIST_1 at GLOB-error-CONFIGURE_DEPENDS-modified\.cmake:[0-9]+ \(file\)
+ CONTENT_LIST_2 at GLOB-error-CONFIGURE_DEPENDS-modified\.cmake:[0-9]+ \(file\)$
diff --git a/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified.cmake b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified.cmake
new file mode 100644
index 000000000..8d74deac6
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-error-CONFIGURE_DEPENDS-modified.cmake
@@ -0,0 +1,21 @@
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/first")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/second")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/third")
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/first/one" "one")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/second/two" "two")
+file(GLOB_RECURSE CONTENT_LIST_1
+ CONFIGURE_DEPENDS
+ "${CMAKE_CURRENT_BINARY_DIR}/test/*"
+ )
+
+file(GLOB_RECURSE CONTENT_LIST_2
+ CONFIGURE_DEPENDS
+ "${CMAKE_CURRENT_BINARY_DIR}/test/*"
+ )
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/third/three" "three")
+file(GLOB_RECURSE CONTENT_LIST_3
+ CONFIGURE_DEPENDS
+ "${CMAKE_CURRENT_BINARY_DIR}/test/*"
+ )
diff --git a/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-result.txt b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-stderr.txt b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-stderr.txt
new file mode 100644
index 000000000..30cec899b
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at GLOB-error-RELATIVE-no-arg\.cmake:[0-9]+ \(file\):
+ file GLOB requires a directory after the RELATIVE tag\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg.cmake b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg.cmake
new file mode 100644
index 000000000..a55588126
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-error-RELATIVE-no-arg.cmake
@@ -0,0 +1 @@
+file(GLOB CONTENT_LIST RELATIVE)
diff --git a/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-result.txt b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-stderr.txt b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-stderr.txt
new file mode 100644
index 000000000..01d204f2b
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at GLOB-noexp-CONFIGURE_DEPENDS\.cmake:[0-9]+ \(file\):
+ file GLOB requires a glob expression after CONFIGURE_DEPENDS\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS.cmake b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS.cmake
new file mode 100644
index 000000000..9dc0f0393
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-noexp-CONFIGURE_DEPENDS.cmake
@@ -0,0 +1 @@
+file(GLOB CONTENT_LIST CONFIGURE_DEPENDS)
diff --git a/Tests/RunCMake/file/GLOB-noexp-FOLLOW_SYMLINKS.cmake b/Tests/RunCMake/file/GLOB-noexp-FOLLOW_SYMLINKS.cmake
new file mode 100644
index 000000000..6d467a0c6
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-noexp-FOLLOW_SYMLINKS.cmake
@@ -0,0 +1 @@
+file(GLOB CONTENT_LIST FOLLOW_SYMLINKS)
diff --git a/Tests/RunCMake/file/GLOB-noexp-RELATIVE-result.txt b/Tests/RunCMake/file/GLOB-noexp-RELATIVE-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-noexp-RELATIVE-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/GLOB-noexp-RELATIVE-stderr.txt b/Tests/RunCMake/file/GLOB-noexp-RELATIVE-stderr.txt
new file mode 100644
index 000000000..9c666312d
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-noexp-RELATIVE-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at GLOB-noexp-RELATIVE\.cmake:[0-9]+ \(file\):
+ file GLOB requires a glob expression after the directory\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/GLOB-noexp-RELATIVE.cmake b/Tests/RunCMake/file/GLOB-noexp-RELATIVE.cmake
new file mode 100644
index 000000000..7b2d40420
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-noexp-RELATIVE.cmake
@@ -0,0 +1 @@
+file(GLOB CONTENT_LIST RELATIVE "${CMAKE_CURRENT_BINARY_DIR}")
diff --git a/Tests/RunCMake/file/GLOB-sort-dedup-stderr.txt b/Tests/RunCMake/file/GLOB-sort-dedup-stderr.txt
new file mode 100644
index 000000000..d2565e4a9
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-sort-dedup-stderr.txt
@@ -0,0 +1,2 @@
+content: 7[ ]
+1aAb/\.hide;1aAb/1\.log;1aAb/1\.txt;1aAb/xkcd\.txt;a/1\.log;a/1\.txt;a/boot\.ini
diff --git a/Tests/RunCMake/file/GLOB-sort-dedup.cmake b/Tests/RunCMake/file/GLOB-sort-dedup.cmake
new file mode 100644
index 000000000..1e1c5797f
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-sort-dedup.cmake
@@ -0,0 +1,21 @@
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/a")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/1aAb")
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/a/1.log" "")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/a/1.txt" "")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/a/boot.ini" "")
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/1aAb/.hide" "")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/1aAb/1.txt" "")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/1aAb/1.log" "")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/1aAb/xkcd.txt" "")
+
+file(GLOB CONTENT_LIST
+ LIST_DIRECTORIES false
+ RELATIVE "${CMAKE_CURRENT_BINARY_DIR}/test"
+ "${CMAKE_CURRENT_BINARY_DIR}/test/a/*"
+ "${CMAKE_CURRENT_BINARY_DIR}/test/*/*"
+ )
+list(LENGTH CONTENT_LIST CONTENT_COUNT)
+message("content: ${CONTENT_COUNT} ")
+message("${CONTENT_LIST}")
diff --git a/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late-stderr.txt b/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late-stderr.txt
new file mode 100644
index 000000000..af722a4e1
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Warning \(dev\) at GLOB-warn-CONFIGURE_DEPENDS-late\.cmake:[0-9]+ \(file\):
+ CONFIGURE_DEPENDS flag was given after a glob expression was already
+ evaluated\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+This warning is for project developers\. Use -Wno-dev to suppress it\.$
diff --git a/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late.cmake b/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late.cmake
new file mode 100644
index 000000000..0b6955291
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB-warn-CONFIGURE_DEPENDS-late.cmake
@@ -0,0 +1,11 @@
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/first")
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/second")
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/first/one" "Hi, Mom!")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/second/two" "Love you!")
+
+file(GLOB CONTENT_LIST
+ "${CMAKE_CURRENT_BINARY_DIR}/test/first/*"
+ CONFIGURE_DEPENDS
+ "${CMAKE_CURRENT_BINARY_DIR}/test/second/*"
+ )
diff --git a/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-result.txt b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-stderr.txt b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-stderr.txt
new file mode 100644
index 000000000..d0b2bffa1
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at GLOB_RECURSE-noexp-FOLLOW_SYMLINKS\.cmake:[0-9]+ \(file\):
+ file GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS.cmake b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS.cmake
new file mode 100644
index 000000000..5e5ce9288
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB_RECURSE-noexp-FOLLOW_SYMLINKS.cmake
@@ -0,0 +1 @@
+file(GLOB_RECURSE CONTENT_LIST FOLLOW_SYMLINKS)
diff --git a/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version-stderr.txt b/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version-stderr.txt
new file mode 100644
index 000000000..8d2233286
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version-stderr.txt
@@ -0,0 +1,13 @@
+^CMake Warning \(dev\):
+ The detected version of Ninja:
+
+ .*
+
+ is less than the version of Ninja required by CMake for adding restat
+ dependencies to the build\.ninja manifest regeneration target:
+
+ 1\.8
+
+ Any pre-check scripts, such as those generated for file\(GLOB
+ CONFIGURE_DEPENDS\), will not be run by Ninja\.
+This warning is for project developers\. Use -Wno-dev to suppress it\.$
diff --git a/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version.cmake b/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version.cmake
new file mode 100644
index 000000000..8e8089516
--- /dev/null
+++ b/Tests/RunCMake/file/GLOB_RECURSE-warn-CONFIGURE_DEPENDS-ninja-version.cmake
@@ -0,0 +1,6 @@
+file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test/first")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/test/first/one" "one")
+file(GLOB_RECURSE CONTENT_LIST
+ CONFIGURE_DEPENDS
+ "${CMAKE_CURRENT_BINARY_DIR}/test/*"
+ )
diff --git a/Tests/RunCMake/file/INSTALL-FOLLOW_SYMLINK_CHAIN.cmake b/Tests/RunCMake/file/INSTALL-FOLLOW_SYMLINK_CHAIN.cmake
new file mode 100644
index 000000000..d8a12ebba
--- /dev/null
+++ b/Tests/RunCMake/file/INSTALL-FOLLOW_SYMLINK_CHAIN.cmake
@@ -0,0 +1,168 @@
+file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/dest1")
+
+file(TOUCH "${CMAKE_BINARY_DIR}/file1.txt")
+file(CREATE_LINK file1.txt "${CMAKE_BINARY_DIR}/file1.txt.sym" SYMBOLIC)
+file(TOUCH "${CMAKE_BINARY_DIR}/dest1/file1.txt.sym")
+
+file(TOUCH "${CMAKE_BINARY_DIR}/file2.txt")
+file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/file2")
+file(CREATE_LINK ../file2.txt "${CMAKE_BINARY_DIR}/file2/file2.txt.sym" SYMBOLIC)
+
+file(TOUCH "${CMAKE_BINARY_DIR}/file3.txt")
+file(CREATE_LINK "${CMAKE_BINARY_DIR}/file3.txt" "${CMAKE_BINARY_DIR}/file3.txt.sym" SYMBOLIC)
+
+file(TOUCH "${CMAKE_BINARY_DIR}/file4.txt")
+file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/file4")
+file(CREATE_LINK "${CMAKE_BINARY_DIR}/file4.txt" "${CMAKE_BINARY_DIR}/file4/file4.txt.sym" SYMBOLIC)
+
+file(TOUCH "${CMAKE_BINARY_DIR}/file5.txt")
+
+file(TOUCH "${CMAKE_BINARY_DIR}/file6.txt")
+file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/file6/file6")
+file(CREATE_LINK file6.txt "${CMAKE_BINARY_DIR}/file6.txt.sym.1" SYMBOLIC)
+file(CREATE_LINK ../file6.txt.sym.1 "${CMAKE_BINARY_DIR}/file6/file6.txt.sym.2" SYMBOLIC)
+file(CREATE_LINK "${CMAKE_BINARY_DIR}/file6/file6.txt.sym.2" "${CMAKE_BINARY_DIR}/file6/file6/file6.txt.sym.3" SYMBOLIC)
+file(CREATE_LINK file6.txt.sym.3 "${CMAKE_BINARY_DIR}/file6/file6/file6.txt.sym.4" SYMBOLIC)
+
+file(TOUCH "${CMAKE_BINARY_DIR}/file7.txt")
+file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/file7")
+
+file(TOUCH "${CMAKE_BINARY_DIR}/file8.txt")
+file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/file8")
+file(CREATE_LINK "${CMAKE_BINARY_DIR}/file8/../file8.txt" "${CMAKE_BINARY_DIR}/file8/file8.txt.sym" SYMBOLIC)
+
+file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/file9")
+file(TOUCH "${CMAKE_BINARY_DIR}/file9/file9.txt")
+file(CREATE_LINK "${CMAKE_BINARY_DIR}/file9" "${CMAKE_BINARY_DIR}/file9.sym" SYMBOLIC)
+
+file(TOUCH "${CMAKE_BINARY_DIR}/file10.txt")
+file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/file10")
+file(CREATE_LINK "." "${CMAKE_BINARY_DIR}/file10/file10" SYMBOLIC)
+file(CREATE_LINK "${CMAKE_BINARY_DIR}/file10/file10/../file10.txt" "${CMAKE_BINARY_DIR}/file10/file10.txt.sym" SYMBOLIC)
+
+file(INSTALL
+ "${CMAKE_BINARY_DIR}/file1.txt.sym"
+ DESTINATION "${CMAKE_BINARY_DIR}/dest1"
+ FOLLOW_SYMLINK_CHAIN
+ )
+
+file(INSTALL
+ "${CMAKE_BINARY_DIR}/file1.txt.sym"
+ "${CMAKE_BINARY_DIR}/file2/file2.txt.sym"
+ "${CMAKE_BINARY_DIR}/file3.txt.sym"
+ "${CMAKE_BINARY_DIR}/file4/file4.txt.sym"
+ "${CMAKE_BINARY_DIR}/file5.txt"
+ "${CMAKE_BINARY_DIR}/file6/file6/file6.txt.sym.4"
+ "${CMAKE_BINARY_DIR}/file8/file8.txt.sym"
+ "${CMAKE_BINARY_DIR}/file7/../file7.txt"
+ "${CMAKE_BINARY_DIR}/file8.txt"
+ "${CMAKE_BINARY_DIR}/file9.sym/file9.txt"
+ "${CMAKE_BINARY_DIR}/file10/file10/file10.txt.sym"
+ DESTINATION "${CMAKE_BINARY_DIR}/dest2"
+ FOLLOW_SYMLINK_CHAIN
+ )
+
+set(resolved_file1.txt.sym file1.txt)
+set(resolved_file10.txt.sym file10.txt)
+set(resolved_file2.txt.sym file2.txt)
+set(resolved_file3.txt.sym file3.txt)
+set(resolved_file4.txt.sym file4.txt)
+set(resolved_file6.txt.sym.1 file6.txt)
+set(resolved_file6.txt.sym.2 file6.txt.sym.1)
+set(resolved_file6.txt.sym.3 file6.txt.sym.2)
+set(resolved_file6.txt.sym.4 file6.txt.sym.3)
+set(resolved_file8.txt.sym file8.txt)
+set(syms)
+foreach(f
+ file1.txt
+ file1.txt.sym
+ file10.txt
+ file10.txt.sym
+ file2.txt
+ file2.txt.sym
+ file3.txt
+ file3.txt.sym
+ file4.txt
+ file4.txt.sym
+ file5.txt
+ file6.txt
+ file6.txt.sym.1
+ file6.txt.sym.2
+ file6.txt.sym.3
+ file6.txt.sym.4
+ file7.txt
+ file8.txt
+ file8.txt.sym
+ file9.txt
+ )
+ string(REPLACE "." "\\." r "${f}")
+ list(APPEND syms "[^;]*/Tests/RunCMake/file/INSTALL-FOLLOW_SYMLINK_CHAIN-build/dest2/${r}")
+ set(filename "${CMAKE_BINARY_DIR}/dest2/${f}")
+ if(DEFINED resolved_${f})
+ file(READ_SYMLINK "${filename}" resolved)
+ if(NOT resolved STREQUAL "${resolved_${f}}")
+ message(SEND_ERROR "Expected symlink resolution for ${f}: ${resolved_${f}}\nActual resolution: ${resolved}")
+ endif()
+ elseif(NOT EXISTS "${filename}" OR IS_SYMLINK "${filename}" OR IS_DIRECTORY "${filename}")
+ message(SEND_ERROR "${f} should be a regular file")
+ endif()
+endforeach()
+
+file(GLOB_RECURSE actual_syms LIST_DIRECTORIES true "${CMAKE_BINARY_DIR}/dest2/*")
+if(NOT actual_syms MATCHES "^${syms}$")
+ message(SEND_ERROR "Expected files:\n\n ^${syms}$\n\nActual files:\n\n ${actual_syms}")
+endif()
+
+file(INSTALL
+ "${CMAKE_BINARY_DIR}/file1.txt.sym"
+ "${CMAKE_BINARY_DIR}/file2/file2.txt.sym"
+ "${CMAKE_BINARY_DIR}/file3.txt.sym"
+ "${CMAKE_BINARY_DIR}/file4/file4.txt.sym"
+ "${CMAKE_BINARY_DIR}/file5.txt"
+ "${CMAKE_BINARY_DIR}/file6/file6/file6.txt.sym.4"
+ "${CMAKE_BINARY_DIR}/file8/file8.txt.sym"
+ "${CMAKE_BINARY_DIR}/file7/../file7.txt"
+ "${CMAKE_BINARY_DIR}/file8.txt"
+ "${CMAKE_BINARY_DIR}/file9.sym/file9.txt"
+ "${CMAKE_BINARY_DIR}/file10/file10/file10.txt.sym"
+ DESTINATION "${CMAKE_BINARY_DIR}/dest3"
+ )
+
+set(resolved_file1.txt.sym [[^file1\.txt$]])
+set(resolved_file10.txt.sym [[/Tests/RunCMake/file/INSTALL-FOLLOW_SYMLINK_CHAIN-build/file10/file10/\.\./file10\.txt$]])
+set(resolved_file2.txt.sym [[^\.\./file2\.txt$]])
+set(resolved_file3.txt.sym [[/Tests/RunCMake/file/INSTALL-FOLLOW_SYMLINK_CHAIN-build/file3\.txt$]])
+set(resolved_file4.txt.sym [[/Tests/RunCMake/file/INSTALL-FOLLOW_SYMLINK_CHAIN-build/file4\.txt$]])
+set(resolved_file6.txt.sym.4 [[^file6\.txt\.sym\.3$]])
+set(resolved_file8.txt.sym [[/Tests/RunCMake/file/INSTALL-FOLLOW_SYMLINK_CHAIN-build/file8/\.\./file8\.txt$]])
+set(syms)
+foreach(f
+ file1.txt.sym
+ file10.txt.sym
+ file2.txt.sym
+ file3.txt.sym
+ file4.txt.sym
+ file5.txt
+ file6.txt.sym.4
+ file7.txt
+ file8.txt
+ file8.txt.sym
+ file9.txt
+ )
+ string(REPLACE "." "\\." r "${f}")
+ list(APPEND syms "[^;]*/Tests/RunCMake/file/INSTALL-FOLLOW_SYMLINK_CHAIN-build/dest3/${r}")
+ set(filename "${CMAKE_BINARY_DIR}/dest3/${f}")
+ if(DEFINED resolved_${f})
+ file(READ_SYMLINK "${filename}" resolved)
+ if(NOT resolved MATCHES "${resolved_${f}}")
+ message(SEND_ERROR "Expected symlink resolution for ${f}: ${resolved_${f}}\nActual resolution: ${resolved}")
+ endif()
+ elseif(NOT EXISTS "${filename}" OR IS_SYMLINK "${filename}" OR IS_DIRECTORY "${filename}")
+ message(SEND_ERROR "${f} should be a regular file")
+ endif()
+endforeach()
+
+file(GLOB_RECURSE actual_syms LIST_DIRECTORIES true "${CMAKE_BINARY_DIR}/dest3/*")
+if(NOT actual_syms MATCHES "^${syms}$")
+ message(SEND_ERROR "Expected files:\n\n ^${syms}$\n\nActual files:\n\n ${actual_syms}")
+endif()
diff --git a/Tests/RunCMake/file/READ_SYMLINK-noexist-result.txt b/Tests/RunCMake/file/READ_SYMLINK-noexist-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/READ_SYMLINK-noexist-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/READ_SYMLINK-noexist-stderr.txt b/Tests/RunCMake/file/READ_SYMLINK-noexist-stderr.txt
new file mode 100644
index 000000000..32b3e8525
--- /dev/null
+++ b/Tests/RunCMake/file/READ_SYMLINK-noexist-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at READ_SYMLINK-noexist\.cmake:[0-9]+ \(file\):
+ file READ_SYMLINK requested of path that is not a symlink:
+
+ .*/Tests/RunCMake/file/READ_SYMLINK-noexist-build/rel\.sym
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/READ_SYMLINK-noexist.cmake b/Tests/RunCMake/file/READ_SYMLINK-noexist.cmake
new file mode 100644
index 000000000..9e57e4ba4
--- /dev/null
+++ b/Tests/RunCMake/file/READ_SYMLINK-noexist.cmake
@@ -0,0 +1 @@
+file(READ_SYMLINK "${CMAKE_CURRENT_BINARY_DIR}/rel.sym" result)
diff --git a/Tests/RunCMake/file/READ_SYMLINK-notsymlink-result.txt b/Tests/RunCMake/file/READ_SYMLINK-notsymlink-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/READ_SYMLINK-notsymlink-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/READ_SYMLINK-notsymlink-stderr.txt b/Tests/RunCMake/file/READ_SYMLINK-notsymlink-stderr.txt
new file mode 100644
index 000000000..63e32ed67
--- /dev/null
+++ b/Tests/RunCMake/file/READ_SYMLINK-notsymlink-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at READ_SYMLINK-notsymlink\.cmake:[0-9]+ \(file\):
+ file READ_SYMLINK requested of path that is not a symlink:
+
+ .*/Tests/RunCMake/file/READ_SYMLINK-notsymlink-build/rel\.sym
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/READ_SYMLINK-notsymlink.cmake b/Tests/RunCMake/file/READ_SYMLINK-notsymlink.cmake
new file mode 100644
index 000000000..a9798b61e
--- /dev/null
+++ b/Tests/RunCMake/file/READ_SYMLINK-notsymlink.cmake
@@ -0,0 +1,2 @@
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/rel.sym" "")
+file(READ_SYMLINK "${CMAKE_CURRENT_BINARY_DIR}/rel.sym" result)
diff --git a/Tests/RunCMake/file/READ_SYMLINK.cmake b/Tests/RunCMake/file/READ_SYMLINK.cmake
new file mode 100644
index 000000000..865a2e931
--- /dev/null
+++ b/Tests/RunCMake/file/READ_SYMLINK.cmake
@@ -0,0 +1,13 @@
+execute_process(COMMAND
+ ${CMAKE_COMMAND} -E create_symlink "test.txt" "${CMAKE_CURRENT_BINARY_DIR}/rel.sym")
+file(READ_SYMLINK "${CMAKE_CURRENT_BINARY_DIR}/rel.sym" result)
+if(NOT result STREQUAL "test.txt")
+ message(SEND_ERROR "Relative symlink is \"${result}\", should be \"test.txt\"")
+endif()
+
+execute_process(COMMAND
+ ${CMAKE_COMMAND} -E create_symlink "${CMAKE_CURRENT_BINARY_DIR}/test.txt" "${CMAKE_CURRENT_BINARY_DIR}/abs.sym")
+file(READ_SYMLINK "${CMAKE_CURRENT_BINARY_DIR}/abs.sym" result)
+if(NOT result MATCHES "^.*/Tests/RunCMake/file/READ_SYMLINK-build/test\\.txt$")
+ message(SEND_ERROR "Absolute symlink is \"${result}\", should be \"*/Tests/RunCMake/file/READ_SYMLINK-build/test.txt\"")
+endif()
diff --git a/Tests/RunCMake/file/REMOVE-empty-stderr.txt b/Tests/RunCMake/file/REMOVE-empty-stderr.txt
new file mode 100644
index 000000000..898a6e16e
--- /dev/null
+++ b/Tests/RunCMake/file/REMOVE-empty-stderr.txt
@@ -0,0 +1,11 @@
+^CMake Warning \(dev\) at REMOVE-empty.cmake:1 \(file\):
+ Ignoring empty file name in REMOVE.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9] \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
++
+CMake Warning \(dev\) at REMOVE-empty.cmake:2 \(file\):
+ Ignoring empty file name in REMOVE_RECURSE.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9] \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/file/REMOVE-empty.cmake b/Tests/RunCMake/file/REMOVE-empty.cmake
new file mode 100644
index 000000000..38046fb51
--- /dev/null
+++ b/Tests/RunCMake/file/REMOVE-empty.cmake
@@ -0,0 +1,2 @@
+file(REMOVE "")
+file(REMOVE_RECURSE "")
diff --git a/Tests/RunCMake/file/SIZE-error-does-not-exist-result.txt b/Tests/RunCMake/file/SIZE-error-does-not-exist-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/SIZE-error-does-not-exist-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/SIZE-error-does-not-exist-stderr.txt b/Tests/RunCMake/file/SIZE-error-does-not-exist-stderr.txt
new file mode 100644
index 000000000..842cf8959
--- /dev/null
+++ b/Tests/RunCMake/file/SIZE-error-does-not-exist-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at SIZE-error-does-not-exist.cmake:[0-9]+ \(file\):
+ file SIZE requested of path that is not readable:
+
+ .*/Tests/RunCMake/file/SIZE-error-does-not-exist-build/does-not-exist
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/file/SIZE-error-does-not-exist.cmake b/Tests/RunCMake/file/SIZE-error-does-not-exist.cmake
new file mode 100644
index 000000000..ebac737dc
--- /dev/null
+++ b/Tests/RunCMake/file/SIZE-error-does-not-exist.cmake
@@ -0,0 +1,3 @@
+set(file "${CMAKE_CURRENT_BINARY_DIR}/does-not-exist")
+
+file(SIZE "${file}" CALCULATED_SIZE)
diff --git a/Tests/RunCMake/file/SIZE.cmake b/Tests/RunCMake/file/SIZE.cmake
new file mode 100644
index 000000000..4d9dbd2c9
--- /dev/null
+++ b/Tests/RunCMake/file/SIZE.cmake
@@ -0,0 +1,9 @@
+set(file "${CMAKE_CURRENT_BINARY_DIR}/a-test-file")
+
+file(WRITE "${file}" "test")
+
+file(SIZE "${file}" CALCULATED_SIZE)
+
+if (NOT CALCULATED_SIZE EQUAL 4)
+ message(FATAL_ERROR "Unexpected file size")
+endif()
diff --git a/Tests/RunCMake/file/TOUCH-error-in-source-directory-result.txt b/Tests/RunCMake/file/TOUCH-error-in-source-directory-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/TOUCH-error-in-source-directory-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/TOUCH-error-in-source-directory-stderr.txt b/Tests/RunCMake/file/TOUCH-error-in-source-directory-stderr.txt
new file mode 100644
index 000000000..f899c759b
--- /dev/null
+++ b/Tests/RunCMake/file/TOUCH-error-in-source-directory-stderr.txt
@@ -0,0 +1 @@
+.*file attempted to touch a file:
diff --git a/Tests/RunCMake/file/TOUCH-error-in-source-directory.cmake b/Tests/RunCMake/file/TOUCH-error-in-source-directory.cmake
new file mode 100644
index 000000000..9aa7c567e
--- /dev/null
+++ b/Tests/RunCMake/file/TOUCH-error-in-source-directory.cmake
@@ -0,0 +1,2 @@
+set(CMAKE_DISABLE_SOURCE_CHANGES ON)
+file(TOUCH "${CMAKE_CURRENT_SOURCE_DIR}/touch_test")
diff --git a/Tests/RunCMake/file/TOUCH-error-missing-directory-result.txt b/Tests/RunCMake/file/TOUCH-error-missing-directory-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/TOUCH-error-missing-directory-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/TOUCH-error-missing-directory-stderr.txt b/Tests/RunCMake/file/TOUCH-error-missing-directory-stderr.txt
new file mode 100644
index 000000000..f52e11a9a
--- /dev/null
+++ b/Tests/RunCMake/file/TOUCH-error-missing-directory-stderr.txt
@@ -0,0 +1 @@
+.*file problem touching file:
diff --git a/Tests/RunCMake/file/TOUCH-error-missing-directory.cmake b/Tests/RunCMake/file/TOUCH-error-missing-directory.cmake
new file mode 100644
index 000000000..0cfb8d9a9
--- /dev/null
+++ b/Tests/RunCMake/file/TOUCH-error-missing-directory.cmake
@@ -0,0 +1 @@
+file(TOUCH "${CMAKE_CURRENT_BINARY_DIR}/missing/directory/file.to-touch")
diff --git a/Tests/RunCMake/file/TOUCH-result.txt b/Tests/RunCMake/file/TOUCH-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/TOUCH-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/TOUCH-stderr.txt b/Tests/RunCMake/file/TOUCH-stderr.txt
new file mode 100644
index 000000000..9f31676db
--- /dev/null
+++ b/Tests/RunCMake/file/TOUCH-stderr.txt
@@ -0,0 +1,9 @@
+^CMake Error at TOUCH\.cmake:[0-9]+ \(file\):
+ file must be called with at least two arguments\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
++
+CMake Error at TOUCH\.cmake:[0-9]+ \(file\):
+ file must be called with at least two arguments\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/file/TOUCH.cmake b/Tests/RunCMake/file/TOUCH.cmake
new file mode 100644
index 000000000..8931eb53a
--- /dev/null
+++ b/Tests/RunCMake/file/TOUCH.cmake
@@ -0,0 +1,16 @@
+set(file "${CMAKE_CURRENT_BINARY_DIR}/file-to-touch")
+
+file(REMOVE "${file}")
+file(TOUCH_NOCREATE "${file}")
+if(EXISTS "${file}")
+ message(FATAL_ERROR "error: TOUCH_NOCREATE created a file!")
+endif()
+
+file(TOUCH "${file}")
+if(NOT EXISTS "${file}")
+ message(FATAL_ERROR "error: TOUCH did not create a file!")
+endif()
+file(REMOVE "${file}")
+
+file(TOUCH)
+file(TOUCH_NOCREATE)
diff --git a/Tests/RunCMake/file/UPLOAD-netrc-bad-result.txt b/Tests/RunCMake/file/UPLOAD-netrc-bad-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-netrc-bad-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/file/UPLOAD-netrc-bad-stderr.txt b/Tests/RunCMake/file/UPLOAD-netrc-bad-stderr.txt
new file mode 100644
index 000000000..d5752eaf9
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-netrc-bad-stderr.txt
@@ -0,0 +1,19 @@
+^CMake Error at UPLOAD-netrc-bad\.cmake:[0-9]+ \(file\):
+ file UPLOAD missing level value for NETRC\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
++
+CMake Error at UPLOAD-netrc-bad\.cmake:[0-9]+ \(file\):
+ file UPLOAD missing file value for NETRC_FILE\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
++
+CMake Error at UPLOAD-netrc-bad\.cmake:[0-9]+ \(file\):
+ file NETRC accepts OPTIONAL, IGNORED or REQUIRED but got: INVALID
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
++
+CMake Error at UPLOAD-netrc-bad\.cmake:[0-9]+ \(file\):
+ file NETRC accepts OPTIONAL, IGNORED or REQUIRED but got: FALSE
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/file/UPLOAD-netrc-bad.cmake b/Tests/RunCMake/file/UPLOAD-netrc-bad.cmake
new file mode 100644
index 000000000..e59a2c498
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-netrc-bad.cmake
@@ -0,0 +1,15 @@
+if(NOT "${CMAKE_CURRENT_SOURCE_DIR}" MATCHES "^/")
+ set(slash /)
+endif()
+file(UPLOAD "" "" NETRC)
+file(UPLOAD "" "" NETRC_FILE)
+set(CMAKE_NETRC FALSE)
+file(UPLOAD
+ "${CMAKE_CURRENT_SOURCE_DIR}/UPLOAD-netrc-bad.txt"
+ "file://${slash}${CMAKE_CURRENT_BINARY_DIR}/netrc-bad.txt"
+ NETRC INVALID
+ )
+file(UPLOAD
+ "${CMAKE_CURRENT_SOURCE_DIR}/UPLOAD-netrc-bad.txt"
+ "file://${slash}${CMAKE_CURRENT_BINARY_DIR}/netrc-bad.txt"
+ )
diff --git a/Tests/RunCMake/file/UPLOAD-netrc-bad.txt b/Tests/RunCMake/file/UPLOAD-netrc-bad.txt
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/file/UPLOAD-netrc-bad.txt
diff --git a/Tests/RunCMake/find_package/CMP0074-OLD-stderr.txt b/Tests/RunCMake/find_package/CMP0074-OLD-stderr.txt
new file mode 100644
index 000000000..4c2e5171d
--- /dev/null
+++ b/Tests/RunCMake/find_package/CMP0074-OLD-stderr.txt
@@ -0,0 +1,12 @@
+----------
+Foo_ROOT :<base>/foo/cmake_root
+ENV{Foo_ROOT} :<base>/foo/env_root
+
+find_package\(Foo\)
+FOO_TEST_FILE_FOO :FOO_TEST_FILE_FOO-NOTFOUND
+FOO_TEST_FILE_ZOT :FOO_TEST_FILE_ZOT-NOTFOUND
+FOO_TEST_PATH_FOO :FOO_TEST_PATH_FOO-NOTFOUND
+FOO_TEST_PATH_ZOT :FOO_TEST_PATH_ZOT-NOTFOUND
+FOO_TEST_PROG_FOO :FOO_TEST_PROG_FOO-NOTFOUND
+
+----------
diff --git a/Tests/RunCMake/find_package/CMP0074-OLD.cmake b/Tests/RunCMake/find_package/CMP0074-OLD.cmake
new file mode 100644
index 000000000..435831702
--- /dev/null
+++ b/Tests/RunCMake/find_package/CMP0074-OLD.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0074 OLD)
+include(CMP0074-common.cmake)
diff --git a/Tests/RunCMake/find_package/CMP0074-WARN-stderr.txt b/Tests/RunCMake/find_package/CMP0074-WARN-stderr.txt
new file mode 100644
index 000000000..fc08163cd
--- /dev/null
+++ b/Tests/RunCMake/find_package/CMP0074-WARN-stderr.txt
@@ -0,0 +1,32 @@
+----------
+Foo_ROOT :<base>/foo/cmake_root
+ENV{Foo_ROOT} :<base>/foo/env_root
++
+CMake Warning \(dev\) at CMP0074-common.cmake:[0-9]+ \(find_package\):
+ Policy CMP0074 is not set: find_package uses <PackageName>_ROOT variables.
+ Run "cmake --help-policy CMP0074" for policy details. Use the cmake_policy
+ command to set the policy and suppress this warning.
+
+ CMake variable Foo_ROOT is set to:
+
+ .*/Tests/RunCMake/find_package/PackageRoot/foo/cmake_root
+
+ Environment variable Foo_ROOT is set to:
+
+ .*/Tests/RunCMake/find_package/PackageRoot/foo/env_root
+
+ For compatibility, CMake is ignoring the variable.
+Call Stack \(most recent call first\):
+ CMP0074-common.cmake:[0-9]+ \(RunPackageRootTest\)
+ CMP0074-WARN.cmake:[0-9]+ \(include\)
+ CMakeLists.txt:[0-9]+ \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
++
+find_package\(Foo\)
+FOO_TEST_FILE_FOO :FOO_TEST_FILE_FOO-NOTFOUND
+FOO_TEST_FILE_ZOT :FOO_TEST_FILE_ZOT-NOTFOUND
+FOO_TEST_PATH_FOO :FOO_TEST_PATH_FOO-NOTFOUND
+FOO_TEST_PATH_ZOT :FOO_TEST_PATH_ZOT-NOTFOUND
+FOO_TEST_PROG_FOO :FOO_TEST_PROG_FOO-NOTFOUND
+
+----------
diff --git a/Tests/RunCMake/find_package/CMP0074-WARN.cmake b/Tests/RunCMake/find_package/CMP0074-WARN.cmake
new file mode 100644
index 000000000..0d4ada78c
--- /dev/null
+++ b/Tests/RunCMake/find_package/CMP0074-WARN.cmake
@@ -0,0 +1,2 @@
+# (do not set CMP0074)
+include(CMP0074-common.cmake)
diff --git a/Tests/RunCMake/find_package/CMP0074-common.cmake b/Tests/RunCMake/find_package/CMP0074-common.cmake
new file mode 100644
index 000000000..bfacd82c4
--- /dev/null
+++ b/Tests/RunCMake/find_package/CMP0074-common.cmake
@@ -0,0 +1,46 @@
+# (includer selects CMP0074)
+cmake_policy(SET CMP0057 NEW)
+list(INSERT CMAKE_MODULE_PATH 0 ${CMAKE_CURRENT_SOURCE_DIR}/PackageRoot)
+set(PackageRoot_BASE ${CMAKE_CURRENT_SOURCE_DIR}/PackageRoot)
+
+function(PrintPath label path)
+ string(REPLACE "${PackageRoot_BASE}" "<base>" out "${path}")
+ message("${label}${out}")
+endfunction()
+
+macro(CleanUpPackageRootTest)
+ unset(Foo_ROOT)
+ unset(ENV{Foo_ROOT})
+ unset(FOO_TEST_FILE_FOO)
+ unset(FOO_TEST_FILE_ZOT)
+ unset(FOO_TEST_PATH_FOO)
+ unset(FOO_TEST_PATH_ZOT)
+ unset(FOO_TEST_PROG_FOO)
+ unset(FOO_TEST_FILE_FOO CACHE)
+ unset(FOO_TEST_FILE_ZOT CACHE)
+ unset(FOO_TEST_PATH_FOO CACHE)
+ unset(FOO_TEST_PATH_ZOT CACHE)
+ unset(FOO_TEST_PROG_FOO CACHE)
+endmacro()
+
+macro(RunPackageRootTest)
+ message("----------")
+ PrintPath("Foo_ROOT :" "${Foo_ROOT}")
+ PrintPath("ENV{Foo_ROOT} :" "$ENV{Foo_ROOT}")
+ message("")
+
+ find_package(Foo)
+ message("find_package(Foo)")
+ PrintPath("FOO_TEST_FILE_FOO :" "${FOO_TEST_FILE_FOO}")
+ PrintPath("FOO_TEST_FILE_ZOT :" "${FOO_TEST_FILE_ZOT}")
+ PrintPath("FOO_TEST_PATH_FOO :" "${FOO_TEST_PATH_FOO}")
+ PrintPath("FOO_TEST_PATH_ZOT :" "${FOO_TEST_PATH_ZOT}")
+ PrintPath("FOO_TEST_PROG_FOO :" "${FOO_TEST_PROG_FOO}")
+ CleanUpPackageRootTest()
+ message("")
+endmacro()
+
+set(Foo_ROOT ${PackageRoot_BASE}/foo/cmake_root)
+set(ENV{Foo_ROOT} ${PackageRoot_BASE}/foo/env_root)
+RunPackageRootTest()
+message("----------")
diff --git a/Tests/RunCMake/find_package/CMP0084-NEW-stderr.txt b/Tests/RunCMake/find_package/CMP0084-NEW-stderr.txt
new file mode 100644
index 000000000..280ff8c30
--- /dev/null
+++ b/Tests/RunCMake/find_package/CMP0084-NEW-stderr.txt
@@ -0,0 +1,20 @@
+^CMake Warning at CMP0084-NEW\.cmake:[0-9]+ \(find_package\):
+ No "FindQt\.cmake" found in CMAKE_MODULE_PATH\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:3 \(include\)
++
+CMake Warning \(dev\) at CMP0084-NEW\.cmake:[0-9]+ \(find_package\):
+ FindQt\.cmake must either be part of this project itself, in this case
+ adjust CMAKE_MODULE_PATH so that it points to the correct location inside
+ its source tree\.
+
+ Or it must be installed by a package which has already been found via
+ find_package\(\)\. In this case make sure that package has indeed been found
+ and adjust CMAKE_MODULE_PATH to contain the location where that package has
+ installed FindQt\.cmake\. This must be a location provided by that package\.
+ This error in general means that the buildsystem of this project is relying
+ on a Find-module without ensuring that it is actually available\.
+
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+This warning is for project developers\. Use -Wno-dev to suppress it\.$
diff --git a/Tests/RunCMake/find_package/CMP0084-NEW.cmake b/Tests/RunCMake/find_package/CMP0084-NEW.cmake
new file mode 100644
index 000000000..68fd6cff6
--- /dev/null
+++ b/Tests/RunCMake/find_package/CMP0084-NEW.cmake
@@ -0,0 +1,7 @@
+cmake_policy(SET CMP0084 NEW)
+set(_findqt_testing TRUE)
+find_package(Qt MODULE)
+
+if(_findqt_included)
+ message(FATAL_ERROR "FindQt.cmake erroneously included")
+endif()
diff --git a/Tests/RunCMake/find_package/CMP0084-OLD.cmake b/Tests/RunCMake/find_package/CMP0084-OLD.cmake
new file mode 100644
index 000000000..7bd472653
--- /dev/null
+++ b/Tests/RunCMake/find_package/CMP0084-OLD.cmake
@@ -0,0 +1,7 @@
+cmake_policy(SET CMP0084 OLD)
+set(_findqt_testing TRUE)
+find_package(Qt MODULE)
+
+if(NOT _findqt_included)
+ message(FATAL_ERROR "FindQt.cmake not included")
+endif()
diff --git a/Tests/RunCMake/find_package/CMP0084-WARN-stderr.txt b/Tests/RunCMake/find_package/CMP0084-WARN-stderr.txt
new file mode 100644
index 000000000..9ecebd3c7
--- /dev/null
+++ b/Tests/RunCMake/find_package/CMP0084-WARN-stderr.txt
@@ -0,0 +1,8 @@
+^CMake Warning \(dev\) at CMP0084-WARN\.cmake:[0-9]+ \(find_package\):
+ Policy CMP0084 is not set: The FindQt module does not exist for
+ find_package\(\)\. Run "cmake --help-policy CMP0084" for policy details\. Use
+ the cmake_policy command to set the policy and suppress this warning\.
+
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+This warning is for project developers\. Use -Wno-dev to suppress it\.$
diff --git a/Tests/RunCMake/find_package/CMP0084-WARN.cmake b/Tests/RunCMake/find_package/CMP0084-WARN.cmake
new file mode 100644
index 000000000..4ea22cb5c
--- /dev/null
+++ b/Tests/RunCMake/find_package/CMP0084-WARN.cmake
@@ -0,0 +1,6 @@
+set(_findqt_testing TRUE)
+find_package(Qt MODULE)
+
+if(NOT _findqt_included)
+ message(FATAL_ERROR "FindQt.cmake not included")
+endif()
diff --git a/Tests/RunCMake/find_package/PackageRoot/ResolvedConfig.cmake b/Tests/RunCMake/find_package/PackageRoot/ResolvedConfig.cmake
new file mode 100644
index 000000000..4496a051c
--- /dev/null
+++ b/Tests/RunCMake/find_package/PackageRoot/ResolvedConfig.cmake
@@ -0,0 +1 @@
+set(Resolved_DIR "${CMAKE_CURRENT_LIST_DIR}")
diff --git a/Tests/RunCMake/find_package/SetFoundResolved-stderr.txt b/Tests/RunCMake/find_package/SetFoundResolved-stderr.txt
new file mode 100644
index 000000000..ea94be5a9
--- /dev/null
+++ b/Tests/RunCMake/find_package/SetFoundResolved-stderr.txt
@@ -0,0 +1,10 @@
+CMake Warning at SetFoundResolved.cmake:10 \(message\):
+ .*/Tests/RunCMake/find_package/symlink
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+
+
+CMake Warning at SetFoundResolved.cmake:15 \(message\):
+ .*/Tests/RunCMake/find_package/PackageRoot
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/find_package/SetFoundResolved.cmake b/Tests/RunCMake/find_package/SetFoundResolved.cmake
new file mode 100644
index 000000000..8d5651357
--- /dev/null
+++ b/Tests/RunCMake/find_package/SetFoundResolved.cmake
@@ -0,0 +1,17 @@
+# Create ./symlink pointing back here.
+execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink
+ PackageRoot "${CMAKE_CURRENT_SOURCE_DIR}/symlink")
+
+# Make find_package search through the symlink.
+set(CMAKE_PREFIX_PATH "${CMAKE_CURRENT_SOURCE_DIR}/symlink")
+
+# Test preservation of symlinks.
+find_package(Resolved)
+message(WARNING "${Resolved_DIR}")
+
+# Test resolving symlinks.
+set(CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS ON)
+find_package(Resolved)
+message(WARNING "${Resolved_DIR}")
+
+file(REMOVE "${CMAKE_CURRENT_SOURCE_DIR}/symlink")
diff --git a/Tests/RunCMake/find_path/EmptyOldStyle-stdout.txt b/Tests/RunCMake/find_path/EmptyOldStyle-stdout.txt
new file mode 100644
index 000000000..8f21eb85c
--- /dev/null
+++ b/Tests/RunCMake/find_path/EmptyOldStyle-stdout.txt
@@ -0,0 +1 @@
+-- VAR-NOTFOUND
diff --git a/Tests/RunCMake/find_path/EmptyOldStyle.cmake b/Tests/RunCMake/find_path/EmptyOldStyle.cmake
new file mode 100644
index 000000000..d78bb65e0
--- /dev/null
+++ b/Tests/RunCMake/find_path/EmptyOldStyle.cmake
@@ -0,0 +1,2 @@
+find_path(VAR ONLY_CMAKE_FIND_ROOT_PATH)
+message(STATUS "${VAR}")
diff --git a/Tests/RunCMake/find_program/RelAndAbsPath-stdout.txt b/Tests/RunCMake/find_program/RelAndAbsPath-stdout.txt
new file mode 100644
index 000000000..cb3c99f5e
--- /dev/null
+++ b/Tests/RunCMake/find_program/RelAndAbsPath-stdout.txt
@@ -0,0 +1,6 @@
+-- PROG_ABS='PROG_ABS-NOTFOUND'
+-- PROG_ABS_NPD='PROG_ABS_NPD-NOTFOUND'
+-- PROG_CWD='PROG_CWD-NOTFOUND'
+-- PROG_CWD_NPD='PROG_CWD_NPD-NOTFOUND'
+-- PROG_CWD_DOT='[^']*/Tests/RunCMake/find_program/testCWD'
+-- PROG_CWD_DOT_NPD='[^']*/Tests/RunCMake/find_program/testCWD'
diff --git a/Tests/RunCMake/find_program/RelAndAbsPath.cmake b/Tests/RunCMake/find_program/RelAndAbsPath.cmake
new file mode 100644
index 000000000..9a42c5e17
--- /dev/null
+++ b/Tests/RunCMake/find_program/RelAndAbsPath.cmake
@@ -0,0 +1,63 @@
+# testNoSuchFile should only be found if the file absolute path is
+# incorrectly prepended with the search path.
+
+function(strip_windows_path_prefix p outvar)
+ if(CMAKE_HOST_SYSTEM_NAME MATCHES "Windows")
+ string(REGEX REPLACE "^.:" "" p "${p}")
+ endif()
+ set(${outvar} "${p}" PARENT_SCOPE)
+endfunction()
+
+strip_windows_path_prefix("${CMAKE_CURRENT_SOURCE_DIR}" srcdir)
+
+file(MAKE_DIRECTORY "tmp${srcdir}")
+configure_file(testCWD "tmp${srcdir}/testNoSuchFile" COPYONLY)
+
+find_program(PROG_ABS
+ NAMES "${srcdir}/testNoSuchFile"
+ PATHS "${CMAKE_CURRENT_BINARY_DIR}/tmp"
+ NO_DEFAULT_PATH
+ )
+message(STATUS "PROG_ABS='${PROG_ABS}'")
+
+find_program(PROG_ABS_NPD
+ NAMES "${srcdir}/testNoSuchFile"
+ PATHS "${CMAKE_CURRENT_BINARY_DIR}/tmp"
+ NAMES_PER_DIR
+ NO_DEFAULT_PATH
+ )
+message(STATUS "PROG_ABS_NPD='${PROG_ABS_NPD}'")
+
+# ./testCWD should not be found without '.' being in the path list.
+
+configure_file(testCWD testCWD COPYONLY)
+
+find_program(PROG_CWD
+ NAMES testCWD
+ NO_DEFAULT_PATH
+ )
+message(STATUS "PROG_CWD='${PROG_CWD}'")
+
+find_program(PROG_CWD_NPD
+ NAMES testCWD
+ NAMES_PER_DIR
+ NO_DEFAULT_PATH
+ )
+message(STATUS "PROG_CWD_NPD='${PROG_CWD_NPD}'")
+
+# Confirm that adding '.' to path does locate ./testCWD.
+
+find_program(PROG_CWD_DOT
+ NAMES testCWD
+ PATHS .
+ NO_DEFAULT_PATH
+ )
+message(STATUS "PROG_CWD_DOT='${PROG_CWD_DOT}'")
+
+find_program(PROG_CWD_DOT_NPD
+ NAMES testCWD
+ PATHS .
+ NAMES_PER_DIR
+ NO_DEFAULT_PATH
+ )
+message(STATUS "PROG_CWD_DOT_NPD='${PROG_CWD_DOT_NPD}'")
diff --git a/Tests/RunCMake/find_program/testCWD b/Tests/RunCMake/find_program/testCWD
new file mode 100755
index 000000000..1a2485251
--- /dev/null
+++ b/Tests/RunCMake/find_program/testCWD
@@ -0,0 +1 @@
+#!/bin/sh
diff --git a/Tests/RunCMake/foreach/BadRangeInFunction-result.txt b/Tests/RunCMake/foreach/BadRangeInFunction-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/foreach/BadRangeInFunction-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/foreach/BadRangeInFunction-stderr.txt b/Tests/RunCMake/foreach/BadRangeInFunction-stderr.txt
new file mode 100644
index 000000000..e16a0f15b
--- /dev/null
+++ b/Tests/RunCMake/foreach/BadRangeInFunction-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at BadRangeInFunction.cmake:2 \(foreach\):
+ foreach called with incorrect range specification: start 2, stop 1, step 1
+Call Stack \(most recent call first\):
+ BadRangeInFunction.cmake:5 \(func\)
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/foreach/BadRangeInFunction.cmake b/Tests/RunCMake/foreach/BadRangeInFunction.cmake
new file mode 100644
index 000000000..f51cbbf11
--- /dev/null
+++ b/Tests/RunCMake/foreach/BadRangeInFunction.cmake
@@ -0,0 +1,5 @@
+function(func)
+ foreach(bad_range RANGE 2 1 1)
+ endforeach()
+endfunction()
+func()
diff --git a/Tests/RunCMake/foreach/CMakeLists.txt b/Tests/RunCMake/foreach/CMakeLists.txt
new file mode 100644
index 000000000..bf2ef1506
--- /dev/null
+++ b/Tests/RunCMake/foreach/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/foreach/RunCMakeTest.cmake b/Tests/RunCMake/foreach/RunCMakeTest.cmake
new file mode 100644
index 000000000..4b74cfe49
--- /dev/null
+++ b/Tests/RunCMake/foreach/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(BadRangeInFunction)
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..698e89ab0
--- /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:[0-9]+ \(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..58f62a362
--- /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:[0-9]+ \(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/install/CMP0062-OLD-stderr.txt b/Tests/RunCMake/install/CMP0062-OLD-stderr.txt
new file mode 100644
index 000000000..de0b70ffc
--- /dev/null
+++ b/Tests/RunCMake/install/CMP0062-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0062-OLD.cmake:[0-9]+ \(cmake_policy\):
+ The OLD behavior for policy CMP0062 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/install/CMP0087-NEW-check.cmake b/Tests/RunCMake/install/CMP0087-NEW-check.cmake
new file mode 100644
index 000000000..422c53202
--- /dev/null
+++ b/Tests/RunCMake/install/CMP0087-NEW-check.cmake
@@ -0,0 +1,7 @@
+execute_process(COMMAND ${CMAKE_COMMAND} -P ${RunCMake_TEST_BINARY_DIR}/cmake_install.cmake
+ OUTPUT_VARIABLE out ERROR_VARIABLE err)
+if(NOT out MATCHES "-- Install configuration: .*-- codegenexlib")
+ string(REGEX REPLACE "\n" "\n " out " ${out}")
+ string(APPEND RunCMake_TEST_FAILED
+ "\"-- codegenexlib\" was not found:\n${out}")
+endif()
diff --git a/Tests/RunCMake/install/CMP0087-NEW.cmake b/Tests/RunCMake/install/CMP0087-NEW.cmake
new file mode 100644
index 000000000..01779609c
--- /dev/null
+++ b/Tests/RunCMake/install/CMP0087-NEW.cmake
@@ -0,0 +1,3 @@
+# Need a new directory scope, not just a new policy scope
+# to test this correctly
+add_subdirectory(CMP0087-NEW)
diff --git a/Tests/RunCMake/install/CMP0087-NEW/CMakeLists.txt b/Tests/RunCMake/install/CMP0087-NEW/CMakeLists.txt
new file mode 100644
index 000000000..07b4589cf
--- /dev/null
+++ b/Tests/RunCMake/install/CMP0087-NEW/CMakeLists.txt
@@ -0,0 +1,7 @@
+# Note that it is the policy settings at the end of the directory
+# scope that will be used when deciding whether or not generator
+# expressions should be evaluated in the installed code.
+cmake_policy(VERSION 3.13)
+cmake_policy(SET CMP0087 NEW)
+add_library( codegenexlib INTERFACE )
+install(CODE "message( STATUS \"$<TARGET_PROPERTY:codegenexlib,NAME>\")")
diff --git a/Tests/RunCMake/install/CMP0087-OLD-check.cmake b/Tests/RunCMake/install/CMP0087-OLD-check.cmake
new file mode 100644
index 000000000..c5984bca7
--- /dev/null
+++ b/Tests/RunCMake/install/CMP0087-OLD-check.cmake
@@ -0,0 +1,8 @@
+execute_process(COMMAND ${CMAKE_COMMAND} -P ${RunCMake_TEST_BINARY_DIR}/cmake_install.cmake
+ OUTPUT_VARIABLE out ERROR_VARIABLE err)
+
+if(NOT out MATCHES "-- Install configuration: .*-- \\$<TARGET_PROPERTY:codegenexlib,NAME>")
+ string(REGEX REPLACE "\n" "\n " out " ${out}")
+ string(APPEND RunCMake_TEST_FAILED
+ "\"-- $<TARGET_PROPERTY:codegenexlib,NAME>\" was not found:\n${out}")
+endif()
diff --git a/Tests/RunCMake/install/CMP0087-OLD.cmake b/Tests/RunCMake/install/CMP0087-OLD.cmake
new file mode 100644
index 000000000..e7ed4ee98
--- /dev/null
+++ b/Tests/RunCMake/install/CMP0087-OLD.cmake
@@ -0,0 +1,3 @@
+# Need a new directory scope, not just a new policy scope
+# to test this correctly
+add_subdirectory(CMP0087-OLD)
diff --git a/Tests/RunCMake/install/CMP0087-OLD/CMakeLists.txt b/Tests/RunCMake/install/CMP0087-OLD/CMakeLists.txt
new file mode 100644
index 000000000..b1d4e2e7d
--- /dev/null
+++ b/Tests/RunCMake/install/CMP0087-OLD/CMakeLists.txt
@@ -0,0 +1,6 @@
+# Note that it is the policy settings at the end of the directory
+# scope that will be used when deciding whether or not generator
+# expressions should be evaluated in the installed code.
+cmake_policy(VERSION 3.13)
+cmake_policy(SET CMP0087 OLD)
+install(CODE "message( STATUS \"$<TARGET_PROPERTY:codegenexlib,NAME>\")")
diff --git a/Tests/RunCMake/install/CMP0087-WARN-stderr.txt b/Tests/RunCMake/install/CMP0087-WARN-stderr.txt
new file mode 100644
index 000000000..75fbf2c0c
--- /dev/null
+++ b/Tests/RunCMake/install/CMP0087-WARN-stderr.txt
@@ -0,0 +1,5 @@
+CMake Warning (dev) in CMakeLists.txt:
+ Policy CMP0087 is not set: Install CODE|SCRIPT allow the use of generator
+ expressions. Run "cmake --help-policy CMP0087" for policy details. Use
+ the cmake_policy command to set the policy and suppress this warning.
+This warning is for project developers. Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/install/CMP0087-WARN.cmake b/Tests/RunCMake/install/CMP0087-WARN.cmake
new file mode 100644
index 000000000..3b8513d64
--- /dev/null
+++ b/Tests/RunCMake/install/CMP0087-WARN.cmake
@@ -0,0 +1,2 @@
+add_library( codegenexlib INTERFACE )
+install(CODE "message( STATUS \"$<TARGET_PROPERTY:codegenexlib,NAME>\")")
diff --git a/Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE-result.txt b/Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE-stderr.txt b/Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE-stderr.txt
new file mode 100644
index 000000000..c847c430f
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at DIRECTORY-DESTINATION-TYPE\.cmake:[0-9]+ \(install\):
+ install DIRECTORY given both TYPE and DESTINATION arguments\. You may only
+ specify one\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE.cmake b/Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE.cmake
new file mode 100644
index 000000000..4404d6b76
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-DESTINATION-TYPE.cmake
@@ -0,0 +1 @@
+install(DIRECTORY dir TYPE BIN DESTINATION mybin)
diff --git a/Tests/RunCMake/install/DIRECTORY-OPTIONAL-all-check.cmake b/Tests/RunCMake/install/DIRECTORY-OPTIONAL-all-check.cmake
new file mode 100644
index 000000000..c14998ecf
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-OPTIONAL-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^dir;dir/empty.txt$]])
diff --git a/Tests/RunCMake/install/DIRECTORY-OPTIONAL.cmake b/Tests/RunCMake/install/DIRECTORY-OPTIONAL.cmake
new file mode 100644
index 000000000..e57aab005
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-OPTIONAL.cmake
@@ -0,0 +1 @@
+install(DIRECTORY dir/ noexist/ DESTINATION dir OPTIONAL)
diff --git a/Tests/RunCMake/install/DIRECTORY-PATTERN-all-check.cmake b/Tests/RunCMake/install/DIRECTORY-PATTERN-all-check.cmake
new file mode 100644
index 000000000..7a20edc36
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-PATTERN-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^dir1;dir1/empty\.c;dir1/empty\.h;dir2;dir2/pattern;dir2/pattern/empty\.txt;dir3;dir3/empty\.c;dir3/empty\.h;dir3/empty\.txt;dir4;dir4/empty\.c;dir4/empty\.h;dir4/empty\.txt;empty$]])
diff --git a/Tests/RunCMake/install/DIRECTORY-PATTERN.cmake b/Tests/RunCMake/install/DIRECTORY-PATTERN.cmake
new file mode 100644
index 000000000..74d804351
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-PATTERN.cmake
@@ -0,0 +1,36 @@
+install(
+ DIRECTORY pattern/
+ DESTINATION dir1
+ FILES_MATCHING
+ PATTERN "*.h"
+ REGEX "\\.c$"
+ )
+
+# FIXME: If/when CMake gains a good way to read file permissions, we should
+# check that these permissions were set correctly.
+install(
+ DIRECTORY pattern
+ DESTINATION dir2
+ FILE_PERMISSIONS OWNER_READ OWNER_WRITE
+ DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE
+ PATTERN "*.h" EXCLUDE
+ REGEX "\\.c$" EXCLUDE
+ )
+
+install(
+ DIRECTORY pattern/
+ DESTINATION dir3
+ PATTERN "*.h"
+ PERMISSIONS OWNER_READ OWNER_WRITE
+ )
+
+install(
+ DIRECTORY pattern/
+ DESTINATION dir4
+ USE_SOURCE_PERMISSIONS
+ )
+
+install(
+ DIRECTORY
+ DESTINATION empty
+ )
diff --git a/Tests/RunCMake/install/DIRECTORY-TYPE-Cache-all-check.cmake b/Tests/RunCMake/install/DIRECTORY-TYPE-Cache-all-check.cmake
new file mode 100644
index 000000000..fb393e396
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-TYPE-Cache-all-check.cmake
@@ -0,0 +1,42 @@
+set(_check_files
+ [[mybin]]
+ [[mybin/dir]]
+ [[mybin/dir/empty\.txt]]
+ [[mycom]]
+ [[mycom/dir]]
+ [[mycom/dir/empty\.txt]]
+ [[mydoc]]
+ [[mydoc/dir]]
+ [[mydoc/dir/empty\.txt]]
+ [[myetc]]
+ [[myetc/dir]]
+ [[myetc/dir/empty\.txt]]
+ [[myinclude]]
+ [[myinclude/dir]]
+ [[myinclude/dir/empty\.txt]]
+ [[myinfo]]
+ [[myinfo/dir]]
+ [[myinfo/dir/empty\.txt]]
+ [[mylib]]
+ [[mylib/dir]]
+ [[mylib/dir/empty\.txt]]
+ [[mylocale]]
+ [[mylocale/dir]]
+ [[mylocale/dir/empty\.txt]]
+ [[myman]]
+ [[myman/dir]]
+ [[myman/dir/empty\.txt]]
+ [[myrun]]
+ [[myrun/dir]]
+ [[myrun/dir/empty\.txt]]
+ [[mysbin]]
+ [[mysbin/dir]]
+ [[mysbin/dir/empty\.txt]]
+ [[myshare]]
+ [[myshare/dir]]
+ [[myshare/dir/empty\.txt]]
+ [[myvar]]
+ [[myvar/dir]]
+ [[myvar/dir/empty\.txt]]
+ )
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/DIRECTORY-TYPE-Cache.cmake b/Tests/RunCMake/install/DIRECTORY-TYPE-Cache.cmake
new file mode 100644
index 000000000..53e95f8ee
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-TYPE-Cache.cmake
@@ -0,0 +1,13 @@
+install(DIRECTORY dir TYPE BIN)
+install(DIRECTORY dir TYPE SBIN)
+install(DIRECTORY dir TYPE LIB)
+install(DIRECTORY dir TYPE INCLUDE)
+install(DIRECTORY dir TYPE SYSCONF)
+install(DIRECTORY dir TYPE SHAREDSTATE)
+install(DIRECTORY dir TYPE LOCALSTATE)
+install(DIRECTORY dir TYPE RUNSTATE)
+install(DIRECTORY dir TYPE DATA)
+install(DIRECTORY dir TYPE INFO)
+install(DIRECTORY dir TYPE LOCALE)
+install(DIRECTORY dir TYPE MAN)
+install(DIRECTORY dir TYPE DOC)
diff --git a/Tests/RunCMake/install/DIRECTORY-TYPE-CacheDependent-all-check.cmake b/Tests/RunCMake/install/DIRECTORY-TYPE-CacheDependent-all-check.cmake
new file mode 100644
index 000000000..03f7bd657
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-TYPE-CacheDependent-all-check.cmake
@@ -0,0 +1,24 @@
+set(_check_files
+ [[myshare]]
+ [[myshare/dir]]
+ [[myshare/dir/empty\.txt]]
+ [[myshare/doc]]
+ [[myshare/doc/dir]]
+ [[myshare/doc/dir/empty\.txt]]
+ [[myshare/info]]
+ [[myshare/info/dir]]
+ [[myshare/info/dir/empty\.txt]]
+ [[myshare/locale]]
+ [[myshare/locale/dir]]
+ [[myshare/locale/dir/empty\.txt]]
+ [[myshare/man]]
+ [[myshare/man/dir]]
+ [[myshare/man/dir/empty.txt]]
+ [[myvar]]
+ [[myvar/dir]]
+ [[myvar/dir/empty\.txt]]
+ [[myvar/run]]
+ [[myvar/run/dir]]
+ [[myvar/run/dir/empty\.txt]]
+ )
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/DIRECTORY-TYPE-CacheDependent.cmake b/Tests/RunCMake/install/DIRECTORY-TYPE-CacheDependent.cmake
new file mode 100644
index 000000000..e797abb91
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-TYPE-CacheDependent.cmake
@@ -0,0 +1,7 @@
+install(DIRECTORY dir TYPE LOCALSTATE)
+install(DIRECTORY dir TYPE RUNSTATE)
+install(DIRECTORY dir TYPE DATA)
+install(DIRECTORY dir TYPE INFO)
+install(DIRECTORY dir TYPE LOCALE)
+install(DIRECTORY dir TYPE MAN)
+install(DIRECTORY dir TYPE DOC)
diff --git a/Tests/RunCMake/install/DIRECTORY-TYPE-all-check.cmake b/Tests/RunCMake/install/DIRECTORY-TYPE-all-check.cmake
new file mode 100644
index 000000000..03fa3c832
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-TYPE-all-check.cmake
@@ -0,0 +1,42 @@
+set(_check_files
+ [[bin]]
+ [[bin/dir]]
+ [[bin/dir/empty\.txt]]
+ [[com]]
+ [[com/dir]]
+ [[com/dir/empty\.txt]]
+ [[etc]]
+ [[etc/dir]]
+ [[etc/dir/empty\.txt]]
+ [[include]]
+ [[include/dir]]
+ [[include/dir/empty\.txt]]
+ [[lib]]
+ [[lib/dir]]
+ [[lib/dir/empty\.txt]]
+ [[sbin]]
+ [[sbin/dir]]
+ [[sbin/dir/empty\.txt]]
+ [[share]]
+ [[share/dir]]
+ [[share/dir/empty\.txt]]
+ [[share/doc]]
+ [[share/doc/dir]]
+ [[share/doc/dir/empty\.txt]]
+ [[share/info]]
+ [[share/info/dir]]
+ [[share/info/dir/empty\.txt]]
+ [[share/locale]]
+ [[share/locale/dir]]
+ [[share/locale/dir/empty\.txt]]
+ [[share/man]]
+ [[share/man/dir]]
+ [[share/man/dir/empty\.txt]]
+ [[var]]
+ [[var/dir]]
+ [[var/dir/empty\.txt]]
+ [[var/run]]
+ [[var/run/dir]]
+ [[var/run/dir/empty\.txt]]
+ )
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/DIRECTORY-TYPE.cmake b/Tests/RunCMake/install/DIRECTORY-TYPE.cmake
new file mode 100644
index 000000000..53e95f8ee
--- /dev/null
+++ b/Tests/RunCMake/install/DIRECTORY-TYPE.cmake
@@ -0,0 +1,13 @@
+install(DIRECTORY dir TYPE BIN)
+install(DIRECTORY dir TYPE SBIN)
+install(DIRECTORY dir TYPE LIB)
+install(DIRECTORY dir TYPE INCLUDE)
+install(DIRECTORY dir TYPE SYSCONF)
+install(DIRECTORY dir TYPE SHAREDSTATE)
+install(DIRECTORY dir TYPE LOCALSTATE)
+install(DIRECTORY dir TYPE RUNSTATE)
+install(DIRECTORY dir TYPE DATA)
+install(DIRECTORY dir TYPE INFO)
+install(DIRECTORY dir TYPE LOCALE)
+install(DIRECTORY dir TYPE MAN)
+install(DIRECTORY dir TYPE DOC)
diff --git a/Tests/RunCMake/install/Deprecated-all-check.cmake b/Tests/RunCMake/install/Deprecated-all-check.cmake
new file mode 100644
index 000000000..9ea33a6b4
--- /dev/null
+++ b/Tests/RunCMake/install/Deprecated-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^bin;bin/myexe(\.exe)?;scripts1;scripts1/script;scripts1/script\.bat;scripts2;scripts2/script;scripts2/script\.bat;scripts3;scripts3/script;scripts3/script\.bat;src;src/empty\.c;src/obj1\.c;src/obj\2.c$]])
diff --git a/Tests/RunCMake/install/Deprecated.cmake b/Tests/RunCMake/install/Deprecated.cmake
new file mode 100644
index 000000000..c435cb507
--- /dev/null
+++ b/Tests/RunCMake/install/Deprecated.cmake
@@ -0,0 +1,13 @@
+enable_language(C)
+
+add_executable(myexe main.c)
+
+install_files(/src FILES empty.c)
+install_files(/src .c obj1)
+install_files(/src "^obj2.c$")
+
+install_targets(/bin myexe)
+
+install_programs(/scripts1 FILES script script.bat)
+install_programs(/scripts2 script script.bat)
+install_programs(/scripts3 "^script(\.bat)?$")
diff --git a/Tests/RunCMake/install/FILES-DESTINATION-TYPE-result.txt b/Tests/RunCMake/install/FILES-DESTINATION-TYPE-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-DESTINATION-TYPE-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/install/FILES-DESTINATION-TYPE-stderr.txt b/Tests/RunCMake/install/FILES-DESTINATION-TYPE-stderr.txt
new file mode 100644
index 000000000..ce8fc2386
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-DESTINATION-TYPE-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at FILES-DESTINATION-TYPE\.cmake:[0-9]+ \(install\):
+ install FILES given both TYPE and DESTINATION arguments\. You may only
+ specify one\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/install/FILES-DESTINATION-TYPE.cmake b/Tests/RunCMake/install/FILES-DESTINATION-TYPE.cmake
new file mode 100644
index 000000000..576c98f36
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-DESTINATION-TYPE.cmake
@@ -0,0 +1 @@
+install(FILES main.c TYPE BIN DESTINATION mybin)
diff --git a/Tests/RunCMake/install/FILES-OPTIONAL-all-check.cmake b/Tests/RunCMake/install/FILES-OPTIONAL-all-check.cmake
new file mode 100644
index 000000000..2997a8d4e
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-OPTIONAL-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^src;src/main.c$]])
diff --git a/Tests/RunCMake/install/FILES-OPTIONAL.cmake b/Tests/RunCMake/install/FILES-OPTIONAL.cmake
new file mode 100644
index 000000000..812bf4f02
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-OPTIONAL.cmake
@@ -0,0 +1 @@
+install(FILES main.c noexist.c DESTINATION src OPTIONAL)
diff --git a/Tests/RunCMake/install/FILES-PERMISSIONS-all-check.cmake b/Tests/RunCMake/install/FILES-PERMISSIONS-all-check.cmake
new file mode 100644
index 000000000..b8ba6d0d5
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-PERMISSIONS-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^src;src/empty.c]])
diff --git a/Tests/RunCMake/install/FILES-PERMISSIONS.cmake b/Tests/RunCMake/install/FILES-PERMISSIONS.cmake
new file mode 100644
index 000000000..999c271f9
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-PERMISSIONS.cmake
@@ -0,0 +1,5 @@
+install(
+ FILES empty.c
+ DESTINATION src
+ PERMISSIONS OWNER_READ OWNER_WRITE
+ )
diff --git a/Tests/RunCMake/install/FILES-TYPE-Cache-all-check.cmake b/Tests/RunCMake/install/FILES-TYPE-Cache-all-check.cmake
new file mode 100644
index 000000000..dfb90cf02
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-TYPE-Cache-all-check.cmake
@@ -0,0 +1,29 @@
+set(_check_files
+ [[mybin]]
+ [[mybin/main\.c]]
+ [[mycom]]
+ [[mycom/main\.c]]
+ [[mydoc]]
+ [[mydoc/main\.c]]
+ [[myetc]]
+ [[myetc/main\.c]]
+ [[myinclude]]
+ [[myinclude/main\.c]]
+ [[myinfo]]
+ [[myinfo/main\.c]]
+ [[mylib]]
+ [[mylib/main\.c]]
+ [[mylocale]]
+ [[mylocale/main\.c]]
+ [[myman]]
+ [[myman/main\.c]]
+ [[myrun]]
+ [[myrun/main\.c]]
+ [[mysbin]]
+ [[mysbin/main\.c]]
+ [[myshare]]
+ [[myshare/main\.c]]
+ [[myvar]]
+ [[myvar/main\.c]]
+ )
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/FILES-TYPE-Cache.cmake b/Tests/RunCMake/install/FILES-TYPE-Cache.cmake
new file mode 100644
index 000000000..2e2bfc7fa
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-TYPE-Cache.cmake
@@ -0,0 +1,13 @@
+install(FILES main.c TYPE BIN)
+install(FILES main.c TYPE SBIN)
+install(FILES main.c TYPE LIB)
+install(FILES main.c TYPE INCLUDE)
+install(FILES main.c TYPE SYSCONF)
+install(FILES main.c TYPE SHAREDSTATE)
+install(FILES main.c TYPE LOCALSTATE)
+install(FILES main.c TYPE RUNSTATE)
+install(FILES main.c TYPE DATA)
+install(FILES main.c TYPE INFO)
+install(FILES main.c TYPE LOCALE)
+install(FILES main.c TYPE MAN)
+install(FILES main.c TYPE DOC)
diff --git a/Tests/RunCMake/install/FILES-TYPE-CacheDependent-all-check.cmake b/Tests/RunCMake/install/FILES-TYPE-CacheDependent-all-check.cmake
new file mode 100644
index 000000000..e58c80ad3
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-TYPE-CacheDependent-all-check.cmake
@@ -0,0 +1,17 @@
+set(_check_files
+ [[myshare]]
+ [[myshare/doc]]
+ [[myshare/doc/main\.c]]
+ [[myshare/info]]
+ [[myshare/info/main\.c]]
+ [[myshare/locale]]
+ [[myshare/locale/main\.c]]
+ [[myshare/main\.c]]
+ [[myshare/man]]
+ [[myshare/man/main\.c]]
+ [[myvar]]
+ [[myvar/main\.c]]
+ [[myvar/run]]
+ [[myvar/run/main\.c]]
+ )
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/FILES-TYPE-CacheDependent.cmake b/Tests/RunCMake/install/FILES-TYPE-CacheDependent.cmake
new file mode 100644
index 000000000..d7d5aaa11
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-TYPE-CacheDependent.cmake
@@ -0,0 +1,7 @@
+install(FILES main.c TYPE LOCALSTATE)
+install(FILES main.c TYPE RUNSTATE)
+install(FILES main.c TYPE DATA)
+install(FILES main.c TYPE INFO)
+install(FILES main.c TYPE LOCALE)
+install(FILES main.c TYPE MAN)
+install(FILES main.c TYPE DOC)
diff --git a/Tests/RunCMake/install/FILES-TYPE-all-check.cmake b/Tests/RunCMake/install/FILES-TYPE-all-check.cmake
new file mode 100644
index 000000000..c4ec66149
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-TYPE-all-check.cmake
@@ -0,0 +1,29 @@
+set(_check_files
+ [[bin]]
+ [[bin/main\.c]]
+ [[com]]
+ [[com/main\.c]]
+ [[etc]]
+ [[etc/main\.c]]
+ [[include]]
+ [[include/main\.c]]
+ [[lib]]
+ [[lib/main\.c]]
+ [[sbin]]
+ [[sbin/main\.c]]
+ [[share]]
+ [[share/doc]]
+ [[share/doc/main\.c]]
+ [[share/info]]
+ [[share/info/main\.c]]
+ [[share/locale]]
+ [[share/locale/main\.c]]
+ [[share/main\.c]]
+ [[share/man]]
+ [[share/man/main\.c]]
+ [[var]]
+ [[var/main\.c]]
+ [[var/run]]
+ [[var/run/main\.c]]
+ )
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/FILES-TYPE.cmake b/Tests/RunCMake/install/FILES-TYPE.cmake
new file mode 100644
index 000000000..2e2bfc7fa
--- /dev/null
+++ b/Tests/RunCMake/install/FILES-TYPE.cmake
@@ -0,0 +1,13 @@
+install(FILES main.c TYPE BIN)
+install(FILES main.c TYPE SBIN)
+install(FILES main.c TYPE LIB)
+install(FILES main.c TYPE INCLUDE)
+install(FILES main.c TYPE SYSCONF)
+install(FILES main.c TYPE SHAREDSTATE)
+install(FILES main.c TYPE LOCALSTATE)
+install(FILES main.c TYPE RUNSTATE)
+install(FILES main.c TYPE DATA)
+install(FILES main.c TYPE INFO)
+install(FILES main.c TYPE LOCALE)
+install(FILES main.c TYPE MAN)
+install(FILES main.c TYPE DOC)
diff --git a/Tests/RunCMake/install/InstallRequiredSystemLibraries-stderr.txt b/Tests/RunCMake/install/InstallRequiredSystemLibraries-stderr.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/install/InstallRequiredSystemLibraries-stderr.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/install/InstallRequiredSystemLibraries.cmake b/Tests/RunCMake/install/InstallRequiredSystemLibraries.cmake
new file mode 100644
index 000000000..27ff68387
--- /dev/null
+++ b/Tests/RunCMake/install/InstallRequiredSystemLibraries.cmake
@@ -0,0 +1,10 @@
+enable_language(C)
+set(CMAKE_INSTALL_MFC_LIBRARIES 1)
+set(CMAKE_INSTALL_DEBUG_LIBRARIES 1)
+set(CMAKE_INSTALL_UCRT_LIBRARIES 1)
+set(CMAKE_INSTALL_OPENMP_LIBRARIES 1)
+include(InstallRequiredSystemLibraries)
+
+# FIXME: This test emits warnings because InstallRequiredSystemLibraries
+# doesn't currently work properly. The warnings have been suppressed in
+# InstallRequiredSystemLibraries-stderr.txt. This needs to be fixed.
diff --git a/Tests/RunCMake/install/PRE_POST_INSTALL_SCRIPT-all-check.cmake b/Tests/RunCMake/install/PRE_POST_INSTALL_SCRIPT-all-check.cmake
new file mode 100644
index 000000000..16ff1e1c1
--- /dev/null
+++ b/Tests/RunCMake/install/PRE_POST_INSTALL_SCRIPT-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^bin;bin/myexe(\.exe)?;postinstall;preinstall]])
diff --git a/Tests/RunCMake/install/PRE_POST_INSTALL_SCRIPT.cmake b/Tests/RunCMake/install/PRE_POST_INSTALL_SCRIPT.cmake
new file mode 100644
index 000000000..357c68872
--- /dev/null
+++ b/Tests/RunCMake/install/PRE_POST_INSTALL_SCRIPT.cmake
@@ -0,0 +1,7 @@
+enable_language(C)
+
+add_executable(myexe main.c)
+set_property(TARGET myexe PROPERTY PRE_INSTALL_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/preinstall.cmake")
+set_property(TARGET myexe PROPERTY POST_INSTALL_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/postinstall.cmake")
+
+install(TARGETS myexe DESTINATION bin)
diff --git a/Tests/RunCMake/install/SCRIPT-COMPONENT-all-check.cmake b/Tests/RunCMake/install/SCRIPT-COMPONENT-all-check.cmake
new file mode 100644
index 000000000..48d8e1aec
--- /dev/null
+++ b/Tests/RunCMake/install/SCRIPT-COMPONENT-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^empty1.txt;empty2.txt$]])
diff --git a/Tests/RunCMake/install/SCRIPT-COMPONENT-dev-check.cmake b/Tests/RunCMake/install/SCRIPT-COMPONENT-dev-check.cmake
new file mode 100644
index 000000000..48d8e1aec
--- /dev/null
+++ b/Tests/RunCMake/install/SCRIPT-COMPONENT-dev-check.cmake
@@ -0,0 +1 @@
+check_installed([[^empty1.txt;empty2.txt$]])
diff --git a/Tests/RunCMake/install/SCRIPT-COMPONENT-uns-check.cmake b/Tests/RunCMake/install/SCRIPT-COMPONENT-uns-check.cmake
new file mode 100644
index 000000000..e09a102af
--- /dev/null
+++ b/Tests/RunCMake/install/SCRIPT-COMPONENT-uns-check.cmake
@@ -0,0 +1 @@
+check_installed([[^$]])
diff --git a/Tests/RunCMake/install/SCRIPT-COMPONENT.cmake b/Tests/RunCMake/install/SCRIPT-COMPONENT.cmake
new file mode 100644
index 000000000..aaa9bd45a
--- /dev/null
+++ b/Tests/RunCMake/install/SCRIPT-COMPONENT.cmake
@@ -0,0 +1,5 @@
+install(
+ SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/install_script.cmake"
+ CODE "write_empty_file(empty2.txt)"
+ COMPONENT dev
+ )
diff --git a/Tests/RunCMake/install/SCRIPT-all-check.cmake b/Tests/RunCMake/install/SCRIPT-all-check.cmake
new file mode 100644
index 000000000..48d8e1aec
--- /dev/null
+++ b/Tests/RunCMake/install/SCRIPT-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^empty1.txt;empty2.txt$]])
diff --git a/Tests/RunCMake/install/SCRIPT.cmake b/Tests/RunCMake/install/SCRIPT.cmake
new file mode 100644
index 000000000..f857b5437
--- /dev/null
+++ b/Tests/RunCMake/install/SCRIPT.cmake
@@ -0,0 +1,4 @@
+install(
+ SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/install_script.cmake"
+ CODE "write_empty_file(empty2.txt)"
+ )
diff --git a/Tests/RunCMake/install/TARGETS-Apple-Defaults-result.txt b/Tests/RunCMake/install/TARGETS-Apple-Defaults-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-Apple-Defaults-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/install/TARGETS-Apple-Defaults-stderr.txt b/Tests/RunCMake/install/TARGETS-Apple-Defaults-stderr.txt
new file mode 100644
index 000000000..645882f52
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-Apple-Defaults-stderr.txt
@@ -0,0 +1,12 @@
+^CMake Error at TARGETS-Apple-Defaults\.cmake:[0-9]+ \(install\):
+ install TARGETS given no BUNDLE DESTINATION for MACOSX_BUNDLE executable
+ target "exe"\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+
+
+CMake Error at TARGETS-Apple-Defaults\.cmake:[0-9]+ \(install\):
+ install TARGETS given no FRAMEWORK DESTINATION for shared library FRAMEWORK
+ target "lib1"\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/install/TARGETS-Apple-Defaults.cmake b/Tests/RunCMake/install/TARGETS-Apple-Defaults.cmake
new file mode 100644
index 000000000..b60c31894
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-Apple-Defaults.cmake
@@ -0,0 +1,8 @@
+enable_language(C)
+
+add_executable(exe MACOSX_BUNDLE main.c)
+add_library(lib1 SHARED obj1.c)
+set_property(TARGET lib1 PROPERTY FRAMEWORK ON)
+
+install(TARGETS exe)
+install(TARGETS lib1)
diff --git a/Tests/RunCMake/install/TARGETS-CONFIGURATIONS-all-check.cmake b/Tests/RunCMake/install/TARGETS-CONFIGURATIONS-all-check.cmake
new file mode 100644
index 000000000..2866e7fb9
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-CONFIGURATIONS-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^src;src/main-d.c$]])
diff --git a/Tests/RunCMake/install/TARGETS-CONFIGURATIONS.cmake b/Tests/RunCMake/install/TARGETS-CONFIGURATIONS.cmake
new file mode 100644
index 000000000..5531cd2ff
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-CONFIGURATIONS.cmake
@@ -0,0 +1,2 @@
+install(FILES main.c DESTINATION src CONFIGURATIONS Debug RENAME main-d.c)
+install(FILES main.c DESTINATION src CONFIGURATIONS Release RENAME main-r.c)
diff --git a/Tests/RunCMake/install/TARGETS-Defaults-Cache-all-check.cmake b/Tests/RunCMake/install/TARGETS-Defaults-Cache-all-check.cmake
new file mode 100644
index 000000000..57ad6e140
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-Defaults-Cache-all-check.cmake
@@ -0,0 +1,49 @@
+if(WIN32)
+ set(_check_files
+ [[lib3]]
+ [[lib3/(lib)?lib3\.(dll\.a|lib)]]
+ [[lib4]]
+ [[lib4/(lib)?lib4\.dll]]
+ [[mybin]]
+ [[mybin/exe\.exe]]
+ [[mybin/(lib)?lib1\.dll]]
+ [[myinclude]]
+ [[myinclude/obj4\.h]]
+ [[myinclude/obj5\.h]]
+ [[mylib]]
+ [[mylib/(lib)?lib1\.(dll\.a|lib)]]
+ [[mylib/(lib)?lib2\.(a|lib)]]
+ )
+elseif(CYGWIN)
+ set(_check_files
+ [[lib3]]
+ [[lib3/liblib3\.dll\.a]]
+ [[lib4]]
+ [[lib4/cyglib4\.dll]]
+ [[mybin]]
+ [[mybin/cyglib1\.dll]]
+ [[mybin/exe\.exe]]
+ [[myinclude]]
+ [[myinclude/obj4\.h]]
+ [[myinclude/obj5\.h]]
+ [[mylib]]
+ [[mylib/liblib1\.dll\.a]]
+ [[mylib/liblib2\.a]]
+ )
+else()
+ set(_check_files
+ [[lib3]]
+ [[lib3/liblib3\.(dylib|so)]]
+ [[lib4]]
+ [[lib4/liblib4\.(dylib|so)]]
+ [[mybin]]
+ [[mybin/exe]]
+ [[myinclude]]
+ [[myinclude/obj4\.h]]
+ [[myinclude/obj5\.h]]
+ [[mylib]]
+ [[mylib/liblib1\.(dylib|so)]]
+ [[mylib/liblib2\.a]]
+ )
+endif()
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/TARGETS-Defaults-Cache.cmake b/Tests/RunCMake/install/TARGETS-Defaults-Cache.cmake
new file mode 100644
index 000000000..bfd8c2c61
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-Defaults-Cache.cmake
@@ -0,0 +1,19 @@
+enable_language(C)
+
+add_executable(exe main.c)
+add_library(lib1 SHARED obj1.c)
+add_library(lib2 STATIC obj3.c)
+add_library(lib3 SHARED obj4.c)
+set_property(TARGET lib3 PROPERTY PRIVATE_HEADER ${CMAKE_CURRENT_SOURCE_DIR}/obj4.h)
+add_library(lib4 SHARED obj5.c)
+set_property(TARGET lib4 PROPERTY PUBLIC_HEADER ${CMAKE_CURRENT_SOURCE_DIR}/obj5.h)
+
+install(TARGETS exe lib1 lib2)
+install(TARGETS lib3
+ LIBRARY DESTINATION lib3
+ ARCHIVE DESTINATION lib3
+ )
+install(TARGETS lib4
+ LIBRARY DESTINATION lib4
+ RUNTIME DESTINATION lib4
+ )
diff --git a/Tests/RunCMake/install/TARGETS-Defaults-all-check.cmake b/Tests/RunCMake/install/TARGETS-Defaults-all-check.cmake
new file mode 100644
index 000000000..15335b2a9
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-Defaults-all-check.cmake
@@ -0,0 +1,55 @@
+if(WIN32)
+ set(_check_files
+ [[bin]]
+ [[bin/exe\.exe]]
+ [[bin/(lib)?lib1\.dll]]
+ [[include]]
+ [[include/obj1\.h]]
+ [[include/obj2\.h]]
+ [[include/obj4\.h]]
+ [[include/obj5\.h]]
+ [[lib]]
+ [[lib/(lib)?lib1\.(dll\.a|lib)]]
+ [[lib/(lib)?lib2\.(a|lib)]]
+ [[lib3]]
+ [[lib3/(lib)?lib3\.(dll\.a|lib)]]
+ [[lib4]]
+ [[lib4/(lib)?lib4\.dll]]
+ )
+elseif(CYGWIN)
+ set(_check_files
+ [[bin]]
+ [[bin/cyglib1\.dll]]
+ [[bin/exe\.exe]]
+ [[include]]
+ [[include/obj1\.h]]
+ [[include/obj2\.h]]
+ [[include/obj4\.h]]
+ [[include/obj5\.h]]
+ [[lib]]
+ [[lib/liblib1\.dll\.a]]
+ [[lib/liblib2\.a]]
+ [[lib3]]
+ [[lib3/liblib3\.dll\.a]]
+ [[lib4]]
+ [[lib4/cyglib4\.dll]]
+ )
+else()
+ set(_check_files
+ [[bin]]
+ [[bin/exe]]
+ [[include]]
+ [[include/obj1\.h]]
+ [[include/obj2\.h]]
+ [[include/obj4\.h]]
+ [[include/obj5\.h]]
+ [[lib]]
+ [[lib/liblib1\.(dylib|so)]]
+ [[lib/liblib2\.a]]
+ [[lib3]]
+ [[lib3/liblib3\.(dylib|so)]]
+ [[lib4]]
+ [[lib4/liblib4\.(dylib|so)]]
+ )
+endif()
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/TARGETS-Defaults.cmake b/Tests/RunCMake/install/TARGETS-Defaults.cmake
new file mode 100644
index 000000000..324aa111f
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-Defaults.cmake
@@ -0,0 +1,27 @@
+enable_language(C)
+
+add_executable(exe main.c)
+add_library(lib1 SHARED obj1.c)
+add_library(lib2 STATIC obj3.c)
+add_library(lib3 SHARED obj4.c)
+set_property(TARGET lib3 PROPERTY PRIVATE_HEADER ${CMAKE_CURRENT_SOURCE_DIR}/obj4.h)
+add_library(lib4 SHARED obj5.c)
+set_property(TARGET lib4 PROPERTY PUBLIC_HEADER ${CMAKE_CURRENT_SOURCE_DIR}/obj5.h)
+
+add_library(iface INTERFACE)
+set_target_properties(iface PROPERTIES
+ PUBLIC_HEADER ${CMAKE_CURRENT_SOURCE_DIR}/obj1.h
+ PRIVATE_HEADER ${CMAKE_CURRENT_SOURCE_DIR}/obj2.h)
+
+install(TARGETS exe lib1 lib2)
+install(TARGETS lib3
+ LIBRARY DESTINATION lib3
+ ARCHIVE DESTINATION lib3
+ )
+install(TARGETS lib4
+ LIBRARY DESTINATION lib4
+ RUNTIME DESTINATION lib4
+ )
+install(TARGETS iface
+ PUBLIC_HEADER DESTINATION include
+ PRIVATE_HEADER DESTINATION include)
diff --git a/Tests/RunCMake/install/TARGETS-ImportedGlobal-result.txt b/Tests/RunCMake/install/TARGETS-ImportedGlobal-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-ImportedGlobal-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/install/TARGETS-ImportedGlobal-stderr.txt b/Tests/RunCMake/install/TARGETS-ImportedGlobal-stderr.txt
new file mode 100644
index 000000000..d67802bb5
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-ImportedGlobal-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TARGETS-ImportedGlobal.cmake:[0-9]+ \(install\):
+ install TARGETS given target "imported_global" which does not exist.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/install/TARGETS-ImportedGlobal.cmake b/Tests/RunCMake/install/TARGETS-ImportedGlobal.cmake
new file mode 100644
index 000000000..08c20bd4e
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-ImportedGlobal.cmake
@@ -0,0 +1,3 @@
+add_library(imported_global STATIC IMPORTED GLOBAL)
+set_property(TARGET imported_global PROPERTY IMPORTED_LOCATION /does_not_exist)
+install(TARGETS imported_global DESTINATION bin)
diff --git a/Tests/RunCMake/install/TARGETS-InstallFromSubDir-all-check.cmake b/Tests/RunCMake/install/TARGETS-InstallFromSubDir-all-check.cmake
new file mode 100644
index 000000000..1d747c301
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-InstallFromSubDir-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^bin;bin/myexe(\.exe)?;bin/subexe(\.exe)?$]])
diff --git a/Tests/RunCMake/install/TARGETS-InstallFromSubDir.cmake b/Tests/RunCMake/install/TARGETS-InstallFromSubDir.cmake
new file mode 100644
index 000000000..8615d6ecb
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-InstallFromSubDir.cmake
@@ -0,0 +1,4 @@
+enable_language(C)
+add_executable(myexe main.c)
+add_subdirectory(TARGETS-InstallFromSubDir)
+install(TARGETS myexe subexe DESTINATION bin)
diff --git a/Tests/RunCMake/install/TARGETS-InstallFromSubDir/CMakeLists.txt b/Tests/RunCMake/install/TARGETS-InstallFromSubDir/CMakeLists.txt
new file mode 100644
index 000000000..477d9381f
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-InstallFromSubDir/CMakeLists.txt
@@ -0,0 +1 @@
+add_executable(subexe ../main.c)
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-all-check.cmake b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-all-check.cmake
new file mode 100644
index 000000000..bc9ebd192
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-all-check.cmake
@@ -0,0 +1,73 @@
+if(WIN32)
+ set(_check_files
+ [[lib]]
+ [[lib/(lib)?namelink-none\.dll]]
+ [[lib/(lib)?namelink-same\.dll]]
+ [[lib/(lib)?namelink-sep\.dll]]
+ [[lib/(lib)?namelink-skip\.dll]]
+ [[lib/(lib)?namelink-uns-dev\.dll]]
+ [[lib/(lib)?namelink-uns\.dll]]
+ )
+elseif(CYGWIN)
+ set(_check_files
+ [[lib]]
+ [[lib/cygnamelink-none\.dll]]
+ [[lib/cygnamelink-same-1\.dll]]
+ [[lib/cygnamelink-sep-1\.dll]]
+ [[lib/cygnamelink-skip-1\.dll]]
+ [[lib/cygnamelink-uns-1\.dll]]
+ [[lib/cygnamelink-uns-dev-1\.dll]]
+ )
+elseif(APPLE)
+ set(_check_files
+ [[lib]]
+ [[lib/libnamelink-none\.dylib]]
+ [[lib/libnamelink-only\.dylib]]
+ [[lib/libnamelink-same\.1\.0\.dylib]]
+ [[lib/libnamelink-same\.1\.dylib]]
+ [[lib/libnamelink-same\.dylib]]
+ [[lib/libnamelink-sep\.1\.0\.dylib]]
+ [[lib/libnamelink-sep\.1\.dylib]]
+ [[lib/libnamelink-sep\.dylib]]
+ [[lib/libnamelink-skip\.1\.0\.dylib]]
+ [[lib/libnamelink-skip\.1\.dylib]]
+ [[lib/libnamelink-uns-dev\.1\.0\.dylib]]
+ [[lib/libnamelink-uns-dev\.1\.dylib]]
+ [[lib/libnamelink-uns-dev\.dylib]]
+ [[lib/libnamelink-uns\.1\.0\.dylib]]
+ [[lib/libnamelink-uns\.1\.dylib]]
+ [[lib/libnamelink-uns\.dylib]]
+ )
+elseif(NO_NAMELINK)
+ set(_check_files
+ [[lib]]
+ [[lib/libnamelink-none\.so]]
+ [[lib/libnamelink-same\.so]]
+ [[lib/libnamelink-sep\.so]]
+ [[lib/libnamelink-skip\.so]]
+ [[lib/libnamelink-uns-dev\.so]]
+ [[lib/libnamelink-uns\.so]]
+ )
+else()
+ set(_check_files
+ [[lib]]
+ [[lib/libnamelink-none\.so]]
+ [[lib/libnamelink-only\.so]]
+ [[lib/libnamelink-same\.so]]
+ [[lib/libnamelink-same\.so\.1]]
+ [[lib/libnamelink-same\.so\.1\.0]]
+ [[lib/libnamelink-sep\.so]]
+ [[lib/libnamelink-sep\.so\.1]]
+ [[lib/libnamelink-sep\.so\.1\.0]]
+ [[lib/libnamelink-skip\.so\.1]]
+ [[lib/libnamelink-skip\.so\.1\.0]]
+ [[lib/libnamelink-uns-dev\.so]]
+ [[lib/libnamelink-uns-dev\.so\.1]]
+ [[lib/libnamelink-uns-dev\.so\.1\.0]]
+ [[lib/libnamelink-uns\.so]]
+ [[lib/libnamelink-uns\.so\.1]]
+ [[lib/libnamelink-uns\.so\.1\.0]]
+ )
+endif()
+
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all-result.txt b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all-stderr.txt b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all-stderr.txt
new file mode 100644
index 000000000..fe65fd300
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at TARGETS-NAMELINK_COMPONENT-bad-all\.cmake:5 \(install\):
+ install TARGETS given NAMELINK_COMPONENT option not in LIBRARY group\. The
+ NAMELINK_COMPONENT option may be specified only following LIBRARY\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all.cmake b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all.cmake
new file mode 100644
index 000000000..701d0931c
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-all.cmake
@@ -0,0 +1,9 @@
+enable_language(C)
+
+add_library(namelink-lib empty.c)
+
+install(TARGETS namelink-lib
+ DESTINATION lib
+ COMPONENT lib
+ NAMELINK_COMPONENT dev
+)
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc-result.txt b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc-stderr.txt b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc-stderr.txt
new file mode 100644
index 000000000..60f52c488
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at TARGETS-NAMELINK_COMPONENT-bad-exc\.cmake:5 \(install\):
+ install TARGETS given NAMELINK_COMPONENT option not in LIBRARY group\. The
+ NAMELINK_COMPONENT option may be specified only following LIBRARY\.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc.cmake b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc.cmake
new file mode 100644
index 000000000..19c12d4bc
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-bad-exc.cmake
@@ -0,0 +1,10 @@
+enable_language(C)
+
+add_executable(namelink-exc main.c)
+
+install(TARGETS namelink-exc
+ RUNTIME
+ DESTINATION bin
+ COMPONENT exc
+ NAMELINK_COMPONENT dev
+)
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-dev-check.cmake b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-dev-check.cmake
new file mode 100644
index 000000000..5396cdbf3
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-dev-check.cmake
@@ -0,0 +1,11 @@
+if(WIN32 OR CYGWIN OR NO_NAMELINK)
+ set(_check_files)
+else()
+ set(_check_files
+ [[lib]]
+ [[lib/libnamelink-only\.(so|dylib)]]
+ [[lib/libnamelink-sep\.(so|dylib)]]
+ [[lib/libnamelink-uns-dev\.(so|dylib)]]
+ )
+endif()
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-lib-check.cmake b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-lib-check.cmake
new file mode 100644
index 000000000..3f6be686c
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-lib-check.cmake
@@ -0,0 +1,50 @@
+if(WIN32)
+ set(_check_files
+ [[lib]]
+ [[lib/(lib)?namelink-none\.dll]]
+ [[lib/(lib)?namelink-same\.dll]]
+ [[lib/(lib)?namelink-sep\.dll]]
+ [[lib/(lib)?namelink-skip\.dll]]
+ )
+elseif(CYGWIN)
+ set(_check_files
+ [[lib]]
+ [[lib/cygnamelink-none\.dll]]
+ [[lib/cygnamelink-same-1\.dll]]
+ [[lib/cygnamelink-sep-1\.dll]]
+ [[lib/cygnamelink-skip-1\.dll]]
+ )
+elseif(APPLE)
+ set(_check_files
+ [[lib]]
+ [[lib/libnamelink-none\.dylib]]
+ [[lib/libnamelink-same\.1\.0\.dylib]]
+ [[lib/libnamelink-same\.1\.dylib]]
+ [[lib/libnamelink-same\.dylib]]
+ [[lib/libnamelink-sep\.1\.0\.dylib]]
+ [[lib/libnamelink-sep\.1\.dylib]]
+ [[lib/libnamelink-skip\.1\.0\.dylib]]
+ [[lib/libnamelink-skip\.1\.dylib]]
+ )
+elseif(NO_NAMELINK)
+ set(_check_files
+ [[lib]]
+ [[lib/libnamelink-none\.so]]
+ [[lib/libnamelink-same\.so]]
+ [[lib/libnamelink-sep\.so]]
+ [[lib/libnamelink-skip\.so]]
+ )
+else()
+ set(_check_files
+ [[lib]]
+ [[lib/libnamelink-none\.so]]
+ [[lib/libnamelink-same\.so]]
+ [[lib/libnamelink-same\.so\.1]]
+ [[lib/libnamelink-same\.so\.1\.0]]
+ [[lib/libnamelink-sep\.so\.1]]
+ [[lib/libnamelink-sep\.so\.1\.0]]
+ [[lib/libnamelink-skip\.so\.1]]
+ [[lib/libnamelink-skip\.so\.1\.0]]
+ )
+endif()
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-uns-check.cmake b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-uns-check.cmake
new file mode 100644
index 000000000..0033c88e4
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT-uns-check.cmake
@@ -0,0 +1,38 @@
+if(WIN32)
+ set(_check_files
+ [[lib]]
+ [[lib/(lib)?namelink-uns-dev\.dll]]
+ [[lib/(lib)?namelink-uns\.dll]]
+ )
+elseif(CYGWIN)
+ set(_check_files
+ [[lib]]
+ [[lib/cygnamelink-uns-1\.dll]]
+ [[lib/cygnamelink-uns-dev-1\.dll]]
+ )
+elseif(APPLE)
+ set(_check_files
+ [[lib]]
+ [[lib/libnamelink-uns-dev\.1\.0\.dylib]]
+ [[lib/libnamelink-uns-dev\.1\.dylib]]
+ [[lib/libnamelink-uns\.1\.0\.dylib]]
+ [[lib/libnamelink-uns\.1\.dylib]]
+ [[lib/libnamelink-uns\.dylib]]
+ )
+elseif(NO_NAMELINK)
+ set(_check_files
+ [[lib]]
+ [[lib/libnamelink-uns-dev\.so]]
+ [[lib/libnamelink-uns\.so]]
+ )
+else()
+ set(_check_files
+ [[lib]]
+ [[lib/libnamelink-uns-dev\.so\.1]]
+ [[lib/libnamelink-uns-dev\.so\.1\.0]]
+ [[lib/libnamelink-uns\.so]]
+ [[lib/libnamelink-uns\.so\.1]]
+ [[lib/libnamelink-uns\.so\.1\.0]]
+ )
+endif()
+check_installed("^${_check_files}$")
diff --git a/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT.cmake b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT.cmake
new file mode 100644
index 000000000..0e684e184
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-NAMELINK_COMPONENT.cmake
@@ -0,0 +1,68 @@
+enable_language(C)
+
+macro(add_versioned_library NAME)
+ add_library(${NAME} SHARED obj1.c)
+ set_target_properties(${NAME} PROPERTIES
+ VERSION 1.0
+ SOVERSION 1
+ )
+endmacro()
+
+add_versioned_library(namelink-sep)
+add_versioned_library(namelink-same)
+add_versioned_library(namelink-uns)
+add_versioned_library(namelink-uns-dev)
+add_versioned_library(namelink-only)
+add_versioned_library(namelink-skip)
+add_library(namelink-none SHARED obj1.c)
+
+install(TARGETS namelink-sep namelink-none
+ RUNTIME
+ DESTINATION lib
+ COMPONENT lib
+ LIBRARY
+ DESTINATION lib
+ COMPONENT lib
+ NAMELINK_COMPONENT dev
+)
+install(TARGETS namelink-same
+ RUNTIME
+ DESTINATION lib
+ COMPONENT lib
+ LIBRARY
+ DESTINATION lib
+ COMPONENT lib
+)
+install(TARGETS namelink-uns
+ RUNTIME
+ DESTINATION lib
+ LIBRARY
+ DESTINATION lib
+)
+install(TARGETS namelink-uns-dev
+ RUNTIME
+ DESTINATION lib
+ LIBRARY
+ DESTINATION lib
+ NAMELINK_COMPONENT dev
+)
+install(TARGETS namelink-only
+ RUNTIME
+ DESTINATION lib
+ COMPONENT lib
+ LIBRARY
+ DESTINATION lib
+ COMPONENT lib
+ NAMELINK_COMPONENT dev
+ NAMELINK_ONLY
+)
+install(TARGETS namelink-skip
+ RUNTIME
+ DESTINATION lib
+ COMPONENT lib
+ LIBRARY
+ DESTINATION lib
+ COMPONENT lib
+ NAMELINK_COMPONENT dev
+ NAMELINK_SKIP
+)
diff --git a/Tests/RunCMake/install/TARGETS-OPTIONAL-all-check.cmake b/Tests/RunCMake/install/TARGETS-OPTIONAL-all-check.cmake
new file mode 100644
index 000000000..bcf71ddfe
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-OPTIONAL-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^bin;bin/myexe(\.exe)?$]])
diff --git a/Tests/RunCMake/install/TARGETS-OPTIONAL.cmake b/Tests/RunCMake/install/TARGETS-OPTIONAL.cmake
new file mode 100644
index 000000000..d3c5cdae2
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-OPTIONAL.cmake
@@ -0,0 +1,4 @@
+enable_language(C)
+add_executable(myexe main.c)
+add_executable(notall EXCLUDE_FROM_ALL main.c)
+install(TARGETS myexe notall DESTINATION bin OPTIONAL)
diff --git a/Tests/RunCMake/install/TARGETS-OUTPUT_NAME-all-check.cmake b/Tests/RunCMake/install/TARGETS-OUTPUT_NAME-all-check.cmake
new file mode 100644
index 000000000..5daecc815
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-OUTPUT_NAME-all-check.cmake
@@ -0,0 +1,13 @@
+if(WIN32)
+ set(test123 [[bin/test1out\.exe;bin/test2deb\.exe;bin/test3exc\.exe]])
+ set(libtest45 [[bin/libtest4\.dll;bin/libtest4\.dll\.a;bin/libtest5ar\.a]])
+ set(test45 [[bin/test4\.dll;bin/test4\.lib;bin/test5ar\.lib]])
+
+ check_installed("^bin;(${libtest45};${test123})|(${test123};${test45})\$")
+elseif(CYGWIN)
+ check_installed([[^bin;bin/cygtest4\.dll;bin/libtest4\.dll\.a;bin/libtest5ar\.a;bin/test1out\.exe;bin/test2deb\.exe;bin/test3exc\.exe$]])
+elseif(APPLE)
+ check_installed([[^bin;bin/libtest4lib\.dylib;bin/libtest5ar\.a;bin/test1out;bin/test2deb;bin/test3exc$]])
+else()
+ check_installed([[^bin;bin/libtest4lib\.so;bin/libtest5ar\.a;bin/test1out;bin/test2deb;bin/test3exc$]])
+endif()
diff --git a/Tests/RunCMake/install/TARGETS-OUTPUT_NAME.cmake b/Tests/RunCMake/install/TARGETS-OUTPUT_NAME.cmake
new file mode 100644
index 000000000..67e706941
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-OUTPUT_NAME.cmake
@@ -0,0 +1,27 @@
+enable_language(C)
+
+add_executable(test1 main.c)
+set_property(TARGET test1 PROPERTY OUTPUT_NAME test1out)
+set_property(TARGET test1 PROPERTY RELEASE_OUTPUT_NAME test1rel)
+
+add_executable(test2 main.c)
+set_property(TARGET test2 PROPERTY OUTPUT_NAME test2out)
+set_property(TARGET test2 PROPERTY DEBUG_OUTPUT_NAME test2deb)
+
+add_executable(test3 main.c)
+set_property(TARGET test3 PROPERTY RUNTIME_OUTPUT_NAME test3exc)
+
+add_library(test4 SHARED obj1.c)
+set_property(TARGET test4 PROPERTY LIBRARY_OUTPUT_NAME test4lib)
+
+add_library(test5 STATIC obj1.c)
+set_property(TARGET test5 PROPERTY ARCHIVE_OUTPUT_NAME test5ar)
+
+install(TARGETS
+ test1
+ test2
+ test3
+ test4
+ test5
+ DESTINATION bin
+ )
diff --git a/Tests/RunCMake/install/TARGETS-Parts-all-check.cmake b/Tests/RunCMake/install/TARGETS-Parts-all-check.cmake
new file mode 100644
index 000000000..6245839fc
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-Parts-all-check.cmake
@@ -0,0 +1 @@
+check_installed([[^include;include/obj1\.h;lib;lib/(mylib\.lib|(lib|cyg)mylib\.a)$]])
diff --git a/Tests/RunCMake/install/TARGETS-Parts.cmake b/Tests/RunCMake/install/TARGETS-Parts.cmake
new file mode 100644
index 000000000..2a46ab9a9
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-Parts.cmake
@@ -0,0 +1,7 @@
+enable_language(C)
+add_library(mylib STATIC obj1.c)
+set_property(TARGET mylib PROPERTY PUBLIC_HEADER obj1.h)
+install(TARGETS mylib
+ ARCHIVE DESTINATION lib
+ PUBLIC_HEADER DESTINATION include
+ )
diff --git a/Tests/RunCMake/install/TARGETS-RPATH-all-check.cmake b/Tests/RunCMake/install/TARGETS-RPATH-all-check.cmake
new file mode 100644
index 000000000..fa52d65cf
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-RPATH-all-check.cmake
@@ -0,0 +1,14 @@
+execute_process(
+ COMMAND "${CMAKE_INSTALL_PREFIX}/bin/myexe"
+ RESULT_VARIABLE MYEXE_RESULT
+ OUTPUT_VARIABLE MYEXE_OUTPUT
+ ERROR_VARIABLE MYEXE_ERROR
+ )
+
+if(NOT MYEXE_RESULT EQUAL "0")
+ set(RunCMake_TEST_FAILED "myexe returned [${MYEXE_RESULT}], was expecting [0]")
+elseif(NOT MYEXE_OUTPUT STREQUAL "")
+ set(RunCMake_TEST_FAILED "myexe printed nonempty output:\n${MYEXE_OUTPUT}")
+elseif(NOT MYEXE_ERROR STREQUAL "")
+ set(RunCMake_TEST_FAILED "myexe printed nonempty error:\n${MYEXE_ERROR}")
+endif()
diff --git a/Tests/RunCMake/install/TARGETS-RPATH.cmake b/Tests/RunCMake/install/TARGETS-RPATH.cmake
new file mode 100644
index 000000000..b75deffff
--- /dev/null
+++ b/Tests/RunCMake/install/TARGETS-RPATH.cmake
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.9)
+
+enable_language(C)
+
+set(CMAKE_BUILD_WITH_INSTALL_RPATH 1)
+add_library(mylib SHARED obj1.c)
+add_executable(myexe testobj1.c)
+target_link_libraries(myexe mylib)
+set_property(TARGET myexe PROPERTY INSTALL_RPATH "${CMAKE_CURRENT_BINARY_DIR}/root-all/bin")
+set_target_properties(mylib PROPERTIES VERSION 1.0 SOVERSION 1)
+
+install(TARGETS mylib myexe
+ DESTINATION bin
+ )
diff --git a/Tests/RunCMake/install/install_script.cmake b/Tests/RunCMake/install/install_script.cmake
new file mode 100644
index 000000000..1f8522c70
--- /dev/null
+++ b/Tests/RunCMake/install/install_script.cmake
@@ -0,0 +1,5 @@
+function(write_empty_file FILENAME)
+ file(WRITE "${CMAKE_INSTALL_PREFIX}/${FILENAME}" "")
+endfunction()
+
+write_empty_file(empty1.txt)
diff --git a/Tests/RunCMake/install/obj1.h b/Tests/RunCMake/install/obj1.h
new file mode 100644
index 000000000..d88d5d2b9
--- /dev/null
+++ b/Tests/RunCMake/install/obj1.h
@@ -0,0 +1,6 @@
+#ifndef OBJ1_H
+#define OBJ1_H
+
+int obj1(void);
+
+#endif /* OBJ1_H */
diff --git a/Tests/RunCMake/install/obj2.h b/Tests/RunCMake/install/obj2.h
new file mode 100644
index 000000000..90bcd3444
--- /dev/null
+++ b/Tests/RunCMake/install/obj2.h
@@ -0,0 +1,6 @@
+#ifndef OBJ2_H
+#define OBJ2_H
+
+int obj2(void);
+
+#endif /* OBJ2_H */
diff --git a/Tests/RunCMake/install/obj3.c b/Tests/RunCMake/install/obj3.c
new file mode 100644
index 000000000..991fed369
--- /dev/null
+++ b/Tests/RunCMake/install/obj3.c
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int obj3(void)
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/install/obj3.h b/Tests/RunCMake/install/obj3.h
new file mode 100644
index 000000000..9e8bb760a
--- /dev/null
+++ b/Tests/RunCMake/install/obj3.h
@@ -0,0 +1,6 @@
+#ifndef OBJ3_H
+#define OBJ3_H
+
+int obj3(void);
+
+#endif /* OBJ3_H */
diff --git a/Tests/RunCMake/install/obj4.c b/Tests/RunCMake/install/obj4.c
new file mode 100644
index 000000000..edd61725d
--- /dev/null
+++ b/Tests/RunCMake/install/obj4.c
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int obj4(void)
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/install/obj4.h b/Tests/RunCMake/install/obj4.h
new file mode 100644
index 000000000..6195aa77e
--- /dev/null
+++ b/Tests/RunCMake/install/obj4.h
@@ -0,0 +1,6 @@
+#ifndef OBJ4_H
+#define OBJ4_H
+
+int obj4(void);
+
+#endif /* OBJ4_H */
diff --git a/Tests/RunCMake/install/obj5.c b/Tests/RunCMake/install/obj5.c
new file mode 100644
index 000000000..df3e9973e
--- /dev/null
+++ b/Tests/RunCMake/install/obj5.c
@@ -0,0 +1,7 @@
+#ifdef _WIN32
+__declspec(dllexport)
+#endif
+ int obj5(void)
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/install/obj5.h b/Tests/RunCMake/install/obj5.h
new file mode 100644
index 000000000..a16a1b0c4
--- /dev/null
+++ b/Tests/RunCMake/install/obj5.h
@@ -0,0 +1,6 @@
+#ifndef OBJ5_H
+#define OBJ5_H
+
+int obj5(void);
+
+#endif /* OBJ5_H */
diff --git a/Tests/RunCMake/install/pattern/empty.c b/Tests/RunCMake/install/pattern/empty.c
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/install/pattern/empty.c
diff --git a/Tests/RunCMake/install/pattern/empty.h b/Tests/RunCMake/install/pattern/empty.h
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/install/pattern/empty.h
diff --git a/Tests/RunCMake/install/pattern/empty.txt b/Tests/RunCMake/install/pattern/empty.txt
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/install/pattern/empty.txt
diff --git a/Tests/RunCMake/install/postinstall.cmake b/Tests/RunCMake/install/postinstall.cmake
new file mode 100644
index 000000000..7607f40e1
--- /dev/null
+++ b/Tests/RunCMake/install/postinstall.cmake
@@ -0,0 +1 @@
+file(WRITE "${CMAKE_INSTALL_PREFIX}/postinstall" "postinstall")
diff --git a/Tests/RunCMake/install/preinstall.cmake b/Tests/RunCMake/install/preinstall.cmake
new file mode 100644
index 000000000..4b28d1626
--- /dev/null
+++ b/Tests/RunCMake/install/preinstall.cmake
@@ -0,0 +1 @@
+file(WRITE "${CMAKE_INSTALL_PREFIX}/preinstall" "preinstall")
diff --git a/Tests/RunCMake/install/script b/Tests/RunCMake/install/script
new file mode 100755
index 000000000..81f9f5315
--- /dev/null
+++ b/Tests/RunCMake/install/script
@@ -0,0 +1,2 @@
+#!/bin/sh
+echo "Sample Script Output"
diff --git a/Tests/RunCMake/install/script.bat b/Tests/RunCMake/install/script.bat
new file mode 100755
index 000000000..64a77b5b0
--- /dev/null
+++ b/Tests/RunCMake/install/script.bat
@@ -0,0 +1 @@
+@echo Sample Script Output
diff --git a/Tests/RunCMake/install/testobj1.c b/Tests/RunCMake/install/testobj1.c
new file mode 100644
index 000000000..081ef2027
--- /dev/null
+++ b/Tests/RunCMake/install/testobj1.c
@@ -0,0 +1,9 @@
+#ifdef _WIN32
+__declspec(dllimport)
+#endif
+ int obj1(void);
+
+int main(void)
+{
+ return obj1();
+}
diff --git a/Tests/RunCMake/list/JOIN-NoArguments-result.txt b/Tests/RunCMake/list/JOIN-NoArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/JOIN-NoArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/JOIN-NoArguments-stderr.txt b/Tests/RunCMake/list/JOIN-NoArguments-stderr.txt
new file mode 100644
index 000000000..5e1b98f35
--- /dev/null
+++ b/Tests/RunCMake/list/JOIN-NoArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at JOIN-NoArguments.cmake:1 \(list\):
+ list sub-command JOIN requires three arguments \(1 found\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/JOIN-NoArguments.cmake b/Tests/RunCMake/list/JOIN-NoArguments.cmake
new file mode 100644
index 000000000..2ab449a97
--- /dev/null
+++ b/Tests/RunCMake/list/JOIN-NoArguments.cmake
@@ -0,0 +1 @@
+list(JOIN mylist)
diff --git a/Tests/RunCMake/list/JOIN-NoVariable-result.txt b/Tests/RunCMake/list/JOIN-NoVariable-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/JOIN-NoVariable-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/JOIN-NoVariable-stderr.txt b/Tests/RunCMake/list/JOIN-NoVariable-stderr.txt
new file mode 100644
index 000000000..db1d77307
--- /dev/null
+++ b/Tests/RunCMake/list/JOIN-NoVariable-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at JOIN-NoVariable.cmake:1 \(list\):
+ list sub-command JOIN requires three arguments \(2 found\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/JOIN-NoVariable.cmake b/Tests/RunCMake/list/JOIN-NoVariable.cmake
new file mode 100644
index 000000000..b60d8f14f
--- /dev/null
+++ b/Tests/RunCMake/list/JOIN-NoVariable.cmake
@@ -0,0 +1 @@
+list(JOIN mylist "glue")
diff --git a/Tests/RunCMake/list/JOIN-TooManyArguments-result.txt b/Tests/RunCMake/list/JOIN-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/JOIN-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/JOIN-TooManyArguments-stderr.txt b/Tests/RunCMake/list/JOIN-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..2b09e22a2
--- /dev/null
+++ b/Tests/RunCMake/list/JOIN-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at JOIN-TooManyArguments.cmake:1 \(list\):
+ list sub-command JOIN requires three arguments \(4 found\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/JOIN-TooManyArguments.cmake b/Tests/RunCMake/list/JOIN-TooManyArguments.cmake
new file mode 100644
index 000000000..dc651f6c1
--- /dev/null
+++ b/Tests/RunCMake/list/JOIN-TooManyArguments.cmake
@@ -0,0 +1 @@
+list(JOIN mylist "glue" out one_too_many)
diff --git a/Tests/RunCMake/list/JOIN.cmake b/Tests/RunCMake/list/JOIN.cmake
new file mode 100644
index 000000000..24a623e66
--- /dev/null
+++ b/Tests/RunCMake/list/JOIN.cmake
@@ -0,0 +1,18 @@
+list(JOIN undefList % out)
+if(NOT out STREQUAL "")
+ message(FATAL_ERROR "\"list(JOIN undefList % out)\" set out to \"${out}\"")
+endif()
+set(myList a)
+list(JOIN myList % out)
+if(NOT out STREQUAL "a")
+ message(FATAL_ERROR "\"list(JOIN \"a\" % out)\" set out to \"${out}\"")
+endif()
+set(myList a b)
+list(JOIN myList % out)
+if(NOT out STREQUAL "a%b")
+ message(FATAL_ERROR "\"list(JOIN \"a;b\" % out)\" set out to \"${out}\"")
+endif()
+list(JOIN myList "" out)
+if(NOT out STREQUAL "ab")
+ message(FATAL_ERROR "\"list(JOIN \"a;b\" \"\" out a)\" set out to \"${out}\"")
+endif()
diff --git a/Tests/RunCMake/list/POP_BACK-NoArgs-result.txt b/Tests/RunCMake/list/POP_BACK-NoArgs-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/POP_BACK-NoArgs-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/POP_BACK-NoArgs-stderr.txt b/Tests/RunCMake/list/POP_BACK-NoArgs-stderr.txt
new file mode 100644
index 000000000..83060b44c
--- /dev/null
+++ b/Tests/RunCMake/list/POP_BACK-NoArgs-stderr.txt
@@ -0,0 +1 @@
+list must be called with at least two arguments
diff --git a/Tests/RunCMake/list/POP_BACK-NoArgs.cmake b/Tests/RunCMake/list/POP_BACK-NoArgs.cmake
new file mode 100644
index 000000000..518924d71
--- /dev/null
+++ b/Tests/RunCMake/list/POP_BACK-NoArgs.cmake
@@ -0,0 +1 @@
+list(POP_FRONT)
diff --git a/Tests/RunCMake/list/POP_BACK.cmake b/Tests/RunCMake/list/POP_BACK.cmake
new file mode 100644
index 000000000..479479632
--- /dev/null
+++ b/Tests/RunCMake/list/POP_BACK.cmake
@@ -0,0 +1,79 @@
+cmake_policy(SET CMP0054 NEW)
+
+function(assert_expected_list_len list_var expected_size)
+ list(LENGTH ${list_var} _size)
+ if(NOT _size EQUAL ${expected_size})
+ message(FATAL_ERROR "list size expected to be `${expected_size}`, got `${_size}` instead")
+ endif()
+endfunction()
+
+# Pop from undefined list
+list(POP_BACK test)
+if(DEFINED test)
+ message(FATAL_ERROR "`test` expected to be undefined")
+endif()
+
+# Pop from empty list
+set(test)
+list(POP_BACK test)
+if(DEFINED test)
+ message(FATAL_ERROR "`test` expected to be undefined")
+endif()
+
+# Default pop from 1-item list
+list(APPEND test one)
+list(POP_BACK test)
+assert_expected_list_len(test 0)
+
+# Pop from 1-item list to var
+list(APPEND test one)
+list(POP_BACK test one)
+assert_expected_list_len(test 0)
+if(NOT DEFINED one)
+ message(FATAL_ERROR "`one` expected to be defined")
+endif()
+if(NOT one STREQUAL "one")
+ message(FATAL_ERROR "`one` has unexpected value `${one}`")
+endif()
+
+unset(one)
+unset(two)
+
+# Pop from 1-item list to vars
+list(APPEND test one)
+list(POP_BACK test one two)
+assert_expected_list_len(test 0)
+if(NOT DEFINED one)
+ message(FATAL_ERROR "`one` expected to be defined")
+endif()
+if(NOT one STREQUAL "one")
+ message(FATAL_ERROR "`one` has unexpected value `${one}`")
+endif()
+if(DEFINED two)
+ message(FATAL_ERROR "`two` expected to be undefined")
+endif()
+
+unset(one)
+unset(two)
+
+# Default pop from 2-item list
+list(APPEND test one two)
+list(POP_BACK test)
+assert_expected_list_len(test 1)
+if(NOT test STREQUAL "one")
+ message(FATAL_ERROR "`test` has unexpected value `${test}`")
+endif()
+
+# Pop from 2-item list
+list(APPEND test two)
+list(POP_BACK test two)
+assert_expected_list_len(test 1)
+if(NOT DEFINED two)
+ message(FATAL_ERROR "`two` expected to be defined")
+endif()
+if(NOT two STREQUAL "two")
+ message(FATAL_ERROR "`two` has unexpected value `${two}`")
+endif()
+if(NOT test STREQUAL "one")
+ message(FATAL_ERROR "`test` has unexpected value `${test}`")
+endif()
diff --git a/Tests/RunCMake/list/POP_FRONT-NoArgs-result.txt b/Tests/RunCMake/list/POP_FRONT-NoArgs-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/POP_FRONT-NoArgs-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/POP_FRONT-NoArgs-stderr.txt b/Tests/RunCMake/list/POP_FRONT-NoArgs-stderr.txt
new file mode 100644
index 000000000..83060b44c
--- /dev/null
+++ b/Tests/RunCMake/list/POP_FRONT-NoArgs-stderr.txt
@@ -0,0 +1 @@
+list must be called with at least two arguments
diff --git a/Tests/RunCMake/list/POP_FRONT-NoArgs.cmake b/Tests/RunCMake/list/POP_FRONT-NoArgs.cmake
new file mode 100644
index 000000000..c5cf83739
--- /dev/null
+++ b/Tests/RunCMake/list/POP_FRONT-NoArgs.cmake
@@ -0,0 +1 @@
+list(POP_BACK)
diff --git a/Tests/RunCMake/list/POP_FRONT.cmake b/Tests/RunCMake/list/POP_FRONT.cmake
new file mode 100644
index 000000000..70f757a27
--- /dev/null
+++ b/Tests/RunCMake/list/POP_FRONT.cmake
@@ -0,0 +1,92 @@
+cmake_policy(SET CMP0054 NEW)
+
+function(assert_expected_list_len list_var expected_size)
+ list(LENGTH ${list_var} _size)
+ if(NOT _size EQUAL ${expected_size})
+ message(FATAL_ERROR "list size expected to be `${expected_size}`, got `${_size}` instead")
+ endif()
+endfunction()
+
+# Pop from undefined list
+list(POP_FRONT test)
+if(DEFINED test)
+ message(FATAL_ERROR "`test` expected to be undefined")
+endif()
+
+# Pop from empty list
+set(test)
+list(POP_FRONT test)
+if(DEFINED test)
+ message(FATAL_ERROR "`test` expected to be undefined")
+endif()
+
+# Default pop from 1-item list
+list(APPEND test one)
+list(POP_FRONT test)
+assert_expected_list_len(test 0)
+
+# Pop from 1-item list to var
+list(APPEND test one)
+list(POP_FRONT test one)
+assert_expected_list_len(test 0)
+if(NOT DEFINED one)
+ message(FATAL_ERROR "`one` expected to be defined")
+endif()
+if(NOT one STREQUAL "one")
+ message(FATAL_ERROR "`one` has unexpected value `${one}`")
+endif()
+
+unset(one)
+unset(two)
+
+# Pop from 1-item list to vars
+list(APPEND test one)
+list(POP_FRONT test one two)
+assert_expected_list_len(test 0)
+if(NOT DEFINED one)
+ message(FATAL_ERROR "`one` expected to be defined")
+endif()
+if(NOT one STREQUAL "one")
+ message(FATAL_ERROR "`one` has unexpected value `${one}`")
+endif()
+if(DEFINED two)
+ message(FATAL_ERROR "`two` expected to be undefined")
+endif()
+
+unset(one)
+unset(two)
+
+# Default pop from 2-item list
+list(APPEND test one two)
+list(POP_FRONT test)
+assert_expected_list_len(test 1)
+if(NOT test STREQUAL "two")
+ message(FATAL_ERROR "`test` has unexpected value `${test}`")
+endif()
+
+# Pop from 2-item list
+list(PREPEND test one)
+list(POP_FRONT test one)
+assert_expected_list_len(test 1)
+if(NOT DEFINED one)
+ message(FATAL_ERROR "`one` expected to be defined")
+endif()
+if(NOT one STREQUAL "one")
+ message(FATAL_ERROR "`one` has unexpected value `${one}`")
+endif()
+if(NOT test STREQUAL "two")
+ message(FATAL_ERROR "`test` has unexpected value `${test}`")
+endif()
+
+# BUG 19436
+set(myList a b c)
+list(POP_FRONT myList first second)
+if(NOT first STREQUAL "a")
+ message(FATAL_ERROR "BUG#19436: `first` has unexpected value `${first}`")
+endif()
+if(NOT second STREQUAL "b")
+ message(FATAL_ERROR "BUG#19436: `second` has unexpected value `${second}`")
+endif()
+if(NOT myList STREQUAL "c")
+ message(FATAL_ERROR "BUG#19436: `myList` has unexpected value `${myList}`")
+endif()
diff --git a/Tests/RunCMake/list/PREPEND-NoArgs-result.txt b/Tests/RunCMake/list/PREPEND-NoArgs-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/PREPEND-NoArgs-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/PREPEND-NoArgs-stderr.txt b/Tests/RunCMake/list/PREPEND-NoArgs-stderr.txt
new file mode 100644
index 000000000..83060b44c
--- /dev/null
+++ b/Tests/RunCMake/list/PREPEND-NoArgs-stderr.txt
@@ -0,0 +1 @@
+list must be called with at least two arguments
diff --git a/Tests/RunCMake/list/PREPEND-NoArgs.cmake b/Tests/RunCMake/list/PREPEND-NoArgs.cmake
new file mode 100644
index 000000000..8935fa9c5
--- /dev/null
+++ b/Tests/RunCMake/list/PREPEND-NoArgs.cmake
@@ -0,0 +1 @@
+list(PREPEND)
diff --git a/Tests/RunCMake/list/PREPEND.cmake b/Tests/RunCMake/list/PREPEND.cmake
new file mode 100644
index 000000000..17b292126
--- /dev/null
+++ b/Tests/RunCMake/list/PREPEND.cmake
@@ -0,0 +1,33 @@
+list(PREPEND test)
+if(test)
+ message(FATAL_ERROR "failed")
+endif()
+
+list(PREPEND test satu)
+if(NOT test STREQUAL "satu")
+ message(FATAL_ERROR "failed")
+endif()
+
+list(PREPEND test dua)
+if(NOT test STREQUAL "dua;satu")
+ message(FATAL_ERROR "failed")
+endif()
+
+list(PREPEND test tiga)
+if(NOT test STREQUAL "tiga;dua;satu")
+ message(FATAL_ERROR "failed")
+endif()
+
+# Scope test
+function(foo)
+ list(PREPEND test empat)
+ if(NOT test STREQUAL "empat;tiga;dua;satu")
+ message(FATAL_ERROR "failed")
+ endif()
+endfunction()
+
+foo()
+
+if(NOT test STREQUAL "tiga;dua;satu")
+ message(FATAL_ERROR "failed")
+endif()
diff --git a/Tests/RunCMake/list/REMOVE_AT-EmptyList-result.txt b/Tests/RunCMake/list/REMOVE_AT-EmptyList-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/REMOVE_AT-EmptyList-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/REMOVE_AT-EmptyList-stderr.txt b/Tests/RunCMake/list/REMOVE_AT-EmptyList-stderr.txt
new file mode 100644
index 000000000..582b74b04
--- /dev/null
+++ b/Tests/RunCMake/list/REMOVE_AT-EmptyList-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at REMOVE_AT-EmptyList.cmake:2 \(list\):
+ list index: nosuchlist, 0 out of range \(0, 0\)
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/REMOVE_AT-EmptyList.cmake b/Tests/RunCMake/list/REMOVE_AT-EmptyList.cmake
new file mode 100644
index 000000000..ff0dde84f
--- /dev/null
+++ b/Tests/RunCMake/list/REMOVE_AT-EmptyList.cmake
@@ -0,0 +1,6 @@
+set(nosuchlist "")
+list(REMOVE_AT nosuchlist 0)
+if (NOT DEFINED nosuchlist OR NOT nosuchlist STREQUAL "")
+ message(FATAL_ERROR
+ "list(REMOVE_AT) modified our list")
+endif ()
diff --git a/Tests/RunCMake/list/REMOVE_DUPLICATES-PreserveOrder.cmake b/Tests/RunCMake/list/REMOVE_DUPLICATES-PreserveOrder.cmake
new file mode 100644
index 000000000..91abbd61a
--- /dev/null
+++ b/Tests/RunCMake/list/REMOVE_DUPLICATES-PreserveOrder.cmake
@@ -0,0 +1,5 @@
+set(mylist "b;c;b;a;a;c;b;a;c;b")
+list(REMOVE_DUPLICATES mylist)
+if(NOT mylist STREQUAL "b;c;a")
+ message(SEND_ERROR "Expected b;c;a, got ${mylist}")
+endif()
diff --git a/Tests/RunCMake/list/SORT-BadCaseOption-result.txt b/Tests/RunCMake/list/SORT-BadCaseOption-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-BadCaseOption-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SORT-BadCaseOption-stderr.txt b/Tests/RunCMake/list/SORT-BadCaseOption-stderr.txt
new file mode 100644
index 000000000..87dd50283
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-BadCaseOption-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SORT-BadCaseOption.cmake:1 \(list\):
+ list sub-command SORT value "BAD_CASE_OPTION" for option "CASE" is invalid.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SORT-BadCaseOption.cmake b/Tests/RunCMake/list/SORT-BadCaseOption.cmake
new file mode 100644
index 000000000..ac5c102b6
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-BadCaseOption.cmake
@@ -0,0 +1 @@
+list(SORT mylist CASE BAD_CASE_OPTION)
diff --git a/Tests/RunCMake/list/SORT-BadCompareOption-result.txt b/Tests/RunCMake/list/SORT-BadCompareOption-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-BadCompareOption-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SORT-BadCompareOption-stderr.txt b/Tests/RunCMake/list/SORT-BadCompareOption-stderr.txt
new file mode 100644
index 000000000..51b4de291
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-BadCompareOption-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at SORT-BadCompareOption.cmake:1 \(list\):
+ list sub-command SORT value "BAD_COMPARE_OPTION" for option "COMPARE" is
+ invalid.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SORT-BadCompareOption.cmake b/Tests/RunCMake/list/SORT-BadCompareOption.cmake
new file mode 100644
index 000000000..d5c632e39
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-BadCompareOption.cmake
@@ -0,0 +1 @@
+list(SORT mylist COMPARE BAD_COMPARE_OPTION)
diff --git a/Tests/RunCMake/list/SORT-BadOrderOption-result.txt b/Tests/RunCMake/list/SORT-BadOrderOption-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-BadOrderOption-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SORT-BadOrderOption-stderr.txt b/Tests/RunCMake/list/SORT-BadOrderOption-stderr.txt
new file mode 100644
index 000000000..7984e5c92
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-BadOrderOption-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at SORT-BadOrderOption.cmake:1 \(list\):
+ list sub-command SORT value "BAD_ODER_OPTION" for option "ORDER" is
+ invalid.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SORT-BadOrderOption.cmake b/Tests/RunCMake/list/SORT-BadOrderOption.cmake
new file mode 100644
index 000000000..e23219772
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-BadOrderOption.cmake
@@ -0,0 +1 @@
+list(SORT mylist ORDER BAD_ODER_OPTION)
diff --git a/Tests/RunCMake/list/SORT-DuplicateCaseOption-result.txt b/Tests/RunCMake/list/SORT-DuplicateCaseOption-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-DuplicateCaseOption-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SORT-DuplicateCaseOption-stderr.txt b/Tests/RunCMake/list/SORT-DuplicateCaseOption-stderr.txt
new file mode 100644
index 000000000..b893f50eb
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-DuplicateCaseOption-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SORT-DuplicateCaseOption.cmake:2 \(list\):
+ list sub-command SORT option "CASE" has been specified multiple times.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SORT-DuplicateCaseOption.cmake b/Tests/RunCMake/list/SORT-DuplicateCaseOption.cmake
new file mode 100644
index 000000000..ba52b2410
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-DuplicateCaseOption.cmake
@@ -0,0 +1,2 @@
+set (mylist a b c)
+list(SORT mylist CASE INSENSITIVE CASE INSENSITIVE )
diff --git a/Tests/RunCMake/list/SORT-DuplicateCompareOption-result.txt b/Tests/RunCMake/list/SORT-DuplicateCompareOption-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-DuplicateCompareOption-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SORT-DuplicateCompareOption-stderr.txt b/Tests/RunCMake/list/SORT-DuplicateCompareOption-stderr.txt
new file mode 100644
index 000000000..83624be42
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-DuplicateCompareOption-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SORT-DuplicateCompareOption.cmake:2 \(list\):
+ list sub-command SORT option "COMPARE" has been specified multiple times.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SORT-DuplicateCompareOption.cmake b/Tests/RunCMake/list/SORT-DuplicateCompareOption.cmake
new file mode 100644
index 000000000..fd2e31d1e
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-DuplicateCompareOption.cmake
@@ -0,0 +1,2 @@
+set (mylist a b c)
+list(SORT mylist COMPARE STRING COMPARE STRING)
diff --git a/Tests/RunCMake/list/SORT-DuplicateOrderOption-result.txt b/Tests/RunCMake/list/SORT-DuplicateOrderOption-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-DuplicateOrderOption-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SORT-DuplicateOrderOption-stderr.txt b/Tests/RunCMake/list/SORT-DuplicateOrderOption-stderr.txt
new file mode 100644
index 000000000..9e95178a2
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-DuplicateOrderOption-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SORT-DuplicateOrderOption.cmake:2 \(list\):
+ list sub-command SORT option "ORDER" has been specified multiple times.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SORT-DuplicateOrderOption.cmake b/Tests/RunCMake/list/SORT-DuplicateOrderOption.cmake
new file mode 100644
index 000000000..26d9c7d8a
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-DuplicateOrderOption.cmake
@@ -0,0 +1,2 @@
+set (mylist a b c)
+list(SORT mylist ORDER ASCENDING ORDER ASCENDING)
diff --git a/Tests/RunCMake/list/SORT-NoCaseOption-result.txt b/Tests/RunCMake/list/SORT-NoCaseOption-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-NoCaseOption-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SORT-NoCaseOption-stderr.txt b/Tests/RunCMake/list/SORT-NoCaseOption-stderr.txt
new file mode 100644
index 000000000..5c63e77a3
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-NoCaseOption-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SORT-NoCaseOption.cmake:1 \(list\):
+ list sub-command SORT missing argument for option "CASE".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SORT-NoCaseOption.cmake b/Tests/RunCMake/list/SORT-NoCaseOption.cmake
new file mode 100644
index 000000000..57cc4292c
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-NoCaseOption.cmake
@@ -0,0 +1 @@
+list(SORT mylist CASE)
diff --git a/Tests/RunCMake/list/SORT-WrongOption-result.txt b/Tests/RunCMake/list/SORT-WrongOption-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-WrongOption-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SORT-WrongOption-stderr.txt b/Tests/RunCMake/list/SORT-WrongOption-stderr.txt
new file mode 100644
index 000000000..597cb298d
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-WrongOption-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SORT-WrongOption.cmake:1 \(list\):
+ list sub-command SORT option "one_too_many" is unknown.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SORT-WrongOption.cmake b/Tests/RunCMake/list/SORT-WrongOption.cmake
new file mode 100644
index 000000000..81b195d67
--- /dev/null
+++ b/Tests/RunCMake/list/SORT-WrongOption.cmake
@@ -0,0 +1 @@
+list(SORT mylist one_too_many)
diff --git a/Tests/RunCMake/list/SORT.cmake b/Tests/RunCMake/list/SORT.cmake
new file mode 100644
index 000000000..4a9e064dd
--- /dev/null
+++ b/Tests/RunCMake/list/SORT.cmake
@@ -0,0 +1,114 @@
+set(source_unsorted
+ c/B.h
+ a/c.h
+ B/a.h
+ )
+
+## Test with default options
+set(expected
+ B/a.h
+ a/c.h
+ c/B.h
+ )
+set(list ${source_unsorted})
+list(SORT list)
+if (NOT expected STREQUAL list)
+ message(FATAL_ERROR "wrong sort result with command list(SORT list CASE SENSITIVE ORDER ASCENDING COMPARE STRING)")
+endif ()
+
+
+## Test CASE INSENSITIVE ORDER ASCENDING COMPARE STRING
+set(expected
+ a/c.h
+ B/a.h
+ c/B.h
+ )
+set(list ${source_unsorted})
+list(SORT list CASE INSENSITIVE ORDER ASCENDING COMPARE STRING)
+if (NOT expected STREQUAL list)
+ message(FATAL_ERROR "wrong sort result with command list(SORT list CASE INSENSITIVE ORDER ASCENDING COMPARE STRING)")
+endif ()
+
+## Test CASE INSENSITIVE ORDER DESCENDING COMPARE STRING
+set(expected
+ c/B.h
+ B/a.h
+ a/c.h
+ )
+set(list ${source_unsorted})
+list(SORT list CASE INSENSITIVE ORDER DESCENDING COMPARE STRING)
+if (NOT expected STREQUAL list)
+ message(FATAL_ERROR "wrong sort result with command list(SORT list CASE INSENSITIVE ORDER DESCENDING COMPARE STRING)")
+endif ()
+
+## Test CASE SENSITIVE ORDER ASCENDING COMPARE STRING
+set(expected
+ B/a.h
+ a/c.h
+ c/B.h
+ )
+set(list ${source_unsorted})
+list(SORT list CASE SENSITIVE ORDER ASCENDING COMPARE STRING)
+if (NOT expected STREQUAL list)
+ message(FATAL_ERROR "wrong sort result with command list(SORT list CASE SENSITIVE ORDER ASCENDING COMPARE STRING)")
+endif ()
+
+## Test CASE SENSITIVE ORDER DESCENDING COMPARE STRING
+set(expected
+ c/B.h
+ a/c.h
+ B/a.h
+ )
+set(list ${source_unsorted})
+list(SORT list CASE SENSITIVE ORDER DESCENDING COMPARE STRING)
+if (NOT expected STREQUAL list)
+ message(FATAL_ERROR "wrong sort result with command list(SORT list CASE SENSITIVE ORDER DESCENDING COMPARE STRING)")
+endif ()
+
+## Test CASE INSENSITIVE ORDER ASCENDING COMPARE FILE_BASENAME
+set(expected
+ B/a.h
+ c/B.h
+ a/c.h
+ )
+set(list ${source_unsorted})
+list(SORT list CASE INSENSITIVE ORDER ASCENDING COMPARE FILE_BASENAME)
+if (NOT expected STREQUAL list)
+ message(FATAL_ERROR "wrong sort result with command list(SORT list CASE INSENSITIVE ORDER ASCENDING COMPARE FILE_BASENAME)")
+endif ()
+
+## Test CASE INSENSITIVE ORDER DESCENDING COMPARE FILE_BASENAME
+set(expected
+ a/c.h
+ c/B.h
+ B/a.h
+ )
+set(list ${source_unsorted})
+list(SORT list CASE INSENSITIVE ORDER DESCENDING COMPARE FILE_BASENAME)
+if (NOT expected STREQUAL list)
+ message(FATAL_ERROR "wrong sort result with command list(SORT list CASE INSENSITIVE ORDER DESCENDING COMPARE FILE_BASENAME)")
+endif ()
+
+## Test CASE SENSITIVE ORDER ASCENDING COMPARE FILE_BASENAME
+set(expected
+ c/B.h
+ B/a.h
+ a/c.h
+ )
+set(list ${source_unsorted})
+list(SORT list CASE SENSITIVE ORDER ASCENDING COMPARE FILE_BASENAME)
+if (NOT expected STREQUAL list)
+ message(FATAL_ERROR "wrong sort result with command list(SORT list CASE SENSITIVE ORDER ASCENDING COMPARE FILE_BASENAME)")
+endif ()
+
+## Test CASE SENSITIVE ORDER DESCENDING COMPARE FILE_BASENAME
+set(expected
+ a/c.h
+ B/a.h
+ c/B.h
+ )
+set(list ${source_unsorted})
+list(SORT list CASE SENSITIVE ORDER DESCENDING COMPARE FILE_BASENAME)
+if (NOT expected STREQUAL list)
+ message(FATAL_ERROR "wrong sort result with command list(SORT list CASE SENSITIVE ORDER DESCENDING COMPARE FILE_BASENAME)")
+endif ()
diff --git a/Tests/RunCMake/list/SUBLIST-InvalidIndex-result.txt b/Tests/RunCMake/list/SUBLIST-InvalidIndex-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-InvalidIndex-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SUBLIST-InvalidIndex-stderr.txt b/Tests/RunCMake/list/SUBLIST-InvalidIndex-stderr.txt
new file mode 100644
index 000000000..5e67b271d
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-InvalidIndex-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SUBLIST-InvalidIndex.cmake:2 \(list\):
+ list begin index: 3 is out of range 0 - 2
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SUBLIST-InvalidIndex.cmake b/Tests/RunCMake/list/SUBLIST-InvalidIndex.cmake
new file mode 100644
index 000000000..565b9dc39
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-InvalidIndex.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(SUBLIST mylist 3 -1 result)
diff --git a/Tests/RunCMake/list/SUBLIST-InvalidLength-result.txt b/Tests/RunCMake/list/SUBLIST-InvalidLength-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-InvalidLength-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SUBLIST-InvalidLength-stderr.txt b/Tests/RunCMake/list/SUBLIST-InvalidLength-stderr.txt
new file mode 100644
index 000000000..16c6ecb34
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-InvalidLength-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SUBLIST-InvalidLength.cmake:2 \(list\):
+ list length: -2 should be -1 or greater
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SUBLIST-InvalidLength.cmake b/Tests/RunCMake/list/SUBLIST-InvalidLength.cmake
new file mode 100644
index 000000000..1dab83f22
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-InvalidLength.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(SUBLIST mylist 0 -2 result)
diff --git a/Tests/RunCMake/list/SUBLIST-NoArguments-result.txt b/Tests/RunCMake/list/SUBLIST-NoArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-NoArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SUBLIST-NoArguments-stderr.txt b/Tests/RunCMake/list/SUBLIST-NoArguments-stderr.txt
new file mode 100644
index 000000000..073173cde
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-NoArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SUBLIST-NoArguments.cmake:1 \(list\):
+ list sub-command SUBLIST requires four arguments \(1 found\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SUBLIST-NoArguments.cmake b/Tests/RunCMake/list/SUBLIST-NoArguments.cmake
new file mode 100644
index 000000000..df38b8780
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-NoArguments.cmake
@@ -0,0 +1 @@
+list(SUBLIST mylist)
diff --git a/Tests/RunCMake/list/SUBLIST-NoVariable-result.txt b/Tests/RunCMake/list/SUBLIST-NoVariable-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-NoVariable-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SUBLIST-NoVariable-stderr.txt b/Tests/RunCMake/list/SUBLIST-NoVariable-stderr.txt
new file mode 100644
index 000000000..6f80c1a98
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-NoVariable-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SUBLIST-NoVariable.cmake:2 \(list\):
+ list sub-command SUBLIST requires four arguments \(3 found\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SUBLIST-NoVariable.cmake b/Tests/RunCMake/list/SUBLIST-NoVariable.cmake
new file mode 100644
index 000000000..83edae9f3
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-NoVariable.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(SUBLIST mylist 0 -1)
diff --git a/Tests/RunCMake/list/SUBLIST-TooManyArguments-result.txt b/Tests/RunCMake/list/SUBLIST-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/SUBLIST-TooManyArguments-stderr.txt b/Tests/RunCMake/list/SUBLIST-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..eb468449b
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at SUBLIST-TooManyArguments.cmake:1 \(list\):
+ list sub-command SUBLIST requires four arguments \(5 found\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/SUBLIST-TooManyArguments.cmake b/Tests/RunCMake/list/SUBLIST-TooManyArguments.cmake
new file mode 100644
index 000000000..28f20c120
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST-TooManyArguments.cmake
@@ -0,0 +1 @@
+list(SUBLIST mylist 0 -1 result one_too_many)
diff --git a/Tests/RunCMake/list/SUBLIST.cmake b/Tests/RunCMake/list/SUBLIST.cmake
new file mode 100644
index 000000000..fd15c2844
--- /dev/null
+++ b/Tests/RunCMake/list/SUBLIST.cmake
@@ -0,0 +1,46 @@
+set(mylist alpha bravo charlie delta)
+list(SUBLIST mylist 1 2 result)
+
+if (NOT result STREQUAL "bravo;charlie")
+ message (FATAL_ERROR "SUBLIST is \"${result}\", expected is \"bravo;charlie\"")
+endif()
+
+
+unset(result)
+list(SUBLIST mylist 0 2 result)
+
+if (NOT result STREQUAL "alpha;bravo")
+ message (FATAL_ERROR "SUBLIST is \"${result}\", expected is \"alpha;bravo\"")
+endif()
+
+
+unset(result)
+list(SUBLIST mylist 3 2 result)
+
+if (NOT result STREQUAL "delta")
+ message (FATAL_ERROR "SUBLIST is \"${result}\", expected is \"delta\"")
+endif()
+
+
+unset(result)
+list(SUBLIST mylist 2 0 result)
+list(LENGTH result length)
+if (NOT length EQUAL 0)
+ message (FATAL_ERROR "SUBLIST is \"${result}\", expected is an empty list")
+endif()
+
+
+unset(result)
+list(SUBLIST mylist 1 5 result)
+
+if (NOT result STREQUAL "bravo;charlie;delta")
+ message (FATAL_ERROR "SUBLIST is \"${result}\", expected is \"bravo;charlie;delta\"")
+endif()
+
+
+unset(result)
+list(SUBLIST mylist 1 -1 result)
+
+if (NOT result STREQUAL "bravo;charlie;delta")
+ message (FATAL_ERROR "SUBLIST is \"${result}\", expected is \"bravo;charlie;delta\"")
+endif()
diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-stderr.txt
new file mode 100644
index 000000000..028f8d589
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-APPEND-NoArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, action APPEND expects 1 argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments.cmake
new file mode 100644
index 000000000..f1611870d
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-APPEND-NoArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist APPEND)
diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..aeb646daf
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-APPEND-TooManyArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments.cmake
new file mode 100644
index 000000000..8430a4c8c
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-APPEND-TooManyArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist APPEND delta one_too_many)
diff --git a/Tests/RunCMake/list/TRANSFORM-APPEND.cmake b/Tests/RunCMake/list/TRANSFORM-APPEND.cmake
new file mode 100644
index 000000000..96390882f
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-APPEND.cmake
@@ -0,0 +1,48 @@
+set(mylist alpha bravo charlie delta)
+
+list(TRANSFORM mylist APPEND "_A" OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha_A;bravo_A;charlie_A;delta_A")
+ message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha_A;bravo_A;charlie_A;delta_A\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist APPEND "_A" AT 1 3 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo_A;charlie;delta_A")
+ message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha;bravo_A;charlie;delta_A\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist APPEND "_A" AT 1 -2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo_A;charlie_A;delta")
+ message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha;bravo_A;charlie_A;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist APPEND "_A" FOR 1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo_A;charlie_A;delta")
+ message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha;bravo_A;charlie_A;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist APPEND "_A" FOR 1 -1 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo_A;charlie_A;delta_A")
+ message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha;bravo_A;charlie_A;delta_A\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist APPEND "_A" FOR 0 -1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha_A;bravo;charlie_A;delta")
+ message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha_A;bravo;charlie_A;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist APPEND "_A" REGEX "(r|t)a" OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo_A;charlie;delta_A")
+ message (FATAL_ERROR "TRANSFORM(APPEND) is \"${output}\", expected is \"alpha;bravo_A;charlie;delta_A\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist APPEND "_A" REGEX "(r|t)a")
+if (NOT mylist STREQUAL "alpha;bravo_A;charlie;delta_A")
+ message (FATAL_ERROR "TRANSFORM(APPEND) is \"${mylist}\", expected is \"alpha;bravo_A;charlie;delta_A\"")
+endif()
diff --git a/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..6071a0079
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-GENEX_STRIP-TooManyArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments.cmake
new file mode 100644
index 000000000..257d7fe8a
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP-TooManyArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist GENEX_STRIP one_too_many)
diff --git a/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP.cmake b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP.cmake
new file mode 100644
index 000000000..8045eef6d
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-GENEX_STRIP.cmake
@@ -0,0 +1,49 @@
+set(mylist one "$<1:two\;three>" four "$<TARGET_OBJECTS:some_target>")
+
+list(TRANSFORM mylist GENEX_STRIP OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "one;;four;")
+ message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one;;four;\"")
+endif()
+
+set(mylist "one $<CONFIG>" "$<1:two\;three>-$<PLATFORM_ID>" "$<ANGLE-R>four" "$<TARGET_OBJECTS:some_target>")
+unset(output)
+list(TRANSFORM mylist GENEX_STRIP AT 1 3 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "one $<CONFIG>;-;$<ANGLE-R>four;")
+ message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one $<CONFIG>;-;$<ANGLE-R>four;\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist GENEX_STRIP AT 1 -2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "one $<CONFIG>;-;four;$<TARGET_OBJECTS:some_target>")
+ message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one $<CONFIG>;-;four;$<TARGET_OBJECTS:some_target>\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist GENEX_STRIP FOR 1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "one $<CONFIG>;-;four;$<TARGET_OBJECTS:some_target>")
+ message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one $<CONFIG>;-;four;$<TARGET_OBJECTS:some_target>\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist GENEX_STRIP FOR 1 -1 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "one $<CONFIG>;-;four;")
+ message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one $<CONFIG>;-;four;\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist GENEX_STRIP FOR 0 -1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "one ;$<1:two;three>-$<PLATFORM_ID>;four;$<TARGET_OBJECTS:some_target>")
+ message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one ;$<1:two;three>-$<PLATFORM_ID>;four;$<TARGET_OBJECTS:some_target>\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist GENEX_STRIP REGEX "(D|G)>" OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "one ;-;$<ANGLE-R>four;$<TARGET_OBJECTS:some_target>")
+ message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${output}\", expected is \"one ;-;$<ANGLE-R>four;$<TARGET_OBJECTS:some_target>\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist GENEX_STRIP REGEX "(D|G)>")
+if (NOT mylist STREQUAL "one ;-;$<ANGLE-R>four;$<TARGET_OBJECTS:some_target>")
+ message (FATAL_ERROR "TRANSFORM(GENEX_STRIP) is \"${mylist}\", expected is \"one ;-;$<ANGLE-R>four;$<TARGET_OBJECTS:some_target>\"")
+endif()
diff --git a/Tests/RunCMake/list/TRANSFORM-InvalidAction-result.txt b/Tests/RunCMake/list/TRANSFORM-InvalidAction-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-InvalidAction-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-InvalidAction-stderr.txt b/Tests/RunCMake/list/TRANSFORM-InvalidAction-stderr.txt
new file mode 100644
index 000000000..0fa45c927
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-InvalidAction-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-InvalidAction.cmake:2 \(list\):
+ list sub-command TRANSFORM, BAD_ACTION invalid action.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-InvalidAction.cmake b/Tests/RunCMake/list/TRANSFORM-InvalidAction.cmake
new file mode 100644
index 000000000..fb2cc30d9
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-InvalidAction.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist BAD_ACTION)
diff --git a/Tests/RunCMake/list/TRANSFORM-NoAction-result.txt b/Tests/RunCMake/list/TRANSFORM-NoAction-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-NoAction-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-NoAction-stderr.txt b/Tests/RunCMake/list/TRANSFORM-NoAction-stderr.txt
new file mode 100644
index 000000000..68e9e9db2
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-NoAction-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-NoAction.cmake:2 \(list\):
+ list sub-command TRANSFORM requires an action to be specified.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-NoAction.cmake b/Tests/RunCMake/list/TRANSFORM-NoAction.cmake
new file mode 100644
index 000000000..3690f1436
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-NoAction.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist)
diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-stderr.txt
new file mode 100644
index 000000000..b4f4e0614
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, OUTPUT_VARIABLE expects variable name argument.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments.cmake
new file mode 100644
index 000000000..acc409484
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-NoArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER OUTPUT_VARIABLE)
diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..9a5834622
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments.cmake
new file mode 100644
index 000000000..c4da86416
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Output-OUTPUT_VARIABLE-TooManyArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER OUTPUT_VARIABLE output one_too_many)
diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-stderr.txt
new file mode 100644
index 000000000..413ce3021
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-PREPEND-NoArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, action PREPEND expects 1 argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments.cmake
new file mode 100644
index 000000000..a8e453058
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-NoArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist PREPEND)
diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..6ff1b89ad
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-PREPEND-TooManyArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments.cmake
new file mode 100644
index 000000000..1f904ad66
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-PREPEND-TooManyArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist PREPEND delta one_too_many)
diff --git a/Tests/RunCMake/list/TRANSFORM-PREPEND.cmake b/Tests/RunCMake/list/TRANSFORM-PREPEND.cmake
new file mode 100644
index 000000000..55b8867d5
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-PREPEND.cmake
@@ -0,0 +1,48 @@
+set(mylist alpha bravo charlie delta)
+
+list(TRANSFORM mylist PREPEND "P_" OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "P_alpha;P_bravo;P_charlie;P_delta")
+ message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"P_alpha;P_bravo;P_charlie;P_delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist PREPEND "P_" AT 1 3 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;P_bravo;charlie;P_delta")
+ message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"alpha;P_bravo;charlie;P_delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist PREPEND "P_" AT 1 -2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;P_bravo;P_charlie;delta")
+ message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"alpha;P_bravo;P_charlie;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist PREPEND "P_" FOR 1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;P_bravo;P_charlie;delta")
+ message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"alpha;P_bravo;P_charlie;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist PREPEND "P_" FOR 1 -1 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;P_bravo;P_charlie;P_delta")
+ message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"alpha;P_bravo;P_charlie;P_delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist PREPEND "P_" FOR 0 -1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "P_alpha;bravo;P_charlie;delta")
+ message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"P_alpha;bravo;P_charlie;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist PREPEND "P_" REGEX "(r|t)a" OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;P_bravo;charlie;P_delta")
+ message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${output}\", expected is \"alpha;P_bravo;charlie;P_delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist PREPEND "P_" REGEX "(r|t)a")
+if (NOT mylist STREQUAL "alpha;P_bravo;charlie;P_delta")
+ message (FATAL_ERROR "TRANSFORM(PREPEND) is \"${mylist}\", expected is \"alpha;P_bravo;charlie;P_delta\"")
+endif()
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-stderr.txt
new file mode 100644
index 000000000..334c96ecc
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at TRANSFORM-REPLACE-InvalidRegex.cmake:2 \(list\):
+ list sub-command TRANSFORM, action REPLACE: Failed to compile regex
+ "\^\(alpha\$".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex.cmake
new file mode 100644
index 000000000..f440c3563
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidRegex.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist REPLACE "^(alpha$" "zulu")
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-stderr.txt
new file mode 100644
index 000000000..7671c8322
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at TRANSFORM-REPLACE-InvalidReplace1.cmake:2 \(list\):
+ list sub-command TRANSFORM, action REPLACE: replace-expression ends in a
+ backslash.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1.cmake
new file mode 100644
index 000000000..35387f000
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace1.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist REPLACE "^alpha$" "zulu\\")
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-stderr.txt
new file mode 100644
index 000000000..e0aabd7c7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at TRANSFORM-REPLACE-InvalidReplace2.cmake:2 \(list\):
+ list sub-command TRANSFORM, action REPLACE: Unknown escape "\\z" in
+ replace-expression.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2.cmake
new file mode 100644
index 000000000..2f1f2c7e1
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-InvalidReplace2.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist REPLACE "^alpha$" "\\zulu")
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-stderr.txt
new file mode 100644
index 000000000..3d39e7283
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-REPLACE-NoArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, action REPLACE expects 2 argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments.cmake
new file mode 100644
index 000000000..b7b1e9dd1
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist REPLACE)
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-stderr.txt
new file mode 100644
index 000000000..dc80f33a8
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-REPLACE-NoEnoughArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, action REPLACE expects 2 argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments.cmake
new file mode 100644
index 000000000..1d418c00e
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-NoEnoughArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist REPLACE "^alpha$")
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..3d4e15a0e
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-REPLACE-TooManyArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments.cmake
new file mode 100644
index 000000000..baed0af27
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE-TooManyArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist REPLACE "^alpha$" "zulu" "one_too_many")
diff --git a/Tests/RunCMake/list/TRANSFORM-REPLACE.cmake b/Tests/RunCMake/list/TRANSFORM-REPLACE.cmake
new file mode 100644
index 000000000..256b1b8c6
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-REPLACE.cmake
@@ -0,0 +1,48 @@
+set(mylist alpha bravo charlie delta)
+
+list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha_alpha;bravo;charlie;delta_delta")
+ message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha_alpha;bravo;charlie;delta_delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" AT 1 3 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo;charlie;delta_delta")
+ message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha;bravo;charlie;delta_delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist REPLACE "(.+e)$" "\\1_\\1" AT 1 -2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo;charlie_charlie;delta")
+ message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha;bravo;charlie_charlie;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist REPLACE "(.+e)$" "\\1_\\1" FOR 1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo;charlie_charlie;delta")
+ message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha;bravo;charlie_charlie;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" FOR 1 -1 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo;charlie;delta_delta")
+ message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha;bravo;charlie_A;delta_delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" FOR 0 -1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha_alpha;bravo;charlie;delta")
+ message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha_alpha;bravo;charlie;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" REGEX "(r|t)a" OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo;charlie;delta_delta")
+ message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${output}\", expected is \"alpha;bravo;charlie;delta_delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist REPLACE "(.+a)$" "\\1_\\1" REGEX "(r|t)a")
+if (NOT mylist STREQUAL "alpha;bravo;charlie;delta_delta")
+ message (FATAL_ERROR "TRANSFORM(REPLACE) is \"${mylist}\", expected is \"alpha;bravo;charlie;delta_delta\"")
+endif()
diff --git a/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..534f940a5
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-STRIP-TooManyArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments.cmake
new file mode 100644
index 000000000..c6a821314
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-STRIP-TooManyArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist STRIP one_too_many)
diff --git a/Tests/RunCMake/list/TRANSFORM-STRIP.cmake b/Tests/RunCMake/list/TRANSFORM-STRIP.cmake
new file mode 100644
index 000000000..366c63a83
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-STRIP.cmake
@@ -0,0 +1,49 @@
+set(mylist " alpha" "bravo " " charlie " delta)
+
+list(TRANSFORM mylist STRIP OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo;charlie;delta")
+ message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \"alpha;bravo;charlie;delta\"")
+endif()
+
+set(mylist " alpha" "bravo " " charlie " "delta ")
+unset(output)
+list(TRANSFORM mylist STRIP AT 1 3 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL " alpha;bravo; charlie ;delta")
+ message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \" alpha;bravo; charlie ;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist STRIP AT 1 -2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL " alpha;bravo;charlie;delta ")
+ message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \" alpha;bravo;charlie;delta \"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist STRIP FOR 1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL " alpha;bravo;charlie;delta ")
+ message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \" alpha;bravo;charlie;delta \"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist STRIP FOR 1 -1 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL " alpha;bravo;charlie;delta")
+ message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \" alpha;bravo;charlie;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist STRIP FOR 0 -1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo ;charlie;delta ")
+ message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \"alpha;bravo ;charlie;delta \"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist STRIP REGEX "(r|t)a" OUTPUT_VARIABLE output)
+if (NOT output STREQUAL " alpha;bravo; charlie ;delta")
+ message (FATAL_ERROR "TRANSFORM(STRIP) is \"${output}\", expected is \" alpha;bravo; charlie ;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist STRIP REGEX "(r|t)a")
+if (NOT mylist STREQUAL " alpha;bravo; charlie ;delta")
+ message (FATAL_ERROR "TRANSFORM(STRIP) is \"${mylist}\", expected is \" alpha;bravo; charlie ;delta\"")
+endif()
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-stderr.txt
new file mode 100644
index 000000000..cec520f2e
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-Selector-AT-BadArgument.cmake:2 \(list\):
+ list sub-command TRANSFORM, '1x 2': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument.cmake
new file mode 100644
index 000000000..f61b86bc2
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-BadArgument.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER AT 0 1x 2)
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-stderr.txt
new file mode 100644
index 000000000..7e2898b3a
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-Selector-AT-InvalidIndex.cmake:2 \(list\):
+ list sub-command TRANSFORM, selector AT, index: 3 out of range \(-3, 2\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex.cmake
new file mode 100644
index 000000000..d33586c36
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-InvalidIndex.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER AT 0 3 2)
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-stderr.txt
new file mode 100644
index 000000000..eaf5281db
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-Selector-AT-NoArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, selector AT expects at least one numeric value.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments.cmake
new file mode 100644
index 000000000..052b79bbe
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-AT-NoArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER AT)
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-stderr.txt
new file mode 100644
index 000000000..a0f701f01
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at TRANSFORM-Selector-FOR-BadArgument.cmake:2 \(list\):
+ list sub-command TRANSFORM, selector FOR expects, at least, two numeric
+ values.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument.cmake
new file mode 100644
index 000000000..55527be21
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-BadArgument.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER FOR 0 1x 2)
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-stderr.txt
new file mode 100644
index 000000000..c50cc0a61
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-Selector-FOR-InvalidIndex.cmake:2 \(list\):
+ list sub-command TRANSFORM, selector FOR, index: 6 out of range \(-3, 2\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex.cmake
new file mode 100644
index 000000000..6e2374e31
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-InvalidIndex.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER FOR 0 6 2)
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-stderr.txt
new file mode 100644
index 000000000..5881b67b4
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-Selector-FOR-NoArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, selector FOR expects, at least, two arguments.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments.cmake
new file mode 100644
index 000000000..4902cc9a7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER FOR)
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-stderr.txt
new file mode 100644
index 000000000..b1081d98d
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-Selector-FOR-NoEnoughArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, selector FOR expects, at least, two arguments.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments.cmake
new file mode 100644
index 000000000..81417de57
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-NoEnoughArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER FOR 1)
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..2221cb3cd
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-Selector-FOR-TooManyArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, '3': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments.cmake
new file mode 100644
index 000000000..80917d65a
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-FOR-TooManyArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER FOR 0 1 2 3)
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-stderr.txt
new file mode 100644
index 000000000..31ba93986
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at TRANSFORM-Selector-REGEX-InvalidRegex.cmake:2 \(list\):
+ list sub-command TRANSFORM, selector REGEX failed to compile regex
+ "\^\(alpha\$".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex.cmake
new file mode 100644
index 000000000..56e202bb4
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-InvalidRegex.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER REGEX "^(alpha$")
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-stderr.txt
new file mode 100644
index 000000000..278478555
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at TRANSFORM-Selector-REGEX-NoArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, selector REGEX expects 'regular expression'
+ argument.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments.cmake
new file mode 100644
index 000000000..f199d0e12
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-NoArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER REGEX)
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..db5b1ffb5
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-Selector-REGEX-TooManyArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments.cmake
new file mode 100644
index 000000000..4aa1619d7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-Selector-REGEX-TooManyArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER REGEX "^alpha$" "one_too_many")
diff --git a/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..90248aec3
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-TOLOWER-TooManyArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments.cmake
new file mode 100644
index 000000000..1758e19e4
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-TOLOWER-TooManyArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOLOWER one_too_many)
diff --git a/Tests/RunCMake/list/TRANSFORM-TOLOWER.cmake b/Tests/RunCMake/list/TRANSFORM-TOLOWER.cmake
new file mode 100644
index 000000000..a2d73480c
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-TOLOWER.cmake
@@ -0,0 +1,48 @@
+set(mylist ALPHA BRAVO CHARLIE DELTA)
+
+list(TRANSFORM mylist TOLOWER OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;bravo;charlie;delta")
+ message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"alpha;bravo;charlie;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOLOWER AT 1 3 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "ALPHA;bravo;CHARLIE;delta")
+ message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"ALPHA;bravo;CHARLIE;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOLOWER AT 1 -2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "ALPHA;bravo;charlie;DELTA")
+ message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"ALPHA;bravo;charlie;DELTA\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOLOWER FOR 1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "ALPHA;bravo;charlie;DELTA")
+ message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"ALPHA;bravo;charlie;DELTA\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOLOWER FOR 1 -1 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "ALPHA;bravo;charlie;delta")
+ message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"ALPHA;bravo;charlie;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOLOWER FOR 0 -1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;BRAVO;charlie;DELTA")
+ message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"alpha;BRAVO;charlie;DELTA\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOLOWER REGEX "(R|T)A" OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "ALPHA;bravo;CHARLIE;delta")
+ message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${output}\", expected is \"ALPHA;bravo;CHARLIE;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOLOWER REGEX "(R|T)A")
+if (NOT mylist STREQUAL "ALPHA;bravo;CHARLIE;delta")
+ message (FATAL_ERROR "TRANSFORM(TOLOWER) is \"${mylist}\", expected is \"ALPHA;bravo;CHARLIE;delta\"")
+endif()
diff --git a/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-result.txt b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-stderr.txt b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..9da241ba8
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at TRANSFORM-TOUPPER-TooManyArguments.cmake:2 \(list\):
+ list sub-command TRANSFORM, 'one_too_many': unexpected argument\(s\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments.cmake b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments.cmake
new file mode 100644
index 000000000..58d6a8cd7
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-TOUPPER-TooManyArguments.cmake
@@ -0,0 +1,2 @@
+set(mylist alpha bravo charlie)
+list(TRANSFORM mylist TOUPPER one_too_many)
diff --git a/Tests/RunCMake/list/TRANSFORM-TOUPPER.cmake b/Tests/RunCMake/list/TRANSFORM-TOUPPER.cmake
new file mode 100644
index 000000000..5b1fcb66e
--- /dev/null
+++ b/Tests/RunCMake/list/TRANSFORM-TOUPPER.cmake
@@ -0,0 +1,48 @@
+set(mylist alpha bravo charlie delta)
+
+list(TRANSFORM mylist TOUPPER OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "ALPHA;BRAVO;CHARLIE;DELTA")
+ message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"ALPHA;BRAVO;CHARLIE;DELTA\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOUPPER AT 1 3 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;BRAVO;charlie;DELTA")
+ message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"alpha;BRAVO;charlie;DELTA\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOUPPER AT 1 -2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;BRAVO;CHARLIE;delta")
+ message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"alpha;BRAVO;CHARLIE;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOUPPER FOR 1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;BRAVO;CHARLIE;delta")
+ message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"alpha;BRAVO;CHARLIE;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOUPPER FOR 1 -1 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;BRAVO;CHARLIE;DELTA")
+ message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"alpha;BRAVO;CHARLIE;DELTA\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOUPPER FOR 0 -1 2 OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "ALPHA;bravo;CHARLIE;delta")
+ message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"ALPHA;bravo;CHARLIE;delta\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOUPPER REGEX "(r|t)a" OUTPUT_VARIABLE output)
+if (NOT output STREQUAL "alpha;BRAVO;charlie;DELTA")
+ message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${output}\", expected is \"alpha;BRAVO;charlie;DELTA\"")
+endif()
+
+unset(output)
+list(TRANSFORM mylist TOUPPER REGEX "(r|t)a")
+if (NOT mylist STREQUAL "alpha;BRAVO;charlie;DELTA")
+ message (FATAL_ERROR "TRANSFORM(TOUPPER) is \"${mylist}\", expected is \"alpha;BRAVO;charlie;DELTA\"")
+endif()
diff --git a/Tests/RunCMake/math/CMakeLists.txt b/Tests/RunCMake/math/CMakeLists.txt
new file mode 100644
index 000000000..12cd3c775
--- /dev/null
+++ b/Tests/RunCMake/math/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 2.8.4)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/math/MATH-DivideByZero-result.txt b/Tests/RunCMake/math/MATH-DivideByZero-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-DivideByZero-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/math/MATH-DivideByZero-stderr.txt b/Tests/RunCMake/math/MATH-DivideByZero-stderr.txt
new file mode 100644
index 000000000..66ad6332f
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-DivideByZero-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at MATH-DivideByZero.cmake:1 \(math\):
+ math cannot evaluate the expression: "100/0": divide by zero.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/math/MATH-DivideByZero.cmake b/Tests/RunCMake/math/MATH-DivideByZero.cmake
new file mode 100644
index 000000000..3ac161e11
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-DivideByZero.cmake
@@ -0,0 +1 @@
+math(EXPR var "100/0")
diff --git a/Tests/RunCMake/math/MATH-DoubleOption-result.txt b/Tests/RunCMake/math/MATH-DoubleOption-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-DoubleOption-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/math/MATH-DoubleOption-stderr.txt b/Tests/RunCMake/math/MATH-DoubleOption-stderr.txt
new file mode 100644
index 000000000..767a060fc
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-DoubleOption-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at MATH-DoubleOption.cmake:1 \(math\):
+ math EXPR called with incorrect arguments.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/math/MATH-DoubleOption.cmake b/Tests/RunCMake/math/MATH-DoubleOption.cmake
new file mode 100644
index 000000000..7bcb78ec2
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-DoubleOption.cmake
@@ -0,0 +1 @@
+math(EXPR var "10*10" OUTPUT_FORMAT DECIMAL OUTPUT_FORMAT HEXADECIMAL)
diff --git a/Tests/RunCMake/math/MATH-InvalidExpression-result.txt b/Tests/RunCMake/math/MATH-InvalidExpression-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-InvalidExpression-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/math/MATH-InvalidExpression-stderr.txt b/Tests/RunCMake/math/MATH-InvalidExpression-stderr.txt
new file mode 100644
index 000000000..9e73ed5b2
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-InvalidExpression-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at MATH-InvalidExpression.cmake:1 \(math\):
+ math cannot parse the expression: "INVALID": syntax error, unexpected \$end,
+ expecting exp_PLUS or exp_MINUS or exp_OPENPARENT or exp_NUMBER \(7\).
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/math/MATH-InvalidExpression.cmake b/Tests/RunCMake/math/MATH-InvalidExpression.cmake
new file mode 100644
index 000000000..6e37128d7
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-InvalidExpression.cmake
@@ -0,0 +1 @@
+math(EXPR var "INVALID")
diff --git a/Tests/RunCMake/math/MATH-ToleratedExpression-stderr.txt b/Tests/RunCMake/math/MATH-ToleratedExpression-stderr.txt
new file mode 100644
index 000000000..732ce6f16
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-ToleratedExpression-stderr.txt
@@ -0,0 +1,8 @@
+^CMake Warning \(dev\) at MATH-ToleratedExpression.cmake:1 \(math\):
+ Unexpected character in expression at position 1: '
+
+ Unexpected character in expression at position 7: '
+
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/math/MATH-ToleratedExpression.cmake b/Tests/RunCMake/math/MATH-ToleratedExpression.cmake
new file mode 100644
index 000000000..d1be218c8
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-ToleratedExpression.cmake
@@ -0,0 +1,4 @@
+math(EXPR var "'2*1-1'")
+if(NOT var EQUAL 1)
+ message(FATAL_ERROR "Expression did not evaluate to 1")
+endif()
diff --git a/Tests/RunCMake/math/MATH-TooManyArguments-result.txt b/Tests/RunCMake/math/MATH-TooManyArguments-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-TooManyArguments-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/math/MATH-TooManyArguments-stderr.txt b/Tests/RunCMake/math/MATH-TooManyArguments-stderr.txt
new file mode 100644
index 000000000..fdcfecf7f
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-TooManyArguments-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at MATH-TooManyArguments.cmake:1 \(math\):
+ math EXPR called with incorrect arguments.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/math/MATH-TooManyArguments.cmake b/Tests/RunCMake/math/MATH-TooManyArguments.cmake
new file mode 100644
index 000000000..969dc80f0
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-TooManyArguments.cmake
@@ -0,0 +1 @@
+math(EXPR var "10*10" OUTPUT_FORMAT DECIMAL OUTPUT_FORMAT )
diff --git a/Tests/RunCMake/math/MATH-WrongArgument-result.txt b/Tests/RunCMake/math/MATH-WrongArgument-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-WrongArgument-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/math/MATH-WrongArgument-stderr.txt b/Tests/RunCMake/math/MATH-WrongArgument-stderr.txt
new file mode 100644
index 000000000..bbe54bf1f
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-WrongArgument-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at MATH-WrongArgument.cmake:1 \(math\):
+ math sub-command EXPR option "OUT" is unknown.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/math/MATH-WrongArgument.cmake b/Tests/RunCMake/math/MATH-WrongArgument.cmake
new file mode 100644
index 000000000..fb6d2e725
--- /dev/null
+++ b/Tests/RunCMake/math/MATH-WrongArgument.cmake
@@ -0,0 +1 @@
+math(EXPR var "10*10" OUT HEX )
diff --git a/Tests/RunCMake/math/MATH.cmake b/Tests/RunCMake/math/MATH.cmake
new file mode 100644
index 000000000..a5f50cd90
--- /dev/null
+++ b/Tests/RunCMake/math/MATH.cmake
@@ -0,0 +1,12 @@
+macro(math_test expression expected)
+ math(EXPR evaluated ${expression} ${ARGN})
+ if (NOT evaluated STREQUAL ${expected})
+ message(FATAL_ERROR "wrong math result: ${evaluated} != ${expected}")
+ endif ()
+endmacro()
+
+
+math_test("100 * 10" 1000)
+math_test("100 * 10" 1000 OUTPUT_FORMAT DECIMAL)
+math_test("100 * 0xA" 1000 OUTPUT_FORMAT DECIMAL)
+math_test("100 * 0xA" 0x3e8 OUTPUT_FORMAT HEXADECIMAL)
diff --git a/Tests/RunCMake/math/RunCMakeTest.cmake b/Tests/RunCMake/math/RunCMakeTest.cmake
new file mode 100644
index 000000000..a4d5c31df
--- /dev/null
+++ b/Tests/RunCMake/math/RunCMakeTest.cmake
@@ -0,0 +1,9 @@
+include(RunCMake)
+
+run_cmake(MATH)
+run_cmake(MATH-WrongArgument)
+run_cmake(MATH-DoubleOption)
+run_cmake(MATH-TooManyArguments)
+run_cmake(MATH-InvalidExpression)
+run_cmake(MATH-ToleratedExpression)
+run_cmake(MATH-DivideByZero)
diff --git a/Tests/RunCMake/message/message-all-loglevels.cmake b/Tests/RunCMake/message/message-all-loglevels.cmake
new file mode 100644
index 000000000..f8d884154
--- /dev/null
+++ b/Tests/RunCMake/message/message-all-loglevels.cmake
@@ -0,0 +1,10 @@
+# Produce a message for everything except FATAL_ERROR and SEND_ERROR
+message(DEPRECATION "Deprecation warning")
+message(AUTHOR_WARNING "Author warning message")
+message(WARNING "Warning message")
+message("Default NOTICE message")
+message(NOTICE "NOTICE message")
+message(STATUS "STATUS message")
+message(VERBOSE "VERBOSE message")
+message(DEBUG "DEBUG message")
+message(TRACE "TRACE message")
diff --git a/Tests/RunCMake/message/message-loglevel-debug-stderr.txt b/Tests/RunCMake/message/message-loglevel-debug-stderr.txt
new file mode 100644
index 000000000..efec736fe
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-debug-stderr.txt
@@ -0,0 +1,12 @@
+^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\):
+ Deprecation warning
++
+CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\):
+ Author warning message
+This warning is for project developers\. Use -Wno-dev to suppress it\.
++
+CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\):
+ Warning message
++
+Default NOTICE message
+NOTICE message$
diff --git a/Tests/RunCMake/message/message-loglevel-debug-stdout.txt b/Tests/RunCMake/message/message-loglevel-debug-stdout.txt
new file mode 100644
index 000000000..145213703
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-debug-stdout.txt
@@ -0,0 +1,3 @@
+-- STATUS message
+-- VERBOSE message
+-- DEBUG message
diff --git a/Tests/RunCMake/message/message-loglevel-default-stderr.txt b/Tests/RunCMake/message/message-loglevel-default-stderr.txt
new file mode 100644
index 000000000..efec736fe
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-default-stderr.txt
@@ -0,0 +1,12 @@
+^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\):
+ Deprecation warning
++
+CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\):
+ Author warning message
+This warning is for project developers\. Use -Wno-dev to suppress it\.
++
+CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\):
+ Warning message
++
+Default NOTICE message
+NOTICE message$
diff --git a/Tests/RunCMake/message/message-loglevel-default-stdout.txt b/Tests/RunCMake/message/message-loglevel-default-stdout.txt
new file mode 100644
index 000000000..809f4cc4a
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-default-stdout.txt
@@ -0,0 +1 @@
+-- STATUS message
diff --git a/Tests/RunCMake/message/message-loglevel-invalid-result.txt b/Tests/RunCMake/message/message-loglevel-invalid-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-invalid-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/message/message-loglevel-invalid-stderr.txt b/Tests/RunCMake/message/message-loglevel-invalid-stderr.txt
new file mode 100644
index 000000000..f54d0f844
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-invalid-stderr.txt
@@ -0,0 +1 @@
+CMake Error: Invalid level specified for --loglevel
diff --git a/Tests/RunCMake/message/message-loglevel-notice-stderr.txt b/Tests/RunCMake/message/message-loglevel-notice-stderr.txt
new file mode 100644
index 000000000..efec736fe
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-notice-stderr.txt
@@ -0,0 +1,12 @@
+^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\):
+ Deprecation warning
++
+CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\):
+ Author warning message
+This warning is for project developers\. Use -Wno-dev to suppress it\.
++
+CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\):
+ Warning message
++
+Default NOTICE message
+NOTICE message$
diff --git a/Tests/RunCMake/message/message-loglevel-status-stderr.txt b/Tests/RunCMake/message/message-loglevel-status-stderr.txt
new file mode 100644
index 000000000..efec736fe
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-status-stderr.txt
@@ -0,0 +1,12 @@
+^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\):
+ Deprecation warning
++
+CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\):
+ Author warning message
+This warning is for project developers\. Use -Wno-dev to suppress it\.
++
+CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\):
+ Warning message
++
+Default NOTICE message
+NOTICE message$
diff --git a/Tests/RunCMake/message/message-loglevel-status-stdout.txt b/Tests/RunCMake/message/message-loglevel-status-stdout.txt
new file mode 100644
index 000000000..809f4cc4a
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-status-stdout.txt
@@ -0,0 +1 @@
+-- STATUS message
diff --git a/Tests/RunCMake/message/message-loglevel-trace-stderr.txt b/Tests/RunCMake/message/message-loglevel-trace-stderr.txt
new file mode 100644
index 000000000..efec736fe
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-trace-stderr.txt
@@ -0,0 +1,12 @@
+^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\):
+ Deprecation warning
++
+CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\):
+ Author warning message
+This warning is for project developers\. Use -Wno-dev to suppress it\.
++
+CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\):
+ Warning message
++
+Default NOTICE message
+NOTICE message$
diff --git a/Tests/RunCMake/message/message-loglevel-trace-stdout.txt b/Tests/RunCMake/message/message-loglevel-trace-stdout.txt
new file mode 100644
index 000000000..1cfce6f11
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-trace-stdout.txt
@@ -0,0 +1,4 @@
+-- STATUS message
+-- VERBOSE message
+-- DEBUG message
+-- TRACE message
diff --git a/Tests/RunCMake/message/message-loglevel-verbose-stderr.txt b/Tests/RunCMake/message/message-loglevel-verbose-stderr.txt
new file mode 100644
index 000000000..efec736fe
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-verbose-stderr.txt
@@ -0,0 +1,12 @@
+^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\):
+ Deprecation warning
++
+CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\):
+ Author warning message
+This warning is for project developers\. Use -Wno-dev to suppress it\.
++
+CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\):
+ Warning message
++
+Default NOTICE message
+NOTICE message$
diff --git a/Tests/RunCMake/message/message-loglevel-verbose-stdout.txt b/Tests/RunCMake/message/message-loglevel-verbose-stdout.txt
new file mode 100644
index 000000000..c15d43fc4
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-verbose-stdout.txt
@@ -0,0 +1,2 @@
+-- STATUS message
+-- VERBOSE message
diff --git a/Tests/RunCMake/message/message-loglevel-warning-stderr.txt b/Tests/RunCMake/message/message-loglevel-warning-stderr.txt
new file mode 100644
index 000000000..c721b063c
--- /dev/null
+++ b/Tests/RunCMake/message/message-loglevel-warning-stderr.txt
@@ -0,0 +1,9 @@
+^CMake Deprecation Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:2 \(message\):
+ Deprecation warning
++
+CMake Warning \(dev\) at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:3 \(message\):
+ Author warning message
+This warning is for project developers\. Use -Wno-dev to suppress it\.
++
+CMake Warning at.*/Tests/RunCMake/message/message-all-loglevels\.cmake:4 \(message\):
+ Warning message$
diff --git a/Tests/RunCMake/option/CMP0077-NEW.cmake b/Tests/RunCMake/option/CMP0077-NEW.cmake
new file mode 100644
index 000000000..d4c518b1e
--- /dev/null
+++ b/Tests/RunCMake/option/CMP0077-NEW.cmake
@@ -0,0 +1,14 @@
+
+#Verify that option DOESN'T overwrite existing normal variable when the policy
+#is set to NEW
+cmake_policy(SET CMP0077 NEW)
+set(OPT_LOCAL_VAR FALSE)
+option(OPT_LOCAL_VAR "TEST_VAR" ON)
+if(OPT_LOCAL_VAR)
+ message(FATAL_ERROR "option failed to overwrite existing normal variable")
+endif()
+
+get_property(_exists_in_cache CACHE OPT_LOCAL_VAR PROPERTY VALUE SET)
+if(_exists_in_cache)
+ message(FATAL_ERROR "value should not exist in cache as it was already a local variable")
+endif()
diff --git a/Tests/RunCMake/option/CMP0077-OLD.cmake b/Tests/RunCMake/option/CMP0077-OLD.cmake
new file mode 100644
index 000000000..4c52d4b92
--- /dev/null
+++ b/Tests/RunCMake/option/CMP0077-OLD.cmake
@@ -0,0 +1,9 @@
+
+#Verify that option overwrites existing normal variable when the policy
+#is set to OLD
+cmake_policy(SET CMP0077 OLD)
+set(OPT_LOCAL_VAR FALSE)
+option(OPT_LOCAL_VAR "TEST_VAR" ON)
+if(NOT OPT_LOCAL_VAR)
+ message(FATAL_ERROR "option failed to overwrite existing normal variable")
+endif()
diff --git a/Tests/RunCMake/option/CMP0077-SECOND-PASS.cmake b/Tests/RunCMake/option/CMP0077-SECOND-PASS.cmake
new file mode 100644
index 000000000..f62a85370
--- /dev/null
+++ b/Tests/RunCMake/option/CMP0077-SECOND-PASS.cmake
@@ -0,0 +1,14 @@
+
+#Verify that when both a cache and local version of a value exist that CMake
+#doesn't produce a CMP0077 warning and that we get the expected values.
+option(OPT_LOCAL_VAR "TEST_VAR" ON)
+set(OPT_LOCAL_VAR FALSE)
+option(OPT_LOCAL_VAR "TEST_VAR" ON)
+if(OPT_LOCAL_VAR)
+ message(FATAL_ERROR "option improperly set a cache variable that already exists")
+endif()
+
+get_property(_exists_in_cache CACHE OPT_LOCAL_VAR PROPERTY VALUE SET)
+if(NOT _exists_in_cache)
+ message(FATAL_ERROR "value should exist in cache")
+endif()
diff --git a/Tests/RunCMake/option/CMP0077-WARN-stderr.txt b/Tests/RunCMake/option/CMP0077-WARN-stderr.txt
new file mode 100644
index 000000000..0d02ffbf7
--- /dev/null
+++ b/Tests/RunCMake/option/CMP0077-WARN-stderr.txt
@@ -0,0 +1,7 @@
+CMake Warning \(dev\) at CMP0077-WARN.cmake:5 \(option\):
+ Policy CMP0077 is not set: option\(\) honors normal variables. Run "cmake
+ --help-policy CMP0077" for policy details. Use the cmake_policy command to
+ set the policy and suppress this warning.
+
+ For compatibility with older versions of CMake, option is clearing the
+ normal variable 'OPT_LOCAL_VAR'.
diff --git a/Tests/RunCMake/option/CMP0077-WARN.cmake b/Tests/RunCMake/option/CMP0077-WARN.cmake
new file mode 100644
index 000000000..7f994569f
--- /dev/null
+++ b/Tests/RunCMake/option/CMP0077-WARN.cmake
@@ -0,0 +1,5 @@
+
+#Verify that option overwrites existing normal variable when the policy
+#is set to OLD
+set(OPT_LOCAL_VAR FALSE)
+option(OPT_LOCAL_VAR "TEST_VAR" ON)
diff --git a/Tests/RunCMake/option/CMakeLists.txt b/Tests/RunCMake/option/CMakeLists.txt
new file mode 100644
index 000000000..11dc49a05
--- /dev/null
+++ b/Tests/RunCMake/option/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.12)
+project(${RunCMake_TEST} CXX)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/option/RunCMakeTest.cmake b/Tests/RunCMake/option/RunCMakeTest.cmake
new file mode 100644
index 000000000..979afa1ce
--- /dev/null
+++ b/Tests/RunCMake/option/RunCMakeTest.cmake
@@ -0,0 +1,6 @@
+include(RunCMake)
+
+run_cmake(CMP0077-OLD)
+run_cmake(CMP0077-NEW)
+run_cmake(CMP0077-WARN)
+run_cmake(CMP0077-SECOND-PASS)
diff --git a/Tests/RunCMake/print_stdin.c b/Tests/RunCMake/print_stdin.c
new file mode 100644
index 000000000..e083e6297
--- /dev/null
+++ b/Tests/RunCMake/print_stdin.c
@@ -0,0 +1,18 @@
+#include <stdio.h>
+
+int main()
+{
+ char buf[1024];
+ size_t nIn = sizeof(buf);
+ while (nIn == sizeof(buf)) {
+ nIn = fread(buf, 1, sizeof(buf), stdin);
+ if (nIn > 0) {
+ size_t nOut;
+ nOut = fwrite(buf, 1, nIn, stdout);
+ if (nOut != nIn) {
+ return 1;
+ }
+ }
+ }
+ return 0;
+}
diff --git a/Tests/RunCMake/project/CMP0048-OLD-stderr.txt b/Tests/RunCMake/project/CMP0048-OLD-stderr.txt
new file mode 100644
index 000000000..1fa70f88b
--- /dev/null
+++ b/Tests/RunCMake/project/CMP0048-OLD-stderr.txt
@@ -0,0 +1,10 @@
+^CMake Deprecation Warning at CMP0048-OLD.cmake:1 \(cmake_policy\):
+ The OLD behavior for policy CMP0048 will be removed from a future version
+ of CMake.
+
+ The cmake-policies\(7\) manual explains that the OLD behaviors of all
+ policies are deprecated and that a policy should be set to OLD only under
+ specific short-term circumstances. Projects should be ported to the NEW
+ behavior and not rely on setting a policy to OLD.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)$
diff --git a/Tests/RunCMake/project/LanguagesUnordered-stderr.txt b/Tests/RunCMake/project/LanguagesUnordered-stderr.txt
new file mode 100644
index 000000000..51086700c
--- /dev/null
+++ b/Tests/RunCMake/project/LanguagesUnordered-stderr.txt
@@ -0,0 +1 @@
+ the following parameters must be specified after LANGUAGES keyword: C.
diff --git a/Tests/RunCMake/project/LanguagesUnordered.cmake b/Tests/RunCMake/project/LanguagesUnordered.cmake
new file mode 100644
index 000000000..cd3ba2872
--- /dev/null
+++ b/Tests/RunCMake/project/LanguagesUnordered.cmake
@@ -0,0 +1 @@
+project(ProjectA C LANGUAGES CXX)
diff --git a/Tests/RunCMake/project/ProjectDescriptionNoArg-stderr.txt b/Tests/RunCMake/project/ProjectDescriptionNoArg-stderr.txt
new file mode 100644
index 000000000..910106f40
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectDescriptionNoArg-stderr.txt
@@ -0,0 +1,2 @@
+ DESCRIPTION keyword not followed by a value or was followed by a value that
+ expanded to nothing.
diff --git a/Tests/RunCMake/project/ProjectDescriptionNoArg.cmake b/Tests/RunCMake/project/ProjectDescriptionNoArg.cmake
new file mode 100644
index 000000000..25acff840
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectDescriptionNoArg.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0048 NEW)
+project(ProjectDescriptionTest VERSION 1.0.0 LANGUAGES NONE DESCRIPTION)
diff --git a/Tests/RunCMake/project/ProjectDescriptionNoArg2-stderr.txt b/Tests/RunCMake/project/ProjectDescriptionNoArg2-stderr.txt
new file mode 100644
index 000000000..910106f40
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectDescriptionNoArg2-stderr.txt
@@ -0,0 +1,2 @@
+ DESCRIPTION keyword not followed by a value or was followed by a value that
+ expanded to nothing.
diff --git a/Tests/RunCMake/project/ProjectDescriptionNoArg2.cmake b/Tests/RunCMake/project/ProjectDescriptionNoArg2.cmake
new file mode 100644
index 000000000..f50a2f688
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectDescriptionNoArg2.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0048 NEW)
+project(ProjectDescriptionTest VERSION 1.0.0 DESCRIPTION LANGUAGES NONE)
diff --git a/Tests/RunCMake/project/ProjectHomepage-stdout.txt b/Tests/RunCMake/project/ProjectHomepage-stdout.txt
new file mode 100644
index 000000000..253990f3d
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectHomepage-stdout.txt
@@ -0,0 +1,3 @@
+-- PROJECT_HOMEPAGE_URL=http://example.com
+-- CMAKE_PROJECT_HOMEPAGE_URL=http://example.com
+-- ProjectHomepageTest_HOMEPAGE_URL=http://example.com
diff --git a/Tests/RunCMake/project/ProjectHomepage.cmake b/Tests/RunCMake/project/ProjectHomepage.cmake
new file mode 100644
index 000000000..3307f1fc9
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectHomepage.cmake
@@ -0,0 +1,14 @@
+cmake_policy(SET CMP0048 NEW)
+project(ProjectHomepageTest VERSION 1.0.0 HOMEPAGE_URL "http://example.com" LANGUAGES)
+if(NOT PROJECT_HOMEPAGE_URL)
+ message(FATAL_ERROR "PROJECT_HOMEPAGE_URL expected to be set")
+endif()
+if(NOT CMAKE_PROJECT_HOMEPAGE_URL)
+ message(FATAL_ERROR "CMAKE_PROJECT_HOMEPAGE_URL expected to be set")
+endif()
+if(NOT ProjectHomepageTest_HOMEPAGE_URL)
+ message(FATAL_ERROR "ProjectHomepageTest_HOMEPAGE_URL expected to be set")
+endif()
+message(STATUS "PROJECT_HOMEPAGE_URL=${PROJECT_HOMEPAGE_URL}")
+message(STATUS "CMAKE_PROJECT_HOMEPAGE_URL=${CMAKE_PROJECT_HOMEPAGE_URL}")
+message(STATUS "ProjectHomepageTest_HOMEPAGE_URL=${ProjectHomepageTest_HOMEPAGE_URL}")
diff --git a/Tests/RunCMake/project/ProjectHomepage2-result.txt b/Tests/RunCMake/project/ProjectHomepage2-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectHomepage2-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/project/ProjectHomepage2-stderr.txt b/Tests/RunCMake/project/ProjectHomepage2-stderr.txt
new file mode 100644
index 000000000..4a0adc2d3
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectHomepage2-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at ProjectHomepage2.cmake:2 \(project\):
+ HOMEPAGE_URL may be specified at most once.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/project/ProjectHomepage2.cmake b/Tests/RunCMake/project/ProjectHomepage2.cmake
new file mode 100644
index 000000000..184c392c4
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectHomepage2.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0048 NEW)
+project(ProjectDescriptionTest VERSION 1.0.0 HOMEPAGE_URL "http://example.com" HOMEPAGE_URL "http://example.com" LANGUAGES)
diff --git a/Tests/RunCMake/project/ProjectHomepageNoArg-stderr.txt b/Tests/RunCMake/project/ProjectHomepageNoArg-stderr.txt
new file mode 100644
index 000000000..c9503b74b
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectHomepageNoArg-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Warning at ProjectHomepageNoArg.cmake:2 \(project\):
+ HOMEPAGE_URL keyword not followed by a value or was followed by a value
+ that expanded to nothing.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/project/ProjectHomepageNoArg.cmake b/Tests/RunCMake/project/ProjectHomepageNoArg.cmake
new file mode 100644
index 000000000..460554194
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectHomepageNoArg.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0048 NEW)
+project(ProjectDescriptionTest VERSION 1.0.0 LANGUAGES NONE HOMEPAGE_URL)
diff --git a/Tests/RunCMake/project/ProjectTwice.cmake b/Tests/RunCMake/project/ProjectTwice.cmake
new file mode 100644
index 000000000..d053834dc
--- /dev/null
+++ b/Tests/RunCMake/project/ProjectTwice.cmake
@@ -0,0 +1,26 @@
+cmake_policy(SET CMP0048 NEW)
+project(ProjectTwiceTestFirst
+ VERSION 1.2.3.4
+ DESCRIPTION "Test Project"
+ HOMEPAGE_URL "http://example.com"
+ LANGUAGES NONE
+)
+
+project(ProjectTwiceTestSecond LANGUAGES NONE)
+
+foreach(var
+ PROJECT_VERSION
+ PROJECT_VERSION_MAJOR
+ PROJECT_VERSION_MINOR
+ PROJECT_VERSION_PATCH
+ PROJECT_VERSION_TWEAK
+ PROJECT_DESCRIPTION
+ PROJECT_HOMEPAGE_URL
+)
+ if(${var})
+ message(SEND_ERROR "${var} set but should be empty")
+ endif()
+ if(CMAKE_${var})
+ message(SEND_ERROR "CMAKE_${var} set but should be empty")
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/project/VersionMissingValueOkay-stderr.txt b/Tests/RunCMake/project/VersionMissingValueOkay-stderr.txt
new file mode 100644
index 000000000..3228df7eb
--- /dev/null
+++ b/Tests/RunCMake/project/VersionMissingValueOkay-stderr.txt
@@ -0,0 +1,2 @@
+ VERSION keyword not followed by a value or was followed by a value that
+ expanded to nothing.
diff --git a/Tests/RunCMake/project_injected/CMP0048-WARN-stderr.txt b/Tests/RunCMake/project_injected/CMP0048-WARN-stderr.txt
new file mode 100644
index 000000000..fc1a02b43
--- /dev/null
+++ b/Tests/RunCMake/project_injected/CMP0048-WARN-stderr.txt
@@ -0,0 +1,12 @@
+^CMake Warning \(dev\) in CMakeLists.txt:
+ No project\(\) command is present. The top-level CMakeLists.txt file must
+ contain a literal, direct call to the project\(\) command. Add a line of
+ code such as
+
+ project\(ProjectName\)
+
+ near the top of the file, but after cmake_minimum_required\(\).
+
+ CMake is pretending there is a "project\(Project\)" command on the first
+ line.
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/project_injected/CMP0048-WARN.cmake b/Tests/RunCMake/project_injected/CMP0048-WARN.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/project_injected/CMP0048-WARN.cmake
diff --git a/Tests/RunCMake/project_injected/CMakeLists.txt b/Tests/RunCMake/project_injected/CMakeLists.txt
new file mode 100644
index 000000000..1b4931b8f
--- /dev/null
+++ b/Tests/RunCMake/project_injected/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 2.8.12.2) # old enough to not set CMP0048
+# no project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/project_injected/RunCMakeTest.cmake b/Tests/RunCMake/project_injected/RunCMakeTest.cmake
new file mode 100644
index 000000000..ba1a00377
--- /dev/null
+++ b/Tests/RunCMake/project_injected/RunCMakeTest.cmake
@@ -0,0 +1,12 @@
+include(RunCMake)
+
+set(RunCMake_TEST_OPTIONS
+ # Simulate a previous CMake run that used `project(... VERSION ...)`
+ # in a non-injected call site.
+ -DCMAKE_PROJECT_VERSION:STATIC=1.2.3
+ -DCMAKE_PROJECT_VERSION_MAJOR:STATIC=1
+ -DCMAKE_PROJECT_VERSION_MINOR:STATIC=2
+ -DCMAKE_PROJECT_VERSION_PATCH:STATIC=3
+ )
+run_cmake(CMP0048-WARN)
+unset(RunCMake_TEST_OPTIONS)
diff --git a/Tests/RunCMake/pseudo_cppcheck.c b/Tests/RunCMake/pseudo_cppcheck.c
new file mode 100644
index 000000000..5b1531bb4
--- /dev/null
+++ b/Tests/RunCMake/pseudo_cppcheck.c
@@ -0,0 +1,39 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+int main(int argc, char* argv[])
+{
+ int i;
+ int result = 0;
+ for (i = 1; i < argc; ++i) {
+ if (strcmp(argv[i], "-bad") == 0) {
+ fprintf(stdout, "stdout from bad command line arg '-bad'\n");
+ fprintf(stderr, "stderr from bad command line arg '-bad'\n");
+ return 1;
+ } else if (strcmp(argv[i], "-error") == 0) {
+ // The real cppcheck allows to set the exitcode with --error-exitcode
+ result = 5;
+ }
+ }
+ 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");
+
+ return result;
+}
diff --git a/Tests/RunCMake/pseudo_emulator_custom_command_arg.c b/Tests/RunCMake/pseudo_emulator_custom_command_arg.c
new file mode 100644
index 000000000..d00deda53
--- /dev/null
+++ b/Tests/RunCMake/pseudo_emulator_custom_command_arg.c
@@ -0,0 +1,30 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+// Usage:
+//
+// /path/to/program arg1 [arg2 [...]]
+//
+// Return EXIT_SUCCESS if 'custom_argument' string was found
+// in <arg1> and 'generated_exe_emulator_expected'
+// string was found in <arg2>
+// Return EXIT_FAILURE if 'custom_argument' string was not
+// found in <arg1> or 'generated_exe_emulator_expected'
+// string was not found in <arg2>.
+
+int main(int argc, const char* argv[])
+{
+ // Require a slash to make sure it is a path and not a target name.
+ const char* substring_success = "/generated_exe_emulator_expected";
+ const char* substring_custom_argument = "custom_argument";
+
+ if (argc < 2) {
+ return EXIT_FAILURE;
+ }
+ if (strstr(argv[1], substring_custom_argument) != 0 &&
+ strstr(argv[2], substring_success) != 0) {
+ return EXIT_SUCCESS;
+ }
+ return EXIT_FAILURE;
+}
diff --git a/Tests/RunCMake/set/ExtraEnvValue-stderr.txt b/Tests/RunCMake/set/ExtraEnvValue-stderr.txt
new file mode 100644
index 000000000..f61f9d287
--- /dev/null
+++ b/Tests/RunCMake/set/ExtraEnvValue-stderr.txt
@@ -0,0 +1,6 @@
+CMake Warning \(dev\) at ExtraEnvValue.cmake:1 \(set\):
+ Only the first value argument is used when setting an environment variable.
+ Argument 'value_2' and later are unused.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/set/ExtraEnvValue.cmake b/Tests/RunCMake/set/ExtraEnvValue.cmake
new file mode 100644
index 000000000..768a6eac2
--- /dev/null
+++ b/Tests/RunCMake/set/ExtraEnvValue.cmake
@@ -0,0 +1 @@
+set (ENV{sample_key} value_1 value_2)
diff --git a/Tests/RunCMake/set/UnknownCacheType-stderr.txt b/Tests/RunCMake/set/UnknownCacheType-stderr.txt
new file mode 100644
index 000000000..6e1c8114a
--- /dev/null
+++ b/Tests/RunCMake/set/UnknownCacheType-stderr.txt
@@ -0,0 +1,5 @@
+CMake Warning \(dev\) at UnknownCacheType.cmake:1 \(set\):
+ implicitly converting 'unknown_type_sample' to 'STRING' type.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
+This warning is for project developers. Use -Wno-dev to suppress it.
diff --git a/Tests/RunCMake/set/UnknownCacheType.cmake b/Tests/RunCMake/set/UnknownCacheType.cmake
new file mode 100644
index 000000000..f2b5d051d
--- /dev/null
+++ b/Tests/RunCMake/set/UnknownCacheType.cmake
@@ -0,0 +1 @@
+set (sample_key sample_value CACHE unknown_type_sample "sample doc")
diff --git a/Tests/RunCMake/set_property/IMPORTED_GLOBAL-result.txt b/Tests/RunCMake/set_property/IMPORTED_GLOBAL-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/set_property/IMPORTED_GLOBAL-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/set_property/IMPORTED_GLOBAL-stderr.txt b/Tests/RunCMake/set_property/IMPORTED_GLOBAL-stderr.txt
new file mode 100644
index 000000000..e45fc64b1
--- /dev/null
+++ b/Tests/RunCMake/set_property/IMPORTED_GLOBAL-stderr.txt
@@ -0,0 +1,61 @@
+^CMake Error at IMPORTED_GLOBAL.cmake:9 \(set_property\):
+ IMPORTED_GLOBAL property can't be set to FALSE on targets
+ \(\"ImportedGlobalTarget\"\)
+
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+
+
+CMake Error at IMPORTED_GLOBAL.cmake:16 \(set_property\):
+ IMPORTED_GLOBAL property can't be appended, only set on imported targets
+ \(\"ImportedGlobalTarget\"\)
+
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+
+
+CMake Error at IMPORTED_GLOBAL.cmake:26 \(set_property\):
+ IMPORTED_GLOBAL property can't be set to FALSE on targets
+ \(\"ImportedLocalTarget\"\)
+
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+
+
+CMake Error at IMPORTED_GLOBAL.cmake:32 \(set_property\):
+ IMPORTED_GLOBAL property can't be set on non-imported targets
+ \(\"NonImportedTarget\"\)
+
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+
+
+CMake Error at IMPORTED_GLOBAL/CMakeLists\.txt:[0-9]+ \(set_property\):
+ Attempt to promote imported target \"ImportedLocalTarget2\" to global scope
+ \(by setting IMPORTED_GLOBAL\) which is not built in this directory.
+
+
+CMake Error in IMPORTED_GLOBAL/CMakeLists.txt:
+ IMPORTED_GLOBAL property can't be set to FALSE on targets
+ \(\"ImportedSubdirTarget1\"\)
+
+
+
+CMake Error at IMPORTED_GLOBAL.cmake:50 \(set_property\):
+ Attempt to promote imported target \"ImportedSubdirTarget1\" to global scope
+ \(by setting IMPORTED_GLOBAL\) which is not built in this directory.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
+
+
+CMake Error in IMPORTED_GLOBAL/CMakeLists.txt:
+ IMPORTED_GLOBAL property can't be set to FALSE on targets
+ \(\"ImportedSubdirTarget2\"\)
+
+
+
+CMake Error at IMPORTED_GLOBAL.cmake:52 \(set_property\):
+ Attempt to promote imported target \"ImportedSubdirTarget2\" to global scope
+ \(by setting IMPORTED_GLOBAL\) which is not built in this directory.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/set_property/IMPORTED_GLOBAL-stdout.txt b/Tests/RunCMake/set_property/IMPORTED_GLOBAL-stdout.txt
new file mode 100644
index 000000000..c5f1d1128
--- /dev/null
+++ b/Tests/RunCMake/set_property/IMPORTED_GLOBAL-stdout.txt
@@ -0,0 +1,17 @@
+-- ImportedGlobalTarget: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedGlobalTarget: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedGlobalTarget: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedGlobalTarget: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedGlobalTarget: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedLocalTarget: Target IMPORTED_GLOBAL is 'FALSE'
+-- ImportedLocalTarget: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedLocalTarget: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedLocalTarget: Target IMPORTED_GLOBAL is 'TRUE'
+-- NonImportedTarget: Target IMPORTED_GLOBAL is 'FALSE'
+-- NonImportedTarget: Target IMPORTED_GLOBAL is 'FALSE'
+-- ImportedLocalTarget2: Target IMPORTED_GLOBAL is 'FALSE'
+-- ImportedLocalTarget2: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedSubdirTarget1: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedSubdirTarget2: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedSubdirTarget1: Target IMPORTED_GLOBAL is 'TRUE'
+-- ImportedSubdirTarget2: Target IMPORTED_GLOBAL is 'TRUE'
diff --git a/Tests/RunCMake/set_property/IMPORTED_GLOBAL.cmake b/Tests/RunCMake/set_property/IMPORTED_GLOBAL.cmake
new file mode 100644
index 000000000..08308ebae
--- /dev/null
+++ b/Tests/RunCMake/set_property/IMPORTED_GLOBAL.cmake
@@ -0,0 +1,53 @@
+macro(print_property TARGET PROP)
+ get_property(val TARGET ${TARGET} PROPERTY ${PROP})
+ message(STATUS "${TARGET}: Target ${PROP} is '${val}'")
+endmacro()
+
+# Changing property on IMPORTED target created with `GLOBAL` option.
+add_library(ImportedGlobalTarget SHARED IMPORTED GLOBAL)
+print_property(ImportedGlobalTarget IMPORTED_GLOBAL)
+set_property(TARGET ImportedGlobalTarget PROPERTY IMPORTED_GLOBAL FALSE)
+print_property(ImportedGlobalTarget IMPORTED_GLOBAL)
+set_property(TARGET ImportedGlobalTarget PROPERTY IMPORTED_GLOBAL TRUE)
+print_property(ImportedGlobalTarget IMPORTED_GLOBAL)
+set_property(TARGET ImportedGlobalTarget PROPERTY IMPORTED_GLOBAL TRUE)
+print_property(ImportedGlobalTarget IMPORTED_GLOBAL)
+# Appending property is never allowed!
+set_property(TARGET ImportedGlobalTarget APPEND PROPERTY IMPORTED_GLOBAL TRUE)
+print_property(ImportedGlobalTarget IMPORTED_GLOBAL)
+
+# Changing property on IMPORTED target created without `GLOBAL` option.
+add_library(ImportedLocalTarget SHARED IMPORTED)
+print_property(ImportedLocalTarget IMPORTED_GLOBAL)
+set_property(TARGET ImportedLocalTarget PROPERTY IMPORTED_GLOBAL TRUE)
+print_property(ImportedLocalTarget IMPORTED_GLOBAL)
+set_property(TARGET ImportedLocalTarget PROPERTY IMPORTED_GLOBAL TRUE)
+print_property(ImportedLocalTarget IMPORTED_GLOBAL)
+set_property(TARGET ImportedLocalTarget PROPERTY IMPORTED_GLOBAL FALSE)
+print_property(ImportedLocalTarget IMPORTED_GLOBAL)
+
+# Setting property on non-IMPORTED target is never allowed!
+add_library(NonImportedTarget SHARED test.cpp)
+print_property(NonImportedTarget IMPORTED_GLOBAL)
+set_property(TARGET NonImportedTarget PROPERTY IMPORTED_GLOBAL TRUE)
+print_property(NonImportedTarget IMPORTED_GLOBAL)
+
+# Local IMPORTED targets can only be promoted from same directory!
+add_library(ImportedLocalTarget2 SHARED IMPORTED)
+print_property(ImportedLocalTarget2 IMPORTED_GLOBAL)
+add_subdirectory(IMPORTED_GLOBAL)
+# Note: The value should not have changed. However, it does change because the
+# check for the same directory comes after it was changed! (At least, that is
+# not really bad because the generation will fail due to this error.)
+print_property(ImportedLocalTarget2 IMPORTED_GLOBAL)
+
+# Global IMPORTED targets from subdir are always visible
+# no matter how they became global.
+print_property(ImportedSubdirTarget1 IMPORTED_GLOBAL)
+print_property(ImportedSubdirTarget2 IMPORTED_GLOBAL)
+
+# Changing property on IMPORTED target from subdir is never possible.
+set_property(TARGET ImportedSubdirTarget1 PROPERTY IMPORTED_GLOBAL FALSE)
+print_property(ImportedSubdirTarget1 IMPORTED_GLOBAL)
+set_property(TARGET ImportedSubdirTarget2 PROPERTY IMPORTED_GLOBAL FALSE)
+print_property(ImportedSubdirTarget2 IMPORTED_GLOBAL)
diff --git a/Tests/RunCMake/set_property/IMPORTED_GLOBAL/CMakeLists.txt b/Tests/RunCMake/set_property/IMPORTED_GLOBAL/CMakeLists.txt
new file mode 100644
index 000000000..468bf781c
--- /dev/null
+++ b/Tests/RunCMake/set_property/IMPORTED_GLOBAL/CMakeLists.txt
@@ -0,0 +1,8 @@
+add_library(ImportedSubdirTarget1 SHARED IMPORTED GLOBAL)
+add_library(ImportedSubdirTarget2 SHARED IMPORTED)
+
+# Extend visibility of ImportedSubdirTarget2 to global scope.
+set_property(TARGET ImportedSubdirTarget2 PROPERTY IMPORTED_GLOBAL TRUE)
+
+# Only targets from the same directory can be promoted.
+set_property(TARGET ImportedLocalTarget2 PROPERTY IMPORTED_GLOBAL TRUE)
diff --git a/Tests/RunCMake/set_property/LINK_DIRECTORIES-stdout.txt b/Tests/RunCMake/set_property/LINK_DIRECTORIES-stdout.txt
new file mode 100644
index 000000000..580c3734f
--- /dev/null
+++ b/Tests/RunCMake/set_property/LINK_DIRECTORIES-stdout.txt
@@ -0,0 +1,2 @@
+-- Target LINK_DIRECTORIES is 'a;b;c;d;;e'
+-- Directory LINK_DIRECTORIES is 'a;b;c;d;;e'
diff --git a/Tests/RunCMake/set_property/LINK_DIRECTORIES.cmake b/Tests/RunCMake/set_property/LINK_DIRECTORIES.cmake
new file mode 100644
index 000000000..8529ef5b2
--- /dev/null
+++ b/Tests/RunCMake/set_property/LINK_DIRECTORIES.cmake
@@ -0,0 +1,3 @@
+include(Common.cmake)
+test_target_property(LINK_DIRECTORIES)
+test_directory_property(LINK_DIRECTORIES)
diff --git a/Tests/RunCMake/set_property/LINK_OPTIONS-stdout.txt b/Tests/RunCMake/set_property/LINK_OPTIONS-stdout.txt
new file mode 100644
index 000000000..033792a47
--- /dev/null
+++ b/Tests/RunCMake/set_property/LINK_OPTIONS-stdout.txt
@@ -0,0 +1,2 @@
+-- Target LINK_OPTIONS is 'a;b;c;d;;e'
+-- Directory LINK_OPTIONS is 'a;b;c;d;;e'
diff --git a/Tests/RunCMake/set_property/LINK_OPTIONS.cmake b/Tests/RunCMake/set_property/LINK_OPTIONS.cmake
new file mode 100644
index 000000000..6daf41b49
--- /dev/null
+++ b/Tests/RunCMake/set_property/LINK_OPTIONS.cmake
@@ -0,0 +1,3 @@
+include(Common.cmake)
+test_target_property(LINK_OPTIONS)
+test_directory_property(LINK_OPTIONS)
diff --git a/Tests/RunCMake/set_property/USER_PROP_INHERITED-stdout.txt b/Tests/RunCMake/set_property/USER_PROP_INHERITED-stdout.txt
new file mode 100644
index 000000000..dcb0f875c
--- /dev/null
+++ b/Tests/RunCMake/set_property/USER_PROP_INHERITED-stdout.txt
@@ -0,0 +1,29 @@
+-- TopDir-to-nothing chaining: ''
+-- TopDir-to-global chaining: 'vGlobal'
+-- TopDir no chaining required: 'vTopDir'
+-- TopDir unset append chaining: 'aTopDir'
+-- TopDir preset append chaining: 'vTopDir;aTopDir'
+-- Subdir-to-parent chaining: 'vTopDir'
+-- Subdir-to-global chaining: 'vGlobal'
+-- Subdir no chaining required: 'vSubdir'
+-- Subdir preset append chaining: 'vSubdir;aSubdir'
+-- Subdir unset append chaining: 'aSubdir'
+-- Subdir undefined append chaining: 'aSubdir'
+-- Target-to-directory chaining: 'vTopDir'
+-- Target unset append chaining: 'aTarget'
+-- Target no chaining required: 'vTarget'
+-- Target preset append chaining: 'vTarget;aTarget'
+-- Target undefined get chaining: ''
+-- Target undefined append chaining: 'aTarget'
+-- Source-to-directory chaining: 'vTopDir'
+-- Source unset append chaining: 'aSource'
+-- Source no chaining required: 'vSource'
+-- Source preset append chaining: 'vSource;aSource'
+-- Source undefined get chaining: ''
+-- Source undefined append chaining: 'aSource'
+-- Test-to-directory chaining: 'vTopDir'
+-- Test unset append chaining: 'aTest'
+-- Test no chaining required: 'vTest'
+-- Test preset append chaining: 'vTest;aTest'
+-- Test undefined get chaining: ''
+-- Test undefined append chaining: 'aTest'
diff --git a/Tests/RunCMake/set_property/USER_PROP_INHERITED.cmake b/Tests/RunCMake/set_property/USER_PROP_INHERITED.cmake
new file mode 100644
index 000000000..2429866ed
--- /dev/null
+++ b/Tests/RunCMake/set_property/USER_PROP_INHERITED.cmake
@@ -0,0 +1,83 @@
+# Needed for source property tests
+enable_language(C)
+
+#=================================================
+# Directory property chaining
+#=================================================
+
+foreach(i RANGE 1 5)
+ foreach(propType DIRECTORY TARGET SOURCE TEST)
+ define_property(${propType} PROPERTY USER_PROP${i} INHERITED
+ BRIEF_DOCS "Brief" FULL_DOCS "Full"
+ )
+ endforeach()
+endforeach()
+
+get_property(val DIRECTORY PROPERTY USER_PROP1)
+message(STATUS "TopDir-to-nothing chaining: '${val}'")
+
+set_property(GLOBAL PROPERTY USER_PROP1 vGlobal)
+set_property(GLOBAL PROPERTY USER_PROP2 vGlobal)
+set_property(DIRECTORY PROPERTY USER_PROP2 vTopDir)
+set_property(GLOBAL PROPERTY USER_PROP3 vGlobal)
+set_property(DIRECTORY PROPERTY USER_PROP4 vTopDir)
+
+get_property(val DIRECTORY PROPERTY USER_PROP1)
+message(STATUS "TopDir-to-global chaining: '${val}'")
+
+get_property(val DIRECTORY PROPERTY USER_PROP2)
+message(STATUS "TopDir no chaining required: '${val}'")
+
+set_property(DIRECTORY APPEND PROPERTY USER_PROP3 aTopDir)
+get_property(val DIRECTORY PROPERTY USER_PROP3)
+message(STATUS "TopDir unset append chaining: '${val}'")
+
+set_property(DIRECTORY APPEND PROPERTY USER_PROP4 aTopDir)
+get_property(val DIRECTORY PROPERTY USER_PROP4)
+message(STATUS "TopDir preset append chaining: '${val}'")
+
+add_subdirectory(USER_PROP_INHERITED)
+
+#=================================================
+# The other property types all chain the same way
+#=================================================
+macro(__chainToDirTests propType)
+ string(TOUPPER ${propType} propTypeUpper)
+
+ get_property(val ${propTypeUpper} ${propType}1 PROPERTY USER_PROP2)
+ message(STATUS "${propType}-to-directory chaining: '${val}'")
+
+ set_property(${propTypeUpper} ${propType}1 APPEND PROPERTY USER_PROP2 a${propType})
+ get_property(val ${propTypeUpper} ${propType}1 PROPERTY USER_PROP2)
+ message(STATUS "${propType} unset append chaining: '${val}'")
+
+ set_property(${propTypeUpper} ${propType}1 PROPERTY USER_PROP1 v${propType})
+ get_property(val ${propTypeUpper} ${propType}1 PROPERTY USER_PROP1)
+ message(STATUS "${propType} no chaining required: '${val}'")
+
+ set_property(${propTypeUpper} ${propType}1 APPEND PROPERTY USER_PROP1 a${propType})
+ get_property(val ${propTypeUpper} ${propType}1 PROPERTY USER_PROP1)
+ message(STATUS "${propType} preset append chaining: '${val}'")
+
+ get_property(val ${propTypeUpper} ${propType}2 PROPERTY USER_PROP5)
+ message(STATUS "${propType} undefined get chaining: '${val}'")
+
+ set_property(${propTypeUpper} ${propType}2 APPEND PROPERTY USER_PROP5 a${propType})
+ get_property(val ${propTypeUpper} ${propType}2 PROPERTY USER_PROP5)
+ message(STATUS "${propType} undefined append chaining: '${val}'")
+endmacro()
+
+add_custom_target(Target1)
+add_custom_target(Target2)
+__chainToDirTests(Target)
+
+foreach(i RANGE 1 2)
+ set(Source${i} "${CMAKE_CURRENT_BINARY_DIR}/src${i}.c")
+ file(WRITE ${Source${i}} "int foo${i}() { return ${i}; }")
+endforeach()
+add_library(srcProps OBJECT ${Source1} ${Source2})
+__chainToDirTests(Source)
+
+add_test(NAME Test1 COMMAND ${CMAKE_COMMAND} -E touch_nocreate iDoNotExist)
+add_test(NAME Test2 COMMAND ${CMAKE_COMMAND} -E touch_nocreate iDoNotExist)
+__chainToDirTests(Test)
diff --git a/Tests/RunCMake/set_property/USER_PROP_INHERITED/CMakeLists.txt b/Tests/RunCMake/set_property/USER_PROP_INHERITED/CMakeLists.txt
new file mode 100644
index 000000000..234f4ee5d
--- /dev/null
+++ b/Tests/RunCMake/set_property/USER_PROP_INHERITED/CMakeLists.txt
@@ -0,0 +1,21 @@
+get_property(val DIRECTORY PROPERTY USER_PROP2)
+message(STATUS "Subdir-to-parent chaining: '${val}'")
+
+get_property(val DIRECTORY PROPERTY USER_PROP1)
+message(STATUS "Subdir-to-global chaining: '${val}'")
+
+set_property(DIRECTORY PROPERTY USER_PROP1 vSubdir)
+get_property(val DIRECTORY PROPERTY USER_PROP1)
+message(STATUS "Subdir no chaining required: '${val}'")
+
+set_property(DIRECTORY APPEND PROPERTY USER_PROP1 aSubdir)
+get_property(val DIRECTORY PROPERTY USER_PROP1)
+message(STATUS "Subdir preset append chaining: '${val}'")
+
+set_property(DIRECTORY APPEND PROPERTY USER_PROP2 aSubdir)
+get_property(val DIRECTORY PROPERTY USER_PROP2)
+message(STATUS "Subdir unset append chaining: '${val}'")
+
+set_property(DIRECTORY APPEND PROPERTY USER_PROP5 aSubdir)
+get_property(val DIRECTORY PROPERTY USER_PROP5)
+message(STATUS "Subdir undefined append chaining: '${val}'")
diff --git a/Tests/RunCMake/set_property/test.cpp b/Tests/RunCMake/set_property/test.cpp
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/set_property/test.cpp
diff --git a/Tests/RunCMake/string/Join.cmake b/Tests/RunCMake/string/Join.cmake
new file mode 100644
index 000000000..081f1e4fc
--- /dev/null
+++ b/Tests/RunCMake/string/Join.cmake
@@ -0,0 +1,16 @@
+string(JOIN % out)
+if(NOT out STREQUAL "")
+ message(FATAL_ERROR "\"string(JOIN % out)\" set out to \"${out}\"")
+endif()
+string(JOIN % out a)
+if(NOT out STREQUAL "a")
+ message(FATAL_ERROR "\"string(JOIN % out a)\" set out to \"${out}\"")
+endif()
+string(JOIN % out a "b")
+if(NOT out STREQUAL "a%b")
+ message(FATAL_ERROR "\"string(JOIN % out a \"b\")\" set out to \"${out}\"")
+endif()
+string(JOIN :: out a "b")
+if(NOT out STREQUAL "a::b")
+ message(FATAL_ERROR "\"string(JOIN :: out a \"b\")\" set out to \"${out}\"")
+endif()
diff --git a/Tests/RunCMake/string/JoinNoArgs-result.txt b/Tests/RunCMake/string/JoinNoArgs-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/string/JoinNoArgs-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/JoinNoArgs-stderr.txt b/Tests/RunCMake/string/JoinNoArgs-stderr.txt
new file mode 100644
index 000000000..7fcd3524d
--- /dev/null
+++ b/Tests/RunCMake/string/JoinNoArgs-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at JoinNoArgs.cmake:1 \(string\):
+ string sub-command JOIN requires at least two arguments.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/string/JoinNoArgs.cmake b/Tests/RunCMake/string/JoinNoArgs.cmake
new file mode 100644
index 000000000..35ba4d9dd
--- /dev/null
+++ b/Tests/RunCMake/string/JoinNoArgs.cmake
@@ -0,0 +1 @@
+string(JOIN)
diff --git a/Tests/RunCMake/string/JoinNoVar-result.txt b/Tests/RunCMake/string/JoinNoVar-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/string/JoinNoVar-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/JoinNoVar-stderr.txt b/Tests/RunCMake/string/JoinNoVar-stderr.txt
new file mode 100644
index 000000000..b4a09c31c
--- /dev/null
+++ b/Tests/RunCMake/string/JoinNoVar-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at JoinNoVar.cmake:1 \(string\):
+ string sub-command JOIN requires at least two arguments.
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/string/JoinNoVar.cmake b/Tests/RunCMake/string/JoinNoVar.cmake
new file mode 100644
index 000000000..35f7b9272
--- /dev/null
+++ b/Tests/RunCMake/string/JoinNoVar.cmake
@@ -0,0 +1 @@
+string(JOIN ";")
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..c8acba8f0
--- /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:[0-9]+ \(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/Repeat.cmake b/Tests/RunCMake/string/Repeat.cmake
new file mode 100644
index 000000000..fc390aa62
--- /dev/null
+++ b/Tests/RunCMake/string/Repeat.cmake
@@ -0,0 +1,45 @@
+string(REPEAT "q" 4 q_out)
+
+if(NOT DEFINED q_out)
+ message(FATAL_ERROR "q_out is not defined")
+endif()
+
+if(NOT q_out STREQUAL "qqqq")
+ message(FATAL_ERROR "unexpected result")
+endif()
+
+string(REPEAT "1234" 0 zero_out)
+
+if(NOT DEFINED zero_out)
+ message(FATAL_ERROR "zero_out is not defined")
+endif()
+
+if(NOT zero_out STREQUAL "")
+ message(FATAL_ERROR "unexpected result")
+endif()
+
+unset(zero_out)
+
+string(REPEAT "" 100 zero_out)
+
+if(NOT DEFINED zero_out)
+ message(FATAL_ERROR "zero_out is not defined")
+endif()
+
+if(NOT zero_out STREQUAL "")
+ message(FATAL_ERROR "unexpected result")
+endif()
+
+string(REPEAT "1" 1 one_out)
+
+if(NOT one_out STREQUAL "1")
+ message(FATAL_ERROR "unexpected result")
+endif()
+
+unset(one_out)
+
+string(REPEAT "one" 1 one_out)
+
+if(NOT one_out STREQUAL "one")
+ message(FATAL_ERROR "unexpected result")
+endif()
diff --git a/Tests/RunCMake/string/RepeatNegativeCount-result.txt b/Tests/RunCMake/string/RepeatNegativeCount-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/string/RepeatNegativeCount-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/RepeatNegativeCount-stderr.txt b/Tests/RunCMake/string/RepeatNegativeCount-stderr.txt
new file mode 100644
index 000000000..bbd498eee
--- /dev/null
+++ b/Tests/RunCMake/string/RepeatNegativeCount-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at RepeatNegativeCount.cmake:[0-9]+ \(string\):
+ repeat count is not a positive number.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/string/RepeatNegativeCount.cmake b/Tests/RunCMake/string/RepeatNegativeCount.cmake
new file mode 100644
index 000000000..769e7c0a1
--- /dev/null
+++ b/Tests/RunCMake/string/RepeatNegativeCount.cmake
@@ -0,0 +1 @@
+string(REPEAT "blah" -1 out)
diff --git a/Tests/RunCMake/string/RepeatNoArgs-result.txt b/Tests/RunCMake/string/RepeatNoArgs-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/string/RepeatNoArgs-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/RepeatNoArgs-stderr.txt b/Tests/RunCMake/string/RepeatNoArgs-stderr.txt
new file mode 100644
index 000000000..5abcb3be7
--- /dev/null
+++ b/Tests/RunCMake/string/RepeatNoArgs-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at RepeatNoArgs.cmake:[0-9]+ \(string\):
+ sub-command REPEAT requires three arguments.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/string/RepeatNoArgs.cmake b/Tests/RunCMake/string/RepeatNoArgs.cmake
new file mode 100644
index 000000000..e327e998e
--- /dev/null
+++ b/Tests/RunCMake/string/RepeatNoArgs.cmake
@@ -0,0 +1 @@
+string(REPEAT)
diff --git a/Tests/RunCMake/target_compile_definitions/CMakeLists.txt b/Tests/RunCMake/target_compile_definitions/CMakeLists.txt
new file mode 100644
index 000000000..14ef56e8e
--- /dev/null
+++ b/Tests/RunCMake/target_compile_definitions/CMakeLists.txt
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.11)
+
+project(${RunCMake_TEST} LANGUAGES NONE)
+
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/target_compile_definitions/RunCMakeTest.cmake b/Tests/RunCMake/target_compile_definitions/RunCMakeTest.cmake
new file mode 100644
index 000000000..b67c5983e
--- /dev/null
+++ b/Tests/RunCMake/target_compile_definitions/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(empty_keyword_args)
diff --git a/Tests/RunCMake/target_compile_definitions/empty_keyword_args.cmake b/Tests/RunCMake/target_compile_definitions/empty_keyword_args.cmake
new file mode 100644
index 000000000..cb94e87be
--- /dev/null
+++ b/Tests/RunCMake/target_compile_definitions/empty_keyword_args.cmake
@@ -0,0 +1,5 @@
+add_library(iface INTERFACE)
+target_compile_definitions(iface PUBLIC PRIVATE INTERFACE)
+# Cannot be called with non-compilable targets.
+#add_library(imported UNKNOWN IMPORTED)
+#target_compile_definitions(imported PUBLIC PRIVATE INTERFACE)
diff --git a/Tests/RunCMake/target_compile_features/empty_keyword_args.cmake b/Tests/RunCMake/target_compile_features/empty_keyword_args.cmake
new file mode 100644
index 000000000..8d57c1cac
--- /dev/null
+++ b/Tests/RunCMake/target_compile_features/empty_keyword_args.cmake
@@ -0,0 +1,5 @@
+add_library(iface INTERFACE)
+target_compile_features(iface PUBLIC PRIVATE INTERFACE)
+# Cannot be called with non-compilable targets.
+#add_library(imported UNKNOWN IMPORTED)
+#target_compile_features(imported PUBLIC PRIVATE INTERFACE)
diff --git a/Tests/RunCMake/target_compile_options/CMakeLists.txt b/Tests/RunCMake/target_compile_options/CMakeLists.txt
new file mode 100644
index 000000000..14ef56e8e
--- /dev/null
+++ b/Tests/RunCMake/target_compile_options/CMakeLists.txt
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.11)
+
+project(${RunCMake_TEST} LANGUAGES NONE)
+
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/target_compile_options/RunCMakeTest.cmake b/Tests/RunCMake/target_compile_options/RunCMakeTest.cmake
new file mode 100644
index 000000000..b67c5983e
--- /dev/null
+++ b/Tests/RunCMake/target_compile_options/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(empty_keyword_args)
diff --git a/Tests/RunCMake/target_compile_options/empty_keyword_args.cmake b/Tests/RunCMake/target_compile_options/empty_keyword_args.cmake
new file mode 100644
index 000000000..8b92fcf16
--- /dev/null
+++ b/Tests/RunCMake/target_compile_options/empty_keyword_args.cmake
@@ -0,0 +1,5 @@
+add_library(iface INTERFACE)
+target_compile_options(iface PUBLIC PRIVATE INTERFACE)
+# Cannot be called with non-compilable targets.
+#add_library(imported UNKNOWN IMPORTED)
+#target_compile_options(imported PUBLIC PRIVATE INTERFACE)
diff --git a/Tests/RunCMake/target_include_directories/CMakeLists.txt b/Tests/RunCMake/target_include_directories/CMakeLists.txt
new file mode 100644
index 000000000..14ef56e8e
--- /dev/null
+++ b/Tests/RunCMake/target_include_directories/CMakeLists.txt
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.11)
+
+project(${RunCMake_TEST} LANGUAGES NONE)
+
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/target_include_directories/RunCMakeTest.cmake b/Tests/RunCMake/target_include_directories/RunCMakeTest.cmake
new file mode 100644
index 000000000..b67c5983e
--- /dev/null
+++ b/Tests/RunCMake/target_include_directories/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(empty_keyword_args)
diff --git a/Tests/RunCMake/target_include_directories/empty_keyword_args.cmake b/Tests/RunCMake/target_include_directories/empty_keyword_args.cmake
new file mode 100644
index 000000000..08eaf9157
--- /dev/null
+++ b/Tests/RunCMake/target_include_directories/empty_keyword_args.cmake
@@ -0,0 +1,5 @@
+add_library(iface INTERFACE)
+target_include_directories(iface PUBLIC PRIVATE INTERFACE)
+# Cannot be called with non-compilable targets.
+#add_library(imported UNKNOWN IMPORTED)
+#target_include_directories(imported PUBLIC PRIVATE INTERFACE)
diff --git a/Tests/RunCMake/target_link_directories/CMakeLists.txt b/Tests/RunCMake/target_link_directories/CMakeLists.txt
new file mode 100644
index 000000000..14ef56e8e
--- /dev/null
+++ b/Tests/RunCMake/target_link_directories/CMakeLists.txt
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.11)
+
+project(${RunCMake_TEST} LANGUAGES NONE)
+
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/target_link_directories/RunCMakeTest.cmake b/Tests/RunCMake/target_link_directories/RunCMakeTest.cmake
new file mode 100644
index 000000000..b67c5983e
--- /dev/null
+++ b/Tests/RunCMake/target_link_directories/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(empty_keyword_args)
diff --git a/Tests/RunCMake/target_link_directories/empty_keyword_args.cmake b/Tests/RunCMake/target_link_directories/empty_keyword_args.cmake
new file mode 100644
index 000000000..aadf80a04
--- /dev/null
+++ b/Tests/RunCMake/target_link_directories/empty_keyword_args.cmake
@@ -0,0 +1,5 @@
+add_library(iface INTERFACE)
+target_link_directories(iface PUBLIC PRIVATE INTERFACE)
+# Cannot be called with non-compilable targets.
+#add_library(imported UNKNOWN IMPORTED)
+#target_link_directories(imported PUBLIC PRIVATE INTERFACE)
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-iface-NEW-stdout.txt b/Tests/RunCMake/target_link_libraries/CMP0079-iface-NEW-stdout.txt
new file mode 100644
index 000000000..89cd80633
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-iface-NEW-stdout.txt
@@ -0,0 +1 @@
+-- INTERFACE_LINK_LIBRARIES='foo::@<[Xx0-9A-Fa-f]+>'
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-iface-NEW.cmake b/Tests/RunCMake/target_link_libraries/CMP0079-iface-NEW.cmake
new file mode 100644
index 000000000..82486c42c
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-iface-NEW.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0079 NEW)
+include(CMP0079-iface-common.cmake)
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-iface-OLD-stdout.txt b/Tests/RunCMake/target_link_libraries/CMP0079-iface-OLD-stdout.txt
new file mode 100644
index 000000000..e575e1675
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-iface-OLD-stdout.txt
@@ -0,0 +1 @@
+-- INTERFACE_LINK_LIBRARIES='foo'
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-iface-OLD.cmake b/Tests/RunCMake/target_link_libraries/CMP0079-iface-OLD.cmake
new file mode 100644
index 000000000..e04a2bb53
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-iface-OLD.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0079 OLD)
+include(CMP0079-iface-common.cmake)
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN-stderr.txt b/Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN-stderr.txt
new file mode 100644
index 000000000..6dd7d3069
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN-stderr.txt
@@ -0,0 +1,17 @@
+^CMake Warning \(dev\) at CMP0079-iface/CMakeLists.txt:[0-9]+ \(target_link_libraries\):
+ Policy CMP0079 is not set: target_link_libraries allows use with targets in
+ other directories. Run "cmake --help-policy CMP0079" for policy details.
+ Use the cmake_policy command to set the policy and suppress this warning.
+
+ Target
+
+ top
+
+ is not created in this directory. For compatibility with older versions of
+ CMake, link library
+
+ foo
+
+ will be looked up in the directory in which the target was created rather
+ than in this calling directory.
+This warning is for project developers. Use -Wno-dev to suppress it.$
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN-stdout.txt b/Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN-stdout.txt
new file mode 100644
index 000000000..e575e1675
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN-stdout.txt
@@ -0,0 +1 @@
+-- INTERFACE_LINK_LIBRARIES='foo'
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN.cmake b/Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN.cmake
new file mode 100644
index 000000000..2041893c8
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-iface-WARN.cmake
@@ -0,0 +1 @@
+include(CMP0079-iface-common.cmake)
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-iface-common.cmake b/Tests/RunCMake/target_link_libraries/CMP0079-iface-common.cmake
new file mode 100644
index 000000000..3982ff264
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-iface-common.cmake
@@ -0,0 +1,6 @@
+enable_language(C)
+
+add_executable(top empty.c)
+add_subdirectory(CMP0079-iface)
+get_property(libs TARGET top PROPERTY INTERFACE_LINK_LIBRARIES)
+message(STATUS "INTERFACE_LINK_LIBRARIES='${libs}'")
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-iface/CMakeLists.txt b/Tests/RunCMake/target_link_libraries/CMP0079-iface/CMakeLists.txt
new file mode 100644
index 000000000..4b15b329b
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-iface/CMakeLists.txt
@@ -0,0 +1 @@
+target_link_libraries(top INTERFACE foo)
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus-result.txt b/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus-stderr.txt b/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus-stderr.txt
new file mode 100644
index 000000000..8ef35c1dc
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus-stderr.txt
@@ -0,0 +1,6 @@
+^CMake Error at CMP0079-link-NEW-bogus.cmake:[0-9]+ \(add_executable\):
+ Target "top" links to target "foo::@<0xdeadbeef>" but the target was not
+ found. Perhaps a find_package\(\) call is missing for an IMPORTED target, or
+ an ALIAS target is missing\?
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus.cmake b/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus.cmake
new file mode 100644
index 000000000..8622f14e7
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-bogus.cmake
@@ -0,0 +1,6 @@
+cmake_policy(SET CMP0028 NEW)
+cmake_policy(SET CMP0079 NEW)
+enable_language(C)
+
+add_executable(top empty.c)
+set_property(TARGET top APPEND PROPERTY LINK_LIBRARIES "foo::@<0xdeadbeef>")
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-stdout.txt b/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-stdout.txt
new file mode 100644
index 000000000..84b30bd0a
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW-stdout.txt
@@ -0,0 +1 @@
+-- LINK_LIBRARIES='foo::@<[Xx0-9A-Fa-f]+>'
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW.cmake b/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW.cmake
new file mode 100644
index 000000000..72e457494
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-NEW.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0079 NEW)
+include(CMP0079-link-common.cmake)
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-OLD-result.txt b/Tests/RunCMake/target_link_libraries/CMP0079-link-OLD-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-OLD-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-OLD-stderr.txt b/Tests/RunCMake/target_link_libraries/CMP0079-link-OLD-stderr.txt
new file mode 100644
index 000000000..0b4c4c683
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-OLD-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at CMP0079-link/CMakeLists.txt:[0-9]+ \(target_link_libraries\):
+ Attempt to add link library "foo" to target "top" which is not built in
+ this directory.
+
+ This is allowed only when policy CMP0079 is set to NEW.$
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-OLD.cmake b/Tests/RunCMake/target_link_libraries/CMP0079-link-OLD.cmake
new file mode 100644
index 000000000..caa7231b7
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-OLD.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0079 OLD)
+include(CMP0079-link-common.cmake)
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-WARN-result.txt b/Tests/RunCMake/target_link_libraries/CMP0079-link-WARN-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-WARN-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-WARN-stderr.txt b/Tests/RunCMake/target_link_libraries/CMP0079-link-WARN-stderr.txt
new file mode 100644
index 000000000..0b4c4c683
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-WARN-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at CMP0079-link/CMakeLists.txt:[0-9]+ \(target_link_libraries\):
+ Attempt to add link library "foo" to target "top" which is not built in
+ this directory.
+
+ This is allowed only when policy CMP0079 is set to NEW.$
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-WARN.cmake b/Tests/RunCMake/target_link_libraries/CMP0079-link-WARN.cmake
new file mode 100644
index 000000000..e83818a9d
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-WARN.cmake
@@ -0,0 +1 @@
+include(CMP0079-link-common.cmake)
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link-common.cmake b/Tests/RunCMake/target_link_libraries/CMP0079-link-common.cmake
new file mode 100644
index 000000000..4f9454f0a
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link-common.cmake
@@ -0,0 +1,6 @@
+enable_language(C)
+
+add_executable(top empty.c)
+add_subdirectory(CMP0079-link)
+get_property(libs TARGET top PROPERTY LINK_LIBRARIES)
+message(STATUS "LINK_LIBRARIES='${libs}'")
diff --git a/Tests/RunCMake/target_link_libraries/CMP0079-link/CMakeLists.txt b/Tests/RunCMake/target_link_libraries/CMP0079-link/CMakeLists.txt
new file mode 100644
index 000000000..8b2b3c94f
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/CMP0079-link/CMakeLists.txt
@@ -0,0 +1 @@
+target_link_libraries(top PUBLIC foo)
diff --git a/Tests/RunCMake/target_link_libraries/ImportedTarget.cmake b/Tests/RunCMake/target_link_libraries/ImportedTarget.cmake
new file mode 100644
index 000000000..e5ec3f6b6
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/ImportedTarget.cmake
@@ -0,0 +1,2 @@
+add_library(UnknownImportedGlobal UNKNOWN IMPORTED GLOBAL)
+target_link_libraries(UnknownImportedGlobal INTERFACE z)
diff --git a/Tests/RunCMake/target_link_libraries/ImportedTargetFailure-result.txt b/Tests/RunCMake/target_link_libraries/ImportedTargetFailure-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/ImportedTargetFailure-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/target_link_libraries/ImportedTargetFailure-stderr.txt b/Tests/RunCMake/target_link_libraries/ImportedTargetFailure-stderr.txt
new file mode 100644
index 000000000..1cafa5b5e
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/ImportedTargetFailure-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at ImportedTargetFailure.cmake:[0-9]+ \(target_link_libraries\):
+ IMPORTED library can only be used with the INTERFACE keyword of
+ target_link_libraries
+Call Stack \(most recent call first\):
+ CMakeLists\.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/target_link_libraries/ImportedTargetFailure.cmake b/Tests/RunCMake/target_link_libraries/ImportedTargetFailure.cmake
new file mode 100644
index 000000000..3ac0aa981
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/ImportedTargetFailure.cmake
@@ -0,0 +1,2 @@
+add_library(UnknownImportedGlobal UNKNOWN IMPORTED GLOBAL)
+target_link_libraries(UnknownImportedGlobal PRIVATE z)
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/target_link_libraries/empty_keyword_args.cmake b/Tests/RunCMake/target_link_libraries/empty_keyword_args.cmake
new file mode 100644
index 000000000..440fa06b8
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/empty_keyword_args.cmake
@@ -0,0 +1,4 @@
+add_library(iface INTERFACE)
+target_link_libraries(iface PUBLIC PRIVATE INTERFACE)
+add_library(imported UNKNOWN IMPORTED)
+target_link_libraries(imported PUBLIC PRIVATE INTERFACE)
diff --git a/Tests/RunCMake/target_link_options/CMakeLists.txt b/Tests/RunCMake/target_link_options/CMakeLists.txt
new file mode 100644
index 000000000..14ef56e8e
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/CMakeLists.txt
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.11)
+
+project(${RunCMake_TEST} LANGUAGES NONE)
+
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/target_link_options/LINKER_expansion-LINKER-check.cmake b/Tests/RunCMake/target_link_options/LINKER_expansion-LINKER-check.cmake
new file mode 100644
index 000000000..d0ef8de85
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINKER_expansion-LINKER-check.cmake
@@ -0,0 +1,2 @@
+
+include ("${CMAKE_CURRENT_LIST_DIR}/LINKER_expansion-validation.cmake")
diff --git a/Tests/RunCMake/target_link_options/LINKER_expansion-LINKER_SHELL-check.cmake b/Tests/RunCMake/target_link_options/LINKER_expansion-LINKER_SHELL-check.cmake
new file mode 100644
index 000000000..d0ef8de85
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINKER_expansion-LINKER_SHELL-check.cmake
@@ -0,0 +1,2 @@
+
+include ("${CMAKE_CURRENT_LIST_DIR}/LINKER_expansion-validation.cmake")
diff --git a/Tests/RunCMake/target_link_options/LINKER_expansion-validation.cmake b/Tests/RunCMake/target_link_options/LINKER_expansion-validation.cmake
new file mode 100644
index 000000000..1af8f13a3
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINKER_expansion-validation.cmake
@@ -0,0 +1,15 @@
+
+if (actual_stdout MATCHES "LINKER:")
+ set (RunCMake_TEST_FAILED "LINKER: prefix was not expanded.")
+ return()
+endif()
+
+if (NOT EXISTS "${RunCMake_TEST_BINARY_DIR}/LINKER.txt")
+ set (RunCMake_TEST_FAILED "${RunCMake_TEST_BINARY_DIR}/LINKER.txt: Reference file not found.")
+ return()
+endif()
+file(READ "${RunCMake_TEST_BINARY_DIR}/LINKER.txt" linker_flag)
+
+if (NOT actual_stdout MATCHES "${linker_flag}")
+ set (RunCMake_TEST_FAILED "LINKER: was not expanded correctly.")
+endif()
diff --git a/Tests/RunCMake/target_link_options/LINKER_expansion.cmake b/Tests/RunCMake/target_link_options/LINKER_expansion.cmake
new file mode 100644
index 000000000..b3448679d
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINKER_expansion.cmake
@@ -0,0 +1,49 @@
+
+enable_language(C)
+
+add_executable(dump dump.c)
+
+# ensure no temp file will be used
+string(REPLACE "${CMAKE_START_TEMP_FILE}" "" CMAKE_C_CREATE_SHARED_LIBRARY "${CMAKE_C_CREATE_SHARED_LIBRARY}")
+string(REPLACE "${CMAKE_END_TEMP_FILE}" "" CMAKE_C_CREATE_SHARED_LIBRARY "${CMAKE_C_CREATE_SHARED_LIBRARY}")
+
+
+# Use LINKER alone
+add_library(linker SHARED LinkOptionsLib.c)
+target_link_options(linker PRIVATE "LINKER:-foo,bar")
+
+# use LAUNCH facility to dump linker command
+set_property(TARGET linker PROPERTY RULE_LAUNCH_LINK "\"${CMAKE_CURRENT_BINARY_DIR}/dump${CMAKE_EXECUTABLE_SUFFIX}\"")
+
+add_dependencies (linker dump)
+
+
+# Use LINKER with SHELL
+add_library(linker_shell SHARED LinkOptionsLib.c)
+target_link_options(linker_shell PRIVATE "LINKER:SHELL:-foo bar")
+
+# use LAUNCH facility to dump linker command
+set_property(TARGET linker_shell PROPERTY RULE_LAUNCH_LINK "\"${CMAKE_CURRENT_BINARY_DIR}/dump${CMAKE_EXECUTABLE_SUFFIX}\"")
+
+add_dependencies (linker_shell dump)
+
+
+# generate reference for LINKER flag
+if (CMAKE_C_LINKER_WRAPPER_FLAG)
+ set(linker_flag ${CMAKE_C_LINKER_WRAPPER_FLAG})
+ list(GET linker_flag -1 linker_space)
+ if (linker_space STREQUAL " ")
+ list(REMOVE_AT linker_flag -1)
+ else()
+ set(linker_space)
+ endif()
+ list (JOIN linker_flag " " linker_flag)
+ if (CMAKE_C_LINKER_WRAPPER_FLAG_SEP)
+ string (APPEND linker_flag "${linker_space}" "-foo${CMAKE_C_LINKER_WRAPPER_FLAG_SEP}bar")
+ else()
+ set (linker_flag "${linker_flag}${linker_space}-foo ${linker_flag}${linker_space}bar")
+ endif()
+else()
+ set(linker_flag "-foo bar")
+endif()
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/LINKER.txt" "${linker_flag}")
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-basic-check.cmake b/Tests/RunCMake/target_link_options/LINK_OPTIONS-basic-check.cmake
new file mode 100644
index 000000000..779950610
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-basic-check.cmake
@@ -0,0 +1,7 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG_PRIVATE")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG_PRIVATE'.")
+endif()
+if (actual_stdout MATCHES "BADFLAG_INTERFACE")
+ string (APPEND RunCMake_TEST_FAILED "\nFound unexpected 'BADFLAG_INTERFACE'.")
+endif()
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-basic-result.txt b/Tests/RunCMake/target_link_options/LINK_OPTIONS-basic-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-basic-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-exe-check.cmake b/Tests/RunCMake/target_link_options/LINK_OPTIONS-exe-check.cmake
new file mode 100644
index 000000000..a686de945
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-exe-check.cmake
@@ -0,0 +1,7 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG_RELEASE")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG_RELEASE'.")
+endif()
+if (actual_stdout MATCHES "SHELL:")
+ string (APPEND RunCMake_TEST_FAILED "\nFound unexpected prefix 'SHELL:'.")
+endif()
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-exe-result.txt b/Tests/RunCMake/target_link_options/LINK_OPTIONS-exe-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-exe-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-check.cmake b/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-check.cmake
new file mode 100644
index 000000000..6c5ffdb36
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-check.cmake
@@ -0,0 +1,4 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG_INTERFACE")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG_INTERFACE'.")
+endif()
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-result.txt b/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-static-check.cmake b/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-static-check.cmake
new file mode 100644
index 000000000..6c5ffdb36
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-static-check.cmake
@@ -0,0 +1,4 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG_INTERFACE")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG_INTERFACE'.")
+endif()
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-static-result.txt b/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-static-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-interface-static-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-mod-check.cmake b/Tests/RunCMake/target_link_options/LINK_OPTIONS-mod-check.cmake
new file mode 100644
index 000000000..a686de945
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-mod-check.cmake
@@ -0,0 +1,7 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG_RELEASE")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG_RELEASE'.")
+endif()
+if (actual_stdout MATCHES "SHELL:")
+ string (APPEND RunCMake_TEST_FAILED "\nFound unexpected prefix 'SHELL:'.")
+endif()
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-mod-result.txt b/Tests/RunCMake/target_link_options/LINK_OPTIONS-mod-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-mod-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-shared-check.cmake b/Tests/RunCMake/target_link_options/LINK_OPTIONS-shared-check.cmake
new file mode 100644
index 000000000..a686de945
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-shared-check.cmake
@@ -0,0 +1,7 @@
+
+if (NOT actual_stdout MATCHES "BADFLAG_RELEASE")
+ set (RunCMake_TEST_FAILED "Not found expected 'BADFLAG_RELEASE'.")
+endif()
+if (actual_stdout MATCHES "SHELL:")
+ string (APPEND RunCMake_TEST_FAILED "\nFound unexpected prefix 'SHELL:'.")
+endif()
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-shared-result.txt b/Tests/RunCMake/target_link_options/LINK_OPTIONS-shared-result.txt
new file mode 100644
index 000000000..8d98f9deb
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-shared-result.txt
@@ -0,0 +1 @@
+.*
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-static-check.cmake b/Tests/RunCMake/target_link_options/LINK_OPTIONS-static-check.cmake
new file mode 100644
index 000000000..b68e45175
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-static-check.cmake
@@ -0,0 +1,7 @@
+
+if (actual_stdout MATCHES "BADFLAG_RELEASE")
+ set (RunCMake_TEST_FAILED "Found 'BADFLAG_RELEASE' which was not expected.")
+endif()
+if (actual_stdout MATCHES "SHELL:")
+ string (APPEND RunCMake_TEST_FAILED "\nFound unexpected prefix 'SHELL:'.")
+endif()
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS-static-result.txt b/Tests/RunCMake/target_link_options/LINK_OPTIONS-static-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS-static-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/target_link_options/LINK_OPTIONS.cmake b/Tests/RunCMake/target_link_options/LINK_OPTIONS.cmake
new file mode 100644
index 000000000..bb048412e
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LINK_OPTIONS.cmake
@@ -0,0 +1,55 @@
+
+enable_language(C)
+
+set(obj "${CMAKE_C_OUTPUT_EXTENSION}")
+if(BORLAND)
+ set(pre -)
+endif()
+
+# basic configuration
+add_library(LinkOptions SHARED LinkOptionsLib.c)
+target_link_options(LinkOptions
+ PRIVATE ${pre}BADFLAG_PRIVATE${obj}
+ INTERFACE ${pre}BADFLAG_INTERFACE${obj})
+
+
+# INTERFACE_LINK_OPTIONS
+add_library(LinkOptions_producer SHARED LinkOptionsLib.c)
+target_link_options(LinkOptions_producer
+ INTERFACE ${pre}BADFLAG_INTERFACE${obj})
+
+add_executable(LinkOptions_consumer LinkOptionsExe.c)
+target_link_libraries(LinkOptions_consumer PRIVATE LinkOptions_producer)
+
+
+# static library with INTERFACE_LINK_OPTIONS
+add_library(LinkOptions_producer_static STATIC LinkOptionsLib.c)
+target_link_options(LinkOptions_producer_static
+ INTERFACE ${pre}BADFLAG_INTERFACE${obj})
+
+add_executable(LinkOptions_consumer_static LinkOptionsExe.c)
+target_link_libraries(LinkOptions_consumer_static PRIVATE LinkOptions_producer_static)
+
+
+# static library with generator expression
+add_library(LinkOptions_static STATIC LinkOptionsLib.c)
+target_link_options(LinkOptions_static PRIVATE $<$<CONFIG:Release>:${pre}BADFLAG_RELEASE${obj}>
+ "SHELL:" # produces no options
+ )
+
+
+# shared library with generator expression
+add_library(LinkOptions_shared SHARED LinkOptionsLib.c)
+target_link_options(LinkOptions_shared PRIVATE $<$<CONFIG:Release>:${pre}BADFLAG_RELEASE${obj}>
+ "SHELL:" # produces no options
+ )
+
+
+# module library with generator expression
+add_library(LinkOptions_mod MODULE LinkOptionsLib.c)
+target_link_options(LinkOptions_mod PRIVATE $<$<CONFIG:Release>:${pre}BADFLAG_RELEASE${obj}>)
+
+
+# executable with generator expression
+add_executable(LinkOptions_exe LinkOptionsExe.c)
+target_link_options(LinkOptions_exe PRIVATE $<$<CONFIG:Release>:${pre}BADFLAG_RELEASE${obj}>)
diff --git a/Tests/RunCMake/target_link_options/LinkOptionsExe.c b/Tests/RunCMake/target_link_options/LinkOptionsExe.c
new file mode 100644
index 000000000..8488f4e58
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LinkOptionsExe.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/target_link_options/LinkOptionsLib.c b/Tests/RunCMake/target_link_options/LinkOptionsLib.c
new file mode 100644
index 000000000..9bbd24cd8
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/LinkOptionsLib.c
@@ -0,0 +1,7 @@
+#if defined(_WIN32)
+__declspec(dllexport)
+#endif
+ int flags_lib(void)
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/target_link_options/RunCMakeTest.cmake b/Tests/RunCMake/target_link_options/RunCMakeTest.cmake
new file mode 100644
index 000000000..1d9ef8b4f
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/RunCMakeTest.cmake
@@ -0,0 +1,43 @@
+
+include(RunCMake)
+
+macro(run_cmake_target test subtest target)
+ set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${test}-build)
+ set(RunCMake_TEST_NO_CLEAN 1)
+ run_cmake_command(${test}-${subtest} ${CMAKE_COMMAND} --build . --target ${target} ${ARGN})
+
+ unset(RunCMake_TEST_BINARY_DIR)
+ unset(RunCMake_TEST_NO_CLEAN)
+endmacro()
+
+if (NOT CMAKE_C_COMPILER_ID STREQUAL "Intel")
+ # Intel compiler does not reject bad flags or objects!
+ set(RunCMake_TEST_OUTPUT_MERGE TRUE)
+ if (NOT RunCMake_GENERATOR_IS_MULTI_CONFIG)
+ set(RunCMake_TEST_OPTIONS -DCMAKE_BUILD_TYPE=Release)
+ endif()
+
+ run_cmake(LINK_OPTIONS)
+
+ run_cmake_target(LINK_OPTIONS basic LinkOptions)
+ run_cmake_target(LINK_OPTIONS interface LinkOptions_consumer)
+ run_cmake_target(LINK_OPTIONS interface-static LinkOptions_consumer_static)
+ run_cmake_target(LINK_OPTIONS static LinkOptions_static --config Release)
+ run_cmake_target(LINK_OPTIONS shared LinkOptions_shared --config Release)
+ run_cmake_target(LINK_OPTIONS mod LinkOptions_mod --config Release)
+ run_cmake_target(LINK_OPTIONS exe LinkOptions_exe --config Release)
+
+ unset(RunCMake_TEST_OPTIONS)
+ unset(RunCMake_TEST_OUTPUT_MERGE)
+endif()
+
+run_cmake(bad_SHELL_usage)
+
+if(RunCMake_GENERATOR MATCHES "(Ninja|Makefile)")
+ run_cmake(LINKER_expansion)
+
+ run_cmake_target(LINKER_expansion LINKER linker)
+ run_cmake_target(LINKER_expansion LINKER_SHELL linker_shell)
+endif()
+
+run_cmake(empty_keyword_args)
diff --git a/Tests/RunCMake/target_link_options/bad_SHELL_usage-result.txt b/Tests/RunCMake/target_link_options/bad_SHELL_usage-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/bad_SHELL_usage-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/target_link_options/bad_SHELL_usage-stderr.txt b/Tests/RunCMake/target_link_options/bad_SHELL_usage-stderr.txt
new file mode 100644
index 000000000..bffd80a00
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/bad_SHELL_usage-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at bad_SHELL_usage.cmake:4 \(add_library\):
+ 'SHELL:' prefix is not supported as part of 'LINKER:' arguments.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:5 \(include\)
diff --git a/Tests/RunCMake/target_link_options/bad_SHELL_usage.cmake b/Tests/RunCMake/target_link_options/bad_SHELL_usage.cmake
new file mode 100644
index 000000000..b0adf1936
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/bad_SHELL_usage.cmake
@@ -0,0 +1,5 @@
+
+enable_language(C)
+
+add_library(example SHARED LinkOptionsLib.c)
+target_link_options(example PRIVATE "LINKER:-foo,SHELL:-bar")
diff --git a/Tests/RunCMake/target_link_options/dump.c b/Tests/RunCMake/target_link_options/dump.c
new file mode 100644
index 000000000..8baa313fd
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/dump.c
@@ -0,0 +1,13 @@
+
+#include "stdio.h"
+
+int main(int argc, char* argv[])
+{
+ int i;
+
+ for (i = 1; i < argc; i++)
+ printf("%s ", argv[i]);
+ printf("\n");
+
+ return 0;
+}
diff --git a/Tests/RunCMake/target_link_options/empty_keyword_args.cmake b/Tests/RunCMake/target_link_options/empty_keyword_args.cmake
new file mode 100644
index 000000000..a1a297ef4
--- /dev/null
+++ b/Tests/RunCMake/target_link_options/empty_keyword_args.cmake
@@ -0,0 +1,5 @@
+add_library(iface INTERFACE)
+target_link_options(iface PUBLIC PRIVATE INTERFACE)
+# Cannot be called with non-compilable targets.
+#add_library(imported UNKNOWN IMPORTED)
+#target_link_options(imported PUBLIC PRIVATE INTERFACE)
diff --git a/Tests/RunCMake/target_sources/CMakeLists.txt b/Tests/RunCMake/target_sources/CMakeLists.txt
new file mode 100644
index 000000000..14ef56e8e
--- /dev/null
+++ b/Tests/RunCMake/target_sources/CMakeLists.txt
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.11)
+
+project(${RunCMake_TEST} LANGUAGES NONE)
+
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/target_sources/RunCMakeTest.cmake b/Tests/RunCMake/target_sources/RunCMakeTest.cmake
new file mode 100644
index 000000000..b67c5983e
--- /dev/null
+++ b/Tests/RunCMake/target_sources/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(empty_keyword_args)
diff --git a/Tests/RunCMake/target_sources/empty_keyword_args.cmake b/Tests/RunCMake/target_sources/empty_keyword_args.cmake
new file mode 100644
index 000000000..5cee451fd
--- /dev/null
+++ b/Tests/RunCMake/target_sources/empty_keyword_args.cmake
@@ -0,0 +1,5 @@
+add_library(iface INTERFACE)
+target_sources(iface PUBLIC PRIVATE INTERFACE)
+# Cannot be called with non-compilable targets.
+#add_library(imported UNKNOWN IMPORTED)
+#target_sources(imported PUBLIC PRIVATE INTERFACE)
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..72056aee3
--- /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(NOT RunCMake_GENERATOR_IS_MULTI_CONFIG)
+ 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/try_compile/LinkOptions.cmake b/Tests/RunCMake/try_compile/LinkOptions.cmake
new file mode 100644
index 000000000..7fae35ca9
--- /dev/null
+++ b/Tests/RunCMake/try_compile/LinkOptions.cmake
@@ -0,0 +1,40 @@
+
+enable_language(C)
+
+cmake_policy(SET CMP0054 NEW)
+
+set (lib_name "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}lib${CMAKE_STATIC_LIBRARY_SUFFIX}")
+if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
+ if (RunCMake_C_COMPILER_ID STREQUAL "MSVC"
+ OR ("x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC" AND
+ NOT CMAKE_C_COMPILER_ID STREQUAL "Clang" OR "x${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "xMSVC"))
+ if (CMAKE_SIZEOF_VOID_P EQUAL 4)
+ set (undef_flag /INCLUDE:_func)
+ else()
+ set (undef_flag /INCLUDE:func)
+ endif()
+ else()
+ if (CMAKE_SIZEOF_VOID_P EQUAL 4)
+ set (undef_flag -u _func)
+ else()
+ set (undef_flag -u func)
+ endif()
+ endif()
+elseif (CMAKE_SYSTEM_NAME STREQUAL "Darwin")
+ set (undef_flag -u _func)
+else()
+ set (undef_flag -u func)
+endif()
+
+set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/lib.c
+ COPY_FILE "${lib_name}")
+
+set(CMAKE_TRY_COMPILE_TARGET_TYPE EXECUTABLE)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/main.c
+ OUTPUT_VARIABLE out
+ LINK_OPTIONS ${undef_flag} "${lib_name}")
+
+if(NOT result)
+ message(FATAL_ERROR "try_compile(... LINK_OPTIONS ...) failed:\n${out}")
+endif()
diff --git a/Tests/RunCMake/try_compile/lib.c b/Tests/RunCMake/try_compile/lib.c
new file mode 100644
index 000000000..b00c576c7
--- /dev/null
+++ b/Tests/RunCMake/try_compile/lib.c
@@ -0,0 +1,4 @@
+
+void func()
+{
+}
diff --git a/Tests/RunCMake/try_compile/main.c b/Tests/RunCMake/try_compile/main.c
new file mode 100644
index 000000000..2128ead9d
--- /dev/null
+++ b/Tests/RunCMake/try_compile/main.c
@@ -0,0 +1,8 @@
+extern void func();
+
+int main(void)
+{
+ func();
+
+ return 0;
+}
diff --git a/Tests/RunCMake/try_run/LinkOptions.cmake b/Tests/RunCMake/try_run/LinkOptions.cmake
new file mode 100644
index 000000000..b9a87f3ca
--- /dev/null
+++ b/Tests/RunCMake/try_run/LinkOptions.cmake
@@ -0,0 +1,44 @@
+
+enable_language(C)
+
+cmake_policy(SET CMP0054 NEW)
+
+set (lib_name "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}lib${CMAKE_STATIC_LIBRARY_SUFFIX}")
+if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
+ if (RunCMake_C_COMPILER_ID STREQUAL "MSVC"
+ OR ("x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC" AND
+ NOT CMAKE_C_COMPILER_ID STREQUAL "Clang" OR "x${CMAKE_C_COMPILER_FRONTEND_VARIANT}" STREQUAL "xMSVC"))
+ if (CMAKE_SIZEOF_VOID_P EQUAL 4)
+ set (undef_flag /INCLUDE:_func)
+ else()
+ set (undef_flag /INCLUDE:func)
+ endif()
+ else()
+ if (CMAKE_SIZEOF_VOID_P EQUAL 4)
+ set (undef_flag -u _func)
+ else()
+ set (undef_flag -u func)
+ endif()
+ endif()
+elseif (CMAKE_SYSTEM_NAME STREQUAL "Darwin")
+ set (undef_flag -u _func)
+else()
+ set (undef_flag -u func)
+endif()
+
+set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
+try_compile(result ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/lib.c
+ COPY_FILE "${lib_name}")
+
+set(CMAKE_TRY_COMPILE_TARGET_TYPE EXECUTABLE)
+try_run(run_result compile_result ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/main.c
+ COMPILE_OUTPUT_VARIABLE compile_out
+ RUN_OUTPUT_VARIABLE run_out
+ LINK_OPTIONS ${undef_flag} "${lib_name}")
+
+if(NOT compile_result)
+ message(FATAL_ERROR "try_run(... LINK_OPTIONS ...) compilation failed:\n${compile_out}")
+endif()
+if(run_result STREQUAL "FAILED_TO_RUN")
+ message(FATAL_ERROR "try_run(... LINK_OPTIONS ...) execution failed:\n${run_out}")
+endif()
diff --git a/Tests/RunCMake/try_run/lib.c b/Tests/RunCMake/try_run/lib.c
new file mode 100644
index 000000000..b00c576c7
--- /dev/null
+++ b/Tests/RunCMake/try_run/lib.c
@@ -0,0 +1,4 @@
+
+void func()
+{
+}
diff --git a/Tests/RunCMake/try_run/main.c b/Tests/RunCMake/try_run/main.c
new file mode 100644
index 000000000..2128ead9d
--- /dev/null
+++ b/Tests/RunCMake/try_run/main.c
@@ -0,0 +1,8 @@
+extern void func();
+
+int main(void)
+{
+ func();
+
+ 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/RaiseInParentScope-stderr.txt b/Tests/RunCMake/variable_watch/RaiseInParentScope-stderr.txt
new file mode 100644
index 000000000..51db19cc3
--- /dev/null
+++ b/Tests/RunCMake/variable_watch/RaiseInParentScope-stderr.txt
@@ -0,0 +1,2 @@
+var MODIFIED_ACCESS a
+var MODIFIED_ACCESS b
diff --git a/Tests/RunCMake/variable_watch/RaiseInParentScope.cmake b/Tests/RunCMake/variable_watch/RaiseInParentScope.cmake
new file mode 100644
index 000000000..207798e4b
--- /dev/null
+++ b/Tests/RunCMake/variable_watch/RaiseInParentScope.cmake
@@ -0,0 +1,15 @@
+
+function(watch variable access value)
+ message("${variable} ${access} ${value}")
+endfunction ()
+
+# --------------
+
+variable_watch(var watch)
+set(var "a")
+
+function(f)
+ set(var "b" PARENT_SCOPE)
+endfunction(f)
+
+f()
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/SourceFileIncludeDirProperty/CMakeLists.txt b/Tests/SourceFileIncludeDirProperty/CMakeLists.txt
new file mode 100644
index 000000000..786d5b683
--- /dev/null
+++ b/Tests/SourceFileIncludeDirProperty/CMakeLists.txt
@@ -0,0 +1,15 @@
+cmake_minimum_required(VERSION 3.0)
+
+project(SourceFileIncludeDirProperty C)
+
+#
+# Check that source level include directory take
+# precedence over target one
+
+add_executable(SourceFileIncludeDirProperty main.c)
+
+set_property (TARGET SourceFileIncludeDirProperty
+ PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/target")
+
+set_property (SOURCE main.c
+ PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/source")
diff --git a/Tests/SourceFileIncludeDirProperty/main.c b/Tests/SourceFileIncludeDirProperty/main.c
new file mode 100644
index 000000000..36144ca06
--- /dev/null
+++ b/Tests/SourceFileIncludeDirProperty/main.c
@@ -0,0 +1,7 @@
+
+#include "header.h"
+
+int main()
+{
+ return 0;
+}
diff --git a/Tests/SourceFileIncludeDirProperty/source/header.h b/Tests/SourceFileIncludeDirProperty/source/header.h
new file mode 100644
index 000000000..0c6f24128
--- /dev/null
+++ b/Tests/SourceFileIncludeDirProperty/source/header.h
@@ -0,0 +1,2 @@
+
+/* used header file */
diff --git a/Tests/SourceFileIncludeDirProperty/target/header.h b/Tests/SourceFileIncludeDirProperty/target/header.h
new file mode 100644
index 000000000..71c1521d5
--- /dev/null
+++ b/Tests/SourceFileIncludeDirProperty/target/header.h
@@ -0,0 +1,2 @@
+
+#error "wrong header file"
diff --git a/Tests/SourceGroups/tree_empty_prefix_bar.c b/Tests/SourceGroups/tree_empty_prefix_bar.c
new file mode 100644
index 000000000..d974c6e8c
--- /dev/null
+++ b/Tests/SourceGroups/tree_empty_prefix_bar.c
@@ -0,0 +1,4 @@
+int tree_empty_prefix_bar(void)
+{
+ return 66;
+}
diff --git a/Tests/SourceGroups/tree_empty_prefix_foo.c b/Tests/SourceGroups/tree_empty_prefix_foo.c
new file mode 100644
index 000000000..277cbd4db
--- /dev/null
+++ b/Tests/SourceGroups/tree_empty_prefix_foo.c
@@ -0,0 +1,4 @@
+int tree_empty_prefix_foo(void)
+{
+ return 6;
+}
diff --git a/Tests/TryCompile/check_a_b.c b/Tests/TryCompile/check_a_b.c
new file mode 100644
index 000000000..05fba0f82
--- /dev/null
+++ b/Tests/TryCompile/check_a_b.c
@@ -0,0 +1,10 @@
+#ifndef DEF_A
+# error DEF_A not defined
+#endif
+#ifndef DEF_B
+# error DEF_B not defined
+#endif
+int main()
+{
+ return 0;
+}
diff --git a/Tests/Tutorial/Complete/CMakeLists.txt b/Tests/Tutorial/Complete/CMakeLists.txt
new file mode 100644
index 000000000..9658e6536
--- /dev/null
+++ b/Tests/Tutorial/Complete/CMakeLists.txt
@@ -0,0 +1,116 @@
+cmake_minimum_required(VERSION 3.3)
+project(Tutorial)
+
+# control where the static and shared libraries are built so that on windows
+# we don't need to tinker with the path to run the executable
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED True)
+
+option(BUILD_SHARED_LIBS "Build using shared libraries" ON)
+
+# the version number.
+set(Tutorial_VERSION_MAJOR 1)
+set(Tutorial_VERSION_MINOR 0)
+
+if(APPLE)
+ set(CMAKE_INSTALL_RPATH "@executable_path/../lib")
+elseif(UNIX)
+ set(CMAKE_INSTALL_RPATH "$ORIGIN/../lib")
+endif()
+
+# configure a header file to pass the version number only
+configure_file(
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ )
+
+# add the MathFunctions library
+add_subdirectory(MathFunctions)
+
+# add the executable
+add_executable(Tutorial tutorial.cxx)
+target_link_libraries(Tutorial MathFunctions)
+
+# add the binary tree to the search path for include files
+# so that we will find TutorialConfig.h
+target_include_directories(Tutorial PUBLIC
+ "${PROJECT_BINARY_DIR}"
+ )
+
+# add the install targets
+install(TARGETS Tutorial DESTINATION bin)
+install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ DESTINATION include
+ )
+
+# enable testing
+enable_testing()
+
+# does the application run
+add_test(NAME Runs COMMAND Tutorial 25)
+
+# does the usage message work?
+add_test(NAME Usage COMMAND Tutorial)
+set_tests_properties(Usage
+ PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
+ )
+
+# define a function to simplify adding tests
+function(do_test target arg result)
+ add_test(NAME Comp${arg} COMMAND ${target} ${arg})
+ set_tests_properties(Comp${arg}
+ PROPERTIES PASS_REGULAR_EXPRESSION ${result}
+ )
+endfunction(do_test)
+
+# do a bunch of result based tests
+do_test(Tutorial 4 "4 is 2")
+do_test(Tutorial 9 "9 is 3")
+do_test(Tutorial 5 "5 is 2.236")
+do_test(Tutorial 7 "7 is 2.645")
+do_test(Tutorial 25 "25 is 5")
+do_test(Tutorial -25 "-25 is [-nan|nan|0]")
+do_test(Tutorial 0.0001 "0.0001 is 0.01")
+
+include(InstallRequiredSystemLibraries)
+set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
+set(CPACK_PACKAGE_VERSION_MAJOR "${Tutorial_VERSION_MAJOR}")
+set(CPACK_PACKAGE_VERSION_MINOR "${Tutorial_VERSION_MINOR}")
+include(CPack)
+
+# install the configuration targets
+install(EXPORT MathFunctionsTargets
+ FILE MathFunctionsTargets.cmake
+ DESTINATION lib/cmake/MathFunctions
+)
+
+include(CMakePackageConfigHelpers)
+# generate the config file that is includes the exports
+configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in
+ "${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfig.cmake"
+ INSTALL_DESTINATION "lib/cmake/example"
+ NO_SET_AND_CHECK_MACRO
+ NO_CHECK_REQUIRED_COMPONENTS_MACRO
+ )
+# generate the version file for the config file
+write_basic_package_version_file(
+ "${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfigVersion.cmake"
+ VERSION "${Tutorial_VERSION_MAJOR}.${Tutorial_VERSION_MINOR}"
+ COMPATIBILITY AnyNewerVersion
+)
+
+# install the configuration file
+install(FILES
+ ${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfig.cmake
+ DESTINATION lib/cmake/MathFunctions
+ )
+
+# generate the export targets for the build tree
+# needs to be after the install(TARGETS ) command
+export(EXPORT MathFunctionsTargets
+ FILE "${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsTargets.cmake"
+)
diff --git a/Tests/Tutorial/Complete/Config.cmake.in b/Tests/Tutorial/Complete/Config.cmake.in
new file mode 100644
index 000000000..17cbabd99
--- /dev/null
+++ b/Tests/Tutorial/Complete/Config.cmake.in
@@ -0,0 +1,4 @@
+
+@PACKAGE_INIT@
+
+include ( "${CMAKE_CURRENT_LIST_DIR}/MathFunctionsTargets.cmake" )
diff --git a/Tests/Tutorial/Complete/License.txt b/Tests/Tutorial/Complete/License.txt
new file mode 100644
index 000000000..c62d00b9e
--- /dev/null
+++ b/Tests/Tutorial/Complete/License.txt
@@ -0,0 +1,2 @@
+This is the open source License.txt file introduced in
+CMake/Tutorial/Step7...
diff --git a/Tests/Tutorial/Complete/MathFunctions/CMakeLists.txt b/Tests/Tutorial/Complete/MathFunctions/CMakeLists.txt
new file mode 100644
index 000000000..161ad6449
--- /dev/null
+++ b/Tests/Tutorial/Complete/MathFunctions/CMakeLists.txt
@@ -0,0 +1,68 @@
+
+# add the library that runs
+add_library(MathFunctions MathFunctions.cxx)
+
+# state that anybody linking to us needs to include the current source dir
+# to find MathFunctions.h, while we don't.
+target_include_directories(MathFunctions
+ INTERFACE
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
+ $<INSTALL_INTERFACE:include>
+ )
+
+# should we use our own math functions
+option(USE_MYMATH "Use tutorial provided math implementation" ON)
+if(USE_MYMATH)
+
+ # does this system provide the log and exp functions?
+ include(CheckSymbolExists)
+ set(CMAKE_REQUIRED_LIBRARIES "m")
+ check_symbol_exists(log "math.h" HAVE_LOG)
+ check_symbol_exists(exp "math.h" HAVE_EXP)
+
+ # first we add the executable that generates the table
+ add_executable(MakeTable MakeTable.cxx)
+
+ # add the command to generate the source code
+ add_custom_command(
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ DEPENDS MakeTable
+ )
+
+ # library that just does sqrt
+ add_library(SqrtLibrary STATIC
+ mysqrt.cxx
+ ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ )
+
+ # state that we depend on our binary dir to find Table.h
+ target_include_directories(SqrtLibrary PRIVATE
+ ${CMAKE_CURRENT_BINARY_DIR}
+ )
+
+ set_target_properties(SqrtLibrary PROPERTIES
+ POSITION_INDEPENDENT_CODE ${BUILD_SHARED_LIBS}
+ )
+
+ target_compile_definitions(SqrtLibrary PRIVATE
+ "$<$<BOOL:${HAVE_LOG}>:HAVE_LOG>"
+ "$<$<BOOL:${HAVE_EXP}>:HAVE_EXP>"
+ )
+ target_link_libraries(MathFunctions PRIVATE SqrtLibrary)
+endif()
+
+target_compile_definitions(MathFunctions PRIVATE "$<$<BOOL:${USE_MYMATH}>:USE_MYMATH>")
+
+# define the symbol stating we are using the declspec(dllexport) when
+# building on windows
+target_compile_definitions(MathFunctions PRIVATE "EXPORTING_MYMATH")
+
+# setup the version numbering
+set_property(TARGET MathFunctions PROPERTY VERSION "1.0.0")
+set_property(TARGET MathFunctions PROPERTY SOVERSION "1")
+
+install(TARGETS MathFunctions
+ DESTINATION lib
+ EXPORT MathFunctionsTargets)
+install(FILES MathFunctions.h DESTINATION include)
diff --git a/Tests/Tutorial/Complete/MathFunctions/MakeTable.cxx b/Tests/Tutorial/Complete/MathFunctions/MakeTable.cxx
new file mode 100644
index 000000000..ee585568c
--- /dev/null
+++ b/Tests/Tutorial/Complete/MathFunctions/MakeTable.cxx
@@ -0,0 +1,25 @@
+// A simple program that builds a sqrt table
+#include <cmath>
+#include <fstream>
+#include <iostream>
+
+int main(int argc, char* argv[])
+{
+ // make sure we have enough arguments
+ if (argc < 2) {
+ return 1;
+ }
+
+ std::ofstream fout(argv[1], std::ios_base::out);
+ const bool fileOpen = fout.is_open();
+ if (fileOpen) {
+ fout << "double sqrtTable[] = {" << std::endl;
+ for (int i = 0; i < 10; ++i) {
+ fout << sqrt(static_cast<double>(i)) << "," << std::endl;
+ }
+ // close the table with a zero
+ fout << "0};" << std::endl;
+ fout.close();
+ }
+ return fileOpen ? 0 : 1; // return 0 if wrote the file
+}
diff --git a/Tests/Tutorial/Complete/MathFunctions/MathFunctions.cxx b/Tests/Tutorial/Complete/MathFunctions/MathFunctions.cxx
new file mode 100644
index 000000000..5351184be
--- /dev/null
+++ b/Tests/Tutorial/Complete/MathFunctions/MathFunctions.cxx
@@ -0,0 +1,18 @@
+
+#include "MathFunctions.h"
+#include <cmath>
+
+#ifdef USE_MYMATH
+# include "mysqrt.h"
+#endif
+
+namespace mathfunctions {
+double sqrt(double x)
+{
+#ifdef USE_MYMATH
+ return detail::mysqrt(x);
+#else
+ return std::sqrt(x);
+#endif
+}
+}
diff --git a/Tests/Tutorial/Complete/MathFunctions/MathFunctions.h b/Tests/Tutorial/Complete/MathFunctions/MathFunctions.h
new file mode 100644
index 000000000..3fb547b4a
--- /dev/null
+++ b/Tests/Tutorial/Complete/MathFunctions/MathFunctions.h
@@ -0,0 +1,14 @@
+
+#if defined(_WIN32)
+# if defined(EXPORTING_MYMATH)
+# define DECLSPEC __declspec(dllexport)
+# else
+# define DECLSPEC __declspec(dllimport)
+# endif
+#else // non windows
+# define DECLSPEC
+#endif
+
+namespace mathfunctions {
+double DECLSPEC sqrt(double x);
+}
diff --git a/Tests/Tutorial/Complete/MathFunctions/mysqrt.cxx b/Tests/Tutorial/Complete/MathFunctions/mysqrt.cxx
new file mode 100644
index 000000000..96d94212d
--- /dev/null
+++ b/Tests/Tutorial/Complete/MathFunctions/mysqrt.cxx
@@ -0,0 +1,45 @@
+#include "MathFunctions.h"
+#include <iostream>
+
+// include the generated table
+#include "Table.h"
+
+#include <cmath>
+
+namespace mathfunctions {
+namespace detail {
+// a hack square root calculation using simple operations
+double mysqrt(double x)
+{
+ if (x <= 0) {
+ return 0;
+ }
+
+ // if we have both log and exp then use them
+#if defined(HAVE_LOG) && defined(HAVE_EXP)
+ double result = exp(log(x) * 0.5);
+ std::cout << "Computing sqrt of " << x << " to be " << result << " using log"
+ << std::endl;
+#else
+ // use the table to help find an initial value
+ double result = x;
+ if (x >= 1 && x < 10) {
+ result = sqrtTable[static_cast<int>(x)];
+ }
+
+ // if we have both log and exp then use them
+
+ // do ten iterations
+ for (int i = 0; i < 10; ++i) {
+ if (result <= 0) {
+ result = 0.1;
+ }
+ double delta = x - (result * result);
+ result = result + 0.5 * delta / result;
+ std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
+ }
+#endif
+ return result;
+}
+}
+}
diff --git a/Tests/Tutorial/Complete/MathFunctions/mysqrt.h b/Tests/Tutorial/Complete/MathFunctions/mysqrt.h
new file mode 100644
index 000000000..e1c42ef0c
--- /dev/null
+++ b/Tests/Tutorial/Complete/MathFunctions/mysqrt.h
@@ -0,0 +1,6 @@
+
+namespace mathfunctions {
+namespace detail {
+double mysqrt(double x);
+}
+}
diff --git a/Tests/Tutorial/Complete/TutorialConfig.h.in b/Tests/Tutorial/Complete/TutorialConfig.h.in
new file mode 100644
index 000000000..8cd2fc9c6
--- /dev/null
+++ b/Tests/Tutorial/Complete/TutorialConfig.h.in
@@ -0,0 +1,3 @@
+// the configured version number
+#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
+#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
diff --git a/Tests/Tutorial/Complete/tutorial.cxx b/Tests/Tutorial/Complete/tutorial.cxx
new file mode 100644
index 000000000..443d19555
--- /dev/null
+++ b/Tests/Tutorial/Complete/tutorial.cxx
@@ -0,0 +1,25 @@
+// A simple program that computes the square root of a number
+#include <iostream>
+#include <sstream>
+#include <string>
+
+#include "MathFunctions.h"
+#include "TutorialConfig.h"
+
+int main(int argc, char* argv[])
+{
+ if (argc < 2) {
+ std::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."
+ << Tutorial_VERSION_MAJOR << std::endl;
+ std::cout << "Usage: " << argv[0] << " number" << std::endl;
+ return 1;
+ }
+
+ double inputValue = std::stod(argv[1]);
+
+ const double outputValue = mathfunctions::sqrt(inputValue);
+
+ std::cout << "The square root of " << inputValue << " is " << outputValue
+ << std::endl;
+ return 0;
+}
diff --git a/Tests/Tutorial/Consumer/CMakeLists.txt b/Tests/Tutorial/Consumer/CMakeLists.txt
new file mode 100644
index 000000000..4033b4da8
--- /dev/null
+++ b/Tests/Tutorial/Consumer/CMakeLists.txt
@@ -0,0 +1,51 @@
+cmake_minimum_required(VERSION 3.3)
+
+if(NOT DEFINED CMAKE_CXX_STANDARD)
+ set(CMAKE_CXX_STANDARD 11)
+ set(CMAKE_CXX_STANDARD_REQUIRED True)
+endif()
+
+
+function(find_external_dependency name)
+ set(${name}_ROOT "" CACHE PATH "Root directory to find ${name}")
+ mark_as_advanced(${name}_DIR)
+ find_package(${name} PATHS ${${name}_ROOT} REQUIRED)
+endfunction()
+
+
+project(Consumer)
+
+find_external_dependency(MathFunctions)
+
+add_library(consumer consumer.cxx)
+target_link_libraries(consumer PUBLIC MathFunctions)
+
+# install the consumer library
+install(TARGETS consumer DESTINATION bin EXPORT ConsumerTargets)
+
+# install the configuration targets
+install(EXPORT ConsumerTargets
+ FILE ConsumerTargets.cmake
+ DESTINATION lib/cmake/Consumer
+)
+
+include(CMakePackageConfigHelpers)
+# generate the config file that is includes the exports
+configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in
+ "${CMAKE_CURRENT_BINARY_DIR}/ConsumerConfig.cmake"
+ INSTALL_DESTINATION "lib/cmake/example"
+ NO_SET_AND_CHECK_MACRO
+ NO_CHECK_REQUIRED_COMPONENTS_MACRO
+ )
+
+# install the configuration file
+install(FILES
+ ${CMAKE_CURRENT_BINARY_DIR}/ConsumerConfig.cmake
+ DESTINATION lib/cmake/Consumer
+ )
+
+# generate the export targets for the build tree
+# needs to be after the install(TARGETS ) command
+export(EXPORT ConsumerTargets
+ FILE "${CMAKE_CURRENT_BINARY_DIR}/ConsumerTargets.cmake"
+)
diff --git a/Tests/Tutorial/Consumer/Config.cmake.in b/Tests/Tutorial/Consumer/Config.cmake.in
new file mode 100644
index 000000000..0b3f1e4ef
--- /dev/null
+++ b/Tests/Tutorial/Consumer/Config.cmake.in
@@ -0,0 +1,14 @@
+
+@PACKAGE_INIT@
+
+include(CMakeFindDependencyMacro)
+
+function(find_external_dependency name)
+ set(${name}_ROOT "" CACHE PATH "Root directory to find ${name}")
+ mark_as_advanced(${name}_DIR)
+ find_dependency(${name} PATHS ${${name}_ROOT} REQUIRED)
+endfunction()
+
+find_external_dependency(MathFunctions)
+
+include ( "${CMAKE_CURRENT_LIST_DIR}/ConsumerTargets.cmake" )
diff --git a/Tests/Tutorial/Consumer/consumer.cxx b/Tests/Tutorial/Consumer/consumer.cxx
new file mode 100644
index 000000000..ae7877b5a
--- /dev/null
+++ b/Tests/Tutorial/Consumer/consumer.cxx
@@ -0,0 +1,11 @@
+// A simple function that computes the square root of a number
+#include <iostream>
+#include <sstream>
+#include <string>
+
+#include "MathFunctions.h"
+
+double string_square_root(std::string const& value)
+{
+ return mathfunctions::sqrt(std::stod(value));
+}
diff --git a/Tests/Tutorial/Consumer/directions.txt b/Tests/Tutorial/Consumer/directions.txt
new file mode 100644
index 000000000..6a70aab5e
--- /dev/null
+++ b/Tests/Tutorial/Consumer/directions.txt
@@ -0,0 +1,6 @@
+# Import a CMake Project#
+
+This examples shows how a project can find other CMake packages that
+generated Config.cmake files.
+
+It also shows how to state a projects external dependencies when generating a Config.cmake.
diff --git a/Tests/Tutorial/MultiPackage/CMakeLists.txt b/Tests/Tutorial/MultiPackage/CMakeLists.txt
new file mode 100644
index 000000000..067e80729
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/CMakeLists.txt
@@ -0,0 +1,109 @@
+cmake_minimum_required(VERSION 3.3)
+project(Tutorial)
+
+# control how we mark up Debug libraries compared to Release libraries
+set(CMAKE_DEBUG_POSTFIX "-d")
+
+# control where the static and shared libraries are built so that on windows
+# we don't need to tinker with the path to run the executable
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+
+option(BUILD_SHARED_LIBS "Build using shared libraries" ON)
+
+# the version number.
+set(Tutorial_VERSION_MAJOR 1)
+set(Tutorial_VERSION_MINOR 0)
+
+# configure a header file to pass the version number only
+configure_file(
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ )
+
+# add the MathFunctions library
+add_subdirectory(MathFunctions)
+
+# add the executable
+add_executable(Tutorial tutorial.cxx)
+target_link_libraries(Tutorial MathFunctions)
+
+# add the binary tree to the search path for include files
+# so that we will find TutorialConfig.h
+target_include_directories(Tutorial PUBLIC
+ "${PROJECT_BINARY_DIR}"
+ )
+
+# add the install targets
+install(TARGETS Tutorial DESTINATION bin)
+install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ DESTINATION include
+ )
+
+# enable testing
+enable_testing()
+
+# does the application run
+add_test(NAME Runs COMMAND Tutorial 25)
+
+# does the usage message work?
+add_test(NAME Usage COMMAND Tutorial)
+set_tests_properties(Usage
+ PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
+ )
+
+# define a function to simplify adding tests
+function(do_test target arg result)
+ add_test(NAME Comp${arg} COMMAND ${target} ${arg})
+ set_tests_properties(Comp${arg}
+ PROPERTIES PASS_REGULAR_EXPRESSION ${result}
+ )
+endfunction(do_test)
+
+# do a bunch of result based tests
+do_test(Tutorial 4 "4 is 2")
+do_test(Tutorial 9 "9 is 3")
+do_test(Tutorial 5 "5 is 2.236")
+do_test(Tutorial 7 "7 is 2.645")
+do_test(Tutorial 25 "25 is 5")
+do_test(Tutorial -25 "-25 is [-nan|nan|0]")
+do_test(Tutorial 0.0001 "0.0001 is 0.01")
+
+include(InstallRequiredSystemLibraries)
+set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
+set(CPACK_PACKAGE_VERSION_MAJOR "${Tutorial_VERSION_MAJOR}")
+set(CPACK_PACKAGE_VERSION_MINOR "${Tutorial_VERSION_MINOR}")
+include(CPack)
+
+# install the configuration targets
+install(EXPORT MathFunctionsTargets
+ FILE MathFunctionsTargets.cmake
+ DESTINATION lib/cmake/MathFunctions
+)
+
+include(CMakePackageConfigHelpers)
+# generate the config file that is includes the exports
+configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in
+ "${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfig.cmake"
+ INSTALL_DESTINATION "lib/cmake/example"
+ NO_SET_AND_CHECK_MACRO
+ NO_CHECK_REQUIRED_COMPONENTS_MACRO
+ )
+# generate the version file for the config file
+write_basic_package_version_file(
+ "${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfigVersion.cmake"
+ VERSION "${Tutorial_VERSION_MAJOR}.${Tutorial_VERSION_MINOR}"
+ COMPATIBILITY AnyNewerVersion
+)
+
+# install the configuration file
+install(FILES
+ ${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfig.cmake
+ DESTINATION lib/cmake/MathFunctions
+ )
+
+# generate the export targets for the build tree
+# needs to be after the install(TARGETS ) command
+export(EXPORT MathFunctionsTargets
+ FILE "${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsTargets.cmake"
+)
diff --git a/Tests/Tutorial/MultiPackage/Config.cmake.in b/Tests/Tutorial/MultiPackage/Config.cmake.in
new file mode 100644
index 000000000..17cbabd99
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/Config.cmake.in
@@ -0,0 +1,4 @@
+
+@PACKAGE_INIT@
+
+include ( "${CMAKE_CURRENT_LIST_DIR}/MathFunctionsTargets.cmake" )
diff --git a/Tests/Tutorial/MultiPackage/License.txt b/Tests/Tutorial/MultiPackage/License.txt
new file mode 100644
index 000000000..c62d00b9e
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/License.txt
@@ -0,0 +1,2 @@
+This is the open source License.txt file introduced in
+CMake/Tutorial/Step7...
diff --git a/Tests/Tutorial/MultiPackage/MathFunctions/CMakeLists.txt b/Tests/Tutorial/MultiPackage/MathFunctions/CMakeLists.txt
new file mode 100644
index 000000000..161ad6449
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/MathFunctions/CMakeLists.txt
@@ -0,0 +1,68 @@
+
+# add the library that runs
+add_library(MathFunctions MathFunctions.cxx)
+
+# state that anybody linking to us needs to include the current source dir
+# to find MathFunctions.h, while we don't.
+target_include_directories(MathFunctions
+ INTERFACE
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
+ $<INSTALL_INTERFACE:include>
+ )
+
+# should we use our own math functions
+option(USE_MYMATH "Use tutorial provided math implementation" ON)
+if(USE_MYMATH)
+
+ # does this system provide the log and exp functions?
+ include(CheckSymbolExists)
+ set(CMAKE_REQUIRED_LIBRARIES "m")
+ check_symbol_exists(log "math.h" HAVE_LOG)
+ check_symbol_exists(exp "math.h" HAVE_EXP)
+
+ # first we add the executable that generates the table
+ add_executable(MakeTable MakeTable.cxx)
+
+ # add the command to generate the source code
+ add_custom_command(
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ DEPENDS MakeTable
+ )
+
+ # library that just does sqrt
+ add_library(SqrtLibrary STATIC
+ mysqrt.cxx
+ ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ )
+
+ # state that we depend on our binary dir to find Table.h
+ target_include_directories(SqrtLibrary PRIVATE
+ ${CMAKE_CURRENT_BINARY_DIR}
+ )
+
+ set_target_properties(SqrtLibrary PROPERTIES
+ POSITION_INDEPENDENT_CODE ${BUILD_SHARED_LIBS}
+ )
+
+ target_compile_definitions(SqrtLibrary PRIVATE
+ "$<$<BOOL:${HAVE_LOG}>:HAVE_LOG>"
+ "$<$<BOOL:${HAVE_EXP}>:HAVE_EXP>"
+ )
+ target_link_libraries(MathFunctions PRIVATE SqrtLibrary)
+endif()
+
+target_compile_definitions(MathFunctions PRIVATE "$<$<BOOL:${USE_MYMATH}>:USE_MYMATH>")
+
+# define the symbol stating we are using the declspec(dllexport) when
+# building on windows
+target_compile_definitions(MathFunctions PRIVATE "EXPORTING_MYMATH")
+
+# setup the version numbering
+set_property(TARGET MathFunctions PROPERTY VERSION "1.0.0")
+set_property(TARGET MathFunctions PROPERTY SOVERSION "1")
+
+install(TARGETS MathFunctions
+ DESTINATION lib
+ EXPORT MathFunctionsTargets)
+install(FILES MathFunctions.h DESTINATION include)
diff --git a/Tests/Tutorial/MultiPackage/MathFunctions/MakeTable.cxx b/Tests/Tutorial/MultiPackage/MathFunctions/MakeTable.cxx
new file mode 100644
index 000000000..ee585568c
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/MathFunctions/MakeTable.cxx
@@ -0,0 +1,25 @@
+// A simple program that builds a sqrt table
+#include <cmath>
+#include <fstream>
+#include <iostream>
+
+int main(int argc, char* argv[])
+{
+ // make sure we have enough arguments
+ if (argc < 2) {
+ return 1;
+ }
+
+ std::ofstream fout(argv[1], std::ios_base::out);
+ const bool fileOpen = fout.is_open();
+ if (fileOpen) {
+ fout << "double sqrtTable[] = {" << std::endl;
+ for (int i = 0; i < 10; ++i) {
+ fout << sqrt(static_cast<double>(i)) << "," << std::endl;
+ }
+ // close the table with a zero
+ fout << "0};" << std::endl;
+ fout.close();
+ }
+ return fileOpen ? 0 : 1; // return 0 if wrote the file
+}
diff --git a/Tests/Tutorial/MultiPackage/MathFunctions/MathFunctions.cxx b/Tests/Tutorial/MultiPackage/MathFunctions/MathFunctions.cxx
new file mode 100644
index 000000000..5351184be
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/MathFunctions/MathFunctions.cxx
@@ -0,0 +1,18 @@
+
+#include "MathFunctions.h"
+#include <cmath>
+
+#ifdef USE_MYMATH
+# include "mysqrt.h"
+#endif
+
+namespace mathfunctions {
+double sqrt(double x)
+{
+#ifdef USE_MYMATH
+ return detail::mysqrt(x);
+#else
+ return std::sqrt(x);
+#endif
+}
+}
diff --git a/Tests/Tutorial/MultiPackage/MathFunctions/MathFunctions.h b/Tests/Tutorial/MultiPackage/MathFunctions/MathFunctions.h
new file mode 100644
index 000000000..3fb547b4a
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/MathFunctions/MathFunctions.h
@@ -0,0 +1,14 @@
+
+#if defined(_WIN32)
+# if defined(EXPORTING_MYMATH)
+# define DECLSPEC __declspec(dllexport)
+# else
+# define DECLSPEC __declspec(dllimport)
+# endif
+#else // non windows
+# define DECLSPEC
+#endif
+
+namespace mathfunctions {
+double DECLSPEC sqrt(double x);
+}
diff --git a/Tests/Tutorial/MultiPackage/MathFunctions/mysqrt.cxx b/Tests/Tutorial/MultiPackage/MathFunctions/mysqrt.cxx
new file mode 100644
index 000000000..96d94212d
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/MathFunctions/mysqrt.cxx
@@ -0,0 +1,45 @@
+#include "MathFunctions.h"
+#include <iostream>
+
+// include the generated table
+#include "Table.h"
+
+#include <cmath>
+
+namespace mathfunctions {
+namespace detail {
+// a hack square root calculation using simple operations
+double mysqrt(double x)
+{
+ if (x <= 0) {
+ return 0;
+ }
+
+ // if we have both log and exp then use them
+#if defined(HAVE_LOG) && defined(HAVE_EXP)
+ double result = exp(log(x) * 0.5);
+ std::cout << "Computing sqrt of " << x << " to be " << result << " using log"
+ << std::endl;
+#else
+ // use the table to help find an initial value
+ double result = x;
+ if (x >= 1 && x < 10) {
+ result = sqrtTable[static_cast<int>(x)];
+ }
+
+ // if we have both log and exp then use them
+
+ // do ten iterations
+ for (int i = 0; i < 10; ++i) {
+ if (result <= 0) {
+ result = 0.1;
+ }
+ double delta = x - (result * result);
+ result = result + 0.5 * delta / result;
+ std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
+ }
+#endif
+ return result;
+}
+}
+}
diff --git a/Tests/Tutorial/MultiPackage/MathFunctions/mysqrt.h b/Tests/Tutorial/MultiPackage/MathFunctions/mysqrt.h
new file mode 100644
index 000000000..e1c42ef0c
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/MathFunctions/mysqrt.h
@@ -0,0 +1,6 @@
+
+namespace mathfunctions {
+namespace detail {
+double mysqrt(double x);
+}
+}
diff --git a/Tests/Tutorial/MultiPackage/MultiCPackConfig.cmake b/Tests/Tutorial/MultiPackage/MultiCPackConfig.cmake
new file mode 100644
index 000000000..403b633e1
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/MultiCPackConfig.cmake
@@ -0,0 +1,7 @@
+
+include("release/CPackConfig.cmake")
+
+set(CPACK_INSTALL_CMAKE_PROJECTS
+ "debug;Tutorial;ALL;/"
+ "release;Tutorial;ALL;/"
+ )
diff --git a/Tests/Tutorial/MultiPackage/TutorialConfig.h.in b/Tests/Tutorial/MultiPackage/TutorialConfig.h.in
new file mode 100644
index 000000000..8cd2fc9c6
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/TutorialConfig.h.in
@@ -0,0 +1,3 @@
+// the configured version number
+#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
+#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
diff --git a/Tests/Tutorial/MultiPackage/directions.txt b/Tests/Tutorial/MultiPackage/directions.txt
new file mode 100644
index 000000000..c3102bb10
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/directions.txt
@@ -0,0 +1,34 @@
+# Packaging Debug and Release #
+
+By default CMake is model is that a build directory only contains a single
+configuration, be it Debug, Release, MinSizeRel, or RelWithDebInfo.
+
+But it is possible to setup CPack to bundle multiple build directories at the same
+time to build a package that contains multiple configurations of the same project.
+
+First we need to ahead and construct a directory called 'multi_config' this
+will contain all the builds that we want to package together.
+
+Second create a 'debug' and 'release' directory underneath 'multi_config'. At
+the end you should have a layout that looks like:
+
+─ multi_config
+ ├── debug
+ └── release
+
+Now we need to setup debug and release builds, which would roughly entail
+the following:
+
+ cd debug
+ cmake -DCMAKE_BUILD_TYPE=Debug ../../MultiPackage/
+ cmake --build .
+ cd ../release
+ cmake -DCMAKE_BUILD_TYPE=Release ../../MultiPackage/
+ cmake --build .
+ cd ..
+
+
+Now that both the debug and release builds are complete we can now use
+the custom MultiCPackConfig to package both builds into a single release.
+
+ cpack --config ../../MultiPackage/MultiCPackConfig.cmake
diff --git a/Tests/Tutorial/MultiPackage/tutorial.cxx b/Tests/Tutorial/MultiPackage/tutorial.cxx
new file mode 100644
index 000000000..443d19555
--- /dev/null
+++ b/Tests/Tutorial/MultiPackage/tutorial.cxx
@@ -0,0 +1,25 @@
+// A simple program that computes the square root of a number
+#include <iostream>
+#include <sstream>
+#include <string>
+
+#include "MathFunctions.h"
+#include "TutorialConfig.h"
+
+int main(int argc, char* argv[])
+{
+ if (argc < 2) {
+ std::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."
+ << Tutorial_VERSION_MAJOR << std::endl;
+ std::cout << "Usage: " << argv[0] << " number" << std::endl;
+ return 1;
+ }
+
+ double inputValue = std::stod(argv[1]);
+
+ const double outputValue = mathfunctions::sqrt(inputValue);
+
+ std::cout << "The square root of " << inputValue << " is " << outputValue
+ << std::endl;
+ return 0;
+}
diff --git a/Tests/Tutorial/Readme.txt b/Tests/Tutorial/Readme.txt
new file mode 100644
index 000000000..74eb01ae5
--- /dev/null
+++ b/Tests/Tutorial/Readme.txt
@@ -0,0 +1,16 @@
+
+Step 0: A Starting Point
+Step 1: Configure a File and C++11 Controls
+Step 2: Adding a Library
+Step 3: Usage Requirements for Library
+Step 4: Installing and Testing
+Step 5: System Introspection
+Step 6: Custom Command and Generated File
+Step 7: Building an Installer
+Step 8: CDash submission
+Step 9: Mixing Static and Shared
+Step 10: Generator Expressions
+Step 11: Adding Export Configuration
+Complete: End result of Step 11
+Consumer: Example of Import Packages
+MultiPackage: How to package Debug and Release versions
diff --git a/Tests/Tutorial/Step1/directions.txt b/Tests/Tutorial/Step1/directions.txt
new file mode 100644
index 000000000..827d7754d
--- /dev/null
+++ b/Tests/Tutorial/Step1/directions.txt
@@ -0,0 +1,95 @@
+# Adding a Version Number and Configured Header File #
+
+The first feature we will add is to provide our executable and project with a
+version number. While we could do this exclusively in the source code, using
+CMakeLists provides more flexibility.
+
+To add a version number we modify the CMakeLists file as follows:
+
+ cmake_minimum_required(VERSION 3.3)
+ project(Tutorial)
+
+ # the version number.
+ set(Tutorial_VERSION_MAJOR 1)
+ set(Tutorial_VERSION_MINOR 0)
+
+ # configure a header file to pass some of the CMake settings
+ # to the source code
+ configure_file(
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ )
+
+ # add the executable
+ add_executable(Tutorial tutorial.cxx)
+
+ # add the binary tree to the search path for include files
+ # so that we will find TutorialConfig.h
+ target_include_directories(Tutorial PUBLIC
+ "${PROJECT_BINARY_DIR}"
+ )
+
+
+We then create a TutorialConfig.h.in file in the source tree with the
+following contents:
+
+ // the configured options and settings for Tutorial
+ #define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
+ #define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
+
+When CMake configures this header file the values for @Tutorial_VERSION_MAJOR@
+and @Tutorial_VERSION_MINOR@ will be replaced by the values from the CMakeLists
+file. Next we modify tutorial.cxx to include the configured header file and to
+make use of the version numbers. The resulting source code is listed below.
+
+ // A simple program that computes the square root of a number
+ #include <cmath>
+ #include <iostream>
+ #include <string>
+ #include <sstream>
+
+ #include "TutorialConfig.h"
+
+ int main (int argc, char *argv[])
+ {
+ if (argc < 2) {
+ std::cout << argv[0] << " Version "
+ << Tutorial_VERSION_MAJOR << "." << Tutorial_VERSION_MINOR
+ << std::endl;
+ std::cout << "Usage: " << argv[0] << " number" << std::endl;
+ return 1;
+ }
+
+ double inputValue = atof(argv[1]);
+
+ double outputValue = sqrt(inputValue);
+ std::cout << "The square root of "
+ << inputValue << " is " << outputValue << std::endl;
+ return 0;
+ }
+
+# Adding C++11 support #
+
+Let's add some C++11 features to our project. We will need to explicitly state
+in the CMake code that it should use the correct flags. The easiest way to
+enable C++11 support for CMake is by using the CMAKE_CXX_STANDARD
+and CMAKE_CXX_STANDARD_REQUIRED variables.
+
+First, replace `atof` with `std::stod` in tutorial.cxx.
+
+Then, add the CMAKE_CXX_STANDARD and CMAKE_CXX_STANDARD_REQUIRED variables to
+the CMakeLists file. The STANADARD value should be set to 11, and REQUIRED
+should be set to True.
+
+
+# Build and Test #
+
+Run cmake or cmake-gui to configure the project and then build it with your
+chosen build tool
+
+cd to the directory where Tutorial was built (likely the make directory or
+a Debug or Release build configuration subdirectory) and run these commands:
+
+ Tutorial 4294967296
+ Tutorial 10
+ Tutorial
diff --git a/Tests/Tutorial/Step10/CMakeLists.txt b/Tests/Tutorial/Step10/CMakeLists.txt
new file mode 100644
index 000000000..b1d46c4b9
--- /dev/null
+++ b/Tests/Tutorial/Step10/CMakeLists.txt
@@ -0,0 +1,77 @@
+cmake_minimum_required(VERSION 3.3)
+project(Tutorial)
+
+# control where the static and shared libraries are built so that on windows
+# we don't need to tinker with the path to run the executable
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED True)
+
+option(BUILD_SHARED_LIBS "Build using shared libraries" ON)
+
+# the version number.
+set(Tutorial_VERSION_MAJOR 1)
+set(Tutorial_VERSION_MINOR 0)
+
+# configure a header file to pass the version number only
+configure_file(
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ )
+
+# add the MathFunctions library
+add_subdirectory(MathFunctions)
+
+# add the executable
+add_executable(Tutorial tutorial.cxx)
+target_link_libraries(Tutorial MathFunctions)
+
+# add the binary tree to the search path for include files
+# so that we will find TutorialConfig.h
+target_include_directories(Tutorial PUBLIC
+ "${PROJECT_BINARY_DIR}"
+ )
+
+# add the install targets
+install(TARGETS Tutorial DESTINATION bin)
+install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ DESTINATION include
+ )
+
+# enable testing
+enable_testing()
+
+# does the application run
+add_test(NAME Runs COMMAND Tutorial 25)
+
+# does the usage message work?
+add_test(NAME Usage COMMAND Tutorial)
+set_tests_properties(Usage
+ PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
+ )
+
+# define a function to simplify adding tests
+function(do_test target arg result)
+ add_test(NAME Comp${arg} COMMAND ${target} ${arg})
+ set_tests_properties(Comp${arg}
+ PROPERTIES PASS_REGULAR_EXPRESSION ${result}
+ )
+endfunction(do_test)
+
+# do a bunch of result based tests
+do_test(Tutorial 4 "4 is 2")
+do_test(Tutorial 9 "9 is 3")
+do_test(Tutorial 5 "5 is 2.236")
+do_test(Tutorial 7 "7 is 2.645")
+do_test(Tutorial 25 "25 is 5")
+do_test(Tutorial -25 "-25 is [-nan|nan|0]")
+do_test(Tutorial 0.0001 "0.0001 is 0.01")
+
+include(InstallRequiredSystemLibraries)
+set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
+set(CPACK_PACKAGE_VERSION_MAJOR "${Tutorial_VERSION_MAJOR}")
+set(CPACK_PACKAGE_VERSION_MINOR "${Tutorial_VERSION_MINOR}")
+include(CPack)
diff --git a/Tests/Tutorial/Step10/License.txt b/Tests/Tutorial/Step10/License.txt
new file mode 100644
index 000000000..c62d00b9e
--- /dev/null
+++ b/Tests/Tutorial/Step10/License.txt
@@ -0,0 +1,2 @@
+This is the open source License.txt file introduced in
+CMake/Tutorial/Step7...
diff --git a/Tests/Tutorial/Step10/MathFunctions/CMakeLists.txt b/Tests/Tutorial/Step10/MathFunctions/CMakeLists.txt
new file mode 100644
index 000000000..7a2350572
--- /dev/null
+++ b/Tests/Tutorial/Step10/MathFunctions/CMakeLists.txt
@@ -0,0 +1,61 @@
+
+# add the library that runs
+add_library(MathFunctions MathFunctions.cxx)
+
+# state that anybody linking to us needs to include the current source dir
+# to find MathFunctions.h, while we don't.
+target_include_directories(MathFunctions
+ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
+ )
+
+# should we use our own math functions
+option(USE_MYMATH "Use tutorial provided math implementation" ON)
+if(USE_MYMATH)
+
+ # does this system provide the log and exp functions?
+ include(CheckSymbolExists)
+ set(CMAKE_REQUIRED_LIBRARIES "m")
+ check_symbol_exists(log "math.h" HAVE_LOG)
+ check_symbol_exists(exp "math.h" HAVE_EXP)
+
+ # first we add the executable that generates the table
+ add_executable(MakeTable MakeTable.cxx)
+
+ # add the command to generate the source code
+ add_custom_command(
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ DEPENDS MakeTable
+ )
+
+ # library that just does sqrt
+ add_library(SqrtLibrary STATIC
+ mysqrt.cxx
+ ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ )
+
+ # state that we depend on our binary dir to find Table.h
+ target_include_directories(SqrtLibrary PRIVATE
+ ${CMAKE_CURRENT_BINARY_DIR}
+ )
+
+ # state that SqrtLibrary need PIC when the default is shared libraries
+ set_target_properties(SqrtLibrary PROPERTIES
+ POSITION_INDEPENDENT_CODE ${BUILD_SHARED_LIBS}
+ )
+
+ target_compile_definitions(MathFunctions PRIVATE "USE_MYMATH")
+ if(HAVE_LOG AND HAVE_EXP)
+ target_compile_definitions(SqrtLibrary
+ PRIVATE "HAVE_LOG" "HAVE_EXP")
+ endif()
+
+ target_link_libraries(MathFunctions PRIVATE SqrtLibrary)
+endif()
+
+# define the symbol stating we are using the declspec(dllexport) when
+# building on windows
+target_compile_definitions(MathFunctions PRIVATE "EXPORTING_MYMATH")
+
+install(TARGETS MathFunctions DESTINATION lib)
+install(FILES MathFunctions.h DESTINATION include)
diff --git a/Tests/Tutorial/Step10/MathFunctions/MakeTable.cxx b/Tests/Tutorial/Step10/MathFunctions/MakeTable.cxx
new file mode 100644
index 000000000..ee585568c
--- /dev/null
+++ b/Tests/Tutorial/Step10/MathFunctions/MakeTable.cxx
@@ -0,0 +1,25 @@
+// A simple program that builds a sqrt table
+#include <cmath>
+#include <fstream>
+#include <iostream>
+
+int main(int argc, char* argv[])
+{
+ // make sure we have enough arguments
+ if (argc < 2) {
+ return 1;
+ }
+
+ std::ofstream fout(argv[1], std::ios_base::out);
+ const bool fileOpen = fout.is_open();
+ if (fileOpen) {
+ fout << "double sqrtTable[] = {" << std::endl;
+ for (int i = 0; i < 10; ++i) {
+ fout << sqrt(static_cast<double>(i)) << "," << std::endl;
+ }
+ // close the table with a zero
+ fout << "0};" << std::endl;
+ fout.close();
+ }
+ return fileOpen ? 0 : 1; // return 0 if wrote the file
+}
diff --git a/Tests/Tutorial/Step10/MathFunctions/MathFunctions.cxx b/Tests/Tutorial/Step10/MathFunctions/MathFunctions.cxx
new file mode 100644
index 000000000..5351184be
--- /dev/null
+++ b/Tests/Tutorial/Step10/MathFunctions/MathFunctions.cxx
@@ -0,0 +1,18 @@
+
+#include "MathFunctions.h"
+#include <cmath>
+
+#ifdef USE_MYMATH
+# include "mysqrt.h"
+#endif
+
+namespace mathfunctions {
+double sqrt(double x)
+{
+#ifdef USE_MYMATH
+ return detail::mysqrt(x);
+#else
+ return std::sqrt(x);
+#endif
+}
+}
diff --git a/Tests/Tutorial/Step10/MathFunctions/MathFunctions.h b/Tests/Tutorial/Step10/MathFunctions/MathFunctions.h
new file mode 100644
index 000000000..3fb547b4a
--- /dev/null
+++ b/Tests/Tutorial/Step10/MathFunctions/MathFunctions.h
@@ -0,0 +1,14 @@
+
+#if defined(_WIN32)
+# if defined(EXPORTING_MYMATH)
+# define DECLSPEC __declspec(dllexport)
+# else
+# define DECLSPEC __declspec(dllimport)
+# endif
+#else // non windows
+# define DECLSPEC
+#endif
+
+namespace mathfunctions {
+double DECLSPEC sqrt(double x);
+}
diff --git a/Tests/Tutorial/Step10/MathFunctions/mysqrt.cxx b/Tests/Tutorial/Step10/MathFunctions/mysqrt.cxx
new file mode 100644
index 000000000..96d94212d
--- /dev/null
+++ b/Tests/Tutorial/Step10/MathFunctions/mysqrt.cxx
@@ -0,0 +1,45 @@
+#include "MathFunctions.h"
+#include <iostream>
+
+// include the generated table
+#include "Table.h"
+
+#include <cmath>
+
+namespace mathfunctions {
+namespace detail {
+// a hack square root calculation using simple operations
+double mysqrt(double x)
+{
+ if (x <= 0) {
+ return 0;
+ }
+
+ // if we have both log and exp then use them
+#if defined(HAVE_LOG) && defined(HAVE_EXP)
+ double result = exp(log(x) * 0.5);
+ std::cout << "Computing sqrt of " << x << " to be " << result << " using log"
+ << std::endl;
+#else
+ // use the table to help find an initial value
+ double result = x;
+ if (x >= 1 && x < 10) {
+ result = sqrtTable[static_cast<int>(x)];
+ }
+
+ // if we have both log and exp then use them
+
+ // do ten iterations
+ for (int i = 0; i < 10; ++i) {
+ if (result <= 0) {
+ result = 0.1;
+ }
+ double delta = x - (result * result);
+ result = result + 0.5 * delta / result;
+ std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
+ }
+#endif
+ return result;
+}
+}
+}
diff --git a/Tests/Tutorial/Step10/MathFunctions/mysqrt.h b/Tests/Tutorial/Step10/MathFunctions/mysqrt.h
new file mode 100644
index 000000000..e1c42ef0c
--- /dev/null
+++ b/Tests/Tutorial/Step10/MathFunctions/mysqrt.h
@@ -0,0 +1,6 @@
+
+namespace mathfunctions {
+namespace detail {
+double mysqrt(double x);
+}
+}
diff --git a/Tests/Tutorial/Step10/TutorialConfig.h.in b/Tests/Tutorial/Step10/TutorialConfig.h.in
new file mode 100644
index 000000000..8cd2fc9c6
--- /dev/null
+++ b/Tests/Tutorial/Step10/TutorialConfig.h.in
@@ -0,0 +1,3 @@
+// the configured version number
+#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
+#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
diff --git a/Tests/Tutorial/Step10/directions.txt b/Tests/Tutorial/Step10/directions.txt
new file mode 100644
index 000000000..5317b5430
--- /dev/null
+++ b/Tests/Tutorial/Step10/directions.txt
@@ -0,0 +1,38 @@
+# Adding Generator Expressions #
+
+Generator expressions are evaluated during build system generation to produce
+information specific to each build configuration.
+
+Generator expressions are allowed in the context of many target properties, such
+as LINK_LIBRARIES, INCLUDE_DIRECTORIES, COMPILE_DEFINITIONS and others. They may
+also be used when using commands to populate those properties, such as
+target_link_libraries(), target_include_directories(),
+target_compile_definitions() and others.
+
+Generator expressions may to used to enable conditional linking, conditional
+definitions used when compiling, and conditional include directories and more.
+The conditions may be based on the build configuration, target properties,
+platform information or any other queryable information.
+
+There are different types of generator expressions including Logical,
+Informational, and Output expressions.
+
+Logical expressions are used to create conditional output. The basic expressions
+are the 0 and 1 expressions. A "$<0:...>" results in the empty string, and
+"$<1:...>" results in the content of "...". They can also be nested.
+For example:
+
+ if(HAVE_LOG AND HAVE_EXP)
+ target_compile_definitions(SqrtLibrary
+ PRIVATE "HAVE_LOG" "HAVE_EXP")
+ endif()
+
+Can be rewritten with generator expressions:
+
+ target_compile_definitions(SqrtLibrary PRIVATE
+ "$<$<BOOL:${HAVE_LOG}>:HAVE_LOG>"
+ "$<$<BOOL:${HAVE_EXP}>:HAVE_EXP>"
+ )
+
+Note that "${HAVE_LOG}" is evaluated at CMake configure time while
+"$<$<BOOL:${HAVE_LOG}>:HAVE_LOG>" is evaluated at build system generation time.
diff --git a/Tests/Tutorial/Step10/tutorial.cxx b/Tests/Tutorial/Step10/tutorial.cxx
new file mode 100644
index 000000000..443d19555
--- /dev/null
+++ b/Tests/Tutorial/Step10/tutorial.cxx
@@ -0,0 +1,25 @@
+// A simple program that computes the square root of a number
+#include <iostream>
+#include <sstream>
+#include <string>
+
+#include "MathFunctions.h"
+#include "TutorialConfig.h"
+
+int main(int argc, char* argv[])
+{
+ if (argc < 2) {
+ std::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."
+ << Tutorial_VERSION_MAJOR << std::endl;
+ std::cout << "Usage: " << argv[0] << " number" << std::endl;
+ return 1;
+ }
+
+ double inputValue = std::stod(argv[1]);
+
+ const double outputValue = mathfunctions::sqrt(inputValue);
+
+ std::cout << "The square root of " << inputValue << " is " << outputValue
+ << std::endl;
+ return 0;
+}
diff --git a/Tests/Tutorial/Step11/CMakeLists.txt b/Tests/Tutorial/Step11/CMakeLists.txt
new file mode 100644
index 000000000..b1d46c4b9
--- /dev/null
+++ b/Tests/Tutorial/Step11/CMakeLists.txt
@@ -0,0 +1,77 @@
+cmake_minimum_required(VERSION 3.3)
+project(Tutorial)
+
+# control where the static and shared libraries are built so that on windows
+# we don't need to tinker with the path to run the executable
+set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED True)
+
+option(BUILD_SHARED_LIBS "Build using shared libraries" ON)
+
+# the version number.
+set(Tutorial_VERSION_MAJOR 1)
+set(Tutorial_VERSION_MINOR 0)
+
+# configure a header file to pass the version number only
+configure_file(
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ )
+
+# add the MathFunctions library
+add_subdirectory(MathFunctions)
+
+# add the executable
+add_executable(Tutorial tutorial.cxx)
+target_link_libraries(Tutorial MathFunctions)
+
+# add the binary tree to the search path for include files
+# so that we will find TutorialConfig.h
+target_include_directories(Tutorial PUBLIC
+ "${PROJECT_BINARY_DIR}"
+ )
+
+# add the install targets
+install(TARGETS Tutorial DESTINATION bin)
+install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ DESTINATION include
+ )
+
+# enable testing
+enable_testing()
+
+# does the application run
+add_test(NAME Runs COMMAND Tutorial 25)
+
+# does the usage message work?
+add_test(NAME Usage COMMAND Tutorial)
+set_tests_properties(Usage
+ PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
+ )
+
+# define a function to simplify adding tests
+function(do_test target arg result)
+ add_test(NAME Comp${arg} COMMAND ${target} ${arg})
+ set_tests_properties(Comp${arg}
+ PROPERTIES PASS_REGULAR_EXPRESSION ${result}
+ )
+endfunction(do_test)
+
+# do a bunch of result based tests
+do_test(Tutorial 4 "4 is 2")
+do_test(Tutorial 9 "9 is 3")
+do_test(Tutorial 5 "5 is 2.236")
+do_test(Tutorial 7 "7 is 2.645")
+do_test(Tutorial 25 "25 is 5")
+do_test(Tutorial -25 "-25 is [-nan|nan|0]")
+do_test(Tutorial 0.0001 "0.0001 is 0.01")
+
+include(InstallRequiredSystemLibraries)
+set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
+set(CPACK_PACKAGE_VERSION_MAJOR "${Tutorial_VERSION_MAJOR}")
+set(CPACK_PACKAGE_VERSION_MINOR "${Tutorial_VERSION_MINOR}")
+include(CPack)
diff --git a/Tests/Tutorial/Step11/License.txt b/Tests/Tutorial/Step11/License.txt
new file mode 100644
index 000000000..c62d00b9e
--- /dev/null
+++ b/Tests/Tutorial/Step11/License.txt
@@ -0,0 +1,2 @@
+This is the open source License.txt file introduced in
+CMake/Tutorial/Step7...
diff --git a/Tests/Tutorial/Step11/MathFunctions/CMakeLists.txt b/Tests/Tutorial/Step11/MathFunctions/CMakeLists.txt
new file mode 100644
index 000000000..760d6a57c
--- /dev/null
+++ b/Tests/Tutorial/Step11/MathFunctions/CMakeLists.txt
@@ -0,0 +1,60 @@
+
+# add the library that runs
+add_library(MathFunctions MathFunctions.cxx)
+
+# state that anybody linking to us needs to include the current source dir
+# to find MathFunctions.h, while we don't.
+target_include_directories(MathFunctions
+ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
+ )
+
+# should we use our own math functions
+option(USE_MYMATH "Use tutorial provided math implementation" ON)
+if(USE_MYMATH)
+
+ # does this system provide the log and exp functions?
+ include(CheckSymbolExists)
+ set(CMAKE_REQUIRED_LIBRARIES "m")
+ check_symbol_exists(log "math.h" HAVE_LOG)
+ check_symbol_exists(exp "math.h" HAVE_EXP)
+
+ # first we add the executable that generates the table
+ add_executable(MakeTable MakeTable.cxx)
+
+ # add the command to generate the source code
+ add_custom_command(
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ DEPENDS MakeTable
+ )
+
+ # library that just does sqrt
+ add_library(SqrtLibrary STATIC
+ mysqrt.cxx
+ ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ )
+
+ # state that we depend on our binary dir to find Table.h
+ target_include_directories(SqrtLibrary PRIVATE
+ ${CMAKE_CURRENT_BINARY_DIR}
+ )
+
+ set_target_properties(SqrtLibrary PROPERTIES
+ POSITION_INDEPENDENT_CODE ${BUILD_SHARED_LIBS}
+ )
+
+ target_compile_definitions(SqrtLibrary PRIVATE
+ "$<$<BOOL:${HAVE_LOG}>:HAVE_LOG>"
+ "$<$<BOOL:${HAVE_EXP}>:HAVE_EXP>"
+ )
+ target_link_libraries(MathFunctions PRIVATE SqrtLibrary)
+endif()
+
+target_compile_definitions(MathFunctions PRIVATE "$<$<BOOL:${USE_MYMATH}>:USE_MYMATH>")
+
+# define the symbol stating we are using the declspec(dllexport) when
+#building on windows
+target_compile_definitions(MathFunctions PRIVATE "EXPORTING_MYMATH")
+
+install(TARGETS MathFunctions DESTINATION lib)
+install(FILES MathFunctions.h DESTINATION include)
diff --git a/Tests/Tutorial/Step11/MathFunctions/MakeTable.cxx b/Tests/Tutorial/Step11/MathFunctions/MakeTable.cxx
new file mode 100644
index 000000000..ee585568c
--- /dev/null
+++ b/Tests/Tutorial/Step11/MathFunctions/MakeTable.cxx
@@ -0,0 +1,25 @@
+// A simple program that builds a sqrt table
+#include <cmath>
+#include <fstream>
+#include <iostream>
+
+int main(int argc, char* argv[])
+{
+ // make sure we have enough arguments
+ if (argc < 2) {
+ return 1;
+ }
+
+ std::ofstream fout(argv[1], std::ios_base::out);
+ const bool fileOpen = fout.is_open();
+ if (fileOpen) {
+ fout << "double sqrtTable[] = {" << std::endl;
+ for (int i = 0; i < 10; ++i) {
+ fout << sqrt(static_cast<double>(i)) << "," << std::endl;
+ }
+ // close the table with a zero
+ fout << "0};" << std::endl;
+ fout.close();
+ }
+ return fileOpen ? 0 : 1; // return 0 if wrote the file
+}
diff --git a/Tests/Tutorial/Step11/MathFunctions/MathFunctions.cxx b/Tests/Tutorial/Step11/MathFunctions/MathFunctions.cxx
new file mode 100644
index 000000000..5351184be
--- /dev/null
+++ b/Tests/Tutorial/Step11/MathFunctions/MathFunctions.cxx
@@ -0,0 +1,18 @@
+
+#include "MathFunctions.h"
+#include <cmath>
+
+#ifdef USE_MYMATH
+# include "mysqrt.h"
+#endif
+
+namespace mathfunctions {
+double sqrt(double x)
+{
+#ifdef USE_MYMATH
+ return detail::mysqrt(x);
+#else
+ return std::sqrt(x);
+#endif
+}
+}
diff --git a/Tests/Tutorial/Step11/MathFunctions/MathFunctions.h b/Tests/Tutorial/Step11/MathFunctions/MathFunctions.h
new file mode 100644
index 000000000..3fb547b4a
--- /dev/null
+++ b/Tests/Tutorial/Step11/MathFunctions/MathFunctions.h
@@ -0,0 +1,14 @@
+
+#if defined(_WIN32)
+# if defined(EXPORTING_MYMATH)
+# define DECLSPEC __declspec(dllexport)
+# else
+# define DECLSPEC __declspec(dllimport)
+# endif
+#else // non windows
+# define DECLSPEC
+#endif
+
+namespace mathfunctions {
+double DECLSPEC sqrt(double x);
+}
diff --git a/Tests/Tutorial/Step11/MathFunctions/mysqrt.cxx b/Tests/Tutorial/Step11/MathFunctions/mysqrt.cxx
new file mode 100644
index 000000000..96d94212d
--- /dev/null
+++ b/Tests/Tutorial/Step11/MathFunctions/mysqrt.cxx
@@ -0,0 +1,45 @@
+#include "MathFunctions.h"
+#include <iostream>
+
+// include the generated table
+#include "Table.h"
+
+#include <cmath>
+
+namespace mathfunctions {
+namespace detail {
+// a hack square root calculation using simple operations
+double mysqrt(double x)
+{
+ if (x <= 0) {
+ return 0;
+ }
+
+ // if we have both log and exp then use them
+#if defined(HAVE_LOG) && defined(HAVE_EXP)
+ double result = exp(log(x) * 0.5);
+ std::cout << "Computing sqrt of " << x << " to be " << result << " using log"
+ << std::endl;
+#else
+ // use the table to help find an initial value
+ double result = x;
+ if (x >= 1 && x < 10) {
+ result = sqrtTable[static_cast<int>(x)];
+ }
+
+ // if we have both log and exp then use them
+
+ // do ten iterations
+ for (int i = 0; i < 10; ++i) {
+ if (result <= 0) {
+ result = 0.1;
+ }
+ double delta = x - (result * result);
+ result = result + 0.5 * delta / result;
+ std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
+ }
+#endif
+ return result;
+}
+}
+}
diff --git a/Tests/Tutorial/Step11/MathFunctions/mysqrt.h b/Tests/Tutorial/Step11/MathFunctions/mysqrt.h
new file mode 100644
index 000000000..e1c42ef0c
--- /dev/null
+++ b/Tests/Tutorial/Step11/MathFunctions/mysqrt.h
@@ -0,0 +1,6 @@
+
+namespace mathfunctions {
+namespace detail {
+double mysqrt(double x);
+}
+}
diff --git a/Tests/Tutorial/Step11/TutorialConfig.h.in b/Tests/Tutorial/Step11/TutorialConfig.h.in
new file mode 100644
index 000000000..8cd2fc9c6
--- /dev/null
+++ b/Tests/Tutorial/Step11/TutorialConfig.h.in
@@ -0,0 +1,3 @@
+// the configured version number
+#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
+#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
diff --git a/Tests/Tutorial/Step11/directions.txt b/Tests/Tutorial/Step11/directions.txt
new file mode 100644
index 000000000..ebb5defff
--- /dev/null
+++ b/Tests/Tutorial/Step11/directions.txt
@@ -0,0 +1,104 @@
+# Adding Export Configuration #
+
+During Step 4 of the tutorial we added the ability for CMake to install the
+library and headers of the project. During Step 7 we added the ability
+to package up this information so it could be distributed to other people.
+
+The next step is to add the necessary information so that other CMake projects
+can use our project, be it from a build directory, a local install or when
+packaged.
+
+The first step is to update our install(TARGETS) commands to not only specify
+a DESTINATION but also an EXPORT. The EXPORT keyword generates and installs a
+CMake file containing code to import all targets listed in the install command
+from the installation tree. So let's go ahead and explicitly EXPORT the
+MathFunctions library by updating the install command in
+MathFunctions/CMakeLists.txt to look like:
+
+ install(TARGETS MathFunctions DESTINATION lib EXPORT MathFunctionsTargets)
+
+Now that we have MathFunctions being exported, we also need to explicitly install
+the generated MathFunctionsTargets.cmake file. This is done by adding
+the following to the bottom of the top-level CMakeLists.txt:
+
+ # install the configuration targets
+ install(EXPORT MathFunctionsTargets
+ FILE MathFunctionsTargets.cmake
+ DESTINATION lib/cmake/MathFunctions
+ )
+
+At this point you should try and run CMake. If everything is setup properly
+you will see that CMake will generate an error that looks like:
+
+ Target "MathFunctions" INTERFACE_INCLUDE_DIRECTORIES property contains
+ path:
+
+ "/Users/robert/Documents/CMakeClass/Tutorial/Step11/MathFunctions"
+
+ which is prefixed in the source directory.
+
+What CMake is trying to say is that during generating the export information
+it will export a path that is intrinsically tied to the current machine and
+will not be valid on other machines. The solution to this is to update the
+MathFunctions target_include_directories to understand that it needs different
+INTERFACE locations when being used from within the build directory and from an
+install / package. This means converting the target_include_directories
+call for MathFunctions to look like:
+
+ target_include_directories(MathFunctions
+ INTERFACE
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
+ $<INSTALL_INTERFACE:include>
+ )
+
+Once this has been updated, we can re-run CMake and see verify that it doesn't
+warn anymore.
+
+At this point, we have CMake properly packaging the target information that is
+required but we will still need to generate a MathFunctionsConfig.cmake, so
+that the CMake find_package command can find our project. So let's go ahead and
+add a new file to the top-level of the project called Config.cmake.in with the
+following contents:
+
+ @PACKAGE_INIT@
+
+ include ( "${CMAKE_CURRENT_LIST_DIR}/MathFunctionsTargets.cmake" )
+
+Then, to properly configure and install that file, add the following to the
+bottom of the top-level CMakeLists:
+
+ include(CMakePackageConfigHelpers)
+ # generate the config file that is includes the exports
+ configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in
+ "${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfig.cmake"
+ INSTALL_DESTINATION "lib/cmake/example"
+ NO_SET_AND_CHECK_MACRO
+ NO_CHECK_REQUIRED_COMPONENTS_MACRO
+ )
+ # generate the version file for the config file
+ write_basic_package_version_file(
+ "${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfigVersion.cmake"
+ VERSION "${Tutorial_VERSION_MAJOR}.${Tutorial_VERSION_MINOR}"
+ COMPATIBILITY AnyNewerVersion
+ )
+
+ # install the configuration file
+ install(FILES
+ ${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsConfig.cmake
+ DESTINATION lib/cmake/MathFunctions
+ )
+
+At this point, we have generated a relocatable CMake Configuration for our project
+that can be used after the project has been installed or packaged. If we want
+our project to also be used from a build directory we only have to add
+the following to the bottom of the top level CMakeLists:
+
+ # generate the export targets for the build tree
+ # needs to be after the install(TARGETS ) command
+ export(EXPORT MathFunctionsTargets
+ FILE "${CMAKE_CURRENT_BINARY_DIR}/MathFunctionsTargets.cmake"
+ )
+
+With this export call we now generate a Targets.cmake, allowing the configured
+MathFunctionsConfig.cmake in the build directory to be used by other projects,
+without needing it to be installed.
diff --git a/Tests/Tutorial/Step11/tutorial.cxx b/Tests/Tutorial/Step11/tutorial.cxx
new file mode 100644
index 000000000..376885526
--- /dev/null
+++ b/Tests/Tutorial/Step11/tutorial.cxx
@@ -0,0 +1,25 @@
+// A simple program that computes the square root of a number
+#include <cmath>
+#include <iostream>
+#include <string>
+
+#include "MathFunctions.h"
+#include "TutorialConfig.h"
+
+int main(int argc, char* argv[])
+{
+ if (argc < 2) {
+ std::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."
+ << Tutorial_VERSION_MAJOR << std::endl;
+ std::cout << "Usage: " << argv[0] << " number" << std::endl;
+ return 1;
+ }
+
+ double inputValue = std::stod(argv[1]);
+
+ const double outputValue = mathfunctions::sqrt(inputValue);
+
+ std::cout << "The square root of " << inputValue << " is " << outputValue
+ << std::endl;
+ return 0;
+}
diff --git a/Tests/Tutorial/Step2/directions.txt b/Tests/Tutorial/Step2/directions.txt
new file mode 100644
index 000000000..bb6662c7e
--- /dev/null
+++ b/Tests/Tutorial/Step2/directions.txt
@@ -0,0 +1,102 @@
+# Adding a Library #
+
+Now we will add a library to our project. This library will contain our own
+implementation for computing the square root of a number. The executable can
+then use this library instead of the standard square root function provided by
+the compiler.
+
+For this tutorial we will put the library into a subdirectory
+called MathFunctions. It will have the following one line CMakeLists file:
+
+ add_library(MathFunctions mysqrt.cxx)
+
+The source file mysqrt.cxx has one function called mysqrt that provides similar
+functionality to the compiler’s sqrt function. To make use of the new library
+we add an add_subdirectory call in the top-level CMakeLists file so that the
+library will get built. We add the new library to the executable, and add the
+MathFunctions as an include directory so that mqsqrt.h header file can be
+found. The last few lines of the top-level CMakeLists file now look like:
+
+
+ add_subdirectory(MathFunctions)
+
+ #add the executable
+ add_executable(Tutorial tutorial.cxx)
+
+ target_link_libraries(Tutorial ${EXTRA_LIBS})
+
+
+Now let us make the MathFunctions library optional. While for the tutorial
+there really isn’t any need to do so, but with larger projects this is a common
+occurrence. The first step is to add an option to the top-level CMakeLists file.
+
+ option (USE_MYMATH
+ "Use tutorial provided math implementation" ON)
+
+This will show up in CMake GUI and ccmake with a default value of ON that can
+be changed by the user. This setting will be stored so that the user does not
+need to set the value each time they run CMake on this build directory.
+
+The next change is to make building and linking the MathFunctions library
+conditional. To do this we change the top-level CMakeLists file to look like
+the following:
+
+ cmake_minimum_required(VERSION 3.3)
+ project(Tutorial)
+
+ set(CMAKE_CXX_STANDARD 11)
+ set(CMAKE_CXX_STANDARD_REQUIRED True)
+
+ # the version number.
+ set(Tutorial_VERSION_MAJOR 1)
+ set(Tutorial_VERSION_MINOR 0)
+
+ # configure a header file to pass some of the CMake settings
+ # to the source code
+ configure_file(
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ )
+
+ # should we use our own math functions
+ option(USE_MYMATH "Use tutorial provided math implementation" ON)
+
+ # add the MathFunctions library?
+ if(USE_MYMATH)
+ add_subdirectory(MathFunctions)
+ list(APPEND EXTRA_LIBS MathFunctions)
+ list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")
+ endif(USE_MYMATH)
+
+ # add the executable
+ add_executable(Tutorial tutorial.cxx)
+
+ target_link_libraries(Tutorial ${EXTRA_LIBS})
+
+ # add the binary tree to the search path for include files
+ # so that we will find TutorialConfig.h
+ target_include_directories(Tutorial PUBLIC
+ "${PROJECT_BINARY_DIR}"
+ ${EXTRA_INCLUDES}
+ )
+
+Note the use of the variables EXTRA_LIBS, and EXTRA_INCLUDES to collect
+up any optional libraries to later be linked into the executable. This is a
+classic approach when dealing with many optional components, we will cover the
+modern approach in the next step. For now the corresponding changes to the
+source code are fairly straightforward and leave us with:
+
+ #ifdef USE_MYMATH
+ double outputValue = mysqrt(inputValue);
+ #else
+ double outputValue = sqrt(inputValue);
+ #endif
+
+Since the source code now requires USE_MYMATH we can add it to the
+TutorialConfig.h.in. Simply add the following line:
+ #cmakedefine USE_MYMATH
+
+Run cmake or cmake-gui to configure the project and then build it with your
+chosen build tool and then run the built Tutorial executable.
+
+Which function gives better results, Step1’s sqrt or Step2’s mysqrt?
diff --git a/Tests/Tutorial/Step3/directions.txt b/Tests/Tutorial/Step3/directions.txt
new file mode 100644
index 000000000..54d031806
--- /dev/null
+++ b/Tests/Tutorial/Step3/directions.txt
@@ -0,0 +1,26 @@
+# Adding Usage Requirements for Library #
+
+Usage requirements allow for far better control over a library / executable's
+link and include line. While also giving more control over the transitive
+property of targets inside CMake. The primary commands that leverage usage
+requirements are:
+
+ - target_compile_definitions
+ - target_compile_options
+ - target_include_directories
+ - target_link_libraries
+
+First up is MathFunctions. We first state that anybody linking to MathFunctions
+needs to include the current source directory, while MathFunctions itself
+doesn't. So this can become an INTERFACE usage requirement.
+
+Remember INTERFACE means things that consumers require but the producer doesn't.
+
+ target_include_directories(MathFunctions
+ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})
+
+Now that we've specified usage requirements for MathFunctions we can safely remove
+our uses of the EXTRA_INCLUDES variable.
+
+Run cmake or cmake-gui to configure the project and then build it with your
+chosen build tool.
diff --git a/Tests/Tutorial/Step4/directions.txt b/Tests/Tutorial/Step4/directions.txt
new file mode 100644
index 000000000..91e4043da
--- /dev/null
+++ b/Tests/Tutorial/Step4/directions.txt
@@ -0,0 +1,72 @@
+# Installing and Testing #
+
+Now we can start adding testing support and install rules to our project.
+
+The install rules are fairly simple; for MathFunctions we install the library
+and header file, for the application we install the executable and configured
+header.
+
+So to MathFunctions/CMakeLists.txt we add:
+
+ install (TARGETS MathFunctions DESTINATION bin)
+ install (FILES MathFunctions.h DESTINATION include)
+
+And the to top-level CMakeLists.txt we add:
+
+ install(TARGETS Tutorial DESTINATION bin)
+ install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ DESTINATION include
+ )
+
+That is all that is needed to create a basic local install of the tutorial.
+
+Run cmake or cmake-gui to configure the project and then build it with your
+chosen build tool. Then build the “install” target by typing 'make install'
+from the command line or build the INSTALL target from an IDE. This will
+install the appropriate header files, libraries, and executables.
+
+Verify that the installed Tutorial runs. Note: The CMake variable
+CMAKE_INSTALL_PREFIX is used to determine the root of where the files will
+be installed.
+
+Next let's test our application. Adding testing is an easy process. At the
+end of the top-level CMakeLists file we can add a number of basic tests to
+verify that the application is working correctly.
+
+ # enable testing
+ enable_testing()
+
+ # does the application run
+ add_test(NAME Runs COMMAND Tutorial 25)
+
+ # does the usage message work?
+ add_test(NAME Usage COMMAND Tutorial)
+ set_tests_properties(Usage
+ PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
+ )
+
+ # define a function to simplify adding tests
+ function(do_test target arg result)
+ add_test(NAME Comp${arg} COMMAND ${target} ${arg})
+ set_tests_properties(Comp${arg}
+ PROPERTIES PASS_REGULAR_EXPRESSION ${result}
+ )
+ endfunction(do_test)
+
+ # do a bunch of result based tests
+ do_test(Tutorial 25 "25 is 5")
+ do_test(Tutorial -25 "-25 is [-nan|nan|0]")
+ do_test(Tutorial 0.0001 "0.0001 is 0.01")
+
+The first test simply verifies that the application runs, does not segfault or
+otherwise crash, and has a zero return value. This is the basic form of a CTest
+test.
+
+The Usage test uses a regular expression to verify that the usage message
+is printed when an incorrect number of arguments are provided.
+
+Lastly, we have a function called do_test that simplifies running the
+application and verifying that the computed square root is correct for given
+input.
+
+To run tests, cd to the binary directory and run “ctest -N” and “ctest -VV”.
diff --git a/Tests/Tutorial/Step5/directions.txt b/Tests/Tutorial/Step5/directions.txt
new file mode 100644
index 000000000..e6f51975c
--- /dev/null
+++ b/Tests/Tutorial/Step5/directions.txt
@@ -0,0 +1,69 @@
+# Adding System Introspection #
+
+Let us consider adding some code to our project that depends on features the
+target platform may not have. For this example, we will add some code that
+depends on whether or not the target platform has the log and exp functions. Of
+course almost every platform has these functions but for this tutorial assume
+that they are not common.
+
+If the platform has log and exp then we will use them to compute the square
+root in the mysqrt function. We first test for the availability of these
+functions using the CheckSymbolExists.cmake macro in the top-level CMakeLists
+file as follows:
+
+ # does this system provide the log and exp functions?
+ include(CheckSymbolExists)
+ set(CMAKE_REQUIRED_LIBRARIES "m")
+ check_symbol_exists(log "math.h" HAVE_LOG)
+ check_symbol_exists(exp "math.h" HAVE_EXP)
+
+Now let's add these defines to TutorialConfig.h.in so that we can use them
+from mysqrt.cxx:
+
+ // does the platform provide exp and log functions?
+ #cmakedefine HAVE_LOG
+ #cmakedefine HAVE_EXP
+
+Modify mysqrt.cxx to include math.h. Next, in the mysqrt function we can
+provide an alternate implementation based on log and exp if they are available
+on the system using the following code:
+
+ // if we have both log and exp then use them
+ #if defined(HAVE_LOG) && defined (HAVE_EXP)
+ double result = exp(log(x)*0.5);
+ std::cout << "Computing sqrt of " << x << " to be " << result << " using log" << std::endl;
+ #else
+ ...
+
+Run cmake or cmake-gui to configure the project and then build it with your
+chosen build tool.
+
+You will notice that even though HAVE_LOG and HAVE_EXP are both defined mysqrt
+isn't using them. We should realize quickly that we have forgotten to include
+TutorialConfig.h in mysqrt.cxx. We will also need to update
+MathFunctions/CMakeLists.txt with where it is located.
+
+So let's go ahead and update MathFunctions/CMakeLists.txt to look like:
+
+ add_library(MathFunctions mysqrt.cxx)
+
+ target_include_directories(MathFunctions
+ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
+ PRIVATE ${Tutorial_BINARY_DIR}
+ )
+
+ install(TARGETS MathFunctions DESTINATION lib)
+ install(FILES MathFunctions.h DESTINATION include)
+
+Now all we need to do is include TutorialConfig.h in mysqrt.cxx
+
+At this point you should go ahead and build the project again.
+
+Run the built Tutorial executable. Which function gives better results now,
+Step1’s sqrt or Step5’s mysqrt?
+
+Exercise: Why is it important that we configure TutorialConfig.h.in after the
+checks for HAVE_LOG and HAVE_EXP? What would happen if we inverted the two?
+
+Exercise: Is there a better place for us to save the HAVE_LOG and HAVE_EXP
+values other than in TutorialConfig.h?
diff --git a/Tests/Tutorial/Step6/directions.txt b/Tests/Tutorial/Step6/directions.txt
new file mode 100644
index 000000000..42b9f06df
--- /dev/null
+++ b/Tests/Tutorial/Step6/directions.txt
@@ -0,0 +1,104 @@
+# Adding a Custom Command and Generated File #
+
+In this section we will show how you can add a generated source file into the
+build process of an application. For this example, we will create a table of
+precomputed square roots as part of the build process, and then compile that
+table into our application.
+
+To accomplish this, we first need a program that will generate the table. In the
+MathFunctions subdirectory a new source file named MakeTable.cxx will do just that.
+
+ // A simple program that builds a sqrt table
+ #include <iostream>
+ #include <fstream>
+ #include <cmath>
+
+ int main (int argc, char *argv[])
+ {
+ // make sure we have enough arguments
+ if (argc < 2) {
+ return 1;
+ }
+
+ std::ofstream fout(argv[1],std::ios_base::out);
+ const bool fileOpen = fout.is_open();
+ if(fileOpen) {
+ fout << "double sqrtTable[] = {" << std::endl;
+ for (int i = 0; i < 10; ++i) {
+ fout << sqrt(static_cast<double>(i)) << "," << std::endl;
+ }
+ // close the table with a zero
+ fout << "0};" << std::endl;
+ fout.close();
+ }
+ return fileOpen ? 0 : 1; // return 0 if wrote the file
+ }
+
+Note that the table is produced as valid C++ code and that the output filename
+is passed in as an argument.
+
+The next step is to add the appropriate commands to MathFunctions’ CMakeLists
+file to build the MakeTable executable and then run it as part of the build
+process. A few commands are needed to accomplish this, as shown below:
+
+ # first we add the executable that generates the table
+ add_executable(MakeTable MakeTable.cxx)
+
+ # add the command to generate the source code
+ add_custom_command(
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ DEPENDS MakeTable
+ )
+
+ # add the main library
+ add_library(MathFunctions
+ mysqrt.cxx
+ ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ )
+
+ target_include_directories(MathFunctions
+ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
+ PUBLIC ${Tutorial_BINARY_DIR}
+ # add the binary tree directory to the search path for include files
+ ${CMAKE_CURRENT_BINARY_DIR}
+ )
+
+ install(TARGETS MathFunctions DESTINATION lib)
+ install(FILES MathFunctions.h DESTINATION include)
+
+First, the executable for MakeTable is added as any other executable would be
+added. Then we add a custom command that specifies how to produce Table.h by
+running MakeTable. Next we have to let CMake know that mysqrt.cxx depends on
+the generated file Table.h. This is done by adding the generated Table.h to the
+list of sources for the library MathFunctions. We also have to add the current
+binary directory to the list of include directories so that Table.h can be
+found and included by mysqrt.cxx.
+
+Now let's use the generated table. First, modify mysqrt.cxx to include Table.h.
+Next, we can rewrite the mysqrt function to use the table:
+
+ if (x <= 0) {
+ return 0;
+ }
+
+ // use the table to help find an initial value
+ double result = x;
+ if (x >= 1 && x < 10) {
+ result = sqrtTable[static_cast<int>(x)];
+ }
+
+ // do ten iterations
+ for (int i = 0; i < 10; ++i) {
+ if (result <= 0) {
+ result = 0.1;
+ }
+ double delta = x - (result*result);
+ result = result + 0.5*delta/result;
+ std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
+ }
+
+Run cmake or cmake-gui to configure the project and then build it with your
+chosen build tool. When this project is built it will first build the MakeTable
+executable. It will then run MakeTable to produce Table.h. Finally, it will
+compile mysqrt.cxx which includes Table.h to produce the MathFunctions library.
diff --git a/Tests/Tutorial/Step7/directions.txt b/Tests/Tutorial/Step7/directions.txt
new file mode 100644
index 000000000..7d7c2eacd
--- /dev/null
+++ b/Tests/Tutorial/Step7/directions.txt
@@ -0,0 +1,40 @@
+# Building an Installer #
+
+Next suppose that we want to distribute our project to other people so that they
+can use it. We want to provide both binary and source distributions on a variety
+of platforms. This is a little different from the install we did previously in
+the Installing and Testing section (Step 4), where we were installing the
+binaries that we had built from the source code. In this example we will be
+building installation packages that support binary installations and package
+management features. To accomplish this we will use CPack to create platform
+specific installers. Specifically we need to add a few lines to the bottom of
+our top-level CMakeLists.txt file.
+
+ include(InstallRequiredSystemLibraries)
+ set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
+ set(CPACK_PACKAGE_VERSION_MAJOR "${Tutorial_VERSION_MAJOR}")
+ set(CPACK_PACKAGE_VERSION_MINOR "${Tutorial_VERSION_MINOR}")
+ include(CPack)
+
+That is all there is to it. We start by including InstallRequiredSystemLibraries.
+This module will include any runtime libraries that are needed by the project
+for the current platform. Next we set some CPack variables to where we have
+stored the license and version information for this project. The version
+information makes use of the variables we set earlier in this tutorial. Finally
+we include the CPack module which will use these variables and some other
+properties of the system you are on to setup an installer.
+
+The next step is to build the project in the usual manner and then run CPack
+on it. To build a binary distribution you would run:
+
+ cpack
+
+To create a source distribution you would type:
+
+ cpack -C CPackSourceConfig.cmake
+
+Alternatively, run “make package” or right click the Package target and
+“Build Project” from an IDE.
+
+Run the installer executable found in the binary directory. Then run the
+installed executable and verify that it works.
diff --git a/Tests/Tutorial/Step8/CMakeLists.txt b/Tests/Tutorial/Step8/CMakeLists.txt
new file mode 100644
index 000000000..c66bf96e3
--- /dev/null
+++ b/Tests/Tutorial/Step8/CMakeLists.txt
@@ -0,0 +1,82 @@
+cmake_minimum_required(VERSION 3.3)
+project(Tutorial)
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED True)
+
+# the version number.
+set(Tutorial_VERSION_MAJOR 1)
+set(Tutorial_VERSION_MINOR 0)
+
+# does this system provide the log and exp functions?
+include(CheckSymbolExists)
+set(CMAKE_REQUIRED_LIBRARIES "m")
+check_symbol_exists(log "math.h" HAVE_LOG)
+check_symbol_exists(exp "math.h" HAVE_EXP)
+
+# should we use our own math functions
+option(USE_MYMATH "Use tutorial provided math implementation" ON)
+
+# configure a header file to pass some of the CMake settings
+# to the source code
+configure_file(
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ )
+
+# add the MathFunctions library?
+if(USE_MYMATH)
+ add_subdirectory(MathFunctions)
+ list(APPEND EXTRA_LIBS MathFunctions)
+endif(USE_MYMATH)
+
+# add the executable
+add_executable(Tutorial tutorial.cxx)
+target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS})
+
+# add the binary tree to the search path for include files
+# so that we will find TutorialConfig.h
+target_include_directories(Tutorial PUBLIC
+ "${PROJECT_BINARY_DIR}"
+ )
+
+# add the install targets
+install(TARGETS Tutorial DESTINATION bin)
+install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ DESTINATION include
+ )
+
+# enable testing
+enable_testing()
+
+# does the application run
+add_test(NAME Runs COMMAND Tutorial 25)
+
+# does the usage message work?
+add_test(NAME Usage COMMAND Tutorial)
+set_tests_properties(Usage
+ PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
+ )
+
+# define a function to simplify adding tests
+function(do_test target arg result)
+add_test(NAME Comp${arg} COMMAND ${target} ${arg})
+ set_tests_properties(Comp${arg}
+ PROPERTIES PASS_REGULAR_EXPRESSION ${result}
+ )
+endfunction(do_test)
+
+# do a bunch of result based tests
+do_test(Tutorial 4 "4 is 2")
+do_test(Tutorial 9 "9 is 3")
+do_test(Tutorial 5 "5 is 2.236")
+do_test(Tutorial 7 "7 is 2.645")
+do_test(Tutorial 25 "25 is 5")
+do_test(Tutorial -25 "-25 is [-nan|nan|0]")
+do_test(Tutorial 0.0001 "0.0001 is 0.01")
+
+include(InstallRequiredSystemLibraries)
+set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
+set(CPACK_PACKAGE_VERSION_MAJOR "${Tutorial_VERSION_MAJOR}")
+set(CPACK_PACKAGE_VERSION_MINOR "${Tutorial_VERSION_MINOR}")
+include(CPack)
diff --git a/Tests/Tutorial/Step8/License.txt b/Tests/Tutorial/Step8/License.txt
new file mode 100644
index 000000000..c62d00b9e
--- /dev/null
+++ b/Tests/Tutorial/Step8/License.txt
@@ -0,0 +1,2 @@
+This is the open source License.txt file introduced in
+CMake/Tutorial/Step7...
diff --git a/Tests/Tutorial/Step8/MathFunctions/CMakeLists.txt b/Tests/Tutorial/Step8/MathFunctions/CMakeLists.txt
new file mode 100644
index 000000000..dc3eb9822
--- /dev/null
+++ b/Tests/Tutorial/Step8/MathFunctions/CMakeLists.txt
@@ -0,0 +1,29 @@
+# first we add the executable that generates the table
+add_executable(MakeTable MakeTable.cxx)
+
+# add the command to generate the source code
+add_custom_command(
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ DEPENDS MakeTable
+ )
+
+# add the main library
+add_library(MathFunctions
+ mysqrt.cxx
+ ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ )
+
+# state that anybody linking to us needs to include the current source dir
+# to find MathFunctions.h, while we don't.
+# state that we depend on Tutorial_BINARY_DIR but consumers don't, as the
+# TutorialConfig.h include is an implementation detail
+# state that we depend on our binary dir to find Table.h
+target_include_directories(MathFunctions
+ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
+ PRIVATE ${Tutorial_BINARY_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ )
+
+install(TARGETS MathFunctions DESTINATION lib)
+install(FILES MathFunctions.h DESTINATION include)
diff --git a/Tests/Tutorial/Step8/MathFunctions/MakeTable.cxx b/Tests/Tutorial/Step8/MathFunctions/MakeTable.cxx
new file mode 100644
index 000000000..ee585568c
--- /dev/null
+++ b/Tests/Tutorial/Step8/MathFunctions/MakeTable.cxx
@@ -0,0 +1,25 @@
+// A simple program that builds a sqrt table
+#include <cmath>
+#include <fstream>
+#include <iostream>
+
+int main(int argc, char* argv[])
+{
+ // make sure we have enough arguments
+ if (argc < 2) {
+ return 1;
+ }
+
+ std::ofstream fout(argv[1], std::ios_base::out);
+ const bool fileOpen = fout.is_open();
+ if (fileOpen) {
+ fout << "double sqrtTable[] = {" << std::endl;
+ for (int i = 0; i < 10; ++i) {
+ fout << sqrt(static_cast<double>(i)) << "," << std::endl;
+ }
+ // close the table with a zero
+ fout << "0};" << std::endl;
+ fout.close();
+ }
+ return fileOpen ? 0 : 1; // return 0 if wrote the file
+}
diff --git a/Tests/Tutorial/Step8/MathFunctions/MathFunctions.h b/Tests/Tutorial/Step8/MathFunctions/MathFunctions.h
new file mode 100644
index 000000000..cd36bccff
--- /dev/null
+++ b/Tests/Tutorial/Step8/MathFunctions/MathFunctions.h
@@ -0,0 +1 @@
+double mysqrt(double x);
diff --git a/Tests/Tutorial/Step8/MathFunctions/mysqrt.cxx b/Tests/Tutorial/Step8/MathFunctions/mysqrt.cxx
new file mode 100644
index 000000000..5b862fbd5
--- /dev/null
+++ b/Tests/Tutorial/Step8/MathFunctions/mysqrt.cxx
@@ -0,0 +1,42 @@
+#include "MathFunctions.h"
+#include "TutorialConfig.h"
+#include <iostream>
+
+// include the generated table
+#include "Table.h"
+
+#include <cmath>
+
+// a hack square root calculation using simple operations
+double mysqrt(double x)
+{
+ if (x <= 0) {
+ return 0;
+ }
+
+ // if we have both log and exp then use them
+#if defined(HAVE_LOG) && defined(HAVE_EXP)
+ double result = exp(log(x) * 0.5);
+ std::cout << "Computing sqrt of " << x << " to be " << result << " using log"
+ << std::endl;
+#else
+ // use the table to help find an initial value
+ double result = x;
+ if (x >= 1 && x < 10) {
+ result = sqrtTable[static_cast<int>(x)];
+ }
+
+ // if we have both log and exp then use them
+
+ // do ten iterations
+ for (int i = 0; i < 10; ++i) {
+ if (result <= 0) {
+ result = 0.1;
+ }
+ double delta = x - (result * result);
+ result = result + 0.5 * delta / result;
+ std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
+ }
+#endif
+ return result;
+}
diff --git a/Tests/Tutorial/Step8/TutorialConfig.h.in b/Tests/Tutorial/Step8/TutorialConfig.h.in
new file mode 100644
index 000000000..e97ce24ea
--- /dev/null
+++ b/Tests/Tutorial/Step8/TutorialConfig.h.in
@@ -0,0 +1,8 @@
+// the configured options and settings for Tutorial
+#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
+#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
+#cmakedefine USE_MYMATH
+
+// does the platform provide exp and log functions?
+#cmakedefine HAVE_LOG
+#cmakedefine HAVE_EXP
diff --git a/Tests/Tutorial/Step8/directions.txt b/Tests/Tutorial/Step8/directions.txt
new file mode 100644
index 000000000..588d9c679
--- /dev/null
+++ b/Tests/Tutorial/Step8/directions.txt
@@ -0,0 +1,38 @@
+# Adding Support for a Dashboard #
+
+Adding support for submitting our test results to a dashboard is very easy. We
+already defined a number of tests for our project in the earlier steps of this
+tutorial. We just have to run those tests and submit them to a dashboard. To
+include support for dashboards we include the CTest module in our top-level
+CMakeLists.txt.
+
+Replace:
+ # enable testing
+ enable_testing()
+
+With:
+ # enable dashboard scripting
+ include(CTest)
+
+The CTest module will automatically call enable_testing(), so
+we can remove it from our CMake files.
+
+We will also need to create a CTestConfig.cmake file where we can specify the
+name of the project and where to submit the dashboard.
+
+ set(CTEST_PROJECT_NAME "CMakeTutorial")
+ set(CTEST_NIGHTLY_START_TIME "01:00:00 UTC")
+
+ set(CTEST_DROP_METHOD "http")
+ set(CTEST_DROP_SITE "my.cdash.org/")
+ set(CTEST_DROP_LOCATION "/submit.php?project=CMakeTutorial")
+ set(CTEST_DROP_SITE_CDASH TRUE)
+
+CTest will read in this file when it runs. To create a simple dashboard you can
+run cmake or cmake-gui to configure the project, but do not build it yet.
+Instead, change directory to the binary tree, and then run:
+ 'ctest [-VV] –D Experimental'. On Windows, build the EXPERIMENTAL target.
+
+Ctest will build and test the project and submit results to the Kitware public
+dashboard. The results of your dashboard will be uploaded to Kitware's public
+dashboard here: https://my.cdash.org/index.php?project=CMakeTutorial.
diff --git a/Tests/Tutorial/Step8/tutorial.cxx b/Tests/Tutorial/Step8/tutorial.cxx
new file mode 100644
index 000000000..1d5742d2d
--- /dev/null
+++ b/Tests/Tutorial/Step8/tutorial.cxx
@@ -0,0 +1,32 @@
+// A simple program that computes the square root of a number
+#include <cmath>
+#include <iostream>
+#include <string>
+
+#include "TutorialConfig.h"
+
+#ifdef USE_MYMATH
+# include "MathFunctions.h"
+#endif
+
+int main(int argc, char* argv[])
+{
+ if (argc < 2) {
+ std::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."
+ << Tutorial_VERSION_MAJOR << std::endl;
+ std::cout << "Usage: " << argv[0] << " number" << std::endl;
+ return 1;
+ }
+
+ double inputValue = std::stod(argv[1]);
+
+#ifdef USE_MYMATH
+ double outputValue = mysqrt(inputValue);
+#else
+ double outputValue = sqrt(inputValue);
+#endif
+
+ std::cout << "The square root of " << inputValue << " is " << outputValue
+ << std::endl;
+ return 0;
+}
diff --git a/Tests/Tutorial/Step9/CMakeLists.txt b/Tests/Tutorial/Step9/CMakeLists.txt
new file mode 100644
index 000000000..309d513ff
--- /dev/null
+++ b/Tests/Tutorial/Step9/CMakeLists.txt
@@ -0,0 +1,81 @@
+cmake_minimum_required(VERSION 3.3)
+project(Tutorial)
+
+set(CMAKE_CXX_STANDARD 11)
+set(CMAKE_CXX_STANDARD_REQUIRED True)
+
+# the version number.
+set(Tutorial_VERSION_MAJOR 1)
+set(Tutorial_VERSION_MINOR 0)
+
+# does this system provide the log and exp functions?
+include(CheckSymbolExists)
+set(CMAKE_REQUIRED_LIBRARIES "m")
+check_symbol_exists(log "math.h" HAVE_LOG)
+check_symbol_exists(exp "math.h" HAVE_EXP)
+
+# should we use our own math functions
+option(USE_MYMATH "Use tutorial provided math implementation" ON)
+
+# configure a header file to pass the version number only
+configure_file(
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ )
+
+# add the MathFunctions library?
+if(USE_MYMATH)
+ add_subdirectory(MathFunctions)
+ list(APPEND EXTRA_LIBS MathFunctions)
+endif()
+
+# add the executable
+add_executable(Tutorial tutorial.cxx)
+target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS})
+
+# add the binary tree to the search path for include files
+# so that we will find TutorialConfig.h
+target_include_directories(Tutorial PUBLIC
+ "${PROJECT_BINARY_DIR}"
+ )
+
+# add the install targets
+install(TARGETS Tutorial DESTINATION bin)
+install(FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ DESTINATION include
+ )
+
+# enable testing
+include(CTest)
+
+# does the application run
+add_test(NAME Runs COMMAND Tutorial 25)
+
+# does the usage message work?
+add_test(NAME Usage COMMAND Tutorial)
+set_tests_properties(Usage
+ PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number"
+ )
+
+# define a function to simplify adding tests
+function(do_test target arg result)
+ add_test(NAME Comp${arg} COMMAND ${target} ${arg})
+ set_tests_properties(Comp${arg}
+ PROPERTIES PASS_REGULAR_EXPRESSION ${result}
+ )
+endfunction(do_test)
+
+# do a bunch of result based tests
+do_test(Tutorial 4 "4 is 2")
+do_test(Tutorial 9 "9 is 3")
+do_test(Tutorial 5 "5 is 2.236")
+do_test(Tutorial 7 "7 is 2.645")
+do_test(Tutorial 25 "25 is 5")
+do_test(Tutorial -25 "-25 is [-nan|nan|0]")
+do_test(Tutorial 0.0001 "0.0001 is 0.01")
+
+include(InstallRequiredSystemLibraries)
+set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
+set(CPACK_PACKAGE_VERSION_MAJOR "${Tutorial_VERSION_MAJOR}")
+set(CPACK_PACKAGE_VERSION_MINOR "${Tutorial_VERSION_MINOR}")
+include(CPack)
diff --git a/Tests/Tutorial/Step9/CTestConfig.cmake b/Tests/Tutorial/Step9/CTestConfig.cmake
new file mode 100644
index 000000000..7a927ac94
--- /dev/null
+++ b/Tests/Tutorial/Step9/CTestConfig.cmake
@@ -0,0 +1,15 @@
+## This file should be placed in the root directory of your project.
+## Then modify the CMakeLists.txt file in the root directory of your
+## project to incorporate the testing dashboard.
+##
+## # The following are required to submit to the CDash dashboard:
+## ENABLE_TESTING()
+## INCLUDE(CTest)
+
+set(CTEST_PROJECT_NAME "CMakeTutorial")
+set(CTEST_NIGHTLY_START_TIME "00:00:00 EST")
+
+set(CTEST_DROP_METHOD "http")
+set(CTEST_DROP_SITE "my.cdash.org")
+set(CTEST_DROP_LOCATION "/submit.php?project=CMakeTutorial")
+set(CTEST_DROP_SITE_CDASH TRUE)
diff --git a/Tests/Tutorial/Step9/License.txt b/Tests/Tutorial/Step9/License.txt
new file mode 100644
index 000000000..c62d00b9e
--- /dev/null
+++ b/Tests/Tutorial/Step9/License.txt
@@ -0,0 +1,2 @@
+This is the open source License.txt file introduced in
+CMake/Tutorial/Step7...
diff --git a/Tests/Tutorial/Step9/MathFunctions/CMakeLists.txt b/Tests/Tutorial/Step9/MathFunctions/CMakeLists.txt
new file mode 100644
index 000000000..e651a5748
--- /dev/null
+++ b/Tests/Tutorial/Step9/MathFunctions/CMakeLists.txt
@@ -0,0 +1,35 @@
+# first we add the executable that generates the table
+add_executable(MakeTable MakeTable.cxx)
+
+# add the command to generate the source code
+add_custom_command(
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ DEPENDS MakeTable
+ )
+
+# add the main library
+add_library(MathFunctions
+ mysqrt.cxx
+ ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ )
+
+# state that anybody linking to us needs to include the current source dir
+# to find MathFunctions.h, while we don't.
+# state that we depend on our binary dir to find Table.h
+target_include_directories(MathFunctions
+ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
+ PRIVATE ${CMAKE_CURRENT_BINARY_DIR}
+ )
+
+# use compile definitions to state if we have enabled USE_MYMATH
+# and that anything that links to use will get this define
+target_compile_definitions(MathFunctions INTERFACE "USE_MYMATH")
+
+if(HAVE_LOG AND HAVE_EXP)
+ target_compile_definitions(MathFunctions
+ PRIVATE "HAVE_LOG" "HAVE_EXP")
+endif()
+
+install(TARGETS MathFunctions DESTINATION lib)
+install(FILES MathFunctions.h DESTINATION include)
diff --git a/Tests/Tutorial/Step9/MathFunctions/MakeTable.cxx b/Tests/Tutorial/Step9/MathFunctions/MakeTable.cxx
new file mode 100644
index 000000000..ee585568c
--- /dev/null
+++ b/Tests/Tutorial/Step9/MathFunctions/MakeTable.cxx
@@ -0,0 +1,25 @@
+// A simple program that builds a sqrt table
+#include <cmath>
+#include <fstream>
+#include <iostream>
+
+int main(int argc, char* argv[])
+{
+ // make sure we have enough arguments
+ if (argc < 2) {
+ return 1;
+ }
+
+ std::ofstream fout(argv[1], std::ios_base::out);
+ const bool fileOpen = fout.is_open();
+ if (fileOpen) {
+ fout << "double sqrtTable[] = {" << std::endl;
+ for (int i = 0; i < 10; ++i) {
+ fout << sqrt(static_cast<double>(i)) << "," << std::endl;
+ }
+ // close the table with a zero
+ fout << "0};" << std::endl;
+ fout.close();
+ }
+ return fileOpen ? 0 : 1; // return 0 if wrote the file
+}
diff --git a/Tests/Tutorial/Step9/MathFunctions/MathFunctions.cxx b/Tests/Tutorial/Step9/MathFunctions/MathFunctions.cxx
new file mode 100644
index 000000000..5351184be
--- /dev/null
+++ b/Tests/Tutorial/Step9/MathFunctions/MathFunctions.cxx
@@ -0,0 +1,18 @@
+
+#include "MathFunctions.h"
+#include <cmath>
+
+#ifdef USE_MYMATH
+# include "mysqrt.h"
+#endif
+
+namespace mathfunctions {
+double sqrt(double x)
+{
+#ifdef USE_MYMATH
+ return detail::mysqrt(x);
+#else
+ return std::sqrt(x);
+#endif
+}
+}
diff --git a/Tests/Tutorial/Step9/MathFunctions/MathFunctions.h b/Tests/Tutorial/Step9/MathFunctions/MathFunctions.h
new file mode 100644
index 000000000..cd36bccff
--- /dev/null
+++ b/Tests/Tutorial/Step9/MathFunctions/MathFunctions.h
@@ -0,0 +1 @@
+double mysqrt(double x);
diff --git a/Tests/Tutorial/Step9/MathFunctions/mysqrt.cxx b/Tests/Tutorial/Step9/MathFunctions/mysqrt.cxx
new file mode 100644
index 000000000..8b8214151
--- /dev/null
+++ b/Tests/Tutorial/Step9/MathFunctions/mysqrt.cxx
@@ -0,0 +1,41 @@
+#include "MathFunctions.h"
+#include <iostream>
+
+// include the generated table
+#include "Table.h"
+
+#include <cmath>
+
+// a hack square root calculation using simple operations
+double mysqrt(double x)
+{
+ if (x <= 0) {
+ return 0;
+ }
+
+ // if we have both log and exp then use them
+#if defined(HAVE_LOG) && defined(HAVE_EXP)
+ double result = exp(log(x) * 0.5);
+ std::cout << "Computing sqrt of " << x << " to be " << result << " using log"
+ << std::endl;
+#else
+ // use the table to help find an initial value
+ double result = x;
+ if (x >= 1 && x < 10) {
+ result = sqrtTable[static_cast<int>(x)];
+ }
+
+ // if we have both log and exp then use them
+
+ // do ten iterations
+ for (int i = 0; i < 10; ++i) {
+ if (result <= 0) {
+ result = 0.1;
+ }
+ double delta = x - (result * result);
+ result = result + 0.5 * delta / result;
+ std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
+ }
+#endif
+ return result;
+}
diff --git a/Tests/Tutorial/Step9/MathFunctions/mysqrt.h b/Tests/Tutorial/Step9/MathFunctions/mysqrt.h
new file mode 100644
index 000000000..e1c42ef0c
--- /dev/null
+++ b/Tests/Tutorial/Step9/MathFunctions/mysqrt.h
@@ -0,0 +1,6 @@
+
+namespace mathfunctions {
+namespace detail {
+double mysqrt(double x);
+}
+}
diff --git a/Tests/Tutorial/Step9/TutorialConfig.h.in b/Tests/Tutorial/Step9/TutorialConfig.h.in
new file mode 100644
index 000000000..8cd2fc9c6
--- /dev/null
+++ b/Tests/Tutorial/Step9/TutorialConfig.h.in
@@ -0,0 +1,3 @@
+// the configured version number
+#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
+#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
diff --git a/Tests/Tutorial/Step9/directions.txt b/Tests/Tutorial/Step9/directions.txt
new file mode 100644
index 000000000..8771637d2
--- /dev/null
+++ b/Tests/Tutorial/Step9/directions.txt
@@ -0,0 +1,166 @@
+# Mixing Static and Shared #
+
+In this section we will show how by using the BUILD_SHARED_LIBS variable we can
+control the default behavior of add_library, and allow control over how
+libraries without an explicit type ( STATIC/SHARED/MODULE/OBJECT ) are built.
+
+To accomplish this we need to add BUILD_SHARED_LIBS to the top level
+CMakeLists.txt. We use the option command as it allows users to optionally
+select if the value should be On or Off.
+
+Next we are going to refactor MathFunctions to become a real library that
+encapsulates using mysqrt or sqrt, instead of requiring the calling code
+to do this logic. This will also mean that USE_MYMATH will not control building
+MathFuctions, but instead will control the behavior of this library.
+
+The first step is to update the starting section of the top level CMakeLists.txt
+to look like:
+
+ cmake_minimum_required(VERSION 3.3)
+ project(Tutorial)
+
+ # control where the static and shared libraries are built so that on windows
+ # we don't need to tinker with the path to run the executable
+ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}")
+
+ set(CMAKE_CXX_STANDARD 11)
+ set(CMAKE_CXX_STANDARD_REQUIRED True)
+
+ option(BUILD_SHARED_LIBS "Build using shared libraries" ON)
+
+ # the version number.
+ set(Tutorial_VERSION_MAJOR 1)
+ set(Tutorial_VERSION_MINOR 0)
+
+ # configure a header file to pass the version number only
+ configure_file(
+ "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
+ "${PROJECT_BINARY_DIR}/TutorialConfig.h"
+ )
+
+ # add the MathFunctions library
+ add_subdirectory(MathFunctions)
+
+ # add the executable
+ add_executable(Tutorial tutorial.cxx)
+ target_link_libraries(Tutorial PUBLIC MathFunctions)
+
+Now that we have made MathFunctions always be used, we will need to update
+the logic of that library. So, in MathFunctions/CMakeLists.txt we need to
+create a SqrtLibrary that will conditionally be built when USE_MYMATH is
+enabled. Now, since this is a tutorial, we are going to explicitly require
+that SqrtLibrary is built statically.
+
+The end result is that MathFunctions/CMakeLists.txt should look like:
+
+ # add the library that runs
+ add_library(MathFunctions MathFunctions.cxx)
+
+ # state that anybody linking to us needs to include the current source dir
+ # to find MathFunctions.h, while we don't.
+ target_include_directories(MathFunctions
+ INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
+ )
+
+ # should we use our own math functions
+ option(USE_MYMATH "Use tutorial provided math implementation" ON)
+ if(USE_MYMATH)
+
+ # does this system provide the log and exp functions?
+ include(CheckSymbolExists)
+ set(CMAKE_REQUIRED_LIBRARIES "m")
+ check_symbol_exists(log "math.h" HAVE_LOG)
+ check_symbol_exists(exp "math.h" HAVE_EXP)
+
+ # first we add the executable that generates the table
+ add_executable(MakeTable MakeTable.cxx)
+
+ # add the command to generate the source code
+ add_custom_command(
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ DEPENDS MakeTable
+ )
+
+ # library that just does sqrt
+ add_library(SqrtLibrary STATIC
+ mysqrt.cxx
+ ${CMAKE_CURRENT_BINARY_DIR}/Table.h
+ )
+
+ # state that we depend on our binary dir to find Table.h
+ target_include_directories(SqrtLibrary PRIVATE
+ ${CMAKE_CURRENT_BINARY_DIR}
+ )
+
+ target_compile_definitions(MathFunctions PRIVATE "USE_MYMATH")
+ if(HAVE_LOG AND HAVE_EXP)
+ target_compile_definitions(SqrtLibrary
+ PRIVATE "HAVE_LOG" "HAVE_EXP")
+ endif()
+
+ target_link_libraries(MathFunctions PRIVATE SqrtLibrary)
+ endif()
+
+ # define the symbol stating we are using the declspec(dllexport) when
+ # building on windows
+ target_compile_definitions(MathFunctions PRIVATE "EXPORTING_MYMATH")
+
+ install(TARGETS MathFunctions DESTINATION lib)
+ install(FILES MathFunctions.h DESTINATION include)
+
+Next, update MathFunctions/mysqrt.cxx to use the mathfunctions and detail namespaces:
+
+ #include <iostream>
+ #include "MathFunctions.h"
+
+ // include the generated table
+ #include "Table.h"
+
+ #include <cmath>
+
+ namespace mathfunctions {
+ namespace detail {
+ // a hack square root calculation using simple operations
+ double mysqrt(double x)
+ {
+ ...
+
+ return result;
+ }
+ }
+ }
+
+We also need to make some changes in tutorial.cxx, so that it no longer uses USE_MYMATH:
+1. Always include MathFunctions.h
+2. Always use mathfunctions::sqrt
+
+Finally, update MathFunctions/MathFunctions.h to use dll export defines:
+
+ #if defined(_WIN32)
+ #if defined(EXPORTING_MYMATH)
+ #define DECLSPEC __declspec(dllexport)
+ #else
+ #define DECLSPEC __declspec(dllimport)
+ #endif
+ #else //non windows
+ #define DECLSPEC
+ #endif
+
+ namespace mathfunctions
+ {
+ double DECLSPEC sqrt(double x);
+ }
+
+At this point, if you build everything, you will notice that linking fails
+as we are combining a static library without position enabled code with a
+library that has position enabled code. This solution to this is to explicitly
+set the POSITION_INDEPENDENT_CODE target property of SqrtLibrary to be True no
+matter the build type.
+
+Exercise: We modified MathFunctions.h to use dll export defines. Using CMake
+documentation can you find a helper module to simplify this?
+
+Exercise: Determine what command is enabling PIC for SqrtLibrary.
+What happens if we remove said command?
diff --git a/Tests/Tutorial/Step9/tutorial.cxx b/Tests/Tutorial/Step9/tutorial.cxx
new file mode 100644
index 000000000..73e67a9c0
--- /dev/null
+++ b/Tests/Tutorial/Step9/tutorial.cxx
@@ -0,0 +1,33 @@
+// A simple program that computes the square root of a number
+#include <cmath>
+#include <iostream>
+#include <sstream>
+#include <string>
+
+#include "TutorialConfig.h"
+
+#ifdef USE_MYMATH
+# include "MathFunctions.h"
+#endif
+
+int main(int argc, char* argv[])
+{
+ if (argc < 2) {
+ std::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."
+ << Tutorial_VERSION_MAJOR << std::endl;
+ std::cout << "Usage: " << argv[0] << " number" << std::endl;
+ return 1;
+ }
+
+ double inputValue = std::stod(argv[1]);
+
+#ifdef USE_MYMATH
+ double outputValue = mysqrt(inputValue);
+#else
+ double outputValue = sqrt(inputValue);
+#endif
+
+ std::cout << "The square root of " << inputValue << " is " << outputValue
+ << std::endl;
+ return 0;
+}
diff --git a/Tests/UseSWIG/AlternateLibraryName/CMakeLists.txt b/Tests/UseSWIG/AlternateLibraryName/CMakeLists.txt
new file mode 100644
index 000000000..a2c239cbd
--- /dev/null
+++ b/Tests/UseSWIG/AlternateLibraryName/CMakeLists.txt
@@ -0,0 +1,35 @@
+cmake_minimum_required(VERSION 3.14...3.15)
+
+project(TestAlternateLibraryName CXX)
+
+include(CTest)
+
+find_package(SWIG REQUIRED)
+include(${SWIG_USE_FILE})
+
+find_package(Python2 REQUIRED COMPONENTS Interpreter Development)
+
+# Path separator
+if (WIN32)
+ set (PS "$<SEMICOLON>")
+else()
+ set (PS ":")
+endif()
+
+unset(CMAKE_SWIG_FLAGS)
+
+set_property(SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/../example.i" PROPERTY CPLUSPLUS ON)
+set_property(SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/../example.i" PROPERTY COMPILE_OPTIONS -includeall)
+
+swig_add_library(example_python
+ LANGUAGE python
+ SOURCES ../example.i ../example.cxx)
+set_target_properties (example_python PROPERTIES
+ INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/.."
+ SWIG_USE_TARGET_INCLUDE_DIRECTORIES TRUE)
+target_link_libraries(example_python PRIVATE Python2::Python)
+
+
+add_test (NAME AlternateLibraryName.example1
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}${PS}$<TARGET_FILE_DIR:example_python>"
+ "${Python2_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py")
diff --git a/Tests/UseSWIG/BasicConfiguration.cmake b/Tests/UseSWIG/BasicConfiguration.cmake
new file mode 100644
index 000000000..fd3ac4031
--- /dev/null
+++ b/Tests/UseSWIG/BasicConfiguration.cmake
@@ -0,0 +1,83 @@
+
+find_package(SWIG REQUIRED)
+include(${SWIG_USE_FILE})
+
+# Path separator
+if (WIN32)
+ set (PS "$<SEMICOLON>")
+else()
+ set (PS ":")
+endif()
+
+unset(SWIG_LANG_TYPE)
+unset(SWIG_LANG_INCLUDE_DIRECTORIES)
+unset(SWIG_LANG_DEFINITIONS)
+unset(SWIG_LANG_OPTIONS)
+unset(SWIG_LANG_LIBRARIES)
+
+if(${language} MATCHES csharp)
+ set(SWIG_LANG_TYPE TYPE SHARED)
+endif()
+if(${language} MATCHES python)
+ find_package(Python REQUIRED COMPONENTS Interpreter Development)
+ set(SWIG_LANG_INCLUDE_DIRECTORIES ${Python_INCLUDE_DIRS})
+ set(SWIG_LANG_LIBRARIES ${Python_LIBRARIES})
+endif()
+if(${language} MATCHES perl)
+ find_package(Perl REQUIRED)
+ find_package(PerlLibs REQUIRED)
+ set(SWIG_LANG_INCLUDE_DIRECTORIES ${PERL_INCLUDE_PATH})
+ separate_arguments(c_flags UNIX_COMMAND "${PERL_EXTRA_C_FLAGS}")
+ set(SWIG_LANG_OPTIONS ${c_flags})
+ set(SWIG_LANG_LIBRARIES ${PERL_LIBRARY})
+endif()
+if(${language} MATCHES tcl)
+ find_package(TCL REQUIRED)
+ set(SWIG_LANG_INCLUDE_DIRECTORIES ${TCL_INCLUDE_PATH})
+ set(SWIG_LANG_LIBRARIES ${TCL_LIBRARY})
+endif()
+if(${language} MATCHES ruby)
+ find_package(Ruby REQUIRED)
+ set(SWIG_LANG_INCLUDE_DIRECTORIES ${RUBY_INCLUDE_PATH})
+ set(SWIG_LANG_LIBRARIES ${RUBY_LIBRARY})
+endif()
+if(${language} MATCHES php4)
+ find_package(PHP4 REQUIRED)
+ set(SWIG_LANG_INCLUDE_DIRECTORIES ${PHP4_INCLUDE_PATH})
+ set(SWIG_LANG_LIBRARIES ${PHP4_LIBRARY})
+endif()
+if(${language} MATCHES pike)
+ find_package(Pike REQUIRED)
+ set(SWIG_LANG_INCLUDE_DIRECTORIES ${PIKE_INCLUDE_PATH})
+ set(SWIG_LANG_LIBRARIES ${PIKE_LIBRARY})
+endif()
+if(${language} MATCHES lua)
+ find_package(Lua REQUIRED)
+ set(SWIG_LANG_INCLUDE_DIRECTORIES ${LUA_INCLUDE_DIR})
+ set(SWIG_LANG_TYPE TYPE SHARED)
+ set(SWIG_LANG_LIBRARIES ${LUA_LIBRARIES})
+endif()
+
+unset(CMAKE_SWIG_FLAGS)
+
+set (CMAKE_INCLUDE_CURRENT_DIR ON)
+
+set_property(SOURCE "${CMAKE_CURRENT_LIST_DIR}/example.i" PROPERTY CPLUSPLUS ON)
+set_property(SOURCE "${CMAKE_CURRENT_LIST_DIR}/example.i" PROPERTY COMPILE_OPTIONS -includeall)
+
+set_property(SOURCE "${CMAKE_CURRENT_LIST_DIR}/example.i"
+ PROPERTY GENERATED_INCLUDE_DIRECTORIES ${SWIG_LANG_INCLUDE_DIRECTORIES}
+ "${CMAKE_CURRENT_LIST_DIR}")
+set_property(SOURCE "${CMAKE_CURRENT_LIST_DIR}/example.i"
+ PROPERTY GENERATED_COMPILE_DEFINITIONS ${SWIG_LANG_DEFINITIONS})
+set_property(SOURCE "${CMAKE_CURRENT_LIST_DIR}/example.i"
+ PROPERTY GENERATED_COMPILE_OPTIONS ${SWIG_LANG_OPTIONS})
+
+
+SWIG_ADD_LIBRARY(example
+ LANGUAGE "${language}"
+ ${SWIG_LANG_TYPE}
+ SOURCES "${CMAKE_CURRENT_LIST_DIR}/example.i"
+ "${CMAKE_CURRENT_LIST_DIR}/example.cxx")
+TARGET_INCLUDE_DIRECTORIES(example PUBLIC ${CMAKE_CURRENT_LIST_DIR})
+TARGET_LINK_LIBRARIES(example PRIVATE ${SWIG_LANG_LIBRARIES})
diff --git a/Tests/UseSWIG/BasicCsharp/CMakeLists.txt b/Tests/UseSWIG/BasicCsharp/CMakeLists.txt
new file mode 100644
index 000000000..1a6c763b5
--- /dev/null
+++ b/Tests/UseSWIG/BasicCsharp/CMakeLists.txt
@@ -0,0 +1,21 @@
+cmake_minimum_required(VERSION 3.12...3.13)
+
+project(TestBasicCsharp CXX CSharp)
+
+include(CTest)
+
+set(language "csharp")
+
+include (../BasicConfiguration.cmake)
+
+set_source_files_properties(Square.cs Circle.cs Shape.cs PROPERTIES GENERATED 1)
+add_library(example_cs SHARED $<TARGET_PROPERTY:example,SWIG_SUPPORT_FILES> Square.cs Circle.cs Shape.cs)
+set_target_properties(example_cs PROPERTIES LINKER_LANGUAGE CSharp)
+target_link_libraries(example_cs example)
+
+add_executable(runme ${CMAKE_CURRENT_SOURCE_DIR}/../runme.cs)
+target_link_libraries(runme example_cs)
+set_target_properties(runme PROPERTIES LINKER_LANGUAGE CSharp)
+
+add_test (NAME BasicCsharp
+ COMMAND $<TARGET_FILE:runme>)
diff --git a/Tests/UseSWIG/BasicPerl/CMakeLists.txt b/Tests/UseSWIG/BasicPerl/CMakeLists.txt
new file mode 100644
index 000000000..cf02de7de
--- /dev/null
+++ b/Tests/UseSWIG/BasicPerl/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.1...3.13)
+
+project(TestBasicPerl CXX)
+
+include(CTest)
+
+set(language "perl")
+
+include (../BasicConfiguration.cmake)
+
+add_test (NAME BasicPerl
+ COMMAND "${PERL_EXECUTABLE}" "-I${CMAKE_CURRENT_BINARY_DIR}"
+ "-I$<TARGET_FILE_DIR:example>"
+ "${CMAKE_CURRENT_SOURCE_DIR}/../runme.pl")
diff --git a/Tests/UseSWIG/BasicPython/CMakeLists.txt b/Tests/UseSWIG/BasicPython/CMakeLists.txt
new file mode 100644
index 000000000..8bbd1cbe8
--- /dev/null
+++ b/Tests/UseSWIG/BasicPython/CMakeLists.txt
@@ -0,0 +1,13 @@
+cmake_minimum_required(VERSION 3.1...3.13)
+
+project(TestBasicPython CXX)
+
+include(CTest)
+
+set(language "python")
+
+include (../BasicConfiguration.cmake)
+
+add_test (NAME BasicPython
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}${PS}$<TARGET_FILE_DIR:example>"
+ "${Python_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py")
diff --git a/Tests/UseSWIG/CMakeLists.txt b/Tests/UseSWIG/CMakeLists.txt
new file mode 100644
index 000000000..3cc910fec
--- /dev/null
+++ b/Tests/UseSWIG/CMakeLists.txt
@@ -0,0 +1,137 @@
+add_test(NAME UseSWIG.LegacyPython COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/LegacyPython"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/LegacyPython"
+ ${build_generator_args}
+ --build-project TestLegacyPython
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+add_test(NAME UseSWIG.LegacyPerl COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/LegacyPerl"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/LegacyPerl"
+ ${build_generator_args}
+ --build-project TestLegacyPerl
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+include(CheckLanguage)
+check_language(CSharp)
+if (CMAKE_CSharp_COMPILER)
+ add_test(NAME UseSWIG.BasicCsharp COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/BasicCsharp"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/BasicCsharp"
+ ${build_generator_args}
+ --build-project TestBasicCsharp
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+endif()
+
+add_test(NAME UseSWIG.BasicPython COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/BasicPython"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/BasicPython"
+ ${build_generator_args}
+ --build-project TestBasicPython
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+add_test(NAME UseSWIG.BasicPerl COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/BasicPerl"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/BasicPerl"
+ ${build_generator_args}
+ --build-project TestBasicPerl
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+
+add_test(NAME UseSWIG.MultipleModules COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/MultipleModules"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/MultipleModules"
+ ${build_generator_args}
+ --build-project TestMultipleModules
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+add_test(NAME UseSWIG.MultiplePython COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/MultiplePython"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/MultiplePython"
+ ${build_generator_args}
+ --build-project TestMultiplePython
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+
+add_test(NAME UseSWIG.ModuleVersion2 COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/ModuleVersion2"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/ModuleVersion2"
+ ${build_generator_args}
+ --build-project TestModuleVersion2
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+
+add_test(NAME UseSWIG.UseTargetINCLUDE_DIRECTORIES COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/UseTargetINCLUDE_DIRECTORIES"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/UseTargetINCLUDE_DIRECTORIES"
+ ${build_generator_args}
+ --build-project TestUseTargetINCLUDE_DIRECTORIES
+ --build-options ${build_options}
+ )
+
+
+add_test(NAME UseSWIG.ModuleName COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/ModuleName"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/ModuleName"
+ ${build_generator_args}
+ --build-project TestModuleName
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+
+add_test(NAME UseSWIG.SwigSrcFileExtension COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/SwigSrcFileExtension"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/SwigSrcFileExtension"
+ ${build_generator_args}
+ --build-project SwigSrcFileExtension
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
+
+
+add_test(NAME UseSWIG.AlternateLibraryName COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/UseSWIG/AlternateLibraryName"
+ "${CMake_BINARY_DIR}/Tests/UseSWIG/AlternateLibraryName"
+ ${build_generator_args}
+ --build-project TestAlternateLibraryName
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/UseSWIG/LegacyConfiguration.cmake b/Tests/UseSWIG/LegacyConfiguration.cmake
new file mode 100644
index 000000000..1acc05a4d
--- /dev/null
+++ b/Tests/UseSWIG/LegacyConfiguration.cmake
@@ -0,0 +1,68 @@
+
+# Prevent deprecated warnings from new UseSWIG module
+set (CMAKE_WARN_DEPRECATED FALSE)
+
+find_package(SWIG REQUIRED)
+include(${SWIG_USE_FILE})
+
+# Path separator
+if (WIN32)
+ set (PS "$<SEMICOLON>")
+else()
+ set (PS ":")
+endif()
+
+unset(SWIG_LANG_TYPE)
+if(${language} MATCHES python)
+ find_package(PythonInterp REQUIRED)
+ find_package(PythonLibs REQUIRED)
+ include_directories(${PYTHON_INCLUDE_PATH})
+ set(SWIG_LANG_LIBRARIES ${PYTHON_LIBRARIES})
+endif()
+if(${language} MATCHES perl)
+ find_package(Perl REQUIRED)
+ find_package(PerlLibs REQUIRED)
+ include_directories(${PERL_INCLUDE_PATH})
+ separate_arguments(c_flags UNIX_COMMAND "${PERL_EXTRA_C_FLAGS}")
+ add_compile_options(${c_flags})
+ set(SWIG_LANG_LIBRARIES ${PERL_LIBRARY})
+endif()
+if(${language} MATCHES tcl)
+ find_package(TCL REQUIRED)
+ include_directories(${TCL_INCLUDE_PATH})
+ set(SWIG_LANG_LIBRARIES ${TCL_LIBRARY})
+endif()
+if(${language} MATCHES ruby)
+ find_package(Ruby REQUIRED)
+ include_directories(${RUBY_INCLUDE_PATH})
+ set(SWIG_LANG_LIBRARIES ${RUBY_LIBRARY})
+endif()
+if(${language} MATCHES php4)
+ find_package(PHP4 REQUIRED)
+ include_directories(${PHP4_INCLUDE_PATH})
+ set(SWIG_LANG_LIBRARIES ${PHP4_LIBRARY})
+endif()
+if(${language} MATCHES pike)
+ find_package(Pike REQUIRED)
+ include_directories(${PIKE_INCLUDE_PATH})
+ set(SWIG_LANG_LIBRARIES ${PIKE_LIBRARY})
+endif()
+if(${language} MATCHES lua)
+ find_package(Lua REQUIRED)
+ include_directories(${LUA_INCLUDE_DIR})
+ set(SWIG_LANG_TYPE TYPE SHARED)
+ set(SWIG_LANG_LIBRARIES ${LUA_LIBRARIES})
+endif()
+
+unset(CMAKE_SWIG_FLAGS)
+
+include_directories(${CMAKE_CURRENT_LIST_DIR})
+
+set_source_files_properties("${CMAKE_CURRENT_LIST_DIR}/example.i" PROPERTIES CPLUSPLUS ON)
+set_source_files_properties("${CMAKE_CURRENT_LIST_DIR}/example.i" PROPERTIES SWIG_FLAGS "-includeall")
+SWIG_ADD_LIBRARY(example
+ LANGUAGE "${language}"
+ ${SWIG_LANG_TYPE}
+ SOURCES "${CMAKE_CURRENT_LIST_DIR}/example.i"
+ "${CMAKE_CURRENT_LIST_DIR}/example.cxx")
+SWIG_LINK_LIBRARIES(example ${SWIG_LANG_LIBRARIES})
diff --git a/Tests/UseSWIG/LegacyPerl/CMakeLists.txt b/Tests/UseSWIG/LegacyPerl/CMakeLists.txt
new file mode 100644
index 000000000..90d92f4eb
--- /dev/null
+++ b/Tests/UseSWIG/LegacyPerl/CMakeLists.txt
@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestLegacyPerl CXX)
+
+include(CTest)
+
+set(language "perl")
+
+include (../LegacyConfiguration.cmake)
+
+add_test (NAME LegacyPerl
+ COMMAND "${PERL_EXECUTABLE}" "-I${CMAKE_CURRENT_BINARY_DIR}"
+ "-I$<TARGET_FILE_DIR:${SWIG_MODULE_example_REAL_NAME}>"
+ "${CMAKE_CURRENT_SOURCE_DIR}/../runme.pl")
diff --git a/Tests/UseSWIG/LegacyPython/CMakeLists.txt b/Tests/UseSWIG/LegacyPython/CMakeLists.txt
new file mode 100644
index 000000000..03facb19a
--- /dev/null
+++ b/Tests/UseSWIG/LegacyPython/CMakeLists.txt
@@ -0,0 +1,13 @@
+cmake_minimum_required(VERSION 3.1)
+
+project(TestLegacyPython CXX)
+
+include(CTest)
+
+set(language "python")
+
+include (../LegacyConfiguration.cmake)
+
+add_test (NAME LegacyPython
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}${PS}$<TARGET_FILE_DIR:${SWIG_MODULE_example_REAL_NAME}>"
+ "${PYTHON_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py")
diff --git a/Tests/UseSWIG/ModuleName/CMakeLists.txt b/Tests/UseSWIG/ModuleName/CMakeLists.txt
new file mode 100644
index 000000000..435b441a4
--- /dev/null
+++ b/Tests/UseSWIG/ModuleName/CMakeLists.txt
@@ -0,0 +1,42 @@
+cmake_minimum_required(VERSION 3.1...3.14)
+
+project(TestModuleName CXX)
+
+include(CTest)
+
+find_package(SWIG REQUIRED)
+cmake_policy(SET CMP0086 NEW)
+include(${SWIG_USE_FILE})
+
+find_package(Python2 REQUIRED COMPONENTS Interpreter Development)
+
+# Path separator
+if (WIN32)
+ set (PS "$<SEMICOLON>")
+else()
+ set (PS ":")
+endif()
+
+unset(CMAKE_SWIG_FLAGS)
+
+set_property(SOURCE "example.i" PROPERTY CPLUSPLUS ON)
+set_property(SOURCE "example.i" PROPERTY COMPILE_OPTIONS -includeall)
+set_property(SOURCE "example.i" PROPERTY SWIG_MODULE_NAME new_example)
+
+swig_add_library(example1
+ LANGUAGE python
+ OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/example1"
+ SOURCES example.i ../example.cxx)
+set_target_properties (example1 PROPERTIES
+ INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/.."
+ SWIG_USE_TARGET_INCLUDE_DIRECTORIES TRUE
+ OUTPUT_NAME new_example
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/example1"
+ ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/example1"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/example1")
+target_link_libraries(example1 PRIVATE Python2::Module)
+
+
+add_test (NAME ModuleName.example1
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/Python2${PS}$<TARGET_FILE_DIR:example1>"
+ "${Python2_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/runme.py")
diff --git a/Tests/UseSWIG/ModuleName/example.i b/Tests/UseSWIG/ModuleName/example.i
new file mode 100644
index 000000000..fbdf7249f
--- /dev/null
+++ b/Tests/UseSWIG/ModuleName/example.i
@@ -0,0 +1,9 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
diff --git a/Tests/UseSWIG/ModuleName/runme.py b/Tests/UseSWIG/ModuleName/runme.py
new file mode 100644
index 000000000..c37e4a736
--- /dev/null
+++ b/Tests/UseSWIG/ModuleName/runme.py
@@ -0,0 +1,52 @@
+# file: runme.py
+
+# This file illustrates the shadow-class C++ interface generated
+# by SWIG.
+
+from __future__ import print_function
+
+import new_example
+
+# ----- Object creation -----
+
+print ("Creating some objects:")
+c = new_example.Circle(10)
+print (" Created circle", c)
+s = new_example.Square(10)
+print (" Created square", s)
+
+# ----- Access a static member -----
+
+print ("\nA total of", new_example.cvar.Shape_nshapes,"shapes were created")
+
+# ----- Member data access -----
+
+# Set the location of the object
+
+c.x = 20
+c.y = 30
+
+s.x = -10
+s.y = 5
+
+print ("\nHere is their current position:")
+print (" Circle = (%f, %f)" % (c.x,c.y))
+print (" Square = (%f, %f)" % (s.x,s.y))
+
+# ----- Call some methods -----
+
+print ("\nHere are some properties of the shapes:")
+for o in [c,s]:
+ print (" ", o)
+ print (" area = ", o.area())
+ print (" perimeter = ", o.perimeter())
+
+print ("\nGuess I'll clean up now")
+
+# Note: this invokes the virtual destructor
+del c
+del s
+
+s = 3
+print (new_example.cvar.Shape_nshapes,"shapes remain")
+print ("Goodbye")
diff --git a/Tests/UseSWIG/ModuleVersion2/CMakeLists.txt b/Tests/UseSWIG/ModuleVersion2/CMakeLists.txt
new file mode 100644
index 000000000..093e8582c
--- /dev/null
+++ b/Tests/UseSWIG/ModuleVersion2/CMakeLists.txt
@@ -0,0 +1,56 @@
+cmake_minimum_required(VERSION 3.1...3.13)
+
+project(TestModuleVersion2 CXX)
+
+include(CTest)
+
+find_package(SWIG REQUIRED)
+include(${SWIG_USE_FILE})
+
+find_package(Python2 REQUIRED COMPONENTS Interpreter Development)
+find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
+
+if (WIN32)
+ set (PS $<SEMICOLON>)
+else()
+ set (PS ":")
+endif()
+
+set (UseSWIG_MODULE_VERSION 2)
+unset(CMAKE_SWIG_FLAGS)
+
+set_property(SOURCE "../example.i" PROPERTY CPLUSPLUS ON)
+set_property(SOURCE "../example.i" PROPERTY COMPILE_OPTIONS -includeall)
+
+set_property(SOURCE "../example.i"
+ PROPERTY GENERATED_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/..")
+
+swig_add_library(example1
+ LANGUAGE python
+ SOURCES ../example.i ../example.cxx)
+set_target_properties (example1 PROPERTIES
+ OUTPUT_NAME example
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2"
+ ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2")
+target_link_libraries(example1 PRIVATE Python2::Module)
+
+# re-use sample interface file for another plugin
+swig_add_library(example2
+ LANGUAGE python
+ SOURCES ../example.i ../example.cxx)
+set_target_properties (example2 PROPERTIES
+ OUTPUT_NAME example
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3"
+ ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3")
+target_link_libraries(example2 PRIVATE Python3::Module)
+
+
+add_test (NAME ModuleVersion2.example1
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_PROPERTY:example1,SWIG_SUPPORT_FILES_DIRECTORY>${PS}$<TARGET_FILE_DIR:example1>"
+ "${Python2_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py")
+
+add_test (NAME ModuleVersion2.example2
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=$<TARGET_PROPERTY:example2,SWIG_SUPPORT_FILES_DIRECTORY>${PS}$<TARGET_FILE_DIR:example2>"
+ "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py")
diff --git a/Tests/UseSWIG/MultipleModules/CMakeLists.txt b/Tests/UseSWIG/MultipleModules/CMakeLists.txt
new file mode 100644
index 000000000..4380080f5
--- /dev/null
+++ b/Tests/UseSWIG/MultipleModules/CMakeLists.txt
@@ -0,0 +1,68 @@
+cmake_minimum_required(VERSION 3.1...3.13)
+
+project(TestMultipleModules CXX)
+
+include(CTest)
+
+find_package(SWIG REQUIRED)
+include(${SWIG_USE_FILE})
+
+find_package(Python REQUIRED COMPONENTS Interpreter Development)
+
+find_package(Perl REQUIRED)
+find_package(PerlLibs REQUIRED)
+
+# Path separator
+if (WIN32)
+ set (PS "$<SEMICOLON>")
+else()
+ set (PS ":")
+endif()
+
+unset(CMAKE_SWIG_FLAGS)
+
+set_property(SOURCE "../example.i" PROPERTY CPLUSPLUS ON)
+set_property(SOURCE "../example.i" PROPERTY COMPILE_OPTIONS -includeall)
+
+set_property(SOURCE "../example.i"
+ PROPERTY GENERATED_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/..")
+
+swig_add_library(example1
+ LANGUAGE python
+ OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/Python"
+ SOURCES ../example.i ../example.cxx)
+set_target_properties (example1 PROPERTIES
+ OUTPUT_NAME example
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python"
+ ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python")
+target_link_libraries(example1 PRIVATE Python::Module)
+
+# re-use sample interface file for another plugin
+set_property(SOURCE "../example.i" APPEND PROPERTY
+ GENERATED_INCLUDE_DIRECTORIES ${PERL_INCLUDE_PATH})
+separate_arguments(c_flags UNIX_COMMAND "${PERL_EXTRA_C_FLAGS}")
+set_property(SOURCE "../example.i" PROPERTY GENERATED_COMPILE_OPTIONS ${c_flags})
+
+swig_add_library(example2
+ LANGUAGE perl
+ OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/Perl"
+ SOURCES ../example.i ../example.cxx)
+set_target_properties (example2 PROPERTIES
+ OUTPUT_NAME example
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Perl"
+ ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Perl"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Perl")
+target_link_libraries(example2 PRIVATE ${PERL_LIBRARY})
+
+
+
+add_test (NAME MultipleModules.Python
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/Python${PS}$<TARGET_FILE_DIR:example1>"
+ "${Python_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py")
+
+
+add_test (NAME MultipleModules.Perl
+ COMMAND "${PERL_EXECUTABLE}" "-I${CMAKE_CURRENT_BINARY_DIR}/Perl"
+ "-I$<TARGET_FILE_DIR:example2>"
+ "${CMAKE_CURRENT_SOURCE_DIR}/../runme.pl")
diff --git a/Tests/UseSWIG/MultiplePython/CMakeLists.txt b/Tests/UseSWIG/MultiplePython/CMakeLists.txt
new file mode 100644
index 000000000..cf6c80e28
--- /dev/null
+++ b/Tests/UseSWIG/MultiplePython/CMakeLists.txt
@@ -0,0 +1,59 @@
+cmake_minimum_required(VERSION 3.1...3.13)
+
+project(TestMultiplePython CXX)
+
+include(CTest)
+
+find_package(SWIG REQUIRED)
+include(${SWIG_USE_FILE})
+
+find_package(Python2 REQUIRED COMPONENTS Interpreter Development)
+find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
+
+# Path separator
+if (WIN32)
+ set (PS "$<SEMICOLON>")
+else()
+ set (PS ":")
+endif()
+
+unset(CMAKE_SWIG_FLAGS)
+
+set_property(SOURCE "../example.i" PROPERTY CPLUSPLUS ON)
+set_property(SOURCE "../example.i" PROPERTY COMPILE_OPTIONS -includeall)
+
+set_property(SOURCE "../example.i"
+ PROPERTY GENERATED_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/..")
+
+swig_add_library(example1
+ LANGUAGE python
+ OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/Python2"
+ SOURCES ../example.i ../example.cxx)
+set_target_properties (example1 PROPERTIES
+ OUTPUT_NAME example
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2"
+ ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python2")
+target_link_libraries(example1 PRIVATE Python2::Module)
+
+# re-use sample interface file for another plugin
+swig_add_library(example2
+ LANGUAGE python
+ OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/Python3"
+ SOURCES ../example.i ../example.cxx)
+set_target_properties (example2 PROPERTIES
+ OUTPUT_NAME example
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3"
+ ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/Python3")
+target_link_libraries(example2 PRIVATE Python3::Module)
+
+
+
+add_test (NAME MultiplePython.example1
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/Python2${PS}$<TARGET_FILE_DIR:example1>"
+ "${Python2_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py")
+
+add_test (NAME MultiplePython.example2
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}/Python3${PS}$<TARGET_FILE_DIR:example2>"
+ "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/../runme.py")
diff --git a/Tests/UseSWIG/SwigSrcFileExtension/CMakeLists.txt b/Tests/UseSWIG/SwigSrcFileExtension/CMakeLists.txt
new file mode 100644
index 000000000..f70ce491d
--- /dev/null
+++ b/Tests/UseSWIG/SwigSrcFileExtension/CMakeLists.txt
@@ -0,0 +1,28 @@
+cmake_minimum_required(VERSION 3.1...3.14)
+
+project(SwigSrcFileExtension C)
+
+include(CTest)
+find_package(SWIG REQUIRED)
+find_package(Python COMPONENTS Interpreter Development REQUIRED)
+
+include(${SWIG_USE_FILE})
+
+# Use the newer target name preference
+set(UseSWIG_TARGET_NAME_PREFERENCE "STANDARD")
+
+# Set the custom source file extension to both .i and .swg
+set(SWIG_SOURCE_FILE_EXTENSIONS ".i" ".swg")
+
+# Generate a Python module out of `.i`
+swig_add_library(my_add LANGUAGE python SOURCES my_add.i)
+target_link_libraries(my_add Python::Module)
+
+# Generate a Python module out of `.swg`
+swig_add_library(my_sub LANGUAGE python SOURCES my_sub.swg)
+target_link_libraries(my_sub Python::Module)
+
+# Add a test
+add_test(NAME SwigSrcFileExtension
+ COMMAND "${CMAKE_COMMAND}" -E env "PYTHONPATH=${CMAKE_CURRENT_BINARY_DIR}"
+ "${Python_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/runme.py")
diff --git a/Tests/UseSWIG/SwigSrcFileExtension/my_add.i b/Tests/UseSWIG/SwigSrcFileExtension/my_add.i
new file mode 100644
index 000000000..d087ab5e2
--- /dev/null
+++ b/Tests/UseSWIG/SwigSrcFileExtension/my_add.i
@@ -0,0 +1,9 @@
+%module my_add
+
+%{
+int add(int a, int b) {
+ return a + b;
+}
+%}
+
+int add(int a, int b);
diff --git a/Tests/UseSWIG/SwigSrcFileExtension/my_sub.swg b/Tests/UseSWIG/SwigSrcFileExtension/my_sub.swg
new file mode 100644
index 000000000..df34b441a
--- /dev/null
+++ b/Tests/UseSWIG/SwigSrcFileExtension/my_sub.swg
@@ -0,0 +1,9 @@
+%module my_sub
+
+%{
+int sub(int a, int b) {
+ return a - b;
+}
+%}
+
+int sub(int a, int b);
diff --git a/Tests/UseSWIG/SwigSrcFileExtension/runme.py b/Tests/UseSWIG/SwigSrcFileExtension/runme.py
new file mode 100755
index 000000000..290175b08
--- /dev/null
+++ b/Tests/UseSWIG/SwigSrcFileExtension/runme.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+
+from __future__ import print_function
+import random
+
+import my_add
+import my_sub
+
+
+# These can be changed, but make sure not to overflow `int`
+a = random.randint(1, 1024)
+b = random.randint(1, 1024)
+
+if my_add.add(a, b) == a + b:
+ print ("Test 1 Passed for SWIG custom source file extension")
+else:
+ print ("Test 1 FAILED for SWIG custom source file extension")
+ exit(1)
+
+if my_sub.sub(a, b) == a - b:
+ print ("Test 2 Passed for SWIG custom source file extension")
+else:
+ print ("Test 2 FAILED for SWIG custom source file extension")
+ exit(1)
diff --git a/Tests/UseSWIG/UseTargetINCLUDE_DIRECTORIES/CMakeLists.txt b/Tests/UseSWIG/UseTargetINCLUDE_DIRECTORIES/CMakeLists.txt
new file mode 100644
index 000000000..80a2e1650
--- /dev/null
+++ b/Tests/UseSWIG/UseTargetINCLUDE_DIRECTORIES/CMakeLists.txt
@@ -0,0 +1,45 @@
+cmake_minimum_required(VERSION 3.1...3.13)
+
+project(TestUseTargetINCLUDE_DIRECTORIES CXX)
+
+include(CTest)
+
+find_package(SWIG REQUIRED)
+include(${SWIG_USE_FILE})
+
+find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
+
+unset(CMAKE_SWIG_FLAGS)
+
+set_property(SOURCE "example.i" PROPERTY CPLUSPLUS ON)
+set_property(SOURCE "example.i" PROPERTY COMPILE_OPTIONS -includeall)
+
+swig_add_library(example1
+ LANGUAGE python
+ OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/example1"
+ SOURCES example.i ../example.cxx)
+set_target_properties (example1 PROPERTIES
+ INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/.."
+ SWIG_USE_TARGET_INCLUDE_DIRECTORIES TRUE
+ OUTPUT_NAME example1
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/example1"
+ ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/example1"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/example1")
+target_link_libraries(example1 PRIVATE Python3::Module)
+
+
+# Check that source property override target property
+set_property(SOURCE "example.i" PROPERTY USE_TARGET_INCLUDE_DIRECTORIES TRUE)
+
+swig_add_library(example2
+ LANGUAGE python
+ OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/example2"
+ SOURCES example.i ../example.cxx)
+set_target_properties (example2 PROPERTIES
+ INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/.."
+ SWIG_USE_TARGET_INCLUDE_DIRECTORIES FALSE
+ OUTPUT_NAME example2
+ LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/example2"
+ ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/example2"
+ RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/example2")
+target_link_libraries(example2 PRIVATE Python3::Module)
diff --git a/Tests/UseSWIG/UseTargetINCLUDE_DIRECTORIES/example.i b/Tests/UseSWIG/UseTargetINCLUDE_DIRECTORIES/example.i
new file mode 100644
index 000000000..fbdf7249f
--- /dev/null
+++ b/Tests/UseSWIG/UseTargetINCLUDE_DIRECTORIES/example.i
@@ -0,0 +1,9 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
diff --git a/Tests/UseSWIG/example.cxx b/Tests/UseSWIG/example.cxx
new file mode 100644
index 000000000..961d6dd9a
--- /dev/null
+++ b/Tests/UseSWIG/example.cxx
@@ -0,0 +1,33 @@
+/* File : example.c */
+
+#include "example.h"
+#define M_PI 3.14159265358979323846
+
+/* Move the shape to a new location */
+void Shape::move(double dx, double dy)
+{
+ x += dx;
+ y += dy;
+}
+
+int Shape::nshapes = 0;
+
+double Circle::area(void)
+{
+ return M_PI * radius * radius;
+}
+
+double Circle::perimeter(void)
+{
+ return 2 * M_PI * radius;
+}
+
+double Square::area(void)
+{
+ return width * width;
+}
+
+double Square::perimeter(void)
+{
+ return 4 * width;
+}
diff --git a/Tests/UseSWIG/example.h b/Tests/UseSWIG/example.h
new file mode 100644
index 000000000..366deb044
--- /dev/null
+++ b/Tests/UseSWIG/example.h
@@ -0,0 +1,37 @@
+/* File : example.h */
+
+class Shape
+{
+public:
+ Shape() { nshapes++; }
+ virtual ~Shape() { nshapes--; };
+ double x, y;
+ void move(double dx, double dy);
+ virtual double area(void) = 0;
+ virtual double perimeter(void) = 0;
+ static int nshapes;
+};
+
+class Circle : public Shape
+{
+private:
+ double radius;
+
+public:
+ Circle(double r)
+ : radius(r){};
+ virtual double area(void);
+ virtual double perimeter(void);
+};
+
+class Square : public Shape
+{
+private:
+ double width;
+
+public:
+ Square(double w)
+ : width(w){};
+ virtual double area(void);
+ virtual double perimeter(void);
+};
diff --git a/Tests/UseSWIG/example.i b/Tests/UseSWIG/example.i
new file mode 100644
index 000000000..fbdf7249f
--- /dev/null
+++ b/Tests/UseSWIG/example.i
@@ -0,0 +1,9 @@
+/* File : example.i */
+%module example
+
+%{
+#include "example.h"
+%}
+
+/* Let's just grab the original header file here */
+%include "example.h"
diff --git a/Tests/UseSWIG/runme.cs b/Tests/UseSWIG/runme.cs
new file mode 100644
index 000000000..f0c1bd220
--- /dev/null
+++ b/Tests/UseSWIG/runme.cs
@@ -0,0 +1,54 @@
+using System;
+using System.Collections.Generic;
+
+public class runme
+{
+ static void Main()
+ {
+ // ----- Object creation -----
+
+ Console.WriteLine("Creating some objects:");
+ Circle c = new Circle(10);
+ Console.WriteLine(" Created " + c);
+ Square s = new Square(10);
+ Console.WriteLine(" Created " + s);
+
+ // ----- Access a static member -----
+
+ Console.WriteLine("\nA total of " + Shape.nshapes + " shapes were created");
+
+ // ----- Member data access -----
+
+ // Set the location of the object
+
+ c.x = 20;
+ c.y = 30;
+
+ s.x = -10;
+ s.y = 5;
+
+ Console.WriteLine("\nHere is their current position:");
+ Console.WriteLine(" Circle = ({0}, {1})", c.x,c.y);
+ Console.WriteLine(" Square = ({0}, {1})", s.x,s.y);
+
+ // ----- Call some methods -----
+
+ Console.WriteLine("\nHere are some properties of the shapes:");
+ List <Shape> shapeList = new List <Shape> { c,s };
+ foreach(var o in shapeList){
+ Console.WriteLine(" " + o);
+ Console.WriteLine(" area = " + o.area());
+ Console.WriteLine(" perimeter = " + o.perimeter());
+ }
+
+ Console.WriteLine("\nGuess I'll clean up now");
+
+ // Note: this invokes the virtual destructor
+ c.Dispose();
+ s.Dispose();
+
+ s = new Square(10);;
+ Console.WriteLine(Shape.nshapes + " shapes remain");
+ Console.WriteLine("Goodbye");
+ }
+}
diff --git a/Tests/UseSWIG/runme.php4 b/Tests/UseSWIG/runme.php4
new file mode 100644
index 000000000..653ced256
--- /dev/null
+++ b/Tests/UseSWIG/runme.php4
@@ -0,0 +1,58 @@
+<?php
+
+# This file illustrates the low-level C++ interface
+# created by SWIG. In this case, all of our C++ classes
+# get converted into function calls.
+
+require("example.php");
+
+# ----- Object creation -----
+
+print "Creating some objects:\n";
+$c = new_Circle(10);
+print " Created circle $c\n";
+$s = new_Square(10);
+print " Created square $s\n";
+
+# ----- Access a static member -----
+
+print "\nA total of " . nshapes() . " shapes were created\n";
+
+# ----- Member data access -----
+
+# Set the location of the object.
+# Note: methods in the base class Shape are used since
+# x and y are defined there.
+
+Shape_x_set($c, 20);
+Shape_y_set($c, 30);
+Shape_x_set($s,-10);
+Shape_y_set($s,5);
+
+print "\nHere is their current position:\n";
+print " Circle = (" . Shape_x_get($c) . "," . Shape_y_get($c) . ")\n";
+print " Square = (" . Shape_x_get($s) . "," . Shape_y_get($s) . ")\n";
+
+# ----- Call some methods -----
+
+print "\nHere are some properties of the shapes:\n";
+foreach (array($c,$s) as $o) {
+ print " $o\n";
+ print " area = " . Shape_area($o) . "\n";
+ print " perimeter = " . Shape_perimeter($o) . "\n";
+ }
+# Notice how the Shape_area() and Shape_perimeter() functions really
+# invoke the appropriate virtual method on each object.
+
+# ----- Delete everything -----
+
+print "\nGuess I'll clean up now\n";
+
+# Note: this invokes the virtual destructor
+delete_Shape($c);
+delete_Shape($s);
+
+print nshapes() . " shapes remain\n";
+print "Goodbye\n";
+
+?>
diff --git a/Tests/UseSWIG/runme.pike b/Tests/UseSWIG/runme.pike
new file mode 100644
index 000000000..ec28dd70e
--- /dev/null
+++ b/Tests/UseSWIG/runme.pike
@@ -0,0 +1,53 @@
+import .example;
+
+int main()
+{
+ // ----- Object creation -----
+
+ write("Creating some objects:\n");
+ Circle c = Circle(10.0);
+ write(" Created circle.\n");
+ Square s = Square(10.0);
+ write(" Created square.\n");
+
+ // ----- Access a static member -----
+
+ write("\nA total of " + Shape_nshapes_get() + " shapes were created\n");
+
+ // ----- Member data access -----
+
+ // Set the location of the object
+
+ c->x_set(20.0);
+ c->y_set(30.0);
+
+ s->x_set(-10.0);
+ s->y_set(5.0);
+
+ write("\nHere is their current position:\n");
+ write(" Circle = (%f, %f)\n", c->x_get(), c->y_get());
+ write(" Square = (%f, %f)\n", s->x_get(), s->y_get());
+
+ // ----- Call some methods -----
+
+ write("\nHere are some properties of the shapes:\n");
+ write(" The circle:\n");
+ write(" area = %f.\n", c->area());
+ write(" perimeter = %f.\n", c->perimeter());
+ write(" The square:\n");
+ write(" area = %f.\n", s->area());
+ write(" perimeter = %f.\n", s->perimeter());
+
+ write("\nGuess I'll clean up now\n");
+
+ /* See if we can force 's' to be garbage-collected */
+ s = 0;
+
+ /* Now we should be down to only 1 shape */
+ write("%d shapes remain\n", Shape_nshapes_get());
+
+ /* Done */
+ write("Goodbye\n");
+
+ return 0;
+}
diff --git a/Tests/UseSWIG/runme.pl b/Tests/UseSWIG/runme.pl
new file mode 100644
index 000000000..965e06382
--- /dev/null
+++ b/Tests/UseSWIG/runme.pl
@@ -0,0 +1,56 @@
+# file: runme.pl
+
+# This file illustrates the low-level C++ interface
+# created by SWIG. In this case, all of our C++ classes
+# get converted into function calls.
+
+use example;
+
+# ----- Object creation -----
+
+print "Creating some objects:\n";
+$c = examplec::new_Circle(10);
+print " Created circle $c\n";
+$s = examplec::new_Square(10);
+print " Created square $s\n";
+
+# ----- Access a static member -----
+
+print "\nA total of $examplec::Shape_nshapes shapes were created\n";
+
+# ----- Member data access -----
+
+# Set the location of the object.
+# Note: methods in the base class Shape are used since
+# x and y are defined there.
+
+examplec::Shape_x_set($c, 20);
+examplec::Shape_y_set($c, 30);
+examplec::Shape_x_set($s,-10);
+examplec::Shape_y_set($s,5);
+
+print "\nHere is their current position:\n";
+print " Circle = (",examplec::Shape_x_get($c),",", examplec::Shape_y_get($c),")\n";
+print " Square = (",examplec::Shape_x_get($s),",", examplec::Shape_y_get($s),")\n";
+
+# ----- Call some methods -----
+
+print "\nHere are some properties of the shapes:\n";
+foreach $o ($c,$s) {
+ print " $o\n";
+ print " area = ", examplec::Shape_area($o), "\n";
+ print " perimeter = ", examplec::Shape_perimeter($o), "\n";
+ }
+# Notice how the Shape_area() and Shape_perimeter() functions really
+# invoke the appropriate virtual method on each object.
+
+# ----- Delete everything -----
+
+print "\nGuess I'll clean up now\n";
+
+# Note: this invokes the virtual destructor
+examplec::delete_Shape($c);
+examplec::delete_Shape($s);
+
+print $examplec::Shape_nshapes," shapes remain\n";
+print "Goodbye\n";
diff --git a/Tests/UseSWIG/runme.py b/Tests/UseSWIG/runme.py
new file mode 100644
index 000000000..af5e07dc2
--- /dev/null
+++ b/Tests/UseSWIG/runme.py
@@ -0,0 +1,52 @@
+# file: runme.py
+
+# This file illustrates the shadow-class C++ interface generated
+# by SWIG.
+
+from __future__ import print_function
+
+import example
+
+# ----- Object creation -----
+
+print ("Creating some objects:")
+c = example.Circle(10)
+print (" Created circle", c)
+s = example.Square(10)
+print (" Created square", s)
+
+# ----- Access a static member -----
+
+print ("\nA total of", example.cvar.Shape_nshapes,"shapes were created")
+
+# ----- Member data access -----
+
+# Set the location of the object
+
+c.x = 20
+c.y = 30
+
+s.x = -10
+s.y = 5
+
+print ("\nHere is their current position:")
+print (" Circle = (%f, %f)" % (c.x,c.y))
+print (" Square = (%f, %f)" % (s.x,s.y))
+
+# ----- Call some methods -----
+
+print ("\nHere are some properties of the shapes:")
+for o in [c,s]:
+ print (" ", o)
+ print (" area = ", o.area())
+ print (" perimeter = ", o.perimeter())
+
+print ("\nGuess I'll clean up now")
+
+# Note: this invokes the virtual destructor
+del c
+del s
+
+s = 3
+print (example.cvar.Shape_nshapes,"shapes remain")
+print ("Goodbye")
diff --git a/Tests/UseSWIG/runme.rb b/Tests/UseSWIG/runme.rb
new file mode 100644
index 000000000..de73bcd46
--- /dev/null
+++ b/Tests/UseSWIG/runme.rb
@@ -0,0 +1,49 @@
+# file: runme.rb
+
+# This file illustrates the C++ interface created by SWIG.
+# All of our C++ classes get converted into Ruby classes.
+
+require 'example'
+
+# ----- Object creation -----
+
+print "Creating some objects:\n"
+c = Example::Circle.new(10)
+print " Created circle #{c}\n"
+s = Example::Square.new(10)
+print " Created square #{s}\n"
+
+# ----- Access a static member -----
+
+print "\nA total of #{Example::Shape.nshapes} shapes were created\n"
+
+# ----- Member data access -----
+
+# Set the location of the object
+
+# Notice how we can do this using functions specific to
+# the 'Circle' class.
+c.x = 20
+c.y = 30
+
+# Now use the same functions in the base class
+s.x = -10
+s.y = 5
+
+print "\nHere is their current position:\n"
+print " Circle = (", c.x, ",", c.y, ")\n"
+print " Square = (", s.x, ",", s.y, ")\n"
+
+# ----- Call some methods -----
+
+print "\nHere are some properties of the shapes:\n"
+for o in [c, s]
+ print " #{o}\n"
+ print " area = ", o.area, "\n"
+ print " perimeter = ", o.perimeter, "\n"
+end
+# Notice how the Shape#area() and Shape#perimeter() functions really
+# invoke the appropriate virtual method on each object.
+
+print "\n", Example::Shape.nshapes," shapes remain\n"
+print "Goodbye\n"
diff --git a/Tests/UseSWIG/runme.tcl b/Tests/UseSWIG/runme.tcl
new file mode 100644
index 000000000..6055cf619
--- /dev/null
+++ b/Tests/UseSWIG/runme.tcl
@@ -0,0 +1,49 @@
+# file: runme.tcl
+
+# This file illustrates the high level C++ interface.
+# In this case C++ classes work kind of like Tk widgets
+
+catch { load ./example[info sharedlibextension] example}
+
+# ----- Object creation -----
+
+puts "Creating some objects:"
+Circle c 10
+puts " Created circle [c cget -this]"
+Square s 10
+puts " Created square [s cget -this]"
+
+# ----- Access a static member -----
+
+puts "\nA total of $Shape_nshapes shapes were created"
+
+# ----- Member data access -----
+
+# Set the location of the object
+
+c configure -x 20 -y 30
+s configure -x -10 -y 5
+
+puts "\nHere is their current position:"
+puts " Circle = ([c cget -x], [c cget -y])"
+puts " Square = ([s cget -x], [s cget -y])"
+
+# ----- Call some methods -----
+
+puts "\nHere are some properties of the shapes:"
+foreach o "c s" {
+ puts " [$o cget -this]"
+ puts " area = [$o area]"
+ puts " perimeter = [$o perimeter]"
+}
+
+# ----- Delete everything -----
+
+puts "\nGuess I'll clean up now"
+
+# Note: this invokes the virtual destructor
+rename c ""
+rename s ""
+
+puts "$Shape_nshapes shapes remain"
+puts "Goodbye"
diff --git a/Tests/UseSWIG/runme2.tcl b/Tests/UseSWIG/runme2.tcl
new file mode 100644
index 000000000..d0b5c219e
--- /dev/null
+++ b/Tests/UseSWIG/runme2.tcl
@@ -0,0 +1,69 @@
+# file: runme2.tcl
+
+# This file illustrates the low-level C++ interface
+# created by SWIG. In this case, all of our C++ classes
+# get converted into function calls.
+
+catch { load ./example[info sharedlibextension] example}
+
+# ----- Object creation -----
+
+puts "Creating some objects:"
+set c [new_Circle 10]
+puts " Created circle $c"
+set s [new_Square 10]
+puts " Created square $s"
+
+# ----- Access a static member -----
+
+puts "\nA total of $Shape_nshapes shapes were created"
+
+# ----- Member data access -----
+
+# Set the location of the object
+# Note: the base class must be used since that's where x and y
+# were declared.
+
+Shape_x_set $c 20
+Shape_y_set $c 30
+Shape_x_set $s -10
+Shape_y_set $s 5
+
+puts "\nHere is their current position:"
+puts " Circle = ([Shape_x_get $c], [Shape_y_get $c])"
+puts " Square = ([Shape_x_get $s], [Shape_y_get $s])"
+
+# ----- Call some methods -----
+
+puts "\nHere are some properties of the shapes:"
+foreach o "$c $s" {
+ puts " $o"
+ puts " area = [Shape_area $o]"
+ puts " perimeter = [Shape_perimeter $o]"
+}
+# Notice how the Shape_area() and Shape_perimeter() functions really
+# invoke the appropriate virtual method on each object.
+
+# ----- Try to cause a type error -----
+
+puts "\nI'm going to try and break the type system"
+
+if { [catch {
+ # Bad script!
+ Square_area $c # Try to invoke Square method on a Circle
+ puts " Bad bad SWIG!"
+
+}]} {
+ puts " Well, it didn't work. Good SWIG."
+}
+
+# ----- Delete everything -----
+
+puts "\nGuess I'll clean up now"
+
+# Note: this invokes the virtual destructor
+delete_Shape $c
+delete_Shape $s
+
+puts "$Shape_nshapes shapes remain"
+puts "Goodbye"
diff --git a/Tests/VSNASM/bar.asm b/Tests/VSNASM/bar.asm
new file mode 100644
index 000000000..b486d82ae
--- /dev/null
+++ b/Tests/VSNASM/bar.asm
@@ -0,0 +1,13 @@
+section .text
+%ifdef TEST2x64
+global bar
+%else
+global _bar
+%endif
+%ifdef TESTx64
+bar:
+%else
+_bar:
+%endif
+ mov EAX_COMMA_SPACE_ZERO
+ ret
diff --git a/Tests/VSWinStorePhone/WinRT/Batman.cpp b/Tests/VSWinStorePhone/WinRT/Batman.cpp
new file mode 100644
index 000000000..e09225898
--- /dev/null
+++ b/Tests/VSWinStorePhone/WinRT/Batman.cpp
@@ -0,0 +1,14 @@
+#include "Batman.h"
+
+using namespace JusticeLeagueWinRT;
+using namespace Platform;
+
+Batman::Batman()
+{
+}
+
+void Batman::savePeople()
+{
+ int i = 0;
+ i++;
+}
diff --git a/Tests/VSWinStorePhone/WinRT/Batman.h b/Tests/VSWinStorePhone/WinRT/Batman.h
new file mode 100644
index 000000000..e2dcabc46
--- /dev/null
+++ b/Tests/VSWinStorePhone/WinRT/Batman.h
@@ -0,0 +1,12 @@
+#pragma once
+
+namespace JusticeLeagueWinRT {
+public
+ref class Batman sealed
+{
+public:
+ Batman();
+
+ void savePeople();
+};
+}
diff --git a/Tests/VSWinStorePhone/WinRT/CMakeLists.txt b/Tests/VSWinStorePhone/WinRT/CMakeLists.txt
new file mode 100644
index 000000000..bb9333360
--- /dev/null
+++ b/Tests/VSWinStorePhone/WinRT/CMakeLists.txt
@@ -0,0 +1,13 @@
+project(JusticeLeagueWinRT CXX)
+
+# create project
+add_library(JusticeLeagueWinRT SHARED
+ "${CMAKE_CURRENT_SOURCE_DIR}/Batman.cpp"
+ "${CMAKE_CURRENT_SOURCE_DIR}/Batman.h"
+)
+
+set_target_properties(JusticeLeagueWinRT PROPERTIES
+ VS_WINRT_COMPONENT TRUE
+ VS_GLOBAL_ROOTNAMESPACE "JusticeLeagueWinRT"
+ OUTPUT_NAME "JusticeLeagueWinRT"
+)
diff --git a/Utilities/Release/push.bash b/Utilities/Release/push.bash
new file mode 100755
index 000000000..1c8efe900
--- /dev/null
+++ b/Utilities/Release/push.bash
@@ -0,0 +1,70 @@
+#!/usr/bin/env bash
+
+usage='usage: push.bash [<options>] [--] <dest>
+
+Options:
+
+ --dir <dir> Specify subdirectory under destination.
+ Defaults to "v<version>".
+ --version <ver> CMake <major>.<minor> version number to push.
+ Defaults to version of source tree.
+'
+
+die() {
+ echo "$@" 1>&2; exit 1
+}
+
+cmake_source_dir="${BASH_SOURCE%/*}/../.."
+
+cmake_version_component()
+{
+ sed -n "
+/^set(CMake_VERSION_${1}/ {s/set(CMake_VERSION_${1} *\([0-9]*\))/\1/;p;}
+" "${cmake_source_dir}/Source/CMakeVersion.cmake"
+}
+
+
+version=''
+dir=''
+while test "$#" != 0; do
+ case "$1" in
+ --dir) shift; dir="$1" ;;
+ --version) shift; version="$1" ;;
+ --) shift ; break ;;
+ -*) die "$usage" ;;
+ *) break ;;
+ esac
+ shift
+done
+test "$#" = 1 || die "$usage"
+readonly dest="$1"
+
+if test -z "$version"; then
+ cmake_version_major="$(cmake_version_component MAJOR)"
+ cmake_version_minor="$(cmake_version_component MINOR)"
+ version="${cmake_version_major}.${cmake_version_minor}"
+fi
+readonly version
+
+if test -z "$dir"; then
+ dir="v${version}"
+fi
+readonly dir
+
+for f in cmake-${version}*; do
+ if ! test -f "${f}"; then
+ continue
+ fi
+
+ echo "pushing '${f}'"
+
+ # Make a copy with a new timestamp and atomically rename into place.
+ tf="${dest}/${dir}/.tmp.${f}"
+ df="${dest}/${dir}/${f}"
+ cp "${f}" "${tf}"
+ mv "${tf}" "${df}"
+
+ # Pause to give each file a distinct time stamp even with 1s resolution
+ # so that sorting by time also sorts alphabetically.
+ sleep 1.1
+done
diff --git a/Utilities/Scripts/regenerate-lexers.bash b/Utilities/Scripts/regenerate-lexers.bash
new file mode 100755
index 000000000..b09f25bf1
--- /dev/null
+++ b/Utilities/Scripts/regenerate-lexers.bash
@@ -0,0 +1,52 @@
+#!/usr/bin/env bash
+
+set -e
+
+forced=1
+if [[ "${1}" = "make" ]]; then
+ forced=0
+fi
+
+pushd "${BASH_SOURCE%/*}/../../Source/LexerParser" > /dev/null
+
+for lexer in \
+ CommandArgument \
+ DependsJava \
+ Expr \
+ Fortran
+do
+ cxx_file=cm${lexer}Lexer.cxx
+ h_file=cm${lexer}Lexer.h
+ in_file=cm${lexer}Lexer.in.l
+
+ if [[ (${in_file} -nt ${cxx_file}) || (${in_file} -nt ${h_file}) || (${forced} -gt 0) ]]; then
+ echo "Generating Lexer ${lexer}"
+ flex --nounistd -DFLEXINT_H --noline --header-file=${h_file} -o${cxx_file} ${in_file}
+ sed -i 's/\s*$//' ${h_file} ${cxx_file} # remove trailing whitespaces
+ sed -i '${/^$/d;}' ${h_file} ${cxx_file} # remove blank line at the end
+ sed -i '1i#include "cmStandardLexer.h"' ${cxx_file} # add cmStandardLexer.h include
+ else
+ echo "Skipped generating Lexer ${lexer}"
+ fi
+done
+
+
+# these lexers (at the moment only the ListFileLexer) are compiled as C and do not generate a header
+for lexer in ListFile
+do
+ c_file=cm${lexer}Lexer.c
+ in_file=cm${lexer}Lexer.in.l
+
+ if [[ (${in_file} -nt ${c_file}) || (${forced} -gt 0) ]]; then
+ echo "Generating Lexer ${lexer}"
+ flex --nounistd -DFLEXINT_H --noline -o${c_file} ${in_file}
+ sed -i 's/\s*$//' ${c_file} # remove trailing whitespaces
+ sed -i '${/^$/d;}' ${c_file} # remove blank line at the end
+ sed -i '1i#include "cmStandardLexer.h"' ${c_file} # add cmStandardLexer.h include
+ else
+ echo "Skipped generating Lexer ${lexer}"
+ fi
+
+done
+
+popd > /dev/null
diff --git a/Utilities/Scripts/regenerate-parsers.bash b/Utilities/Scripts/regenerate-parsers.bash
new file mode 100755
index 000000000..6fb35c028
--- /dev/null
+++ b/Utilities/Scripts/regenerate-parsers.bash
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+
+set -e
+
+forced=1
+if [[ "${1}" = "make" ]]; then
+ forced=0
+fi
+
+pushd "${BASH_SOURCE%/*}/../../Source/LexerParser" > /dev/null
+
+for parser in \
+ CommandArgument \
+ DependsJava \
+ Expr \
+ Fortran
+do
+ in_file=cm${parser}Parser.y
+ cxx_file=cm${parser}Parser.cxx
+ h_file=cm${parser}ParserTokens.h
+ prefix=cm${parser}_yy
+
+ if [[ (${in_file} -nt ${cxx_file}) || (${in_file} -nt ${h_file}) || (${forced} -gt 0) ]]; then
+ echo "Generating Parser ${parser}"
+ bison --yacc --name-prefix=${prefix} --defines=${h_file} -o${cxx_file} ${in_file}
+ sed -i '/\/\* Else will try to reuse/ i\
+#if 0
+/^yyerrlab1:/ a\
+#endif
+' ${cxx_file}
+ else
+ echo "Skipped generating Parser ${parser}"
+ fi
+done
+
+
+popd > /dev/null
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-zstd.bash b/Utilities/Scripts/update-zstd.bash
new file mode 100755
index 000000000..ce2c66b64
--- /dev/null
+++ b/Utilities/Scripts/update-zstd.bash
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+
+set -e
+set -x
+shopt -s dotglob
+
+readonly name="zstd"
+readonly ownership="zstd upstream <kwrobot@kitware.com>"
+readonly subtree="Utilities/cmzstd"
+readonly repo="https://github.com/facebook/zstd.git"
+readonly tag="v1.3.8"
+readonly shortlog=false
+readonly paths="
+ LICENSE
+ README.md
+ lib/common/*.c
+ lib/common/*.h
+ lib/compress/*.c
+ lib/compress/*.h
+ lib/decompress/*.c
+ lib/decompress/*.h
+ lib/deprecated/*.c
+ lib/deprecated/*.h
+ lib/dictBuilder/*.c
+ lib/dictBuilder/*.h
+ lib/zstd.h
+"
+
+extract_source () {
+ git_archive
+ pushd "${extractdir}/${name}-reduced"
+ echo "* -whitespace" > .gitattributes
+ popd
+}
+
+. "${BASH_SOURCE%/*}/update-third-party.bash"
diff --git a/Utilities/Sphinx/colors.py b/Utilities/Sphinx/colors.py
new file mode 100644
index 000000000..dae00634e
--- /dev/null
+++ b/Utilities/Sphinx/colors.py
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+
+from pygments.style import Style
+from pygments.token import Name, Comment, String, Number, Operator, Whitespace
+
+class CMakeTemplateStyle(Style):
+ """
+ for more token names, see pygments/styles.default
+ """
+
+ background_color = "#f8f8f8"
+ default_style = ""
+
+ styles = {
+ Whitespace: "#bbbbbb",
+ Comment: "italic #408080",
+ Operator: "#555555",
+ String: "#217A21",
+ Number: "#105030",
+ Name.Builtin: "#333333", # anything lowercase
+ Name.Function: "#007020", # function
+ Name.Variable: "#1080B0", # <..>
+ Name.Tag: "#bb60d5", # ${..}
+ Name.Constant: "#4070a0", # uppercase only
+ Name.Entity: "italic #70A020", # @..@
+ Name.Attribute: "#906060", # paths, URLs
+ Name.Label: "#A0A000", # anything left over
+ Name.Exception: "bold #FF0000", # for debugging only
+ }
diff --git a/Utilities/cm_zstd.h b/Utilities/cm_zstd.h
new file mode 100644
index 000000000..4bda996aa
--- /dev/null
+++ b/Utilities/cm_zstd.h
@@ -0,0 +1,14 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cm_zstd_h
+#define cm_zstd_h
+
+/* Use the libzstd configured for CMake. */
+#include "cmThirdParty.h"
+#ifdef CMAKE_USE_SYSTEM_ZSTD
+# include <zstd.h>
+#else
+# include <cmzstd/lib/zstd.h>
+#endif
+
+#endif
diff --git a/Utilities/cmcurl/CMake/FindBrotli.cmake b/Utilities/cmcurl/CMake/FindBrotli.cmake
new file mode 100644
index 000000000..351b8f757
--- /dev/null
+++ b/Utilities/cmcurl/CMake/FindBrotli.cmake
@@ -0,0 +1,20 @@
+include(FindPackageHandleStandardArgs)
+
+find_path(BROTLI_INCLUDE_DIR "brotli/decode.h")
+
+find_library(BROTLICOMMON_LIBRARY NAMES brotlicommon)
+find_library(BROTLIDEC_LIBRARY NAMES brotlidec)
+
+find_package_handle_standard_args(BROTLI
+ FOUND_VAR
+ BROTLI_FOUND
+ REQUIRED_VARS
+ BROTLIDEC_LIBRARY
+ BROTLICOMMON_LIBRARY
+ BROTLI_INCLUDE_DIR
+ FAIL_MESSAGE
+ "Could NOT find BROTLI"
+)
+
+set(BROTLI_INCLUDE_DIRS ${BROTLI_INCLUDE_DIR})
+set(BROTLI_LIBRARIES ${BROTLICOMMON_LIBRARY} ${BROTLIDEC_LIBRARY})
diff --git a/Utilities/cmcurl/CMake/cmake_uninstall.cmake.in b/Utilities/cmcurl/CMake/cmake_uninstall.cmake.in
new file mode 100644
index 000000000..db8e5367d
--- /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()
+
+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()
+ else()
+ message(STATUS "File $ENV{DESTDIR}${file} does not exist.")
+ endif()
+endforeach()
diff --git a/Utilities/cmcurl/CMake/curl-config.cmake.in b/Utilities/cmcurl/CMake/curl-config.cmake.in
new file mode 100644
index 000000000..1294e173a
--- /dev/null
+++ b/Utilities/cmcurl/CMake/curl-config.cmake.in
@@ -0,0 +1,12 @@
+@PACKAGE_INIT@
+
+include(CMakeFindDependencyMacro)
+if(@USE_OPENSSL@)
+ find_dependency(OpenSSL @OPENSSL_VERSION_MAJOR@)
+endif()
+if(@USE_ZLIB@)
+ find_dependency(ZLIB @ZLIB_VERSION_MAJOR@)
+endif()
+
+include("${CMAKE_CURRENT_LIST_DIR}/@TARGETS_EXPORT_NAME@.cmake")
+check_required_components("@PROJECT_NAME@")
diff --git a/Utilities/cmcurl/include/curl/urlapi.h b/Utilities/cmcurl/include/curl/urlapi.h
new file mode 100644
index 000000000..58e89d85c
--- /dev/null
+++ b/Utilities/cmcurl/include/curl/urlapi.h
@@ -0,0 +1,123 @@
+#ifndef __CURL_URLAPI_H
+#define __CURL_URLAPI_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2018 - 2019, 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.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* the error codes for the URL API */
+typedef enum {
+ CURLUE_OK,
+ CURLUE_BAD_HANDLE, /* 1 */
+ CURLUE_BAD_PARTPOINTER, /* 2 */
+ CURLUE_MALFORMED_INPUT, /* 3 */
+ CURLUE_BAD_PORT_NUMBER, /* 4 */
+ CURLUE_UNSUPPORTED_SCHEME, /* 5 */
+ CURLUE_URLDECODE, /* 6 */
+ CURLUE_OUT_OF_MEMORY, /* 7 */
+ CURLUE_USER_NOT_ALLOWED, /* 8 */
+ CURLUE_UNKNOWN_PART, /* 9 */
+ CURLUE_NO_SCHEME, /* 10 */
+ CURLUE_NO_USER, /* 11 */
+ CURLUE_NO_PASSWORD, /* 12 */
+ CURLUE_NO_OPTIONS, /* 13 */
+ CURLUE_NO_HOST, /* 14 */
+ CURLUE_NO_PORT, /* 15 */
+ CURLUE_NO_QUERY, /* 16 */
+ CURLUE_NO_FRAGMENT /* 17 */
+} CURLUcode;
+
+typedef enum {
+ CURLUPART_URL,
+ CURLUPART_SCHEME,
+ CURLUPART_USER,
+ CURLUPART_PASSWORD,
+ CURLUPART_OPTIONS,
+ CURLUPART_HOST,
+ CURLUPART_PORT,
+ CURLUPART_PATH,
+ CURLUPART_QUERY,
+ CURLUPART_FRAGMENT,
+ CURLUPART_ZONEID /* added in 7.65.0 */
+} CURLUPart;
+
+#define CURLU_DEFAULT_PORT (1<<0) /* return default port number */
+#define CURLU_NO_DEFAULT_PORT (1<<1) /* act as if no port number was set,
+ if the port number matches the
+ default for the scheme */
+#define CURLU_DEFAULT_SCHEME (1<<2) /* return default scheme if
+ missing */
+#define CURLU_NON_SUPPORT_SCHEME (1<<3) /* allow non-supported scheme */
+#define CURLU_PATH_AS_IS (1<<4) /* leave dot sequences */
+#define CURLU_DISALLOW_USER (1<<5) /* no user+password allowed */
+#define CURLU_URLDECODE (1<<6) /* URL decode on get */
+#define CURLU_URLENCODE (1<<7) /* URL encode on set */
+#define CURLU_APPENDQUERY (1<<8) /* append a form style part */
+#define CURLU_GUESS_SCHEME (1<<9) /* legacy curl-style guessing */
+
+typedef struct Curl_URL CURLU;
+
+/*
+ * curl_url() creates a new CURLU handle and returns a pointer to it.
+ * Must be freed with curl_url_cleanup().
+ */
+CURL_EXTERN CURLU *curl_url(void);
+
+/*
+ * curl_url_cleanup() frees the CURLU handle and related resources used for
+ * the URL parsing. It will not free strings previously returned with the URL
+ * API.
+ */
+CURL_EXTERN void curl_url_cleanup(CURLU *handle);
+
+/*
+ * curl_url_dup() duplicates a CURLU handle and returns a new copy. The new
+ * handle must also be freed with curl_url_cleanup().
+ */
+CURL_EXTERN CURLU *curl_url_dup(CURLU *in);
+
+/*
+ * curl_url_get() extracts a specific part of the URL from a CURLU
+ * handle. Returns error code. The returned pointer MUST be freed with
+ * curl_free() afterwards.
+ */
+CURL_EXTERN CURLUcode curl_url_get(CURLU *handle, CURLUPart what,
+ char **part, unsigned int flags);
+
+/*
+ * curl_url_set() sets a specific part of the URL in a CURLU handle. Returns
+ * error code. The passed in string will be copied. Passing a NULL instead of
+ * a part string, clears that part.
+ */
+CURL_EXTERN CURLUcode curl_url_set(CURLU *handle, CURLUPart what,
+ const char *part, unsigned int flags);
+
+
+#ifdef __cplusplus
+} /* end of extern "C" */
+#endif
+
+#endif
diff --git a/Utilities/cmcurl/lib/altsvc.c b/Utilities/cmcurl/lib/altsvc.c
new file mode 100644
index 000000000..85a4e01b5
--- /dev/null
+++ b/Utilities/cmcurl/lib/altsvc.c
@@ -0,0 +1,569 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2019, 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.
+ *
+ ***************************************************************************/
+/*
+ * The Alt-Svc: header is defined in RFC 7838:
+ * https://tools.ietf.org/html/rfc7838
+ */
+#include "curl_setup.h"
+
+#if !defined(CURL_DISABLE_HTTP) && defined(USE_ALTSVC)
+#include <curl/curl.h>
+#include "urldata.h"
+#include "altsvc.h"
+#include "curl_get_line.h"
+#include "strcase.h"
+#include "parsedate.h"
+#include "sendf.h"
+#include "warnless.h"
+
+/* The last 3 #include files should be in this order */
+#include "curl_printf.h"
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#define MAX_ALTSVC_LINE 4095
+#define MAX_ALTSVC_DATELENSTR "64"
+#define MAX_ALTSVC_DATELEN 64
+#define MAX_ALTSVC_HOSTLENSTR "512"
+#define MAX_ALTSVC_HOSTLEN 512
+#define MAX_ALTSVC_ALPNLENSTR "10"
+#define MAX_ALTSVC_ALPNLEN 10
+
+static enum alpnid alpn2alpnid(char *name)
+{
+ if(strcasecompare(name, "h1"))
+ return ALPN_h1;
+ if(strcasecompare(name, "h2"))
+ return ALPN_h2;
+ if(strcasecompare(name, "h2c"))
+ return ALPN_h2c;
+ if(strcasecompare(name, "h3"))
+ return ALPN_h3;
+ return ALPN_none; /* unknown, probably rubbish input */
+}
+
+/* Given the ALPN ID, return the name */
+const char *Curl_alpnid2str(enum alpnid id)
+{
+ switch(id) {
+ case ALPN_h1:
+ return "h1";
+ case ALPN_h2:
+ return "h2";
+ case ALPN_h2c:
+ return "h2c";
+ case ALPN_h3:
+ return "h3";
+ default:
+ return ""; /* bad */
+ }
+}
+
+
+static void altsvc_free(struct altsvc *as)
+{
+ free(as->srchost);
+ free(as->dsthost);
+ free(as);
+}
+
+static struct altsvc *altsvc_createid(const char *srchost,
+ const char *dsthost,
+ enum alpnid srcalpnid,
+ enum alpnid dstalpnid,
+ unsigned int srcport,
+ unsigned int dstport)
+{
+ struct altsvc *as = calloc(sizeof(struct altsvc), 1);
+ if(!as)
+ return NULL;
+
+ as->srchost = strdup(srchost);
+ if(!as->srchost)
+ goto error;
+ as->dsthost = strdup(dsthost);
+ if(!as->dsthost)
+ goto error;
+
+ as->srcalpnid = srcalpnid;
+ as->dstalpnid = dstalpnid;
+ as->srcport = curlx_ultous(srcport);
+ as->dstport = curlx_ultous(dstport);
+
+ return as;
+ error:
+ altsvc_free(as);
+ return NULL;
+}
+
+static struct altsvc *altsvc_create(char *srchost,
+ char *dsthost,
+ char *srcalpn,
+ char *dstalpn,
+ unsigned int srcport,
+ unsigned int dstport)
+{
+ enum alpnid dstalpnid = alpn2alpnid(dstalpn);
+ enum alpnid srcalpnid = alpn2alpnid(srcalpn);
+ if(!srcalpnid || !dstalpnid)
+ return NULL;
+ return altsvc_createid(srchost, dsthost, srcalpnid, dstalpnid,
+ srcport, dstport);
+}
+
+/* only returns SERIOUS errors */
+static CURLcode altsvc_add(struct altsvcinfo *asi, char *line)
+{
+ /* Example line:
+ h2 example.com 443 h3 shiny.example.com 8443 "20191231 10:00:00" 1
+ */
+ char srchost[MAX_ALTSVC_HOSTLEN + 1];
+ char dsthost[MAX_ALTSVC_HOSTLEN + 1];
+ char srcalpn[MAX_ALTSVC_ALPNLEN + 1];
+ char dstalpn[MAX_ALTSVC_ALPNLEN + 1];
+ char date[MAX_ALTSVC_DATELEN + 1];
+ unsigned int srcport;
+ unsigned int dstport;
+ unsigned int prio;
+ unsigned int persist;
+ int rc;
+
+ rc = sscanf(line,
+ "%" MAX_ALTSVC_ALPNLENSTR "s %" MAX_ALTSVC_HOSTLENSTR "s %u "
+ "%" MAX_ALTSVC_ALPNLENSTR "s %" MAX_ALTSVC_HOSTLENSTR "s %u "
+ "\"%" MAX_ALTSVC_DATELENSTR "[^\"]\" %u %u",
+ srcalpn, srchost, &srcport,
+ dstalpn, dsthost, &dstport,
+ date, &persist, &prio);
+ if(9 == rc) {
+ struct altsvc *as;
+ time_t expires = curl_getdate(date, NULL);
+ as = altsvc_create(srchost, dsthost, srcalpn, dstalpn, srcport, dstport);
+ if(as) {
+ as->expires = expires;
+ as->prio = prio;
+ as->persist = persist ? 1 : 0;
+ Curl_llist_insert_next(&asi->list, asi->list.tail, as, &as->node);
+ asi->num++; /* one more entry */
+ }
+ }
+
+ return CURLE_OK;
+}
+
+/*
+ * Load alt-svc entries from the given file. The text based line-oriented file
+ * format is documented here:
+ * https://github.com/curl/curl/wiki/QUIC-implementation
+ *
+ * This function only returns error on major problems that prevents alt-svc
+ * handling to work completely. It will ignore individual syntactical errors
+ * etc.
+ */
+static CURLcode altsvc_load(struct altsvcinfo *asi, const char *file)
+{
+ CURLcode result = CURLE_OK;
+ char *line = NULL;
+ FILE *fp = fopen(file, FOPEN_READTEXT);
+ if(fp) {
+ line = malloc(MAX_ALTSVC_LINE);
+ if(!line)
+ goto fail;
+ while(Curl_get_line(line, MAX_ALTSVC_LINE, fp)) {
+ char *lineptr = line;
+ while(*lineptr && ISBLANK(*lineptr))
+ lineptr++;
+ if(*lineptr == '#')
+ /* skip commented lines */
+ continue;
+
+ altsvc_add(asi, lineptr);
+ }
+ free(line); /* free the line buffer */
+ fclose(fp);
+ }
+ return result;
+
+ fail:
+ free(line);
+ fclose(fp);
+ return CURLE_OUT_OF_MEMORY;
+}
+
+/*
+ * Write this single altsvc entry to a single output line
+ */
+
+static CURLcode altsvc_out(struct altsvc *as, FILE *fp)
+{
+ struct tm stamp;
+ CURLcode result = Curl_gmtime(as->expires, &stamp);
+ if(result)
+ return result;
+
+ fprintf(fp,
+ "%s %s %u "
+ "%s %s %u "
+ "\"%d%02d%02d "
+ "%02d:%02d:%02d\" "
+ "%u %d\n",
+ Curl_alpnid2str(as->srcalpnid), as->srchost, as->srcport,
+ Curl_alpnid2str(as->dstalpnid), as->dsthost, as->dstport,
+ stamp.tm_year + 1900, stamp.tm_mon + 1, stamp.tm_mday,
+ stamp.tm_hour, stamp.tm_min, stamp.tm_sec,
+ as->persist, as->prio);
+ return CURLE_OK;
+}
+
+/* ---- library-wide functions below ---- */
+
+/*
+ * Curl_altsvc_init() creates a new altsvc cache.
+ * It returns the new instance or NULL if something goes wrong.
+ */
+struct altsvcinfo *Curl_altsvc_init(void)
+{
+ struct altsvcinfo *asi = calloc(sizeof(struct altsvcinfo), 1);
+ if(!asi)
+ return NULL;
+ Curl_llist_init(&asi->list, NULL);
+
+ /* set default behavior */
+ asi->flags = CURLALTSVC_H1
+#ifdef USE_NGHTTP2
+ | CURLALTSVC_H2
+#endif
+#ifdef USE_HTTP3
+ | CURLALTSVC_H3
+#endif
+ ;
+ return asi;
+}
+
+/*
+ * Curl_altsvc_load() loads alt-svc from file.
+ */
+CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file)
+{
+ CURLcode result;
+ DEBUGASSERT(asi);
+ result = altsvc_load(asi, file);
+ return result;
+}
+
+/*
+ * Curl_altsvc_ctrl() passes on the external bitmask.
+ */
+CURLcode Curl_altsvc_ctrl(struct altsvcinfo *asi, const long ctrl)
+{
+ DEBUGASSERT(asi);
+ if(!ctrl)
+ /* unexpected */
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ asi->flags = ctrl;
+ return CURLE_OK;
+}
+
+/*
+ * Curl_altsvc_cleanup() frees an altsvc cache instance and all associated
+ * resources.
+ */
+void Curl_altsvc_cleanup(struct altsvcinfo *altsvc)
+{
+ struct curl_llist_element *e;
+ struct curl_llist_element *n;
+ if(altsvc) {
+ for(e = altsvc->list.head; e; e = n) {
+ struct altsvc *as = e->ptr;
+ n = e->next;
+ altsvc_free(as);
+ }
+ free(altsvc);
+ }
+}
+
+/*
+ * Curl_altsvc_save() writes the altsvc cache to a file.
+ */
+CURLcode Curl_altsvc_save(struct altsvcinfo *altsvc, const char *file)
+{
+ struct curl_llist_element *e;
+ struct curl_llist_element *n;
+ CURLcode result = CURLE_OK;
+ FILE *out;
+
+ if(!altsvc)
+ /* no cache activated */
+ return CURLE_OK;
+
+ if((altsvc->flags & CURLALTSVC_READONLYFILE) || !file[0])
+ /* marked as read-only or zero length file name */
+ return CURLE_OK;
+ out = fopen(file, FOPEN_WRITETEXT);
+ if(!out)
+ return CURLE_WRITE_ERROR;
+ fputs("# Your alt-svc cache. https://curl.haxx.se/docs/alt-svc.html\n"
+ "# This file was generated by libcurl! Edit at your own risk.\n",
+ out);
+ for(e = altsvc->list.head; e; e = n) {
+ struct altsvc *as = e->ptr;
+ n = e->next;
+ result = altsvc_out(as, out);
+ if(result)
+ break;
+ }
+ fclose(out);
+ return result;
+}
+
+static CURLcode getalnum(const char **ptr, char *alpnbuf, size_t buflen)
+{
+ size_t len;
+ const char *protop;
+ const char *p = *ptr;
+ while(*p && ISBLANK(*p))
+ p++;
+ protop = p;
+ while(*p && ISALNUM(*p))
+ p++;
+ len = p - protop;
+
+ if(!len || (len >= buflen))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ memcpy(alpnbuf, protop, len);
+ alpnbuf[len] = 0;
+ *ptr = p;
+ return CURLE_OK;
+}
+
+/* altsvc_flush() removes all alternatives for this source origin from the
+ list */
+static void altsvc_flush(struct altsvcinfo *asi, enum alpnid srcalpnid,
+ const char *srchost, unsigned short srcport)
+{
+ struct curl_llist_element *e;
+ struct curl_llist_element *n;
+ for(e = asi->list.head; e; e = n) {
+ struct altsvc *as = e->ptr;
+ n = e->next;
+ if((srcalpnid == as->srcalpnid) &&
+ (srcport == as->srcport) &&
+ strcasecompare(srchost, as->srchost)) {
+ Curl_llist_remove(&asi->list, e, NULL);
+ altsvc_free(as);
+ asi->num--;
+ }
+ }
+}
+
+#ifdef DEBUGBUILD
+/* to play well with debug builds, we can *set* a fixed time this will
+ return */
+static time_t debugtime(void *unused)
+{
+ char *timestr = getenv("CURL_TIME");
+ (void)unused;
+ if(timestr) {
+ unsigned long val = strtol(timestr, NULL, 10);
+ return (time_t)val;
+ }
+ return time(NULL);
+}
+#define time(x) debugtime(x)
+#endif
+
+/*
+ * Curl_altsvc_parse() takes an incoming alt-svc response header and stores
+ * the data correctly in the cache.
+ *
+ * 'value' points to the header *value*. That's contents to the right of the
+ * header name.
+ */
+CURLcode Curl_altsvc_parse(struct Curl_easy *data,
+ struct altsvcinfo *asi, const char *value,
+ enum alpnid srcalpnid, const char *srchost,
+ unsigned short srcport)
+{
+ const char *p = value;
+ size_t len;
+ enum alpnid dstalpnid = srcalpnid; /* the same by default */
+ char namebuf[MAX_ALTSVC_HOSTLEN] = "";
+ char alpnbuf[MAX_ALTSVC_ALPNLEN] = "";
+ struct altsvc *as;
+ unsigned short dstport = srcport; /* the same by default */
+ const char *semip;
+ time_t maxage = 24 * 3600; /* default is 24 hours */
+ bool persist = FALSE;
+ CURLcode result = getalnum(&p, alpnbuf, sizeof(alpnbuf));
+ if(result)
+ return result;
+
+ DEBUGASSERT(asi);
+
+ /* Flush all cached alternatives for this source origin, if any */
+ altsvc_flush(asi, srcalpnid, srchost, srcport);
+
+ /* "clear" is a magic keyword */
+ if(strcasecompare(alpnbuf, "clear")) {
+ return CURLE_OK;
+ }
+
+ /* The 'ma' and 'persist' flags are annoyingly meant for all alternatives
+ but are set after the list on the line. Scan for the semicolons and get
+ those fields first! */
+ semip = p;
+ do {
+ semip = strchr(semip, ';');
+ if(semip) {
+ char option[32];
+ unsigned long num;
+ char *end_ptr;
+ semip++; /* pass the semicolon */
+ result = getalnum(&semip, option, sizeof(option));
+ if(result)
+ break;
+ while(*semip && ISBLANK(*semip))
+ semip++;
+ if(*semip != '=')
+ continue;
+ semip++;
+ num = strtoul(semip, &end_ptr, 10);
+ if(num < ULONG_MAX) {
+ if(strcasecompare("ma", option))
+ maxage = num;
+ else if(strcasecompare("persist", option) && (num == 1))
+ persist = TRUE;
+ }
+ semip = end_ptr;
+ }
+ } while(semip);
+
+ do {
+ if(*p == '=') {
+ /* [protocol]="[host][:port]" */
+ dstalpnid = alpn2alpnid(alpnbuf);
+ if(!dstalpnid) {
+ infof(data, "Unknown alt-svc protocol \"%s\", ignoring...\n", alpnbuf);
+ return CURLE_OK;
+ }
+ p++;
+ if(*p == '\"') {
+ const char *dsthost;
+ p++;
+ if(*p != ':') {
+ /* host name starts here */
+ const char *hostp = p;
+ while(*p && (ISALNUM(*p) || (*p == '.') || (*p == '-')))
+ p++;
+ len = p - hostp;
+ if(!len || (len >= MAX_ALTSVC_HOSTLEN))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ memcpy(namebuf, hostp, len);
+ namebuf[len] = 0;
+ dsthost = namebuf;
+ }
+ else {
+ /* no destination name, use source host */
+ dsthost = srchost;
+ }
+ if(*p == ':') {
+ /* a port number */
+ char *end_ptr;
+ unsigned long port = strtoul(++p, &end_ptr, 10);
+ if(port > USHRT_MAX || end_ptr == p || *end_ptr != '\"') {
+ infof(data, "Unknown alt-svc port number, ignoring...\n");
+ return CURLE_OK;
+ }
+ p = end_ptr;
+ dstport = curlx_ultous(port);
+ }
+ if(*p++ != '\"')
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ as = altsvc_createid(srchost, dsthost,
+ srcalpnid, dstalpnid,
+ srcport, dstport);
+ if(as) {
+ /* The expires time also needs to take the Age: value (if any) into
+ account. [See RFC 7838 section 3.1] */
+ as->expires = maxage + time(NULL);
+ as->persist = persist;
+ Curl_llist_insert_next(&asi->list, asi->list.tail, as, &as->node);
+ asi->num++; /* one more entry */
+ infof(data, "Added alt-svc: %s:%d over %s\n", dsthost, dstport,
+ Curl_alpnid2str(dstalpnid));
+ }
+ }
+ /* after the double quote there can be a comma if there's another
+ string or a semicolon if no more */
+ if(*p == ',') {
+ /* comma means another alternative is presented */
+ p++;
+ result = getalnum(&p, alpnbuf, sizeof(alpnbuf));
+ if(result)
+ /* failed to parse, but since we already did at least one host we
+ return OK */
+ return CURLE_OK;
+ }
+ }
+ } while(*p && (*p != ';') && (*p != '\n') && (*p != '\r'));
+
+ return CURLE_OK;
+}
+
+/*
+ * Return TRUE on a match
+ */
+bool Curl_altsvc_lookup(struct altsvcinfo *asi,
+ enum alpnid srcalpnid, const char *srchost,
+ int srcport,
+ enum alpnid *dstalpnid, const char **dsthost,
+ int *dstport)
+{
+ struct curl_llist_element *e;
+ struct curl_llist_element *n;
+ time_t now = time(NULL);
+ DEBUGASSERT(asi);
+ DEBUGASSERT(srchost);
+ DEBUGASSERT(dsthost);
+
+ for(e = asi->list.head; e; e = n) {
+ struct altsvc *as = e->ptr;
+ n = e->next;
+ if(as->expires < now) {
+ /* an expired entry, remove */
+ altsvc_free(as);
+ continue;
+ }
+ if((as->srcalpnid == srcalpnid) &&
+ strcasecompare(as->srchost, srchost) &&
+ as->srcport == srcport) {
+ /* match */
+ *dstalpnid = as->dstalpnid;
+ *dsthost = as->dsthost;
+ *dstport = as->dstport;
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+#endif /* CURL_DISABLE_HTTP || USE_ALTSVC */
diff --git a/Utilities/cmcurl/lib/altsvc.h b/Utilities/cmcurl/lib/altsvc.h
new file mode 100644
index 000000000..eefb45bf6
--- /dev/null
+++ b/Utilities/cmcurl/lib/altsvc.h
@@ -0,0 +1,77 @@
+#ifndef HEADER_CURL_ALTSVC_H
+#define HEADER_CURL_ALTSVC_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2019, 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"
+
+#if !defined(CURL_DISABLE_HTTP) && defined(USE_ALTSVC)
+#include <curl/curl.h>
+#include "llist.h"
+
+enum alpnid {
+ ALPN_none,
+ ALPN_h1,
+ ALPN_h2,
+ ALPN_h2c,
+ ALPN_h3
+};
+
+struct altsvc {
+ char *srchost;
+ char *dsthost;
+ unsigned short srcport;
+ unsigned short dstport;
+ enum alpnid srcalpnid;
+ enum alpnid dstalpnid;
+ time_t expires;
+ bool persist;
+ int prio;
+ struct curl_llist_element node;
+};
+
+struct altsvcinfo {
+ char *filename;
+ struct curl_llist list; /* list of entries */
+ size_t num; /* number of alt-svc entries */
+ long flags; /* the publicly set bitmask */
+};
+
+const char *Curl_alpnid2str(enum alpnid id);
+struct altsvcinfo *Curl_altsvc_init(void);
+CURLcode Curl_altsvc_load(struct altsvcinfo *asi, const char *file);
+CURLcode Curl_altsvc_save(struct altsvcinfo *asi, const char *file);
+CURLcode Curl_altsvc_ctrl(struct altsvcinfo *asi, const long ctrl);
+void Curl_altsvc_cleanup(struct altsvcinfo *altsvc);
+CURLcode Curl_altsvc_parse(struct Curl_easy *data,
+ struct altsvcinfo *altsvc, const char *value,
+ enum alpnid srcalpn, const char *srchost,
+ unsigned short srcport);
+bool Curl_altsvc_lookup(struct altsvcinfo *asi,
+ enum alpnid srcalpnid, const char *srchost,
+ int srcport,
+ enum alpnid *dstalpnid, const char **dsthost,
+ int *dstport);
+#else
+/* disabled */
+#define Curl_altsvc_save(a,b)
+#endif /* CURL_DISABLE_HTTP || USE_ALTSVC */
+#endif /* HEADER_CURL_ALTSVC_H */
diff --git a/Utilities/cmcurl/lib/curl_ctype.c b/Utilities/cmcurl/lib/curl_ctype.c
new file mode 100644
index 000000000..1a47fb5e6
--- /dev/null
+++ b/Utilities/cmcurl/lib/curl_ctype.c
@@ -0,0 +1,133 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2018, 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"
+
+#ifndef CURL_DOES_CONVERSIONS
+
+#undef _U
+#define _U (1<<0) /* upper case */
+#undef _L
+#define _L (1<<1) /* lower case */
+#undef _N
+#define _N (1<<2) /* decimal numerical digit */
+#undef _S
+#define _S (1<<3) /* space */
+#undef _P
+#define _P (1<<4) /* punctuation */
+#undef _C
+#define _C (1<<5) /* control */
+#undef _X
+#define _X (1<<6) /* hexadecimal letter */
+#undef _B
+#define _B (1<<7) /* blank */
+
+static const unsigned char ascii[128] = {
+ _C, _C, _C, _C, _C, _C, _C, _C,
+ _C, _C|_S, _C|_S, _C|_S, _C|_S, _C|_S, _C, _C,
+ _C, _C, _C, _C, _C, _C, _C, _C,
+ _C, _C, _C, _C, _C, _C, _C, _C,
+ _S|_B, _P, _P, _P, _P, _P, _P, _P,
+ _P, _P, _P, _P, _P, _P, _P, _P,
+ _N, _N, _N, _N, _N, _N, _N, _N,
+ _N, _N, _P, _P, _P, _P, _P, _P,
+ _P, _U|_X, _U|_X, _U|_X, _U|_X, _U|_X, _U|_X, _U,
+ _U, _U, _U, _U, _U, _U, _U, _U,
+ _U, _U, _U, _U, _U, _U, _U, _U,
+ _U, _U, _U, _P, _P, _P, _P, _P,
+ _P, _L|_X, _L|_X, _L|_X, _L|_X, _L|_X, _L|_X, _L,
+ _L, _L, _L, _L, _L, _L, _L, _L,
+ _L, _L, _L, _L, _L, _L, _L, _L,
+ _L, _L, _L, _P, _P, _P, _P, _C
+};
+
+int Curl_isspace(int c)
+{
+ if((c < 0) || (c >= 0x80))
+ return FALSE;
+ return (ascii[c] & _S);
+}
+
+int Curl_isdigit(int c)
+{
+ if((c < 0) || (c >= 0x80))
+ return FALSE;
+ return (ascii[c] & _N);
+}
+
+int Curl_isalnum(int c)
+{
+ if((c < 0) || (c >= 0x80))
+ return FALSE;
+ return (ascii[c] & (_N|_U|_L));
+}
+
+int Curl_isxdigit(int c)
+{
+ if((c < 0) || (c >= 0x80))
+ return FALSE;
+ return (ascii[c] & (_N|_X));
+}
+
+int Curl_isgraph(int c)
+{
+ if((c < 0) || (c >= 0x80) || (c == ' '))
+ return FALSE;
+ return (ascii[c] & (_N|_X|_U|_L|_P|_S));
+}
+
+int Curl_isprint(int c)
+{
+ if((c < 0) || (c >= 0x80))
+ return FALSE;
+ return (ascii[c] & (_N|_X|_U|_L|_P|_S));
+}
+
+int Curl_isalpha(int c)
+{
+ if((c < 0) || (c >= 0x80))
+ return FALSE;
+ return (ascii[c] & (_U|_L));
+}
+
+int Curl_isupper(int c)
+{
+ if((c < 0) || (c >= 0x80))
+ return FALSE;
+ return (ascii[c] & (_U));
+}
+
+int Curl_islower(int c)
+{
+ if((c < 0) || (c >= 0x80))
+ return FALSE;
+ return (ascii[c] & (_L));
+}
+
+int Curl_iscntrl(int c)
+{
+ if((c < 0) || (c >= 0x80))
+ return FALSE;
+ return (ascii[c] & (_C));
+}
+
+#endif /* !CURL_DOES_CONVERSIONS */
diff --git a/Utilities/cmcurl/lib/curl_ctype.h b/Utilities/cmcurl/lib/curl_ctype.h
new file mode 100644
index 000000000..6e94bb1b4
--- /dev/null
+++ b/Utilities/cmcurl/lib/curl_ctype.h
@@ -0,0 +1,81 @@
+#ifndef HEADER_CURL_CTYPE_H
+#define HEADER_CURL_CTYPE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2018, 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"
+
+#ifdef CURL_DOES_CONVERSIONS
+
+/*
+ * Uppercase macro versions of ANSI/ISO is*() functions/macros which
+ * avoid negative number inputs with argument byte codes > 127.
+ *
+ * For non-ASCII platforms the C library character classification routines
+ * are used despite being locale-dependent, because this is better than
+ * not to work at all.
+ */
+#include <ctype.h>
+
+#define ISSPACE(x) (isspace((int) ((unsigned char)x)))
+#define ISDIGIT(x) (isdigit((int) ((unsigned char)x)))
+#define ISALNUM(x) (isalnum((int) ((unsigned char)x)))
+#define ISXDIGIT(x) (isxdigit((int) ((unsigned char)x)))
+#define ISGRAPH(x) (isgraph((int) ((unsigned char)x)))
+#define ISALPHA(x) (isalpha((int) ((unsigned char)x)))
+#define ISPRINT(x) (isprint((int) ((unsigned char)x)))
+#define ISUPPER(x) (isupper((int) ((unsigned char)x)))
+#define ISLOWER(x) (islower((int) ((unsigned char)x)))
+#define ISCNTRL(x) (iscntrl((int) ((unsigned char)x)))
+#define ISASCII(x) (isascii((int) ((unsigned char)x)))
+
+#else
+
+int Curl_isspace(int c);
+int Curl_isdigit(int c);
+int Curl_isalnum(int c);
+int Curl_isxdigit(int c);
+int Curl_isgraph(int c);
+int Curl_isprint(int c);
+int Curl_isalpha(int c);
+int Curl_isupper(int c);
+int Curl_islower(int c);
+int Curl_iscntrl(int c);
+
+#define ISSPACE(x) (Curl_isspace((int) ((unsigned char)x)))
+#define ISDIGIT(x) (Curl_isdigit((int) ((unsigned char)x)))
+#define ISALNUM(x) (Curl_isalnum((int) ((unsigned char)x)))
+#define ISXDIGIT(x) (Curl_isxdigit((int) ((unsigned char)x)))
+#define ISGRAPH(x) (Curl_isgraph((int) ((unsigned char)x)))
+#define ISALPHA(x) (Curl_isalpha((int) ((unsigned char)x)))
+#define ISPRINT(x) (Curl_isprint((int) ((unsigned char)x)))
+#define ISUPPER(x) (Curl_isupper((int) ((unsigned char)x)))
+#define ISLOWER(x) (Curl_islower((int) ((unsigned char)x)))
+#define ISCNTRL(x) (Curl_iscntrl((int) ((unsigned char)x)))
+#define ISASCII(x) (((x) >= 0) && ((x) <= 0x80))
+
+#endif
+
+#define ISBLANK(x) (int)((((unsigned char)x) == ' ') || \
+ (((unsigned char)x) == '\t'))
+
+#endif /* HEADER_CURL_CTYPE_H */
diff --git a/Utilities/cmcurl/lib/curl_get_line.c b/Utilities/cmcurl/lib/curl_get_line.c
new file mode 100644
index 000000000..c4194851a
--- /dev/null
+++ b/Utilities/cmcurl/lib/curl_get_line.c
@@ -0,0 +1,55 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2019, 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_get_line.h"
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
+/*
+ * get_line() makes sure to only return complete whole lines that fit in 'len'
+ * bytes and end with a newline.
+ */
+char *Curl_get_line(char *buf, int len, FILE *input)
+{
+ bool partial = FALSE;
+ while(1) {
+ char *b = fgets(buf, len, input);
+ if(b) {
+ size_t rlen = strlen(b);
+ if(rlen && (b[rlen-1] == '\n')) {
+ if(partial) {
+ partial = FALSE;
+ continue;
+ }
+ return b;
+ }
+ /* read a partial, discard the next piece that ends with newline */
+ partial = TRUE;
+ }
+ else
+ break;
+ }
+ return NULL;
+}
diff --git a/Utilities/cmcurl/lib/curl_get_line.h b/Utilities/cmcurl/lib/curl_get_line.h
new file mode 100644
index 000000000..532ab080a
--- /dev/null
+++ b/Utilities/cmcurl/lib/curl_get_line.h
@@ -0,0 +1,29 @@
+#ifndef HEADER_CURL_GET_LINE_H
+#define HEADER_CURL_GET_LINE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2019, 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.
+ *
+ ***************************************************************************/
+
+/* get_line() makes sure to only return complete whole lines that fit in 'len'
+ * bytes and end with a newline. */
+char *Curl_get_line(char *buf, int len, FILE *input);
+
+#endif /* HEADER_CURL_GET_LINE_H */
diff --git a/Utilities/cmcurl/lib/curl_path.c b/Utilities/cmcurl/lib/curl_path.c
new file mode 100644
index 000000000..85dddcef1
--- /dev/null
+++ b/Utilities/cmcurl/lib/curl_path.c
@@ -0,0 +1,199 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2019, 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"
+
+#if defined(USE_SSH)
+
+#include <curl/curl.h>
+#include "curl_memory.h"
+#include "curl_path.h"
+#include "escape.h"
+#include "memdebug.h"
+
+/* figure out the path to work with in this particular request */
+CURLcode Curl_getworkingpath(struct connectdata *conn,
+ char *homedir, /* when SFTP is used */
+ char **path) /* returns the allocated
+ real path to work with */
+{
+ struct Curl_easy *data = conn->data;
+ char *real_path = NULL;
+ char *working_path;
+ size_t working_path_len;
+ CURLcode result =
+ Curl_urldecode(data, data->state.up.path, 0, &working_path,
+ &working_path_len, FALSE);
+ if(result)
+ return result;
+
+ /* Check for /~/, indicating relative to the user's home directory */
+ if(conn->handler->protocol & CURLPROTO_SCP) {
+ 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);
+ else
+ memcpy(real_path, working_path, 1 + working_path_len);
+ }
+ else if(conn->handler->protocol & CURLPROTO_SFTP) {
+ if((working_path_len > 1) && (working_path[1] == '~')) {
+ size_t homelen = strlen(homedir);
+ real_path = malloc(homelen + working_path_len + 1);
+ if(real_path == NULL) {
+ free(working_path);
+ return CURLE_OUT_OF_MEMORY;
+ }
+ /* It is referenced to the home directory, so strip the
+ leading '/' */
+ memcpy(real_path, homedir, homelen);
+ real_path[homelen] = '/';
+ real_path[homelen + 1] = '\0';
+ if(working_path_len > 3) {
+ memcpy(real_path + homelen + 1, working_path + 3,
+ 1 + working_path_len -3);
+ }
+ }
+ else {
+ 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);
+ }
+ }
+
+ free(working_path);
+
+ /* store the pointer for the caller to receive */
+ *path = real_path;
+
+ return CURLE_OK;
+}
+
+/* The get_pathname() function is being borrowed from OpenSSH sftp.c
+ version 4.6p1. */
+/*
+ * Copyright (c) 2001-2004 Damien Miller <djm@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+CURLcode Curl_get_pathname(const char **cpp, char **path, char *homedir)
+{
+ const char *cp = *cpp, *end;
+ char quot;
+ unsigned int i, j;
+ size_t fullPathLength, pathLength;
+ bool relativePath = false;
+ static const char WHITESPACE[] = " \t\r\n";
+
+ if(!*cp) {
+ *cpp = NULL;
+ *path = NULL;
+ return CURLE_QUOTE_ERROR;
+ }
+ /* Ignore leading whitespace */
+ cp += strspn(cp, WHITESPACE);
+ /* Allocate enough space for home directory and filename + separator */
+ fullPathLength = strlen(cp) + strlen(homedir) + 2;
+ *path = malloc(fullPathLength);
+ if(*path == NULL)
+ return CURLE_OUT_OF_MEMORY;
+
+ /* Check for quoted filenames */
+ if(*cp == '\"' || *cp == '\'') {
+ quot = *cp++;
+
+ /* Search for terminating quote, unescape some chars */
+ for(i = j = 0; i <= strlen(cp); i++) {
+ if(cp[i] == quot) { /* Found quote */
+ i++;
+ (*path)[j] = '\0';
+ break;
+ }
+ if(cp[i] == '\0') { /* End of string */
+ /*error("Unterminated quote");*/
+ goto fail;
+ }
+ if(cp[i] == '\\') { /* Escaped characters */
+ i++;
+ if(cp[i] != '\'' && cp[i] != '\"' &&
+ cp[i] != '\\') {
+ /*error("Bad escaped character '\\%c'",
+ cp[i]);*/
+ goto fail;
+ }
+ }
+ (*path)[j++] = cp[i];
+ }
+
+ if(j == 0) {
+ /*error("Empty quotes");*/
+ goto fail;
+ }
+ *cpp = cp + i + strspn(cp + i, WHITESPACE);
+ }
+ else {
+ /* Read to end of filename - either to white space or terminator */
+ end = strpbrk(cp, WHITESPACE);
+ if(end == NULL)
+ end = strchr(cp, '\0');
+ /* return pointer to second parameter if it exists */
+ *cpp = end + strspn(end, WHITESPACE);
+ pathLength = 0;
+ relativePath = (cp[0] == '/' && cp[1] == '~' && cp[2] == '/');
+ /* Handling for relative path - prepend home directory */
+ if(relativePath) {
+ strcpy(*path, homedir);
+ pathLength = strlen(homedir);
+ (*path)[pathLength++] = '/';
+ (*path)[pathLength] = '\0';
+ cp += 3;
+ }
+ /* Copy path name up until first "white space" */
+ memcpy(&(*path)[pathLength], cp, (int)(end - cp));
+ pathLength += (int)(end - cp);
+ (*path)[pathLength] = '\0';
+ }
+ return CURLE_OK;
+
+ fail:
+ Curl_safefree(*path);
+ return CURLE_QUOTE_ERROR;
+}
+
+#endif /* if SSH is used */
diff --git a/Utilities/cmcurl/lib/curl_path.h b/Utilities/cmcurl/lib/curl_path.h
new file mode 100644
index 000000000..636c37f20
--- /dev/null
+++ b/Utilities/cmcurl/lib/curl_path.h
@@ -0,0 +1,47 @@
+#ifndef HEADER_CURL_PATH_H
+#define HEADER_CURL_PATH_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2018, 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 "urldata.h"
+
+#ifdef WIN32
+# undef PATH_MAX
+# define PATH_MAX MAX_PATH
+# ifndef R_OK
+# define R_OK 4
+# endif
+#endif
+
+#ifndef PATH_MAX
+#define PATH_MAX 1024 /* just an extra precaution since there are systems that
+ have their definition hidden well */
+#endif
+
+CURLcode Curl_getworkingpath(struct connectdata *conn,
+ char *homedir,
+ char **path);
+
+CURLcode Curl_get_pathname(const char **cpp, char **path, char *homedir);
+#endif /* HEADER_CURL_PATH_H */
diff --git a/Utilities/cmcurl/lib/curl_range.c b/Utilities/cmcurl/lib/curl_range.c
new file mode 100644
index 000000000..aa3c49332
--- /dev/null
+++ b/Utilities/cmcurl/lib/curl_range.c
@@ -0,0 +1,95 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2018, 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 "curl_range.h"
+#include "sendf.h"
+#include "strtoofft.h"
+
+/* Only include this function if one or more of FTP, FILE are enabled. */
+#if !defined(CURL_DISABLE_FTP) || !defined(CURL_DISABLE_FILE)
+
+ /*
+ Check if this is a range download, and if so, set the internal variables
+ properly.
+ */
+CURLcode Curl_range(struct connectdata *conn)
+{
+ curl_off_t from, to;
+ char *ptr;
+ char *ptr2;
+ struct Curl_easy *data = conn->data;
+
+ if(data->state.use_range && data->state.range) {
+ 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_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_t == CURL_OFFT_INVAL) && !to_t) {
+ /* -Y */
+ data->req.maxdownload = to;
+ data->state.resume_from = -to;
+ DEBUGF(infof(data, "RANGE the last %" CURL_FORMAT_CURL_OFF_T " bytes\n",
+ to));
+ }
+ else {
+ /* X-Y */
+ curl_off_t totalsize;
+
+ /* Ensure the range is sensible - to should follow from. */
+ if(from > to)
+ return CURLE_RANGE_ERROR;
+
+ totalsize = to - from;
+ if(totalsize == CURL_OFF_T_MAX)
+ 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",
+ from, data->req.maxdownload));
+ }
+ DEBUGF(infof(data, "range-download from %" CURL_FORMAT_CURL_OFF_T
+ " to %" CURL_FORMAT_CURL_OFF_T ", totally %"
+ CURL_FORMAT_CURL_OFF_T " bytes\n",
+ from, to, data->req.maxdownload));
+ }
+ else
+ data->req.maxdownload = -1;
+ return CURLE_OK;
+}
+
+#endif
diff --git a/Utilities/cmcurl/lib/curl_range.h b/Utilities/cmcurl/lib/curl_range.h
new file mode 100644
index 000000000..2350df992
--- /dev/null
+++ b/Utilities/cmcurl/lib/curl_range.h
@@ -0,0 +1,30 @@
+#ifndef HEADER_CURL_RANGE_H
+#define HEADER_CURL_RANGE_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2018, 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 "urldata.h"
+
+CURLcode Curl_range(struct connectdata *conn);
+
+#endif /* HEADER_CURL_RANGE_H */
diff --git a/Utilities/cmcurl/lib/curl_sha256.h b/Utilities/cmcurl/lib/curl_sha256.h
new file mode 100644
index 000000000..6db4b04db
--- /dev/null
+++ b/Utilities/cmcurl/lib/curl_sha256.h
@@ -0,0 +1,32 @@
+#ifndef HEADER_CURL_SHA256_H
+#define HEADER_CURL_SHA256_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2010, Florin Petriuc, <petriuc.florin@gmail.com>
+ *
+ * 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.
+ *
+ ***************************************************************************/
+
+#ifndef CURL_DISABLE_CRYPTO_AUTH
+
+void Curl_sha256it(unsigned char *outbuffer,
+ const unsigned char *input);
+
+#endif
+
+#endif /* HEADER_CURL_SHA256_H */
diff --git a/Utilities/cmcurl/lib/doh.c b/Utilities/cmcurl/lib/doh.c
new file mode 100644
index 000000000..6d1f3303b
--- /dev/null
+++ b/Utilities/cmcurl/lib/doh.c
@@ -0,0 +1,967 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2018 - 2019, 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"
+
+#ifndef CURL_DISABLE_DOH
+
+#include "urldata.h"
+#include "curl_addrinfo.h"
+#include "doh.h"
+
+#include "sendf.h"
+#include "multiif.h"
+#include "url.h"
+#include "share.h"
+#include "curl_base64.h"
+#include "connect.h"
+#include "strdup.h"
+/* The last 3 #include files should be in this order */
+#include "curl_printf.h"
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#define DNS_CLASS_IN 0x01
+#define DOH_MAX_RESPONSE_SIZE 3000 /* bytes */
+
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
+static const char * const errors[]={
+ "",
+ "Bad label",
+ "Out of range",
+ "Label loop",
+ "Too small",
+ "Out of memory",
+ "RDATA length",
+ "Malformat",
+ "Bad RCODE",
+ "Unexpected TYPE",
+ "Unexpected CLASS",
+ "No content",
+ "Bad ID"
+};
+
+static const char *doh_strerror(DOHcode code)
+{
+ if((code >= DOH_OK) && (code <= DOH_DNS_BAD_ID))
+ return errors[code];
+ return "bad error code";
+}
+#endif
+
+#ifdef DEBUGBUILD
+#define UNITTEST
+#else
+#define UNITTEST static
+#endif
+
+UNITTEST DOHcode doh_encode(const char *host,
+ DNStype dnstype,
+ unsigned char *dnsp, /* buffer */
+ size_t len, /* buffer size */
+ size_t *olen) /* output length */
+{
+ size_t hostlen = strlen(host);
+ unsigned char *orig = dnsp;
+ const char *hostp = host;
+
+ if(len < (12 + hostlen + 4))
+ return DOH_TOO_SMALL_BUFFER;
+
+ *dnsp++ = 0; /* 16 bit id */
+ *dnsp++ = 0;
+ *dnsp++ = 0x01; /* |QR| Opcode |AA|TC|RD| Set the RD bit */
+ *dnsp++ = '\0'; /* |RA| Z | RCODE | */
+ *dnsp++ = '\0';
+ *dnsp++ = 1; /* QDCOUNT (number of entries in the question section) */
+ *dnsp++ = '\0';
+ *dnsp++ = '\0'; /* ANCOUNT */
+ *dnsp++ = '\0';
+ *dnsp++ = '\0'; /* NSCOUNT */
+ *dnsp++ = '\0';
+ *dnsp++ = '\0'; /* ARCOUNT */
+
+ /* store a QNAME */
+ do {
+ char *dot = strchr(hostp, '.');
+ size_t labellen;
+ bool found = false;
+ if(dot) {
+ found = true;
+ labellen = dot - hostp;
+ }
+ else
+ labellen = strlen(hostp);
+ if(labellen > 63) {
+ /* too long label, error out */
+ *olen = 0;
+ return DOH_DNS_BAD_LABEL;
+ }
+ *dnsp++ = (unsigned char)labellen;
+ memcpy(dnsp, hostp, labellen);
+ dnsp += labellen;
+ hostp += labellen + 1;
+ if(!found) {
+ *dnsp++ = 0; /* terminating zero */
+ break;
+ }
+ } while(1);
+
+ *dnsp++ = '\0'; /* upper 8 bit TYPE */
+ *dnsp++ = (unsigned char)dnstype;
+ *dnsp++ = '\0'; /* upper 8 bit CLASS */
+ *dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */
+
+ *olen = dnsp - orig;
+ return DOH_OK;
+}
+
+static size_t
+doh_write_cb(void *contents, size_t size, size_t nmemb, void *userp)
+{
+ size_t realsize = size * nmemb;
+ struct dohresponse *mem = (struct dohresponse *)userp;
+
+ if((mem->size + realsize) > DOH_MAX_RESPONSE_SIZE)
+ /* suspiciously much for us */
+ return 0;
+
+ mem->memory = Curl_saferealloc(mem->memory, mem->size + realsize);
+ if(!mem->memory)
+ /* out of memory! */
+ return 0;
+
+ memcpy(&(mem->memory[mem->size]), contents, realsize);
+ mem->size += realsize;
+
+ return realsize;
+}
+
+/* called from multi.c when this DOH transfer is complete */
+static int Curl_doh_done(struct Curl_easy *doh, CURLcode result)
+{
+ struct Curl_easy *data = doh->set.dohfor;
+ /* so one of the DOH request done for the 'data' transfer is now complete! */
+ data->req.doh.pending--;
+ infof(data, "a DOH request is completed, %u to go\n", data->req.doh.pending);
+ if(result)
+ infof(data, "DOH request %s\n", curl_easy_strerror(result));
+
+ if(!data->req.doh.pending) {
+ /* DOH completed */
+ curl_slist_free_all(data->req.doh.headers);
+ data->req.doh.headers = NULL;
+ Curl_expire(data, 0, EXPIRE_RUN_NOW);
+ }
+ return 0;
+}
+
+#define ERROR_CHECK_SETOPT(x,y) \
+do { \
+ result = curl_easy_setopt(doh, x, y); \
+ if(result) \
+ goto error; \
+} WHILE_FALSE
+
+static CURLcode dohprobe(struct Curl_easy *data,
+ struct dnsprobe *p, DNStype dnstype,
+ const char *host,
+ const char *url, CURLM *multi,
+ struct curl_slist *headers)
+{
+ struct Curl_easy *doh = NULL;
+ char *nurl = NULL;
+ CURLcode result = CURLE_OK;
+ timediff_t timeout_ms;
+ DOHcode d = doh_encode(host, dnstype, p->dohbuffer, sizeof(p->dohbuffer),
+ &p->dohlen);
+ if(d) {
+ failf(data, "Failed to encode DOH packet [%d]\n", d);
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ p->dnstype = dnstype;
+ p->serverdoh.memory = NULL;
+ /* the memory will be grown as needed by realloc in the doh_write_cb
+ function */
+ p->serverdoh.size = 0;
+
+ /* Note: this is code for sending the DoH request with GET but there's still
+ no logic that actually enables this. We should either add that ability or
+ yank out the GET code. Discuss! */
+ if(data->set.doh_get) {
+ char *b64;
+ size_t b64len;
+ result = Curl_base64url_encode(data, (char *)p->dohbuffer, p->dohlen,
+ &b64, &b64len);
+ if(result)
+ goto error;
+ nurl = aprintf("%s?dns=%s", url, b64);
+ free(b64);
+ if(!nurl) {
+ result = CURLE_OUT_OF_MEMORY;
+ goto error;
+ }
+ url = nurl;
+ }
+
+ timeout_ms = Curl_timeleft(data, NULL, TRUE);
+
+ /* Curl_open() is the internal version of curl_easy_init() */
+ result = Curl_open(&doh);
+ if(!result) {
+ /* pass in the struct pointer via a local variable to please coverity and
+ the gcc typecheck helpers */
+ struct dohresponse *resp = &p->serverdoh;
+ ERROR_CHECK_SETOPT(CURLOPT_URL, url);
+ ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_write_cb);
+ ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, resp);
+ if(!data->set.doh_get) {
+ ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, p->dohbuffer);
+ ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)p->dohlen);
+ }
+ ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, headers);
+#ifdef USE_NGHTTP2
+ ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
+#endif
+#ifndef CURLDEBUG
+ /* enforce HTTPS if not debug */
+ ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
+#endif
+ ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms);
+ if(data->set.verbose)
+ ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L);
+ if(data->set.no_signal)
+ ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L);
+
+ /* Inherit *some* SSL options from the user's transfer. This is a
+ best-guess as to which options are needed for compatibility. #3661 */
+ if(data->set.ssl.falsestart)
+ ERROR_CHECK_SETOPT(CURLOPT_SSL_FALSESTART, 1L);
+ if(data->set.ssl.primary.verifyhost)
+ ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST, 2L);
+ if(data->set.proxy_ssl.primary.verifyhost)
+ ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_VERIFYHOST, 2L);
+ if(data->set.ssl.primary.verifypeer)
+ ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER, 1L);
+ if(data->set.proxy_ssl.primary.verifypeer)
+ ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_VERIFYPEER, 1L);
+ if(data->set.ssl.primary.verifystatus)
+ ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS, 1L);
+ if(data->set.str[STRING_SSL_CAFILE_ORIG]) {
+ ERROR_CHECK_SETOPT(CURLOPT_CAINFO,
+ data->set.str[STRING_SSL_CAFILE_ORIG]);
+ }
+ if(data->set.str[STRING_SSL_CAFILE_PROXY]) {
+ ERROR_CHECK_SETOPT(CURLOPT_PROXY_CAINFO,
+ data->set.str[STRING_SSL_CAFILE_PROXY]);
+ }
+ if(data->set.str[STRING_SSL_CAPATH_ORIG]) {
+ ERROR_CHECK_SETOPT(CURLOPT_CAPATH,
+ data->set.str[STRING_SSL_CAPATH_ORIG]);
+ }
+ if(data->set.str[STRING_SSL_CAPATH_PROXY]) {
+ ERROR_CHECK_SETOPT(CURLOPT_PROXY_CAPATH,
+ data->set.str[STRING_SSL_CAPATH_PROXY]);
+ }
+ if(data->set.str[STRING_SSL_CRLFILE_ORIG]) {
+ ERROR_CHECK_SETOPT(CURLOPT_CRLFILE,
+ data->set.str[STRING_SSL_CRLFILE_ORIG]);
+ }
+ if(data->set.str[STRING_SSL_CRLFILE_PROXY]) {
+ ERROR_CHECK_SETOPT(CURLOPT_PROXY_CRLFILE,
+ data->set.str[STRING_SSL_CRLFILE_PROXY]);
+ }
+ if(data->set.ssl.certinfo)
+ ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L);
+ if(data->set.str[STRING_SSL_RANDOM_FILE]) {
+ ERROR_CHECK_SETOPT(CURLOPT_RANDOM_FILE,
+ data->set.str[STRING_SSL_RANDOM_FILE]);
+ }
+ if(data->set.str[STRING_SSL_EGDSOCKET]) {
+ ERROR_CHECK_SETOPT(CURLOPT_EGDSOCKET,
+ data->set.str[STRING_SSL_EGDSOCKET]);
+ }
+ if(data->set.ssl.no_revoke)
+ ERROR_CHECK_SETOPT(CURLOPT_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
+ if(data->set.proxy_ssl.no_revoke)
+ ERROR_CHECK_SETOPT(CURLOPT_PROXY_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
+ if(data->set.ssl.fsslctx)
+ ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl.fsslctx);
+ if(data->set.ssl.fsslctxp)
+ ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl.fsslctxp);
+
+ doh->set.fmultidone = Curl_doh_done;
+ doh->set.dohfor = data; /* identify for which transfer this is done */
+ p->easy = doh;
+
+ /* add this transfer to the multi handle */
+ if(curl_multi_add_handle(multi, doh))
+ goto error;
+ }
+ else
+ goto error;
+ free(nurl);
+ return CURLE_OK;
+
+ error:
+ free(nurl);
+ Curl_close(doh);
+ return result;
+}
+
+/*
+ * Curl_doh() resolves a name using DOH. It resolves a name and returns a
+ * 'Curl_addrinfo *' with the address information.
+ */
+
+Curl_addrinfo *Curl_doh(struct connectdata *conn,
+ const char *hostname,
+ int port,
+ int *waitp)
+{
+ struct Curl_easy *data = conn->data;
+ CURLcode result = CURLE_OK;
+ *waitp = TRUE; /* this never returns synchronously */
+ (void)conn;
+ (void)hostname;
+ (void)port;
+
+ /* start clean, consider allocating this struct on demand */
+ memset(&data->req.doh, 0, sizeof(struct dohdata));
+
+ data->req.doh.host = hostname;
+ data->req.doh.port = port;
+ data->req.doh.headers =
+ curl_slist_append(NULL,
+ "Content-Type: application/dns-message");
+ if(!data->req.doh.headers)
+ goto error;
+
+ if(conn->ip_version != CURL_IPRESOLVE_V6) {
+ /* create IPv4 DOH request */
+ result = dohprobe(data, &data->req.doh.probe[0], DNS_TYPE_A,
+ hostname, data->set.str[STRING_DOH],
+ data->multi, data->req.doh.headers);
+ if(result)
+ goto error;
+ data->req.doh.pending++;
+ }
+
+ if(conn->ip_version != CURL_IPRESOLVE_V4) {
+ /* create IPv6 DOH request */
+ result = dohprobe(data, &data->req.doh.probe[1], DNS_TYPE_AAAA,
+ hostname, data->set.str[STRING_DOH],
+ data->multi, data->req.doh.headers);
+ if(result)
+ goto error;
+ data->req.doh.pending++;
+ }
+ return NULL;
+
+ error:
+ curl_slist_free_all(data->req.doh.headers);
+ data->req.doh.headers = NULL;
+ curl_easy_cleanup(data->req.doh.probe[0].easy);
+ data->req.doh.probe[0].easy = NULL;
+ curl_easy_cleanup(data->req.doh.probe[1].easy);
+ data->req.doh.probe[1].easy = NULL;
+ return NULL;
+}
+
+static DOHcode skipqname(unsigned char *doh, size_t dohlen,
+ unsigned int *indexp)
+{
+ unsigned char length;
+ do {
+ if(dohlen < (*indexp + 1))
+ return DOH_DNS_OUT_OF_RANGE;
+ length = doh[*indexp];
+ if((length & 0xc0) == 0xc0) {
+ /* name pointer, advance over it and be done */
+ if(dohlen < (*indexp + 2))
+ return DOH_DNS_OUT_OF_RANGE;
+ *indexp += 2;
+ break;
+ }
+ if(length & 0xc0)
+ return DOH_DNS_BAD_LABEL;
+ if(dohlen < (*indexp + 1 + length))
+ return DOH_DNS_OUT_OF_RANGE;
+ *indexp += 1 + length;
+ } while(length);
+ return DOH_OK;
+}
+
+static unsigned short get16bit(unsigned char *doh, int index)
+{
+ return (unsigned short)((doh[index] << 8) | doh[index + 1]);
+}
+
+static unsigned int get32bit(unsigned char *doh, int index)
+{
+ return (doh[index] << 24) | (doh[index + 1] << 16) |
+ (doh[index + 2] << 8) | doh[index + 3];
+}
+
+static DOHcode store_a(unsigned char *doh, int index, struct dohentry *d)
+{
+ /* silently ignore addresses over the limit */
+ if(d->numaddr < DOH_MAX_ADDR) {
+ struct dohaddr *a = &d->addr[d->numaddr];
+ a->type = DNS_TYPE_A;
+ memcpy(&a->ip.v4, &doh[index], 4);
+ d->numaddr++;
+ }
+ return DOH_OK;
+}
+
+static DOHcode store_aaaa(unsigned char *doh, int index, struct dohentry *d)
+{
+ /* silently ignore addresses over the limit */
+ if(d->numaddr < DOH_MAX_ADDR) {
+ struct dohaddr *a = &d->addr[d->numaddr];
+ a->type = DNS_TYPE_AAAA;
+ memcpy(&a->ip.v6, &doh[index], 16);
+ d->numaddr++;
+ }
+ return DOH_OK;
+}
+
+static DOHcode cnameappend(struct cnamestore *c,
+ unsigned char *src,
+ size_t len)
+{
+ if(!c->alloc) {
+ c->allocsize = len + 1;
+ c->alloc = malloc(c->allocsize);
+ if(!c->alloc)
+ return DOH_OUT_OF_MEM;
+ }
+ else if(c->allocsize < (c->allocsize + len + 1)) {
+ char *ptr;
+ c->allocsize += len + 1;
+ ptr = realloc(c->alloc, c->allocsize);
+ if(!ptr) {
+ free(c->alloc);
+ return DOH_OUT_OF_MEM;
+ }
+ c->alloc = ptr;
+ }
+ memcpy(&c->alloc[c->len], src, len);
+ c->len += len;
+ c->alloc[c->len] = 0; /* keep it zero terminated */
+ return DOH_OK;
+}
+
+static DOHcode store_cname(unsigned char *doh,
+ size_t dohlen,
+ unsigned int index,
+ struct dohentry *d)
+{
+ struct cnamestore *c;
+ unsigned int loop = 128; /* a valid DNS name can never loop this much */
+ unsigned char length;
+
+ if(d->numcname == DOH_MAX_CNAME)
+ return DOH_OK; /* skip! */
+
+ c = &d->cname[d->numcname++];
+ do {
+ if(index >= dohlen)
+ return DOH_DNS_OUT_OF_RANGE;
+ length = doh[index];
+ if((length & 0xc0) == 0xc0) {
+ int newpos;
+ /* name pointer, get the new offset (14 bits) */
+ if((index + 1) >= dohlen)
+ return DOH_DNS_OUT_OF_RANGE;
+
+ /* move to the the new index */
+ newpos = (length & 0x3f) << 8 | doh[index + 1];
+ index = newpos;
+ continue;
+ }
+ else if(length & 0xc0)
+ return DOH_DNS_BAD_LABEL; /* bad input */
+ else
+ index++;
+
+ if(length) {
+ DOHcode rc;
+ if(c->len) {
+ rc = cnameappend(c, (unsigned char *)".", 1);
+ if(rc)
+ return rc;
+ }
+ if((index + length) > dohlen)
+ return DOH_DNS_BAD_LABEL;
+
+ rc = cnameappend(c, &doh[index], length);
+ if(rc)
+ return rc;
+ index += length;
+ }
+ } while(length && --loop);
+
+ if(!loop)
+ return DOH_DNS_LABEL_LOOP;
+ return DOH_OK;
+}
+
+static DOHcode rdata(unsigned char *doh,
+ size_t dohlen,
+ unsigned short rdlength,
+ unsigned short type,
+ int index,
+ struct dohentry *d)
+{
+ /* RDATA
+ - A (TYPE 1): 4 bytes
+ - AAAA (TYPE 28): 16 bytes
+ - NS (TYPE 2): N bytes */
+ DOHcode rc;
+
+ switch(type) {
+ case DNS_TYPE_A:
+ if(rdlength != 4)
+ return DOH_DNS_RDATA_LEN;
+ rc = store_a(doh, index, d);
+ if(rc)
+ return rc;
+ break;
+ case DNS_TYPE_AAAA:
+ if(rdlength != 16)
+ return DOH_DNS_RDATA_LEN;
+ rc = store_aaaa(doh, index, d);
+ if(rc)
+ return rc;
+ break;
+ case DNS_TYPE_CNAME:
+ rc = store_cname(doh, dohlen, index, d);
+ if(rc)
+ return rc;
+ break;
+ default:
+ /* unsupported type, just skip it */
+ break;
+ }
+ return DOH_OK;
+}
+
+static void init_dohentry(struct dohentry *de)
+{
+ memset(de, 0, sizeof(*de));
+ de->ttl = INT_MAX;
+}
+
+
+UNITTEST DOHcode doh_decode(unsigned char *doh,
+ size_t dohlen,
+ DNStype dnstype,
+ struct dohentry *d)
+{
+ unsigned char rcode;
+ unsigned short qdcount;
+ unsigned short ancount;
+ unsigned short type = 0;
+ unsigned short rdlength;
+ unsigned short nscount;
+ unsigned short arcount;
+ unsigned int index = 12;
+ DOHcode rc;
+
+ if(dohlen < 12)
+ return DOH_TOO_SMALL_BUFFER; /* too small */
+ if(!doh || doh[0] || doh[1])
+ return DOH_DNS_BAD_ID; /* bad ID */
+ rcode = doh[3] & 0x0f;
+ if(rcode)
+ return DOH_DNS_BAD_RCODE; /* bad rcode */
+
+ qdcount = get16bit(doh, 4);
+ while(qdcount) {
+ rc = skipqname(doh, dohlen, &index);
+ if(rc)
+ return rc; /* bad qname */
+ if(dohlen < (index + 4))
+ return DOH_DNS_OUT_OF_RANGE;
+ index += 4; /* skip question's type and class */
+ qdcount--;
+ }
+
+ ancount = get16bit(doh, 6);
+ while(ancount) {
+ unsigned short class;
+ unsigned int ttl;
+
+ rc = skipqname(doh, dohlen, &index);
+ if(rc)
+ return rc; /* bad qname */
+
+ if(dohlen < (index + 2))
+ return DOH_DNS_OUT_OF_RANGE;
+
+ type = get16bit(doh, index);
+ if((type != DNS_TYPE_CNAME) && (type != dnstype))
+ /* Not the same type as was asked for nor CNAME */
+ return DOH_DNS_UNEXPECTED_TYPE;
+ index += 2;
+
+ if(dohlen < (index + 2))
+ return DOH_DNS_OUT_OF_RANGE;
+ class = get16bit(doh, index);
+ if(DNS_CLASS_IN != class)
+ return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */
+ index += 2;
+
+ if(dohlen < (index + 4))
+ return DOH_DNS_OUT_OF_RANGE;
+
+ ttl = get32bit(doh, index);
+ if(ttl < d->ttl)
+ d->ttl = ttl;
+ index += 4;
+
+ if(dohlen < (index + 2))
+ return DOH_DNS_OUT_OF_RANGE;
+
+ rdlength = get16bit(doh, index);
+ index += 2;
+ if(dohlen < (index + rdlength))
+ return DOH_DNS_OUT_OF_RANGE;
+
+ rc = rdata(doh, dohlen, rdlength, type, index, d);
+ if(rc)
+ return rc; /* bad rdata */
+ index += rdlength;
+ ancount--;
+ }
+
+ nscount = get16bit(doh, 8);
+ while(nscount) {
+ rc = skipqname(doh, dohlen, &index);
+ if(rc)
+ return rc; /* bad qname */
+
+ if(dohlen < (index + 8))
+ return DOH_DNS_OUT_OF_RANGE;
+
+ index += 2 + 2 + 4; /* type, class and ttl */
+
+ if(dohlen < (index + 2))
+ return DOH_DNS_OUT_OF_RANGE;
+
+ rdlength = get16bit(doh, index);
+ index += 2;
+ if(dohlen < (index + rdlength))
+ return DOH_DNS_OUT_OF_RANGE;
+ index += rdlength;
+ nscount--;
+ }
+
+ arcount = get16bit(doh, 10);
+ while(arcount) {
+ rc = skipqname(doh, dohlen, &index);
+ if(rc)
+ return rc; /* bad qname */
+
+ if(dohlen < (index + 8))
+ return DOH_DNS_OUT_OF_RANGE;
+
+ index += 2 + 2 + 4; /* type, class and ttl */
+
+ if(dohlen < (index + 2))
+ return DOH_DNS_OUT_OF_RANGE;
+
+ rdlength = get16bit(doh, index);
+ index += 2;
+ if(dohlen < (index + rdlength))
+ return DOH_DNS_OUT_OF_RANGE;
+ index += rdlength;
+ arcount--;
+ }
+
+ if(index != dohlen)
+ return DOH_DNS_MALFORMAT; /* something is wrong */
+
+ if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr)
+ /* nothing stored! */
+ return DOH_NO_CONTENT;
+
+ return DOH_OK; /* ok */
+}
+
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
+static void showdoh(struct Curl_easy *data,
+ struct dohentry *d)
+{
+ int i;
+ infof(data, "TTL: %u seconds\n", d->ttl);
+ for(i = 0; i < d->numaddr; i++) {
+ struct dohaddr *a = &d->addr[i];
+ if(a->type == DNS_TYPE_A) {
+ infof(data, "DOH A: %u.%u.%u.%u\n",
+ a->ip.v4[0], a->ip.v4[1],
+ a->ip.v4[2], a->ip.v4[3]);
+ }
+ else if(a->type == DNS_TYPE_AAAA) {
+ int j;
+ char buffer[128];
+ char *ptr;
+ size_t len;
+ msnprintf(buffer, 128, "DOH AAAA: ");
+ ptr = &buffer[10];
+ len = 118;
+ for(j = 0; j < 16; j += 2) {
+ size_t l;
+ msnprintf(ptr, len, "%s%02x%02x", j?":":"", d->addr[i].ip.v6[j],
+ d->addr[i].ip.v6[j + 1]);
+ l = strlen(ptr);
+ len -= l;
+ ptr += l;
+ }
+ infof(data, "%s\n", buffer);
+ }
+ }
+ for(i = 0; i < d->numcname; i++) {
+ infof(data, "CNAME: %s\n", d->cname[i].alloc);
+ }
+}
+#else
+#define showdoh(x,y)
+#endif
+
+/*
+ * doh2ai()
+ *
+ * This function returns a pointer to the first element of a newly allocated
+ * Curl_addrinfo struct linked list filled with the data from a set of DOH
+ * lookups. Curl_addrinfo is meant to work like the addrinfo struct does for
+ * a IPv6 stack, but usable also for IPv4, all hosts and environments.
+ *
+ * The memory allocated by this function *MUST* be free'd later on calling
+ * Curl_freeaddrinfo(). For each successful call to this function there
+ * must be an associated call later to Curl_freeaddrinfo().
+ */
+
+static Curl_addrinfo *
+doh2ai(const struct dohentry *de, const char *hostname, int port)
+{
+ Curl_addrinfo *ai;
+ Curl_addrinfo *prevai = NULL;
+ Curl_addrinfo *firstai = NULL;
+ struct sockaddr_in *addr;
+#ifdef ENABLE_IPV6
+ struct sockaddr_in6 *addr6;
+#endif
+ CURLcode result = CURLE_OK;
+ int i;
+
+ if(!de)
+ /* no input == no output! */
+ return NULL;
+
+ for(i = 0; i < de->numaddr; i++) {
+ size_t ss_size;
+ CURL_SA_FAMILY_T addrtype;
+ if(de->addr[i].type == DNS_TYPE_AAAA) {
+#ifndef ENABLE_IPV6
+ /* we can't handle IPv6 addresses */
+ continue;
+#else
+ ss_size = sizeof(struct sockaddr_in6);
+ addrtype = AF_INET6;
+#endif
+ }
+ else {
+ ss_size = sizeof(struct sockaddr_in);
+ addrtype = AF_INET;
+ }
+
+ ai = calloc(1, sizeof(Curl_addrinfo));
+ if(!ai) {
+ result = CURLE_OUT_OF_MEMORY;
+ break;
+ }
+ ai->ai_canonname = strdup(hostname);
+ if(!ai->ai_canonname) {
+ result = CURLE_OUT_OF_MEMORY;
+ free(ai);
+ break;
+ }
+ ai->ai_addr = calloc(1, ss_size);
+ if(!ai->ai_addr) {
+ result = CURLE_OUT_OF_MEMORY;
+ free(ai->ai_canonname);
+ free(ai);
+ break;
+ }
+
+ if(!firstai)
+ /* store the pointer we want to return from this function */
+ firstai = ai;
+
+ if(prevai)
+ /* make the previous entry point to this */
+ prevai->ai_next = ai;
+
+ ai->ai_family = addrtype;
+
+ /* we return all names as STREAM, so when using this address for TFTP
+ the type must be ignored and conn->socktype be used instead! */
+ ai->ai_socktype = SOCK_STREAM;
+
+ ai->ai_addrlen = (curl_socklen_t)ss_size;
+
+ /* leave the rest of the struct filled with zero */
+
+ switch(ai->ai_family) {
+ case AF_INET:
+ addr = (void *)ai->ai_addr; /* storage area for this info */
+ DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4));
+ memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr));
+ addr->sin_family = (CURL_SA_FAMILY_T)addrtype;
+ addr->sin_port = htons((unsigned short)port);
+ break;
+
+#ifdef ENABLE_IPV6
+ case AF_INET6:
+ addr6 = (void *)ai->ai_addr; /* storage area for this info */
+ DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6));
+ memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr));
+ addr6->sin6_family = (CURL_SA_FAMILY_T)addrtype;
+ addr6->sin6_port = htons((unsigned short)port);
+ break;
+#endif
+ }
+
+ prevai = ai;
+ }
+
+ if(result) {
+ Curl_freeaddrinfo(firstai);
+ firstai = NULL;
+ }
+
+ return firstai;
+}
+
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
+static const char *type2name(DNStype dnstype)
+{
+ return (dnstype == DNS_TYPE_A)?"A":"AAAA";
+}
+#endif
+
+UNITTEST void de_cleanup(struct dohentry *d)
+{
+ int i = 0;
+ for(i = 0; i < d->numcname; i++) {
+ free(d->cname[i].alloc);
+ }
+}
+
+CURLcode Curl_doh_is_resolved(struct connectdata *conn,
+ struct Curl_dns_entry **dnsp)
+{
+ struct Curl_easy *data = conn->data;
+ *dnsp = NULL; /* defaults to no response */
+
+ if(!data->req.doh.probe[0].easy && !data->req.doh.probe[1].easy) {
+ failf(data, "Could not DOH-resolve: %s", conn->async.hostname);
+ return conn->bits.proxy?CURLE_COULDNT_RESOLVE_PROXY:
+ CURLE_COULDNT_RESOLVE_HOST;
+ }
+ else if(!data->req.doh.pending) {
+ DOHcode rc;
+ DOHcode rc2;
+ struct dohentry de;
+ /* remove DOH handles from multi handle and close them */
+ curl_multi_remove_handle(data->multi, data->req.doh.probe[0].easy);
+ Curl_close(data->req.doh.probe[0].easy);
+ curl_multi_remove_handle(data->multi, data->req.doh.probe[1].easy);
+ Curl_close(data->req.doh.probe[1].easy);
+
+ /* parse the responses, create the struct and return it! */
+ init_dohentry(&de);
+ rc = doh_decode(data->req.doh.probe[0].serverdoh.memory,
+ data->req.doh.probe[0].serverdoh.size,
+ data->req.doh.probe[0].dnstype,
+ &de);
+ free(data->req.doh.probe[0].serverdoh.memory);
+ if(rc) {
+ infof(data, "DOH: %s type %s for %s\n", doh_strerror(rc),
+ type2name(data->req.doh.probe[0].dnstype),
+ data->req.doh.host);
+ }
+ rc2 = doh_decode(data->req.doh.probe[1].serverdoh.memory,
+ data->req.doh.probe[1].serverdoh.size,
+ data->req.doh.probe[1].dnstype,
+ &de);
+ free(data->req.doh.probe[1].serverdoh.memory);
+ if(rc2) {
+ infof(data, "DOH: %s type %s for %s\n", doh_strerror(rc2),
+ type2name(data->req.doh.probe[1].dnstype),
+ data->req.doh.host);
+ }
+ if(!rc || !rc2) {
+ struct Curl_dns_entry *dns;
+ struct Curl_addrinfo *ai;
+
+ infof(data, "DOH Host name: %s\n", data->req.doh.host);
+ showdoh(data, &de);
+
+ ai = doh2ai(&de, data->req.doh.host, data->req.doh.port);
+ if(!ai) {
+ de_cleanup(&de);
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ if(data->share)
+ Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
+
+ /* we got a response, store it in the cache */
+ dns = Curl_cache_addr(data, ai, data->req.doh.host, data->req.doh.port);
+
+ if(data->share)
+ Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
+
+ de_cleanup(&de);
+ if(!dns)
+ /* returned failure, bail out nicely */
+ Curl_freeaddrinfo(ai);
+ else {
+ conn->async.dns = dns;
+ *dnsp = dns;
+ return CURLE_OK;
+ }
+ }
+ de_cleanup(&de);
+
+ return CURLE_COULDNT_RESOLVE_HOST;
+ }
+
+ return CURLE_OK;
+}
+
+#endif /* CURL_DISABLE_DOH */
diff --git a/Utilities/cmcurl/lib/doh.h b/Utilities/cmcurl/lib/doh.h
new file mode 100644
index 000000000..34bfa6f2b
--- /dev/null
+++ b/Utilities/cmcurl/lib/doh.h
@@ -0,0 +1,113 @@
+#ifndef HEADER_CURL_DOH_H
+#define HEADER_CURL_DOH_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2018 - 2019, 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 "urldata.h"
+#include "curl_addrinfo.h"
+
+#ifndef CURL_DISABLE_DOH
+
+/*
+ * Curl_doh() resolve a name using DoH (DNS-over-HTTPS). It resolves a name
+ * and returns a 'Curl_addrinfo *' with the address information.
+ */
+
+Curl_addrinfo *Curl_doh(struct connectdata *conn,
+ const char *hostname,
+ int port,
+ int *waitp);
+
+CURLcode Curl_doh_is_resolved(struct connectdata *conn,
+ struct Curl_dns_entry **dns);
+
+int Curl_doh_getsock(struct connectdata *conn, curl_socket_t *socks,
+ int numsocks);
+
+typedef enum {
+ DOH_OK,
+ DOH_DNS_BAD_LABEL, /* 1 */
+ DOH_DNS_OUT_OF_RANGE, /* 2 */
+ DOH_DNS_LABEL_LOOP, /* 3 */
+ DOH_TOO_SMALL_BUFFER, /* 4 */
+ DOH_OUT_OF_MEM, /* 5 */
+ DOH_DNS_RDATA_LEN, /* 6 */
+ DOH_DNS_MALFORMAT, /* 7 */
+ DOH_DNS_BAD_RCODE, /* 8 - no such name */
+ DOH_DNS_UNEXPECTED_TYPE, /* 9 */
+ DOH_DNS_UNEXPECTED_CLASS, /* 10 */
+ DOH_NO_CONTENT, /* 11 */
+ DOH_DNS_BAD_ID /* 12 */
+} DOHcode;
+
+typedef enum {
+ DNS_TYPE_A = 1,
+ DNS_TYPE_NS = 2,
+ DNS_TYPE_CNAME = 5,
+ DNS_TYPE_AAAA = 28
+} DNStype;
+
+#define DOH_MAX_ADDR 24
+#define DOH_MAX_CNAME 4
+
+struct cnamestore {
+ size_t len; /* length of cname */
+ char *alloc; /* allocated pointer */
+ size_t allocsize; /* allocated size */
+};
+
+struct dohaddr {
+ int type;
+ union {
+ unsigned char v4[4]; /* network byte order */
+ unsigned char v6[16];
+ } ip;
+};
+
+struct dohentry {
+ unsigned int ttl;
+ int numaddr;
+ struct dohaddr addr[DOH_MAX_ADDR];
+ int numcname;
+ struct cnamestore cname[DOH_MAX_CNAME];
+};
+
+
+#ifdef DEBUGBUILD
+DOHcode doh_encode(const char *host,
+ DNStype dnstype,
+ unsigned char *dnsp, /* buffer */
+ size_t len, /* buffer size */
+ size_t *olen); /* output length */
+DOHcode doh_decode(unsigned char *doh,
+ size_t dohlen,
+ DNStype dnstype,
+ struct dohentry *d);
+void de_cleanup(struct dohentry *d);
+#endif
+
+#else /* if DOH is disabled */
+#define Curl_doh(a,b,c,d) NULL
+#define Curl_doh_is_resolved(x,y) CURLE_COULDNT_RESOLVE_HOST
+#endif
+
+#endif /* HEADER_CURL_DOH_H */
diff --git a/Utilities/cmcurl/lib/mime.c b/Utilities/cmcurl/lib/mime.c
new file mode 100644
index 000000000..2135f72c2
--- /dev/null
+++ b/Utilities/cmcurl/lib/mime.c
@@ -0,0 +1,1904 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2019, 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"
+#include "urldata.h"
+#include "sendf.h"
+
+#if (!defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_MIME)) || \
+ !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 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
+ implementation 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 as 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 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) {
+ size_t len = 1;
+ size_t consumed = 1;
+ int 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[part->state.offset], 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;
+
+ 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;
+#ifdef CURL_DOES_CONVERSIONS
+ char *convbuf = buffer;
+#endif
+
+ /* Readback from part. */
+
+ while(bufsize) {
+ size_t sz = 0;
+ struct curl_slist *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;
+#ifdef CURL_DOES_CONVERSIONS
+ char *convbuf = buffer;
+#endif
+
+ (void) size; /* Always 1. */
+
+ while(nitems) {
+ size_t sz = 0;
+ curl_mimepart *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;
+
+ 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) {
+ int 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;
+}
+
+/* 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. */
+ cleanup_encoder_state(&part->encstate);
+ part->kind = MIMEKIND_NONE;
+}
+
+static void mime_subparts_free(void *ptr)
+{
+ curl_mime *mime = (curl_mime *) ptr;
+
+ if(mime && mime->parent) {
+ mime->parent->freefunc = NULL; /* Be sure we won't be called again. */
+ cleanup_part_content(mime->parent); /* Avoid dangling pointer in part. */
+ }
+ curl_mime_free(mime);
+}
+
+/* Do not free subparts: unbind them. This is used for the top level only. */
+static void mime_subparts_unbind(void *ptr)
+{
+ curl_mime *mime = (curl_mime *) ptr;
+
+ if(mime && mime->parent) {
+ mime->parent->freefunc = NULL; /* Be sure we won't be called again. */
+ cleanup_part_content(mime->parent); /* Avoid dangling pointer in part. */
+ mime->parent = NULL;
+ }
+}
+
+
+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) {
+ mime_subparts_unbind(mime); /* Be sure it's not referenced anymore. */
+ while(mime->firstpart) {
+ part = mime->firstpart;
+ mime->firstpart = part->nextpart;
+ Curl_mime_cleanpart(part);
+ free(part);
+ }
+ free(mime);
+ }
+}
+
+CURLcode Curl_mime_duppart(curl_mimepart *dst, const curl_mimepart *src)
+{
+ curl_mime *mime;
+ curl_mimepart *d;
+ const curl_mimepart *s;
+ CURLcode res = CURLE_OK;
+
+ /* Duplicate content. */
+ switch(src->kind) {
+ case MIMEKIND_NONE:
+ break;
+ case MIMEKIND_DATA:
+ res = curl_mime_data(dst, src->data, (size_t) src->datasize);
+ break;
+ case MIMEKIND_FILE:
+ res = curl_mime_filedata(dst, src->data);
+ /* Do not abort duplication if file is not readable. */
+ if(res == CURLE_READ_ERROR)
+ res = CURLE_OK;
+ break;
+ case MIMEKIND_CALLBACK:
+ res = curl_mime_data_cb(dst, src->datasize, src->readfunc,
+ src->seekfunc, src->freefunc, src->arg);
+ break;
+ case MIMEKIND_MULTIPART:
+ /* No one knows about the cloned subparts, thus always attach ownership
+ to the part. */
+ mime = curl_mime_init(dst->easy);
+ res = mime? curl_mime_subparts(dst, mime): CURLE_OUT_OF_MEMORY;
+
+ /* Duplicate subparts. */
+ for(s = ((curl_mime *) src->arg)->firstpart; !res && s; s = s->nextpart) {
+ d = curl_mime_addpart(mime);
+ res = d? Curl_mime_duppart(d, s): CURLE_OUT_OF_MEMORY;
+ }
+ break;
+ default: /* Invalid kind: should not occur. */
+ res = CURLE_BAD_FUNCTION_ARGUMENT; /* Internal error? */
+ break;
+ }
+
+ /* Duplicate headers. */
+ if(!res && src->userheaders) {
+ struct curl_slist *hdrs = Curl_slist_duplicate(src->userheaders);
+
+ if(!hdrs)
+ res = CURLE_OUT_OF_MEMORY;
+ else {
+ /* No one but this procedure knows about the new header list,
+ so always take ownership. */
+ res = curl_mime_headers(dst, hdrs, TRUE);
+ if(res)
+ curl_slist_free_all(hdrs);
+ }
+ }
+
+ /* Duplicate other fields. */
+ if(dst != NULL)
+ dst->encoder = src->encoder;
+ else
+ res = CURLE_WRITE_ERROR;
+ if(!res)
+ res = curl_mime_type(dst, src->mimetype);
+ if(!res)
+ res = curl_mime_name(dst, src->name);
+ if(!res)
+ res = curl_mime_filename(dst, src->filename);
+
+ /* If an error occurred, rollback. */
+ if(res && dst)
+ Curl_mime_cleanpart(dst);
+
+ return res;
+}
+
+/*
+ * 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;
+
+ memset(mime->boundary, '-', 24);
+ if(Curl_rand_hex(easy, (unsigned char *) &mime->boundary[24],
+ MIME_RAND_BOUNDARY_CHARS + 1)) {
+ /* failed to get random separator, bail out */
+ free(mime);
+ return NULL;
+ }
+ 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;
+
+ if(!part)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ cleanup_part_content(part);
+
+ if(filename) {
+ char *base;
+ 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) {
+ if(part->userheaders != headers) /* Allow setting twice the same list. */
+ 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_set_subparts(curl_mimepart *part,
+ curl_mime *subparts, int take_ownership)
+{
+ curl_mime *root;
+
+ 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;
+
+ /* Should not be the part's root. */
+ root = part->parent;
+ if(root) {
+ while(root->parent && root->parent->parent)
+ root = root->parent->parent;
+ if(subparts == root) {
+ if(part->easy)
+ failf(part->easy, "Can't add itself as a subpart!");
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ }
+ }
+
+ subparts->parent = part;
+ part->readfunc = mime_subparts_read;
+ part->seekfunc = mime_subparts_seek;
+ part->freefunc = take_ownership? mime_subparts_free: mime_subparts_unbind;
+ part->arg = subparts;
+ part->datasize = -1;
+ part->kind = MIMEKIND_MULTIPART;
+ }
+
+ return CURLE_OK;
+}
+
+CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts)
+{
+ return Curl_mime_set_subparts(part, subparts, TRUE);
+}
+
+
+/* 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;
+ 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) {
+ curl_off_t 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->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: "");
+}
+
+const char *Curl_mime_contenttype(const char *filename)
+{
+ /*
+ * 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;
+ unsigned int i;
+
+ 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 *customct;
+ 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);
+
+ /* Check if content type is specified. */
+ customct = part->mimetype;
+ if(!customct)
+ customct = search_header(part->userheaders, "Content-Type");
+ if(customct)
+ contenttype = customct;
+
+ /* If content type is not specified, try to determine it. */
+ if(!contenttype) {
+ switch(part->kind) {
+ case MIMEKIND_MULTIPART:
+ contenttype = MULTIPART_CONTENTTYPE_DEFAULT;
+ break;
+ case MIMEKIND_FILE:
+ contenttype = Curl_mime_contenttype(part->filename);
+ if(!contenttype)
+ contenttype = Curl_mime_contenttype(part->data);
+ if(!contenttype && part->filename)
+ contenttype = FILE_CONTENTTYPE_DEFAULT;
+ break;
+ default:
+ contenttype = Curl_mime_contenttype(part->filename);
+ break;
+ }
+ }
+
+ if(part->kind == MIMEKIND_MULTIPART) {
+ mime = (curl_mime *) part->arg;
+ if(mime)
+ boundary = mime->boundary;
+ }
+ else if(contenttype && !customct &&
+ 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;
+}
+
+#endif /* if disabled */
diff --git a/Utilities/cmcurl/lib/mime.h b/Utilities/cmcurl/lib/mime.h
new file mode 100644
index 000000000..4c9a5fb71
--- /dev/null
+++ b/Utilities/cmcurl/lib/mime.h
@@ -0,0 +1,164 @@
+#ifndef HEADER_CURL_MIME_H
+#define HEADER_CURL_MIME_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2019, 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"
+
+#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)
+
+#define FILE_CONTENTTYPE_DEFAULT "application/octet-stream"
+#define MULTIPART_CONTENTTYPE_DEFAULT "multipart/mixed"
+#define DISPOSITION_DEFAULT "attachment"
+
+/* 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;
+
+/* minimum buffer size for the boundary string */
+#define MIME_BOUNDARY_LEN (24 + MIME_RAND_BOUNDARY_CHARS + 1)
+
+/* 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[MIME_BOUNDARY_LEN]; /* 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. */
+};
+
+#if (!defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_MIME)) || \
+ !defined(CURL_DISABLE_SMTP) || !defined(CURL_DISABLE_IMAP)
+
+/* Prototypes. */
+void Curl_mime_initpart(curl_mimepart *part, struct Curl_easy *easy);
+void Curl_mime_cleanpart(curl_mimepart *part);
+CURLcode Curl_mime_duppart(curl_mimepart *dst, const curl_mimepart *src);
+CURLcode Curl_mime_set_subparts(curl_mimepart *part,
+ curl_mime *subparts, int take_ownership);
+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, ...);
+const char *Curl_mime_contenttype(const char *filename);
+
+#else
+/* if disabled */
+#define Curl_mime_initpart(x,y)
+#define Curl_mime_cleanpart(x)
+#define Curl_mime_duppart(x,y) CURLE_OK /* Nothing to duplicate. Succeed */
+#define Curl_mime_set_subparts(a,b,c) CURLE_NOT_BUILT_IN
+#define Curl_mime_prepare_headers(a,b,c,d) CURLE_NOT_BUILT_IN
+#define Curl_mime_size(x) (curl_off_t) -1
+#define Curl_mime_read NULL
+#define Curl_mime_rewind(x) ((void)x, CURLE_NOT_BUILT_IN)
+#define Curl_mime_add_header(x,y,...) CURLE_NOT_BUILT_IN
+#endif
+
+
+#endif /* HEADER_CURL_MIME_H */
diff --git a/Utilities/cmcurl/lib/psl.c b/Utilities/cmcurl/lib/psl.c
new file mode 100644
index 000000000..568baff03
--- /dev/null
+++ b/Utilities/cmcurl/lib/psl.c
@@ -0,0 +1,111 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2018, 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>
+
+#ifdef USE_LIBPSL
+
+#include "psl.h"
+#include "share.h"
+
+/* The last 3 #include files should be in this order */
+#include "curl_printf.h"
+#include "curl_memory.h"
+#include "memdebug.h"
+
+void Curl_psl_destroy(struct PslCache *pslcache)
+{
+ if(pslcache->psl) {
+ if(pslcache->dynamic)
+ psl_free((psl_ctx_t *) pslcache->psl);
+ pslcache->psl = NULL;
+ pslcache->dynamic = FALSE;
+ }
+}
+
+static time_t now_seconds(void)
+{
+ struct curltime now = Curl_now();
+
+ return now.tv_sec;
+}
+
+const psl_ctx_t *Curl_psl_use(struct Curl_easy *easy)
+{
+ struct PslCache *pslcache = easy->psl;
+ const psl_ctx_t *psl;
+ time_t now;
+
+ if(!pslcache)
+ return NULL;
+
+ Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED);
+ now = now_seconds();
+ if(!pslcache->psl || pslcache->expires <= now) {
+ /* Let a chance to other threads to do the job: avoids deadlock. */
+ Curl_share_unlock(easy, CURL_LOCK_DATA_PSL);
+
+ /* Update cache: this needs an exclusive lock. */
+ Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SINGLE);
+
+ /* Recheck in case another thread did the job. */
+ now = now_seconds();
+ if(!pslcache->psl || pslcache->expires <= now) {
+ bool dynamic = FALSE;
+ time_t expires = TIME_T_MAX;
+
+#if defined(PSL_VERSION_NUMBER) && PSL_VERSION_NUMBER >= 0x001000
+ psl = psl_latest(NULL);
+ dynamic = psl != NULL;
+ /* Take care of possible time computation overflow. */
+ expires = now < TIME_T_MAX - PSL_TTL? now + PSL_TTL: TIME_T_MAX;
+
+ /* Only get the built-in PSL if we do not already have the "latest". */
+ if(!psl && !pslcache->dynamic)
+#endif
+
+ psl = psl_builtin();
+
+ if(psl) {
+ Curl_psl_destroy(pslcache);
+ pslcache->psl = psl;
+ pslcache->dynamic = dynamic;
+ pslcache->expires = expires;
+ }
+ }
+ Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); /* Release exclusive lock. */
+ Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED);
+ }
+ psl = pslcache->psl;
+ if(!psl)
+ Curl_share_unlock(easy, CURL_LOCK_DATA_PSL);
+ return psl;
+}
+
+void Curl_psl_release(struct Curl_easy *easy)
+{
+ Curl_share_unlock(easy, CURL_LOCK_DATA_PSL);
+}
+
+#endif /* USE_LIBPSL */
diff --git a/Utilities/cmcurl/lib/psl.h b/Utilities/cmcurl/lib/psl.h
new file mode 100644
index 000000000..e9f99d03e
--- /dev/null
+++ b/Utilities/cmcurl/lib/psl.h
@@ -0,0 +1,47 @@
+#ifndef HEADER_PSL_H
+#define HEADER_PSL_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2018, 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.
+ *
+ ***************************************************************************/
+
+#ifdef USE_LIBPSL
+#include <libpsl.h>
+
+#define PSL_TTL (72 * 3600) /* PSL time to live before a refresh. */
+
+struct PslCache {
+ const psl_ctx_t *psl; /* The PSL. */
+ time_t expires; /* Time this PSL life expires. */
+ bool dynamic; /* PSL should be released when no longer needed. */
+};
+
+const psl_ctx_t *Curl_psl_use(struct Curl_easy *easy);
+void Curl_psl_release(struct Curl_easy *easy);
+void Curl_psl_destroy(struct PslCache *pslcache);
+
+#else
+
+#define Curl_psl_use(easy) NULL
+#define Curl_psl_release(easy)
+#define Curl_psl_destroy(pslcache)
+
+#endif /* USE_LIBPSL */
+#endif /* HEADER_PSL_H */
diff --git a/Utilities/cmcurl/lib/setopt.c b/Utilities/cmcurl/lib/setopt.c
new file mode 100644
index 000000000..92cd5b271
--- /dev/null
+++ b/Utilities/cmcurl/lib/setopt.c
@@ -0,0 +1,2777 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2019, 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 <limits.h>
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+
+#ifdef HAVE_LINUX_TCP_H
+#include <linux/tcp.h>
+#endif
+
+#include "urldata.h"
+#include "url.h"
+#include "progress.h"
+#include "content_encoding.h"
+#include "strcase.h"
+#include "share.h"
+#include "vtls/vtls.h"
+#include "warnless.h"
+#include "sendf.h"
+#include "http2.h"
+#include "setopt.h"
+#include "multiif.h"
+#include "altsvc.h"
+
+/* The last 3 #include files should be in this order */
+#include "curl_printf.h"
+#include "curl_memory.h"
+#include "memdebug.h"
+
+CURLcode Curl_setstropt(char **charp, const char *s)
+{
+ /* Release the previous storage at `charp' and replace by a dynamic storage
+ copy of `s'. Return CURLE_OK or CURLE_OUT_OF_MEMORY. */
+
+ Curl_safefree(*charp);
+
+ if(s) {
+ char *str = strdup(s);
+
+ if(str) {
+ size_t len = strlen(str);
+ if(len > CURL_MAX_INPUT_LENGTH) {
+ free(str);
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ }
+ }
+ if(!str)
+ return CURLE_OUT_OF_MEMORY;
+
+ *charp = str;
+ }
+
+ return CURLE_OK;
+}
+
+static CURLcode setstropt_userpwd(char *option, char **userp, char **passwdp)
+{
+ CURLcode result = CURLE_OK;
+ char *user = NULL;
+ char *passwd = NULL;
+
+ /* Parse the login details if specified. It not then we treat NULL as a hint
+ to clear the existing data */
+ if(option) {
+ result = Curl_parse_login_details(option, strlen(option),
+ (userp ? &user : NULL),
+ (passwdp ? &passwd : NULL),
+ NULL);
+ }
+
+ if(!result) {
+ /* Store the username part of option if required */
+ if(userp) {
+ if(!user && option && option[0] == ':') {
+ /* Allocate an empty string instead of returning NULL as user name */
+ user = strdup("");
+ if(!user)
+ result = CURLE_OUT_OF_MEMORY;
+ }
+
+ Curl_safefree(*userp);
+ *userp = user;
+ }
+
+ /* Store the password part of option if required */
+ if(passwdp) {
+ Curl_safefree(*passwdp);
+ *passwdp = passwd;
+ }
+ }
+
+ return result;
+}
+
+#define C_SSLVERSION_VALUE(x) (x & 0xffff)
+#define C_SSLVERSION_MAX_VALUE(x) (x & 0xffff0000)
+
+static CURLcode vsetopt(struct Curl_easy *data, CURLoption option,
+ va_list param)
+{
+ char *argptr;
+ CURLcode result = CURLE_OK;
+ long arg;
+ unsigned long uarg;
+ curl_off_t bigsize;
+
+ switch(option) {
+ case CURLOPT_DNS_CACHE_TIMEOUT:
+ arg = va_arg(param, long);
+ if(arg < -1)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.dns_cache_timeout = arg;
+ break;
+ case CURLOPT_DNS_USE_GLOBAL_CACHE:
+ /* deprecated */
+ break;
+ case CURLOPT_SSL_CIPHER_LIST:
+ /* set a list of cipher we want to use in the SSL connection */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER_LIST_ORIG],
+ va_arg(param, char *));
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_SSL_CIPHER_LIST:
+ /* set a list of cipher we want to use in the SSL connection for proxy */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER_LIST_PROXY],
+ va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_TLS13_CIPHERS:
+ if(Curl_ssl_tls13_ciphersuites()) {
+ /* set preferred list of TLS 1.3 cipher suites */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER13_LIST_ORIG],
+ va_arg(param, char *));
+ }
+ else
+ return CURLE_NOT_BUILT_IN;
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_TLS13_CIPHERS:
+ if(Curl_ssl_tls13_ciphersuites()) {
+ /* set preferred list of TLS 1.3 cipher suites for proxy */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_CIPHER13_LIST_PROXY],
+ va_arg(param, char *));
+ }
+ else
+ return CURLE_NOT_BUILT_IN;
+ break;
+#endif
+ case CURLOPT_RANDOM_FILE:
+ /*
+ * This is the path name to a file that contains random data to seed
+ * the random SSL stuff with. The file is only used for reading.
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_RANDOM_FILE],
+ va_arg(param, char *));
+ break;
+ case CURLOPT_EGDSOCKET:
+ /*
+ * The Entropy Gathering Daemon socket pathname
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_EGDSOCKET],
+ va_arg(param, char *));
+ break;
+ case CURLOPT_MAXCONNECTS:
+ /*
+ * Set the absolute number of maximum simultaneous alive connection that
+ * libcurl is allowed to have.
+ */
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.maxconnects = arg;
+ break;
+ case CURLOPT_FORBID_REUSE:
+ /*
+ * When this transfer is done, it must not be left to be reused by a
+ * subsequent transfer but shall be closed immediately.
+ */
+ data->set.reuse_forbid = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_FRESH_CONNECT:
+ /*
+ * This transfer shall not use a previously cached connection but
+ * should be made with a fresh new connect!
+ */
+ data->set.reuse_fresh = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_VERBOSE:
+ /*
+ * Verbose means infof() calls that give a lot of information about
+ * the connection and transfer procedures as well as internal choices.
+ */
+ data->set.verbose = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_HEADER:
+ /*
+ * Set to include the header in the general data output stream.
+ */
+ data->set.include_header = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_NOPROGRESS:
+ /*
+ * Shut off the internal supported progress meter
+ */
+ data->set.hide_progress = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ if(data->set.hide_progress)
+ data->progress.flags |= PGRS_HIDE;
+ else
+ data->progress.flags &= ~PGRS_HIDE;
+ break;
+ case CURLOPT_NOBODY:
+ /*
+ * Do not include the body part in the output data stream.
+ */
+ data->set.opt_no_body = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_FAILONERROR:
+ /*
+ * Don't output the >=400 error code HTML-page, but instead only
+ * return error.
+ */
+ data->set.http_fail_on_error = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_KEEP_SENDING_ON_ERROR:
+ data->set.http_keep_sending_on_error = (0 != va_arg(param, long)) ?
+ TRUE : FALSE;
+ break;
+ case CURLOPT_UPLOAD:
+ case CURLOPT_PUT:
+ /*
+ * We want to sent data to the remote host. If this is HTTP, that equals
+ * using the PUT request.
+ */
+ data->set.upload = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ if(data->set.upload) {
+ /* If this is HTTP, PUT is what's needed to "upload" */
+ data->set.httpreq = HTTPREQ_PUT;
+ data->set.opt_no_body = FALSE; /* this is implied */
+ }
+ else
+ /* In HTTP, the opposite of upload is GET (unless NOBODY is true as
+ then this can be changed to HEAD later on) */
+ data->set.httpreq = HTTPREQ_GET;
+ break;
+ case CURLOPT_REQUEST_TARGET:
+ result = Curl_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
+ * later (possibly) become available using curl_easy_getinfo().
+ */
+ data->set.get_filetime = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_SERVER_RESPONSE_TIMEOUT:
+ /*
+ * Option that specifies how quickly an server response must be obtained
+ * before it is considered failure. For pingpong protocols.
+ */
+ arg = va_arg(param, long);
+ if((arg >= 0) && (arg <= (INT_MAX/1000)))
+ data->set.server_response_timeout = arg * 1000;
+ else
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ break;
+#ifndef CURL_DISABLE_TFTP
+ case CURLOPT_TFTP_NO_OPTIONS:
+ /*
+ * Option that prevents libcurl from sending TFTP option requests to the
+ * server.
+ */
+ data->set.tftp_no_options = va_arg(param, long) != 0;
+ break;
+ case CURLOPT_TFTP_BLKSIZE:
+ /*
+ * TFTP option that specifies the block size to use for data transmission.
+ */
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.tftp_blksize = arg;
+ break;
+#endif
+#ifndef CURL_DISABLE_NETRC
+ case CURLOPT_NETRC:
+ /*
+ * Parse the $HOME/.netrc file
+ */
+ arg = va_arg(param, long);
+ if((arg < CURL_NETRC_IGNORED) || (arg > CURL_NETRC_REQUIRED))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.use_netrc = (enum CURL_NETRC_OPTION)arg;
+ break;
+ case CURLOPT_NETRC_FILE:
+ /*
+ * Use this file instead of the $HOME/.netrc file
+ */
+ result = Curl_setstropt(&data->set.str[STRING_NETRC_FILE],
+ va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_TRANSFERTEXT:
+ /*
+ * This option was previously named 'FTPASCII'. Renamed to work with
+ * more protocols than merely FTP.
+ *
+ * Transfer using ASCII (instead of BINARY).
+ */
+ data->set.prefer_ascii = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_TIMECONDITION:
+ /*
+ * Set HTTP time condition. This must be one of the defines in the
+ * curl/curl.h header file.
+ */
+ arg = va_arg(param, long);
+ if((arg < CURL_TIMECOND_NONE) || (arg > CURL_TIMECOND_LASTMOD))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.timecondition = (curl_TimeCond)arg;
+ break;
+ case CURLOPT_TIMEVALUE:
+ /*
+ * This is the value to compare with the remote document with the
+ * method set with CURLOPT_TIMECONDITION
+ */
+ data->set.timevalue = (time_t)va_arg(param, long);
+ break;
+
+ case CURLOPT_TIMEVALUE_LARGE:
+ /*
+ * This is the value to compare with the remote document with the
+ * method set with CURLOPT_TIMECONDITION
+ */
+ data->set.timevalue = (time_t)va_arg(param, curl_off_t);
+ break;
+
+ case CURLOPT_SSLVERSION:
+ case CURLOPT_PROXY_SSLVERSION:
+ /*
+ * Set explicit SSL version to try to connect with, as some SSL
+ * implementations are lame.
+ */
+#ifdef USE_SSL
+ {
+ long version, version_max;
+ struct ssl_primary_config *primary = (option == CURLOPT_SSLVERSION ?
+ &data->set.ssl.primary :
+ &data->set.proxy_ssl.primary);
+
+ arg = va_arg(param, long);
+
+ version = C_SSLVERSION_VALUE(arg);
+ version_max = C_SSLVERSION_MAX_VALUE(arg);
+
+ if(version < CURL_SSLVERSION_DEFAULT ||
+ version >= CURL_SSLVERSION_LAST ||
+ version_max < CURL_SSLVERSION_MAX_NONE ||
+ version_max >= CURL_SSLVERSION_MAX_LAST)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ primary->version = version;
+ primary->version_max = version_max;
+ }
+#else
+ result = CURLE_UNKNOWN_OPTION;
+#endif
+ break;
+
+#ifndef CURL_DISABLE_HTTP
+ case CURLOPT_AUTOREFERER:
+ /*
+ * Switch on automatic referer that gets set if curl follows locations.
+ */
+ data->set.http_auto_referer = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_ACCEPT_ENCODING:
+ /*
+ * String to use at the value of Accept-Encoding header.
+ *
+ * If the encoding is set to "" we use an Accept-Encoding header that
+ * encompasses all the encodings we support.
+ * If the encoding is set to NULL we don't send an Accept-Encoding header
+ * and ignore an received Content-Encoding header.
+ *
+ */
+ argptr = va_arg(param, char *);
+ if(argptr && !*argptr) {
+ argptr = Curl_all_content_encodings();
+ if(!argptr)
+ result = CURLE_OUT_OF_MEMORY;
+ else {
+ result = Curl_setstropt(&data->set.str[STRING_ENCODING], argptr);
+ free(argptr);
+ }
+ }
+ else
+ result = Curl_setstropt(&data->set.str[STRING_ENCODING], argptr);
+ break;
+
+ case CURLOPT_TRANSFER_ENCODING:
+ data->set.http_transfer_encoding = (0 != va_arg(param, long)) ?
+ TRUE : FALSE;
+ break;
+
+ case CURLOPT_FOLLOWLOCATION:
+ /*
+ * Follow Location: header hints on a HTTP-server.
+ */
+ data->set.http_follow_location = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_UNRESTRICTED_AUTH:
+ /*
+ * Send authentication (user+password) when following locations, even when
+ * hostname changed.
+ */
+ data->set.allow_auth_to_other_hosts =
+ (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_MAXREDIRS:
+ /*
+ * The maximum amount of hops you allow curl to follow Location:
+ * headers. This should mostly be used to detect never-ending loops.
+ */
+ arg = va_arg(param, long);
+ if(arg < -1)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.maxredirs = arg;
+ break;
+
+ case CURLOPT_POSTREDIR:
+ /*
+ * Set the behaviour of POST when redirecting
+ * CURL_REDIR_GET_ALL - POST is changed to GET after 301 and 302
+ * CURL_REDIR_POST_301 - POST is kept as POST after 301
+ * CURL_REDIR_POST_302 - POST is kept as POST after 302
+ * CURL_REDIR_POST_303 - POST is kept as POST after 303
+ * CURL_REDIR_POST_ALL - POST is kept as POST after 301, 302 and 303
+ * other - POST is kept as POST after 301 and 302
+ */
+ arg = va_arg(param, long);
+ if(arg < CURL_REDIR_GET_ALL)
+ /* no return error on too high numbers since the bitmask could be
+ extended in a future */
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.keep_post = arg & CURL_REDIR_POST_ALL;
+ break;
+
+ case CURLOPT_POST:
+ /* Does this option serve a purpose anymore? Yes it does, when
+ CURLOPT_POSTFIELDS isn't used and the POST data is read off the
+ callback! */
+ if(va_arg(param, long)) {
+ data->set.httpreq = HTTPREQ_POST;
+ data->set.opt_no_body = FALSE; /* this is implied */
+ }
+ else
+ data->set.httpreq = HTTPREQ_GET;
+ break;
+
+ case CURLOPT_COPYPOSTFIELDS:
+ /*
+ * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
+ * If needed, CURLOPT_POSTFIELDSIZE must have been set prior to
+ * CURLOPT_COPYPOSTFIELDS and not altered later.
+ */
+ argptr = va_arg(param, char *);
+
+ if(!argptr || data->set.postfieldsize == -1)
+ result = Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], argptr);
+ else {
+ /*
+ * Check that requested length does not overflow the size_t type.
+ */
+
+ if((data->set.postfieldsize < 0) ||
+ ((sizeof(curl_off_t) != sizeof(size_t)) &&
+ (data->set.postfieldsize > (curl_off_t)((size_t)-1))))
+ result = CURLE_OUT_OF_MEMORY;
+ else {
+ char *p;
+
+ (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
+
+ /* Allocate even when size == 0. This satisfies the need of possible
+ later address compare to detect the COPYPOSTFIELDS mode, and
+ to mark that postfields is used rather than read function or
+ form data.
+ */
+ p = malloc((size_t)(data->set.postfieldsize?
+ data->set.postfieldsize:1));
+
+ if(!p)
+ result = CURLE_OUT_OF_MEMORY;
+ else {
+ if(data->set.postfieldsize)
+ memcpy(p, argptr, (size_t)data->set.postfieldsize);
+
+ data->set.str[STRING_COPYPOSTFIELDS] = p;
+ }
+ }
+ }
+
+ data->set.postfields = data->set.str[STRING_COPYPOSTFIELDS];
+ data->set.httpreq = HTTPREQ_POST;
+ break;
+
+ case CURLOPT_POSTFIELDS:
+ /*
+ * Like above, but use static data instead of copying it.
+ */
+ data->set.postfields = va_arg(param, void *);
+ /* Release old copied data. */
+ (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
+ data->set.httpreq = HTTPREQ_POST;
+ break;
+
+ case CURLOPT_POSTFIELDSIZE:
+ /*
+ * The size of the POSTFIELD data to prevent libcurl to do strlen() to
+ * figure it out. Enables binary posts.
+ */
+ bigsize = va_arg(param, long);
+ if(bigsize < -1)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ if(data->set.postfieldsize < bigsize &&
+ data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
+ /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
+ (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
+ data->set.postfields = NULL;
+ }
+
+ data->set.postfieldsize = bigsize;
+ break;
+
+ case CURLOPT_POSTFIELDSIZE_LARGE:
+ /*
+ * The size of the POSTFIELD data to prevent libcurl to do strlen() to
+ * figure it out. Enables binary posts.
+ */
+ bigsize = va_arg(param, curl_off_t);
+ if(bigsize < -1)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ if(data->set.postfieldsize < bigsize &&
+ data->set.postfields == data->set.str[STRING_COPYPOSTFIELDS]) {
+ /* Previous CURLOPT_COPYPOSTFIELDS is no longer valid. */
+ (void) Curl_setstropt(&data->set.str[STRING_COPYPOSTFIELDS], NULL);
+ data->set.postfields = NULL;
+ }
+
+ data->set.postfieldsize = bigsize;
+ break;
+
+ case CURLOPT_HTTPPOST:
+ /*
+ * Set to make us do HTTP POST
+ */
+ data->set.httppost = va_arg(param, struct curl_httppost *);
+ 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_set_subparts(&data->set.mimepost,
+ va_arg(param, curl_mime *), FALSE);
+ if(!result) {
+ data->set.httpreq = HTTPREQ_POST_MIME;
+ data->set.opt_no_body = FALSE; /* this is implied */
+ }
+ break;
+
+ case CURLOPT_REFERER:
+ /*
+ * String to set in the HTTP Referer: field.
+ */
+ if(data->change.referer_alloc) {
+ Curl_safefree(data->change.referer);
+ data->change.referer_alloc = FALSE;
+ }
+ result = Curl_setstropt(&data->set.str[STRING_SET_REFERER],
+ va_arg(param, char *));
+ data->change.referer = data->set.str[STRING_SET_REFERER];
+ break;
+
+ case CURLOPT_USERAGENT:
+ /*
+ * String to use in the HTTP User-Agent field
+ */
+ result = Curl_setstropt(&data->set.str[STRING_USERAGENT],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_HTTPHEADER:
+ /*
+ * Set a list with HTTP headers to use (or replace internals with)
+ */
+ data->set.headers = va_arg(param, struct curl_slist *);
+ break;
+
+#ifndef CURL_DISABLE_HTTP
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXYHEADER:
+ /*
+ * Set a list with proxy headers to use (or replace internals with)
+ *
+ * Since CURLOPT_HTTPHEADER was the only way to set HTTP headers for a
+ * long time we remain doing it this way until CURLOPT_PROXYHEADER is
+ * used. As soon as this option has been used, if set to anything but
+ * NULL, custom headers for proxies are only picked from this list.
+ *
+ * Set this option to NULL to restore the previous behavior.
+ */
+ data->set.proxyheaders = va_arg(param, struct curl_slist *);
+ break;
+#endif
+ case CURLOPT_HEADEROPT:
+ /*
+ * Set header option.
+ */
+ arg = va_arg(param, long);
+ data->set.sep_headers = (bool)((arg & CURLHEADER_SEPARATE)? TRUE: FALSE);
+ break;
+
+ case CURLOPT_HTTP200ALIASES:
+ /*
+ * Set a list of aliases for HTTP 200 in response header
+ */
+ data->set.http200aliases = va_arg(param, struct curl_slist *);
+ break;
+
+#if !defined(CURL_DISABLE_COOKIES)
+ case CURLOPT_COOKIE:
+ /*
+ * Cookie string to send to the remote server in the request.
+ */
+ result = Curl_setstropt(&data->set.str[STRING_COOKIE],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_COOKIEFILE:
+ /*
+ * Set cookie file to read and parse. Can be used multiple times.
+ */
+ argptr = (char *)va_arg(param, void *);
+ if(argptr) {
+ struct curl_slist *cl;
+ /* append the cookie file name to the list of file names, and deal with
+ them later */
+ cl = curl_slist_append(data->change.cookielist, argptr);
+ if(!cl) {
+ curl_slist_free_all(data->change.cookielist);
+ data->change.cookielist = NULL;
+ return CURLE_OUT_OF_MEMORY;
+ }
+ data->change.cookielist = cl; /* store the list for later use */
+ }
+ break;
+
+ case CURLOPT_COOKIEJAR:
+ /*
+ * Set cookie file name to dump all cookies to when we're done.
+ */
+ {
+ struct CookieInfo *newcookies;
+ result = Curl_setstropt(&data->set.str[STRING_COOKIEJAR],
+ va_arg(param, char *));
+
+ /*
+ * Activate the cookie parser. This may or may not already
+ * have been made.
+ */
+ newcookies = Curl_cookie_init(data, NULL, data->cookies,
+ data->set.cookiesession);
+ if(!newcookies)
+ result = CURLE_OUT_OF_MEMORY;
+ data->cookies = newcookies;
+ }
+ break;
+
+ case CURLOPT_COOKIESESSION:
+ /*
+ * Set this option to TRUE to start a new "cookie session". It will
+ * prevent the forthcoming read-cookies-from-file actions to accept
+ * cookies that are marked as being session cookies, as they belong to a
+ * previous session.
+ *
+ * In the original Netscape cookie spec, "session cookies" are cookies
+ * with no expire date set. RFC2109 describes the same action if no
+ * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
+ * a 'Discard' action that can enforce the discard even for cookies that
+ * have a Max-Age.
+ *
+ * We run mostly with the original cookie spec, as hardly anyone implements
+ * anything else.
+ */
+ data->set.cookiesession = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_COOKIELIST:
+ argptr = va_arg(param, char *);
+
+ if(argptr == NULL)
+ break;
+
+ if(strcasecompare(argptr, "ALL")) {
+ /* clear all cookies */
+ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
+ Curl_cookie_clearall(data->cookies);
+ Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
+ }
+ else if(strcasecompare(argptr, "SESS")) {
+ /* clear session cookies */
+ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
+ Curl_cookie_clearsess(data->cookies);
+ Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
+ }
+ else if(strcasecompare(argptr, "FLUSH")) {
+ /* flush cookies to file, takes care of the locking */
+ Curl_flush_cookies(data, 0);
+ }
+ else if(strcasecompare(argptr, "RELOAD")) {
+ /* reload cookies from file */
+ Curl_cookie_loadfiles(data);
+ break;
+ }
+ else {
+ if(!data->cookies)
+ /* if cookie engine was not running, activate it */
+ data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
+
+ argptr = strdup(argptr);
+ if(!argptr || !data->cookies) {
+ result = CURLE_OUT_OF_MEMORY;
+ free(argptr);
+ }
+ else {
+ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
+
+ if(checkprefix("Set-Cookie:", argptr))
+ /* HTTP Header format line */
+ Curl_cookie_add(data, data->cookies, TRUE, FALSE, argptr + 11, NULL,
+ NULL, TRUE);
+
+ else
+ /* Netscape format line */
+ Curl_cookie_add(data, data->cookies, FALSE, FALSE, argptr, NULL,
+ NULL, TRUE);
+
+ Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
+ free(argptr);
+ }
+ }
+
+ break;
+#endif /* !CURL_DISABLE_COOKIES */
+
+ case CURLOPT_HTTPGET:
+ /*
+ * Set to force us do HTTP GET
+ */
+ if(va_arg(param, long)) {
+ data->set.httpreq = HTTPREQ_GET;
+ data->set.upload = FALSE; /* switch off upload */
+ data->set.opt_no_body = FALSE; /* this is implied */
+ }
+ break;
+
+ case CURLOPT_HTTP_VERSION:
+ /*
+ * This sets a requested HTTP version to be used. The value is one of
+ * the listed enums in curl/curl.h.
+ */
+ arg = va_arg(param, long);
+ if(arg < CURL_HTTP_VERSION_NONE)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+#ifndef USE_NGHTTP2
+ if(arg >= CURL_HTTP_VERSION_2)
+ return CURLE_UNSUPPORTED_PROTOCOL;
+#else
+ if(arg > CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE)
+ return CURLE_UNSUPPORTED_PROTOCOL;
+ if(arg == CURL_HTTP_VERSION_NONE)
+ arg = CURL_HTTP_VERSION_2TLS;
+#endif
+ 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.
+ */
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.expect_100_timeout = arg;
+ break;
+
+ case CURLOPT_HTTP09_ALLOWED:
+ arg = va_arg(param, unsigned long);
+ if(arg > 1L)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.http09_allowed = arg ? TRUE : FALSE;
+ break;
+#endif /* CURL_DISABLE_HTTP */
+
+ case CURLOPT_HTTPAUTH:
+ /*
+ * Set HTTP Authentication type BITMASK.
+ */
+ {
+ int bitcheck;
+ bool authbits;
+ unsigned long auth = va_arg(param, unsigned long);
+
+ if(auth == CURLAUTH_NONE) {
+ data->set.httpauth = auth;
+ break;
+ }
+
+ /* the DIGEST_IE bit is only used to set a special marker, for all the
+ rest we need to handle it as normal DIGEST */
+ data->state.authhost.iestyle =
+ (bool)((auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE);
+
+ if(auth & CURLAUTH_DIGEST_IE) {
+ auth |= CURLAUTH_DIGEST; /* set standard digest bit */
+ auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
+ }
+
+ /* switch off bits we can't support */
+#ifndef USE_NTLM
+ auth &= ~CURLAUTH_NTLM; /* no NTLM support */
+ auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
+#elif !defined(NTLM_WB_ENABLED)
+ auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
+#endif
+#ifndef USE_SPNEGO
+ auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without
+ GSS-API or SSPI */
+#endif
+
+ /* check if any auth bit lower than CURLAUTH_ONLY is still set */
+ bitcheck = 0;
+ authbits = FALSE;
+ while(bitcheck < 31) {
+ if(auth & (1UL << bitcheck++)) {
+ authbits = TRUE;
+ break;
+ }
+ }
+ if(!authbits)
+ return CURLE_NOT_BUILT_IN; /* no supported types left! */
+
+ data->set.httpauth = auth;
+ }
+ break;
+
+ case CURLOPT_CUSTOMREQUEST:
+ /*
+ * Set a custom string to use as request
+ */
+ result = Curl_setstropt(&data->set.str[STRING_CUSTOMREQUEST],
+ va_arg(param, char *));
+
+ /* we don't set
+ data->set.httpreq = HTTPREQ_CUSTOM;
+ here, we continue as if we were using the already set type
+ and this just changes the actual request keyword */
+ break;
+
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_HTTPPROXYTUNNEL:
+ /*
+ * Tunnel operations through the proxy instead of normal proxy use
+ */
+ data->set.tunnel_thru_httpproxy = (0 != va_arg(param, long)) ?
+ TRUE : FALSE;
+ break;
+
+ case CURLOPT_PROXYPORT:
+ /*
+ * Explicitly set HTTP proxy port number.
+ */
+ arg = va_arg(param, long);
+ if((arg < 0) || (arg > 65535))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.proxyport = arg;
+ break;
+
+ case CURLOPT_PROXYAUTH:
+ /*
+ * Set HTTP Authentication type BITMASK.
+ */
+ {
+ int bitcheck;
+ bool authbits;
+ unsigned long auth = va_arg(param, unsigned long);
+
+ if(auth == CURLAUTH_NONE) {
+ data->set.proxyauth = auth;
+ break;
+ }
+
+ /* the DIGEST_IE bit is only used to set a special marker, for all the
+ rest we need to handle it as normal DIGEST */
+ data->state.authproxy.iestyle =
+ (bool)((auth & CURLAUTH_DIGEST_IE) ? TRUE : FALSE);
+
+ if(auth & CURLAUTH_DIGEST_IE) {
+ auth |= CURLAUTH_DIGEST; /* set standard digest bit */
+ auth &= ~CURLAUTH_DIGEST_IE; /* unset ie digest bit */
+ }
+ /* switch off bits we can't support */
+#ifndef USE_NTLM
+ auth &= ~CURLAUTH_NTLM; /* no NTLM support */
+ auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
+#elif !defined(NTLM_WB_ENABLED)
+ auth &= ~CURLAUTH_NTLM_WB; /* no NTLM_WB support */
+#endif
+#ifndef USE_SPNEGO
+ auth &= ~CURLAUTH_NEGOTIATE; /* no Negotiate (SPNEGO) auth without
+ GSS-API or SSPI */
+#endif
+
+ /* check if any auth bit lower than CURLAUTH_ONLY is still set */
+ bitcheck = 0;
+ authbits = FALSE;
+ while(bitcheck < 31) {
+ if(auth & (1UL << bitcheck++)) {
+ authbits = TRUE;
+ break;
+ }
+ }
+ if(!authbits)
+ return CURLE_NOT_BUILT_IN; /* no supported types left! */
+
+ data->set.proxyauth = auth;
+ }
+ break;
+
+ case CURLOPT_PROXY:
+ /*
+ * Set proxy server:port to use as proxy.
+ *
+ * If the proxy is set to "" (and CURLOPT_SOCKS_PROXY is set to "" or NULL)
+ * we explicitly say that we don't want to use a proxy
+ * (even though there might be environment variables saying so).
+ *
+ * Setting it to NULL, means no proxy but allows the environment variables
+ * to decide for us (if CURLOPT_SOCKS_PROXY setting it to NULL).
+ */
+ result = Curl_setstropt(&data->set.str[STRING_PROXY],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_PRE_PROXY:
+ /*
+ * Set proxy server:port to use as SOCKS proxy.
+ *
+ * If the proxy is set to "" or NULL we explicitly say that we don't want
+ * to use the socks proxy.
+ */
+ result = Curl_setstropt(&data->set.str[STRING_PRE_PROXY],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_PROXYTYPE:
+ /*
+ * Set proxy type. HTTP/HTTP_1_0/SOCKS4/SOCKS4a/SOCKS5/SOCKS5_HOSTNAME
+ */
+ arg = va_arg(param, long);
+ if((arg < CURLPROXY_HTTP) || (arg > CURLPROXY_SOCKS5_HOSTNAME))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.proxytype = (curl_proxytype)arg;
+ break;
+
+ case CURLOPT_PROXY_TRANSFER_MODE:
+ /*
+ * set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy
+ */
+ switch(va_arg(param, long)) {
+ case 0:
+ data->set.proxy_transfer_mode = FALSE;
+ break;
+ case 1:
+ data->set.proxy_transfer_mode = TRUE;
+ break;
+ default:
+ /* reserve other values for future use */
+ result = CURLE_UNKNOWN_OPTION;
+ break;
+ }
+ 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:
+ /*
+ * Set flag for NEC SOCK5 support
+ */
+ data->set.socks5_gssapi_nec = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+#endif
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_SOCKS5_GSSAPI_SERVICE:
+ case CURLOPT_PROXY_SERVICE_NAME:
+ /*
+ * Set proxy authentication service name for Kerberos 5 and SPNEGO
+ */
+ result = Curl_setstropt(&data->set.str[STRING_PROXY_SERVICE_NAME],
+ va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_SERVICE_NAME:
+ /*
+ * Set authentication service name for DIGEST-MD5, Kerberos 5 and SPNEGO
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SERVICE_NAME],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_HEADERDATA:
+ /*
+ * Custom pointer to pass the header write callback function
+ */
+ data->set.writeheader = (void *)va_arg(param, void *);
+ break;
+ case CURLOPT_ERRORBUFFER:
+ /*
+ * Error buffer provided by the caller to get the human readable
+ * error string in.
+ */
+ data->set.errorbuffer = va_arg(param, char *);
+ break;
+ case CURLOPT_WRITEDATA:
+ /*
+ * FILE pointer to write to. Or possibly
+ * used as argument to the write callback.
+ */
+ data->set.out = va_arg(param, void *);
+ break;
+
+ case CURLOPT_DIRLISTONLY:
+ /*
+ * An option that changes the command to one that asks for a list only, no
+ * file info details. Used for FTP, POP3 and SFTP.
+ */
+ data->set.ftp_list_only = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_APPEND:
+ /*
+ * We want to upload and append to an existing file. Used for FTP and
+ * SFTP.
+ */
+ data->set.ftp_append = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+#ifndef CURL_DISABLE_FTP
+ case CURLOPT_FTP_FILEMETHOD:
+ /*
+ * How do access files over FTP.
+ */
+ arg = va_arg(param, long);
+ if((arg < CURLFTPMETHOD_DEFAULT) || (arg > CURLFTPMETHOD_SINGLECWD))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.ftp_filemethod = (curl_ftpfile)arg;
+ break;
+ case CURLOPT_FTPPORT:
+ /*
+ * Use FTP PORT, this also specifies which IP address to use
+ */
+ result = Curl_setstropt(&data->set.str[STRING_FTPPORT],
+ va_arg(param, char *));
+ data->set.ftp_use_port = (data->set.str[STRING_FTPPORT]) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_FTP_USE_EPRT:
+ data->set.ftp_use_eprt = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_FTP_USE_EPSV:
+ data->set.ftp_use_epsv = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_FTP_USE_PRET:
+ data->set.ftp_use_pret = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_FTP_SSL_CCC:
+ arg = va_arg(param, long);
+ if((arg < CURLFTPSSL_CCC_NONE) || (arg > CURLFTPSSL_CCC_ACTIVE))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.ftp_ccc = (curl_ftpccc)arg;
+ break;
+
+ case CURLOPT_FTP_SKIP_PASV_IP:
+ /*
+ * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
+ * bypass of the IP address in PASV responses.
+ */
+ data->set.ftp_skip_ip = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_FTP_ACCOUNT:
+ result = Curl_setstropt(&data->set.str[STRING_FTP_ACCOUNT],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_FTP_ALTERNATIVE_TO_USER:
+ result = Curl_setstropt(&data->set.str[STRING_FTP_ALTERNATIVE_TO_USER],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_FTPSSLAUTH:
+ /*
+ * Set a specific auth for FTP-SSL transfers.
+ */
+ arg = va_arg(param, long);
+ if((arg < CURLFTPAUTH_DEFAULT) || (arg > CURLFTPAUTH_TLS))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.ftpsslauth = (curl_ftpauth)arg;
+ break;
+ case CURLOPT_KRBLEVEL:
+ /*
+ * A string that defines the kerberos security level.
+ */
+ result = Curl_setstropt(&data->set.str[STRING_KRB_LEVEL],
+ va_arg(param, char *));
+ data->set.krb = (data->set.str[STRING_KRB_LEVEL]) ? TRUE : FALSE;
+ break;
+#endif
+ case CURLOPT_FTP_CREATE_MISSING_DIRS:
+ /*
+ * An FTP/SFTP option that modifies an upload to create missing
+ * directories on the server.
+ */
+ switch(va_arg(param, long)) {
+ case 0:
+ data->set.ftp_create_missing_dirs = 0;
+ break;
+ case 1:
+ data->set.ftp_create_missing_dirs = 1;
+ break;
+ case 2:
+ data->set.ftp_create_missing_dirs = 2;
+ break;
+ default:
+ /* reserve other values for future use */
+ result = CURLE_UNKNOWN_OPTION;
+ break;
+ }
+ break;
+ case CURLOPT_READDATA:
+ /*
+ * FILE pointer to read the file to be uploaded from. Or possibly
+ * used as argument to the read callback.
+ */
+ data->set.in_set = va_arg(param, void *);
+ break;
+ case CURLOPT_INFILESIZE:
+ /*
+ * If known, this should inform curl about the file size of the
+ * to-be-uploaded file.
+ */
+ arg = va_arg(param, long);
+ if(arg < -1)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.filesize = arg;
+ break;
+ case CURLOPT_INFILESIZE_LARGE:
+ /*
+ * If known, this should inform curl about the file size of the
+ * to-be-uploaded file.
+ */
+ bigsize = va_arg(param, curl_off_t);
+ if(bigsize < -1)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.filesize = bigsize;
+ break;
+ case CURLOPT_LOW_SPEED_LIMIT:
+ /*
+ * The low speed limit that if transfers are below this for
+ * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
+ */
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.low_speed_limit = arg;
+ 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..
+ */
+ bigsize = va_arg(param, curl_off_t);
+ if(bigsize < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.max_send_speed = bigsize;
+ break;
+ case CURLOPT_MAX_RECV_SPEED_LARGE:
+ /*
+ * When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
+ * second the transfer is throttled..
+ */
+ bigsize = va_arg(param, curl_off_t);
+ if(bigsize < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.max_recv_speed = bigsize;
+ 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.
+ */
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.low_speed_time = arg;
+ break;
+ case CURLOPT_CURLU:
+ /*
+ * pass CURLU to set URL
+ */
+ data->set.uh = va_arg(param, CURLU *);
+ break;
+ case CURLOPT_URL:
+ /*
+ * The URL to fetch.
+ */
+ if(data->change.url_alloc) {
+ /* the already set URL is allocated, free it first! */
+ Curl_safefree(data->change.url);
+ data->change.url_alloc = FALSE;
+ }
+ result = Curl_setstropt(&data->set.str[STRING_SET_URL],
+ va_arg(param, char *));
+ data->change.url = data->set.str[STRING_SET_URL];
+ break;
+ case CURLOPT_PORT:
+ /*
+ * The port number to use when getting the URL
+ */
+ arg = va_arg(param, long);
+ if((arg < 0) || (arg > 65535))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.use_port = arg;
+ break;
+ case CURLOPT_TIMEOUT:
+ /*
+ * The maximum time you allow curl to use for a single transfer
+ * operation.
+ */
+ arg = va_arg(param, long);
+ if((arg >= 0) && (arg <= (INT_MAX/1000)))
+ data->set.timeout = arg * 1000;
+ else
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ break;
+
+ case CURLOPT_TIMEOUT_MS:
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.timeout = arg;
+ break;
+
+ case CURLOPT_CONNECTTIMEOUT:
+ /*
+ * The maximum time you allow curl to use to connect.
+ */
+ arg = va_arg(param, long);
+ if((arg >= 0) && (arg <= (INT_MAX/1000)))
+ data->set.connecttimeout = arg * 1000;
+ else
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ break;
+
+ case CURLOPT_CONNECTTIMEOUT_MS:
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.connecttimeout = arg;
+ break;
+
+ case CURLOPT_ACCEPTTIMEOUT_MS:
+ /*
+ * The maximum time you allow curl to wait for server connect
+ */
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.accepttimeout = arg;
+ break;
+
+ case CURLOPT_USERPWD:
+ /*
+ * user:password to use in the operation
+ */
+ result = setstropt_userpwd(va_arg(param, char *),
+ &data->set.str[STRING_USERNAME],
+ &data->set.str[STRING_PASSWORD]);
+ break;
+
+ case CURLOPT_USERNAME:
+ /*
+ * authentication user name to use in the operation
+ */
+ result = Curl_setstropt(&data->set.str[STRING_USERNAME],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_PASSWORD:
+ /*
+ * authentication password to use in the operation
+ */
+ result = Curl_setstropt(&data->set.str[STRING_PASSWORD],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_LOGIN_OPTIONS:
+ /*
+ * authentication options to use in the operation
+ */
+ result = Curl_setstropt(&data->set.str[STRING_OPTIONS],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_XOAUTH2_BEARER:
+ /*
+ * OAuth 2.0 bearer token to use in the operation
+ */
+ result = Curl_setstropt(&data->set.str[STRING_BEARER],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_POSTQUOTE:
+ /*
+ * List of RAW FTP commands to use after a transfer
+ */
+ data->set.postquote = va_arg(param, struct curl_slist *);
+ break;
+ case CURLOPT_PREQUOTE:
+ /*
+ * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
+ */
+ data->set.prequote = va_arg(param, struct curl_slist *);
+ break;
+ case CURLOPT_QUOTE:
+ /*
+ * List of RAW FTP commands to use before a transfer
+ */
+ data->set.quote = va_arg(param, struct curl_slist *);
+ break;
+ case CURLOPT_RESOLVE:
+ /*
+ * List of NAME:[address] names to populate the DNS cache with
+ * Prefix the NAME with dash (-) to _remove_ the name from the cache.
+ *
+ * Names added with this API will remain in the cache until explicitly
+ * removed or the handle is cleaned up.
+ *
+ * This API can remove any name from the DNS cache, but only entries
+ * that aren't actually in use right now will be pruned immediately.
+ */
+ data->set.resolve = va_arg(param, struct curl_slist *);
+ data->change.resolve = data->set.resolve;
+ break;
+ case CURLOPT_PROGRESSFUNCTION:
+ /*
+ * Progress callback function
+ */
+ data->set.fprogress = va_arg(param, curl_progress_callback);
+ if(data->set.fprogress)
+ data->progress.callback = TRUE; /* no longer internal */
+ else
+ data->progress.callback = FALSE; /* NULL enforces internal */
+ break;
+
+ case CURLOPT_XFERINFOFUNCTION:
+ /*
+ * Transfer info callback function
+ */
+ data->set.fxferinfo = va_arg(param, curl_xferinfo_callback);
+ if(data->set.fxferinfo)
+ data->progress.callback = TRUE; /* no longer internal */
+ else
+ data->progress.callback = FALSE; /* NULL enforces internal */
+
+ break;
+
+ case CURLOPT_PROGRESSDATA:
+ /*
+ * Custom client data to pass to the progress callback
+ */
+ data->set.progress_client = va_arg(param, void *);
+ break;
+
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXYUSERPWD:
+ /*
+ * user:password needed to use the proxy
+ */
+ result = setstropt_userpwd(va_arg(param, char *),
+ &data->set.str[STRING_PROXYUSERNAME],
+ &data->set.str[STRING_PROXYPASSWORD]);
+ break;
+ case CURLOPT_PROXYUSERNAME:
+ /*
+ * authentication user name to use in the operation
+ */
+ result = Curl_setstropt(&data->set.str[STRING_PROXYUSERNAME],
+ va_arg(param, char *));
+ break;
+ case CURLOPT_PROXYPASSWORD:
+ /*
+ * authentication password to use in the operation
+ */
+ result = Curl_setstropt(&data->set.str[STRING_PROXYPASSWORD],
+ va_arg(param, char *));
+ break;
+ case CURLOPT_NOPROXY:
+ /*
+ * proxy exception list
+ */
+ result = Curl_setstropt(&data->set.str[STRING_NOPROXY],
+ va_arg(param, char *));
+ break;
+#endif
+
+ case CURLOPT_RANGE:
+ /*
+ * What range of the file you want to transfer
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SET_RANGE],
+ va_arg(param, char *));
+ break;
+ case CURLOPT_RESUME_FROM:
+ /*
+ * Resume transfer at the given file position
+ */
+ arg = va_arg(param, long);
+ if(arg < -1)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.set_resume_from = arg;
+ break;
+ case CURLOPT_RESUME_FROM_LARGE:
+ /*
+ * Resume transfer at the given file position
+ */
+ bigsize = va_arg(param, curl_off_t);
+ if(bigsize < -1)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.set_resume_from = bigsize;
+ break;
+ case CURLOPT_DEBUGFUNCTION:
+ /*
+ * stderr write callback.
+ */
+ data->set.fdebug = va_arg(param, curl_debug_callback);
+ /*
+ * if the callback provided is NULL, it'll use the default callback
+ */
+ break;
+ case CURLOPT_DEBUGDATA:
+ /*
+ * Set to a void * that should receive all error writes. This
+ * defaults to CURLOPT_STDERR for normal operations.
+ */
+ data->set.debugdata = va_arg(param, void *);
+ break;
+ case CURLOPT_STDERR:
+ /*
+ * Set to a FILE * that should receive all error writes. This
+ * defaults to stderr for normal operations.
+ */
+ data->set.err = va_arg(param, FILE *);
+ if(!data->set.err)
+ data->set.err = stderr;
+ break;
+ case CURLOPT_HEADERFUNCTION:
+ /*
+ * Set header write callback
+ */
+ data->set.fwrite_header = va_arg(param, curl_write_callback);
+ break;
+ case CURLOPT_WRITEFUNCTION:
+ /*
+ * Set data write callback
+ */
+ data->set.fwrite_func = va_arg(param, curl_write_callback);
+ if(!data->set.fwrite_func) {
+ data->set.is_fwrite_set = 0;
+ /* When set to NULL, reset to our internal default function */
+ data->set.fwrite_func = (curl_write_callback)fwrite;
+ }
+ else
+ data->set.is_fwrite_set = 1;
+ break;
+ case CURLOPT_READFUNCTION:
+ /*
+ * Read data callback
+ */
+ data->set.fread_func_set = va_arg(param, curl_read_callback);
+ if(!data->set.fread_func_set) {
+ data->set.is_fread_set = 0;
+ /* When set to NULL, reset to our internal default function */
+ data->set.fread_func_set = (curl_read_callback)fread;
+ }
+ else
+ data->set.is_fread_set = 1;
+ break;
+ case CURLOPT_SEEKFUNCTION:
+ /*
+ * Seek callback. Might be NULL.
+ */
+ data->set.seek_func = va_arg(param, curl_seek_callback);
+ break;
+ case CURLOPT_SEEKDATA:
+ /*
+ * Seek control callback. Might be NULL.
+ */
+ data->set.seek_client = va_arg(param, void *);
+ break;
+ case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
+ /*
+ * "Convert from network encoding" callback
+ */
+ data->set.convfromnetwork = va_arg(param, curl_conv_callback);
+ break;
+ case CURLOPT_CONV_TO_NETWORK_FUNCTION:
+ /*
+ * "Convert to network encoding" callback
+ */
+ data->set.convtonetwork = va_arg(param, curl_conv_callback);
+ break;
+ case CURLOPT_CONV_FROM_UTF8_FUNCTION:
+ /*
+ * "Convert from UTF-8 encoding" callback
+ */
+ data->set.convfromutf8 = va_arg(param, curl_conv_callback);
+ break;
+ case CURLOPT_IOCTLFUNCTION:
+ /*
+ * I/O control callback. Might be NULL.
+ */
+ data->set.ioctl_func = va_arg(param, curl_ioctl_callback);
+ break;
+ case CURLOPT_IOCTLDATA:
+ /*
+ * I/O control data pointer. Might be NULL.
+ */
+ data->set.ioctl_client = va_arg(param, void *);
+ break;
+ case CURLOPT_SSLCERT:
+ /*
+ * String that holds file name of the SSL certificate to use
+ */
+ result = Curl_setstropt(&data->set.str[STRING_CERT_ORIG],
+ va_arg(param, char *));
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_SSLCERT:
+ /*
+ * String that holds file name of the SSL certificate to use for proxy
+ */
+ result = Curl_setstropt(&data->set.str[STRING_CERT_PROXY],
+ va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_SSLCERTTYPE:
+ /*
+ * String that holds file type of the SSL certificate to use
+ */
+ result = Curl_setstropt(&data->set.str[STRING_CERT_TYPE_ORIG],
+ va_arg(param, char *));
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_SSLCERTTYPE:
+ /*
+ * String that holds file type of the SSL certificate to use for proxy
+ */
+ result = Curl_setstropt(&data->set.str[STRING_CERT_TYPE_PROXY],
+ va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_SSLKEY:
+ /*
+ * String that holds file name of the SSL key to use
+ */
+ result = Curl_setstropt(&data->set.str[STRING_KEY_ORIG],
+ va_arg(param, char *));
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_SSLKEY:
+ /*
+ * String that holds file name of the SSL key to use for proxy
+ */
+ result = Curl_setstropt(&data->set.str[STRING_KEY_PROXY],
+ va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_SSLKEYTYPE:
+ /*
+ * String that holds file type of the SSL key to use
+ */
+ result = Curl_setstropt(&data->set.str[STRING_KEY_TYPE_ORIG],
+ va_arg(param, char *));
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_SSLKEYTYPE:
+ /*
+ * String that holds file type of the SSL key to use for proxy
+ */
+ result = Curl_setstropt(&data->set.str[STRING_KEY_TYPE_PROXY],
+ va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_KEYPASSWD:
+ /*
+ * String that holds the SSL or SSH private key password.
+ */
+ result = Curl_setstropt(&data->set.str[STRING_KEY_PASSWD_ORIG],
+ va_arg(param, char *));
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_KEYPASSWD:
+ /*
+ * String that holds the SSL private key password for proxy.
+ */
+ result = Curl_setstropt(&data->set.str[STRING_KEY_PASSWD_PROXY],
+ va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_SSLENGINE:
+ /*
+ * String that holds the SSL crypto engine.
+ */
+ argptr = va_arg(param, char *);
+ if(argptr && argptr[0]) {
+ result = Curl_setstropt(&data->set.str[STRING_SSL_ENGINE], argptr);
+ if(!result) {
+ result = Curl_ssl_set_engine(data, argptr);
+ }
+ }
+ break;
+
+ case CURLOPT_SSLENGINE_DEFAULT:
+ /*
+ * flag to set engine as default.
+ */
+ Curl_setstropt(&data->set.str[STRING_SSL_ENGINE], NULL);
+ result = Curl_ssl_set_engine_default(data);
+ break;
+ case CURLOPT_CRLF:
+ /*
+ * Kludgy option to enable CRLF conversions. Subject for removal.
+ */
+ data->set.crlf = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_HAPROXYPROTOCOL:
+ /*
+ * Set to send the HAProxy Proxy Protocol header
+ */
+ data->set.haproxyprotocol = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+#endif
+ case CURLOPT_INTERFACE:
+ /*
+ * Set what interface or address/hostname to bind the socket to when
+ * performing an operation and thus what from-IP your connection will use.
+ */
+ result = Curl_setstropt(&data->set.str[STRING_DEVICE],
+ va_arg(param, char *));
+ break;
+ case CURLOPT_LOCALPORT:
+ /*
+ * Set what local port to bind the socket to when performing an operation.
+ */
+ arg = va_arg(param, long);
+ if((arg < 0) || (arg > 65535))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.localport = curlx_sltous(arg);
+ break;
+ case CURLOPT_LOCALPORTRANGE:
+ /*
+ * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
+ */
+ arg = va_arg(param, long);
+ if((arg < 0) || (arg > 65535))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.localportrange = curlx_sltosi(arg);
+ break;
+ case CURLOPT_GSSAPI_DELEGATION:
+ /*
+ * GSS-API credential delegation bitmask
+ */
+ arg = va_arg(param, long);
+ if(arg < CURLGSSAPI_DELEGATION_NONE)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.gssapi_delegation = arg;
+ break;
+ case CURLOPT_SSL_VERIFYPEER:
+ /*
+ * Enable peer SSL verifying.
+ */
+ data->set.ssl.primary.verifypeer = (0 != va_arg(param, long)) ?
+ TRUE : FALSE;
+
+ /* Update the current connection ssl_config. */
+ if(data->conn) {
+ data->conn->ssl_config.verifypeer =
+ data->set.ssl.primary.verifypeer;
+ }
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_SSL_VERIFYPEER:
+ /*
+ * Enable peer SSL verifying for proxy.
+ */
+ data->set.proxy_ssl.primary.verifypeer =
+ (0 != va_arg(param, long))?TRUE:FALSE;
+
+ /* Update the current connection proxy_ssl_config. */
+ if(data->conn) {
+ data->conn->proxy_ssl_config.verifypeer =
+ data->set.proxy_ssl.primary.verifypeer;
+ }
+ break;
+#endif
+ case CURLOPT_SSL_VERIFYHOST:
+ /*
+ * Enable verification of the host name in the peer certificate
+ */
+ arg = va_arg(param, long);
+
+ /* Obviously people are not reading documentation and too many thought
+ this argument took a boolean when it wasn't and misused it. We thus ban
+ 1 as a sensible input and we warn about its use. Then we only have the
+ 2 action internally stored as TRUE. */
+
+ if(1 == arg) {
+ failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!");
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ }
+
+ data->set.ssl.primary.verifyhost = (0 != arg) ? TRUE : FALSE;
+
+ /* Update the current connection ssl_config. */
+ if(data->conn) {
+ data->conn->ssl_config.verifyhost =
+ data->set.ssl.primary.verifyhost;
+ }
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_SSL_VERIFYHOST:
+ /*
+ * Enable verification of the host name in the peer certificate for proxy
+ */
+ arg = va_arg(param, long);
+
+ /* Obviously people are not reading documentation and too many thought
+ this argument took a boolean when it wasn't and misused it. We thus ban
+ 1 as a sensible input and we warn about its use. Then we only have the
+ 2 action internally stored as TRUE. */
+
+ if(1 == arg) {
+ failf(data, "CURLOPT_SSL_VERIFYHOST no longer supports 1 as value!");
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ }
+
+ data->set.proxy_ssl.primary.verifyhost = (0 != arg)?TRUE:FALSE;
+
+ /* Update the current connection proxy_ssl_config. */
+ if(data->conn) {
+ data->conn->proxy_ssl_config.verifyhost =
+ data->set.proxy_ssl.primary.verifyhost;
+ }
+ break;
+#endif
+ case CURLOPT_SSL_VERIFYSTATUS:
+ /*
+ * Enable certificate status verifying.
+ */
+ if(!Curl_ssl_cert_status_request()) {
+ result = CURLE_NOT_BUILT_IN;
+ break;
+ }
+
+ data->set.ssl.primary.verifystatus = (0 != va_arg(param, long)) ?
+ TRUE : FALSE;
+
+ /* Update the current connection ssl_config. */
+ if(data->conn) {
+ data->conn->ssl_config.verifystatus =
+ data->set.ssl.primary.verifystatus;
+ }
+ break;
+ case CURLOPT_SSL_CTX_FUNCTION:
+ /*
+ * Set a SSL_CTX callback
+ */
+#ifdef USE_SSL
+ if(Curl_ssl->supports & SSLSUPP_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:
+ /*
+ * Set a SSL_CTX callback parameter pointer
+ */
+#ifdef USE_SSL
+ if(Curl_ssl->supports & SSLSUPP_SSL_CTX)
+ data->set.ssl.fsslctxp = va_arg(param, void *);
+ else
+#endif
+ result = CURLE_NOT_BUILT_IN;
+ break;
+ case CURLOPT_SSL_FALSESTART:
+ /*
+ * Enable TLS false start.
+ */
+ if(!Curl_ssl_false_start()) {
+ result = CURLE_NOT_BUILT_IN;
+ break;
+ }
+
+ data->set.ssl.falsestart = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_CERTINFO:
+#ifdef USE_SSL
+ if(Curl_ssl->supports & SSLSUPP_CERTINFO)
+ data->set.ssl.certinfo = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ else
+#endif
+ result = CURLE_NOT_BUILT_IN;
+ break;
+ case CURLOPT_PINNEDPUBLICKEY:
+ /*
+ * Set pinned public key for SSL connection.
+ * Specify file name of the public key in DER format.
+ */
+#ifdef USE_SSL
+ if(Curl_ssl->supports & SSLSUPP_PINNEDPUBKEY)
+ result = Curl_setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG],
+ va_arg(param, char *));
+ else
+#endif
+ result = CURLE_NOT_BUILT_IN;
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_PINNEDPUBLICKEY:
+ /*
+ * Set pinned public key for SSL connection.
+ * Specify file name of the public key in DER format.
+ */
+#ifdef USE_SSL
+ if(Curl_ssl->supports & SSLSUPP_PINNEDPUBKEY)
+ result = Curl_setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY],
+ va_arg(param, char *));
+ else
+#endif
+ result = CURLE_NOT_BUILT_IN;
+ break;
+#endif
+ case CURLOPT_CAINFO:
+ /*
+ * Set CA info for SSL connection. Specify file name of the CA certificate
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_CAFILE_ORIG],
+ va_arg(param, char *));
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_CAINFO:
+ /*
+ * Set CA info SSL connection for proxy. Specify file name of the
+ * CA certificate
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_CAFILE_PROXY],
+ va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_CAPATH:
+ /*
+ * Set CA path info for SSL connection. Specify directory name of the CA
+ * certificates which have been prepared using openssl c_rehash utility.
+ */
+#ifdef USE_SSL
+ if(Curl_ssl->supports & SSLSUPP_CA_PATH)
+ /* This does not work on windows. */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_CAPATH_ORIG],
+ va_arg(param, char *));
+ else
+#endif
+ result = CURLE_NOT_BUILT_IN;
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_CAPATH:
+ /*
+ * Set CA path info for SSL connection proxy. Specify directory name of the
+ * CA certificates which have been prepared using openssl c_rehash utility.
+ */
+#ifdef USE_SSL
+ if(Curl_ssl->supports & SSLSUPP_CA_PATH)
+ /* This does not work on windows. */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_CAPATH_PROXY],
+ va_arg(param, char *));
+ else
+#endif
+ result = CURLE_NOT_BUILT_IN;
+ break;
+#endif
+ case CURLOPT_CRLFILE:
+ /*
+ * Set CRL file info for SSL connection. Specify file name of the CRL
+ * to check certificates revocation
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_CRLFILE_ORIG],
+ va_arg(param, char *));
+ break;
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_CRLFILE:
+ /*
+ * Set CRL file info for SSL connection for proxy. Specify file name of the
+ * CRL to check certificates revocation
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_CRLFILE_PROXY],
+ va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_ISSUERCERT:
+ /*
+ * Set Issuer certificate file
+ * to check certificates issuer
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSL_ISSUERCERT_ORIG],
+ va_arg(param, char *));
+ break;
+#ifndef CURL_DISABLE_TELNET
+ case CURLOPT_TELNETOPTIONS:
+ /*
+ * Set a linked list of telnet options
+ */
+ data->set.telnet_options = va_arg(param, struct curl_slist *);
+ break;
+#endif
+ case CURLOPT_BUFFERSIZE:
+ /*
+ * The application kindly asks for a differently sized receive buffer.
+ * If it seems reasonable, we'll use it.
+ */
+ arg = va_arg(param, long);
+
+ if(arg > READBUFFER_MAX)
+ arg = READBUFFER_MAX;
+ else if(arg < 1)
+ arg = READBUFFER_SIZE;
+ else if(arg < READBUFFER_MIN)
+ arg = READBUFFER_MIN;
+
+ /* Resize if new size */
+ if(arg != data->set.buffer_size) {
+ char *newbuff = realloc(data->state.buffer, arg + 1);
+ if(!newbuff) {
+ DEBUGF(fprintf(stderr, "Error: realloc of buffer failed\n"));
+ result = CURLE_OUT_OF_MEMORY;
+ }
+ else
+ data->state.buffer = newbuff;
+ }
+ data->set.buffer_size = arg;
+
+ break;
+
+ case CURLOPT_UPLOAD_BUFFERSIZE:
+ /*
+ * The application kindly asks for a differently sized upload buffer.
+ * Cap it to sensible.
+ */
+ arg = va_arg(param, long);
+
+ if(arg > UPLOADBUFFER_MAX)
+ arg = UPLOADBUFFER_MAX;
+ else if(arg < UPLOADBUFFER_MIN)
+ arg = UPLOADBUFFER_MIN;
+
+ data->set.upload_buffer_size = arg;
+ Curl_safefree(data->state.ulbuf); /* force a realloc next opportunity */
+ break;
+
+ case CURLOPT_NOSIGNAL:
+ /*
+ * The application asks not to set any signal() or alarm() handlers,
+ * even when using a timeout.
+ */
+ data->set.no_signal = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_SHARE:
+ {
+ struct Curl_share *set;
+ set = va_arg(param, struct Curl_share *);
+
+ /* disconnect from old share, if any */
+ if(data->share) {
+ Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
+
+ if(data->dns.hostcachetype == HCACHE_SHARED) {
+ data->dns.hostcache = NULL;
+ data->dns.hostcachetype = HCACHE_NONE;
+ }
+
+#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
+ if(data->share->cookies == data->cookies)
+ data->cookies = NULL;
+#endif
+
+ if(data->share->sslsession == data->state.session)
+ data->state.session = NULL;
+
+#ifdef USE_LIBPSL
+ if(data->psl == &data->share->psl)
+ data->psl = data->multi? &data->multi->psl: NULL;
+#endif
+
+ data->share->dirty--;
+
+ Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
+ data->share = NULL;
+ }
+
+ /* use new share if it set */
+ data->share = set;
+ if(data->share) {
+
+ Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
+
+ data->share->dirty++;
+
+ if(data->share->specifier & (1<< CURL_LOCK_DATA_DNS)) {
+ /* use shared host cache */
+ data->dns.hostcache = &data->share->hostcache;
+ data->dns.hostcachetype = HCACHE_SHARED;
+ }
+#if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
+ if(data->share->cookies) {
+ /* use shared cookie list, first free own one if any */
+ Curl_cookie_cleanup(data->cookies);
+ /* enable cookies since we now use a share that uses cookies! */
+ data->cookies = data->share->cookies;
+ }
+#endif /* CURL_DISABLE_HTTP */
+ if(data->share->sslsession) {
+ data->set.general_ssl.max_ssl_sessions = data->share->max_ssl_sessions;
+ data->state.session = data->share->sslsession;
+ }
+#ifdef USE_LIBPSL
+ if(data->share->specifier & (1 << CURL_LOCK_DATA_PSL))
+ data->psl = &data->share->psl;
+#endif
+
+ Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
+ }
+ /* check for host cache not needed,
+ * it will be done by curl_easy_perform */
+ }
+ break;
+
+ case CURLOPT_PRIVATE:
+ /*
+ * Set private data pointer.
+ */
+ data->set.private_data = va_arg(param, void *);
+ break;
+
+ case CURLOPT_MAXFILESIZE:
+ /*
+ * Set the maximum size of a file to download.
+ */
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.max_filesize = arg;
+ break;
+
+#ifdef USE_SSL
+ case CURLOPT_USE_SSL:
+ /*
+ * Make transfers attempt to use SSL/TLS.
+ */
+ arg = va_arg(param, long);
+ if((arg < CURLUSESSL_NONE) || (arg > CURLUSESSL_ALL))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.use_ssl = (curl_usessl)arg;
+ break;
+
+ case CURLOPT_SSL_OPTIONS:
+ arg = va_arg(param, long);
+ data->set.ssl.enable_beast =
+ (bool)((arg&CURLSSLOPT_ALLOW_BEAST) ? TRUE : FALSE);
+ data->set.ssl.no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE);
+ break;
+
+#ifndef CURL_DISABLE_PROXY
+ case CURLOPT_PROXY_SSL_OPTIONS:
+ arg = va_arg(param, long);
+ data->set.proxy_ssl.enable_beast =
+ (bool)((arg&CURLSSLOPT_ALLOW_BEAST) ? TRUE : FALSE);
+ data->set.proxy_ssl.no_revoke = !!(arg & CURLSSLOPT_NO_REVOKE);
+ break;
+#endif
+
+#endif
+ case CURLOPT_IPRESOLVE:
+ arg = va_arg(param, long);
+ if((arg < CURL_IPRESOLVE_WHATEVER) || (arg > CURL_IPRESOLVE_V6))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.ipver = arg;
+ break;
+
+ case CURLOPT_MAXFILESIZE_LARGE:
+ /*
+ * Set the maximum size of a file to download.
+ */
+ bigsize = va_arg(param, curl_off_t);
+ if(bigsize < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.max_filesize = bigsize;
+ break;
+
+ case CURLOPT_TCP_NODELAY:
+ /*
+ * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
+ * algorithm
+ */
+ data->set.tcp_nodelay = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_IGNORE_CONTENT_LENGTH:
+ data->set.ignorecl = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_CONNECT_ONLY:
+ /*
+ * No data transfer, set up connection and let application use the socket
+ */
+ data->set.connect_only = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_SOCKOPTFUNCTION:
+ /*
+ * socket callback function: called after socket() but before connect()
+ */
+ data->set.fsockopt = va_arg(param, curl_sockopt_callback);
+ break;
+
+ case CURLOPT_SOCKOPTDATA:
+ /*
+ * socket callback data pointer. Might be NULL.
+ */
+ data->set.sockopt_client = va_arg(param, void *);
+ break;
+
+ case CURLOPT_OPENSOCKETFUNCTION:
+ /*
+ * open/create socket callback function: called instead of socket(),
+ * before connect()
+ */
+ data->set.fopensocket = va_arg(param, curl_opensocket_callback);
+ break;
+
+ case CURLOPT_OPENSOCKETDATA:
+ /*
+ * socket callback data pointer. Might be NULL.
+ */
+ data->set.opensocket_client = va_arg(param, void *);
+ break;
+
+ case CURLOPT_CLOSESOCKETFUNCTION:
+ /*
+ * close socket callback function: called instead of close()
+ * when shutting down a connection
+ */
+ data->set.fclosesocket = va_arg(param, curl_closesocket_callback);
+ break;
+
+ case CURLOPT_RESOLVER_START_FUNCTION:
+ /*
+ * resolver start callback function: called before a new resolver request
+ * is started
+ */
+ data->set.resolver_start = va_arg(param, curl_resolver_start_callback);
+ break;
+
+ case CURLOPT_RESOLVER_START_DATA:
+ /*
+ * resolver start callback data pointer. Might be NULL.
+ */
+ data->set.resolver_start_client = va_arg(param, void *);
+ break;
+
+ case CURLOPT_CLOSESOCKETDATA:
+ /*
+ * socket callback data pointer. Might be NULL.
+ */
+ data->set.closesocket_client = va_arg(param, void *);
+ break;
+
+ case CURLOPT_SSL_SESSIONID_CACHE:
+ data->set.ssl.primary.sessionid = (0 != va_arg(param, long)) ?
+ TRUE : FALSE;
+ data->set.proxy_ssl.primary.sessionid = data->set.ssl.primary.sessionid;
+ break;
+
+#ifdef USE_SSH
+ /* we only include SSH options if explicitly built to support SSH */
+ case CURLOPT_SSH_AUTH_TYPES:
+ data->set.ssh_auth_types = va_arg(param, long);
+ break;
+
+ case CURLOPT_SSH_PUBLIC_KEYFILE:
+ /*
+ * Use this file instead of the $HOME/.ssh/id_dsa.pub file
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSH_PUBLIC_KEY],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_SSH_PRIVATE_KEYFILE:
+ /*
+ * Use this file instead of the $HOME/.ssh/id_dsa file
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSH_PRIVATE_KEY],
+ va_arg(param, char *));
+ break;
+ case CURLOPT_SSH_HOST_PUBLIC_KEY_MD5:
+ /*
+ * Option to allow for the MD5 of the host public key to be checked
+ * for validation purposes.
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_SSH_KNOWNHOSTS:
+ /*
+ * Store the file name to read known hosts from.
+ */
+ result = Curl_setstropt(&data->set.str[STRING_SSH_KNOWNHOSTS],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_SSH_KEYFUNCTION:
+ /* setting to NULL is fine since the ssh.c functions themselves will
+ then rever to use the internal default */
+ data->set.ssh_keyfunc = va_arg(param, curl_sshkeycallback);
+ break;
+
+ case CURLOPT_SSH_KEYDATA:
+ /*
+ * Custom client data to pass to the SSH keyfunc callback
+ */
+ data->set.ssh_keyfunc_userp = va_arg(param, void *);
+ break;
+
+ case CURLOPT_SSH_COMPRESSION:
+ data->set.ssh_compression = (0 != va_arg(param, long))?TRUE:FALSE;
+ break;
+#endif /* USE_SSH */
+
+ case CURLOPT_HTTP_TRANSFER_DECODING:
+ /*
+ * disable libcurl transfer encoding is used
+ */
+ data->set.http_te_skip = (0 == va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+ case CURLOPT_HTTP_CONTENT_DECODING:
+ /*
+ * raw data passed to the application when content encoding is used
+ */
+ data->set.http_ce_skip = (0 == va_arg(param, long)) ? TRUE : FALSE;
+ break;
+
+#if !defined(CURL_DISABLE_FTP) || defined(USE_SSH)
+ case CURLOPT_NEW_FILE_PERMS:
+ /*
+ * Uses these permissions instead of 0644
+ */
+ arg = va_arg(param, long);
+ if((arg < 0) || (arg > 0777))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.new_file_perms = arg;
+ break;
+
+ case CURLOPT_NEW_DIRECTORY_PERMS:
+ /*
+ * Uses these permissions instead of 0755
+ */
+ arg = va_arg(param, long);
+ if((arg < 0) || (arg > 0777))
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.new_directory_perms = arg;
+ break;
+#endif
+
+ case CURLOPT_ADDRESS_SCOPE:
+ /*
+ * Use this scope id when using IPv6
+ * We always get longs when passed plain numericals so we should check
+ * that the value fits into an unsigned 32 bit integer.
+ */
+ uarg = va_arg(param, unsigned long);
+#if SIZEOF_LONG > 4
+ if(uarg > UINT_MAX)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+#endif
+ data->set.scope_id = (unsigned int)uarg;
+ break;
+
+ case CURLOPT_PROTOCOLS:
+ /* set the bitmask for the protocols that are allowed to be used for the
+ transfer, which thus helps the app which takes URLs from users or other
+ external inputs and want to restrict what protocol(s) to deal
+ with. Defaults to CURLPROTO_ALL. */
+ data->set.allowed_protocols = va_arg(param, long);
+ break;
+
+ case CURLOPT_REDIR_PROTOCOLS:
+ /* set the bitmask for the protocols that libcurl is allowed to follow to,
+ as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
+ to be set in both bitmasks to be allowed to get redirected to. Defaults
+ to all protocols except FILE and SCP. */
+ data->set.redir_protocols = va_arg(param, long);
+ break;
+
+ case CURLOPT_DEFAULT_PROTOCOL:
+ /* Set the protocol to use when the URL doesn't include any protocol */
+ result = Curl_setstropt(&data->set.str[STRING_DEFAULT_PROTOCOL],
+ va_arg(param, char *));
+ break;
+#ifndef CURL_DISABLE_SMTP
+ case CURLOPT_MAIL_FROM:
+ /* Set the SMTP mail originator */
+ result = Curl_setstropt(&data->set.str[STRING_MAIL_FROM],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_MAIL_AUTH:
+ /* Set the SMTP auth originator */
+ result = Curl_setstropt(&data->set.str[STRING_MAIL_AUTH],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_MAIL_RCPT:
+ /* Set the list of mail recipients */
+ data->set.mail_rcpt = va_arg(param, struct curl_slist *);
+ break;
+#endif
+
+ case CURLOPT_SASL_IR:
+ /* Enable/disable SASL initial response */
+ data->set.sasl_ir = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+#ifndef CURL_DISABLE_RTSP
+ case CURLOPT_RTSP_REQUEST:
+ {
+ /*
+ * Set the RTSP request method (OPTIONS, SETUP, PLAY, etc...)
+ * Would this be better if the RTSPREQ_* were just moved into here?
+ */
+ long curl_rtspreq = va_arg(param, long);
+ Curl_RtspReq rtspreq = RTSPREQ_NONE;
+ switch(curl_rtspreq) {
+ case CURL_RTSPREQ_OPTIONS:
+ rtspreq = RTSPREQ_OPTIONS;
+ break;
+
+ case CURL_RTSPREQ_DESCRIBE:
+ rtspreq = RTSPREQ_DESCRIBE;
+ break;
+
+ case CURL_RTSPREQ_ANNOUNCE:
+ rtspreq = RTSPREQ_ANNOUNCE;
+ break;
+
+ case CURL_RTSPREQ_SETUP:
+ rtspreq = RTSPREQ_SETUP;
+ break;
+
+ case CURL_RTSPREQ_PLAY:
+ rtspreq = RTSPREQ_PLAY;
+ break;
+
+ case CURL_RTSPREQ_PAUSE:
+ rtspreq = RTSPREQ_PAUSE;
+ break;
+
+ case CURL_RTSPREQ_TEARDOWN:
+ rtspreq = RTSPREQ_TEARDOWN;
+ break;
+
+ case CURL_RTSPREQ_GET_PARAMETER:
+ rtspreq = RTSPREQ_GET_PARAMETER;
+ break;
+
+ case CURL_RTSPREQ_SET_PARAMETER:
+ rtspreq = RTSPREQ_SET_PARAMETER;
+ break;
+
+ case CURL_RTSPREQ_RECORD:
+ rtspreq = RTSPREQ_RECORD;
+ break;
+
+ case CURL_RTSPREQ_RECEIVE:
+ rtspreq = RTSPREQ_RECEIVE;
+ break;
+ default:
+ rtspreq = RTSPREQ_NONE;
+ }
+
+ data->set.rtspreq = rtspreq;
+ break;
+ }
+
+
+ case CURLOPT_RTSP_SESSION_ID:
+ /*
+ * Set the RTSP Session ID manually. Useful if the application is
+ * resuming a previously established RTSP session
+ */
+ result = Curl_setstropt(&data->set.str[STRING_RTSP_SESSION_ID],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_RTSP_STREAM_URI:
+ /*
+ * Set the Stream URI for the RTSP request. Unless the request is
+ * for generic server options, the application will need to set this.
+ */
+ result = Curl_setstropt(&data->set.str[STRING_RTSP_STREAM_URI],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_RTSP_TRANSPORT:
+ /*
+ * The content of the Transport: header for the RTSP request
+ */
+ result = Curl_setstropt(&data->set.str[STRING_RTSP_TRANSPORT],
+ va_arg(param, char *));
+ break;
+
+ case CURLOPT_RTSP_CLIENT_CSEQ:
+ /*
+ * Set the CSEQ number to issue for the next RTSP request. Useful if the
+ * application is resuming a previously broken connection. The CSEQ
+ * will increment from this new number henceforth.
+ */
+ data->state.rtsp_next_client_CSeq = va_arg(param, long);
+ break;
+
+ case CURLOPT_RTSP_SERVER_CSEQ:
+ /* Same as the above, but for server-initiated requests */
+ data->state.rtsp_next_client_CSeq = va_arg(param, long);
+ break;
+
+ case CURLOPT_INTERLEAVEDATA:
+ data->set.rtp_out = va_arg(param, void *);
+ break;
+ case CURLOPT_INTERLEAVEFUNCTION:
+ /* Set the user defined RTP write function */
+ data->set.fwrite_rtp = va_arg(param, curl_write_callback);
+ break;
+#endif
+#ifndef CURL_DISABLE_FTP
+ case CURLOPT_WILDCARDMATCH:
+ data->set.wildcard_enabled = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_CHUNK_BGN_FUNCTION:
+ data->set.chunk_bgn = va_arg(param, curl_chunk_bgn_callback);
+ break;
+ case CURLOPT_CHUNK_END_FUNCTION:
+ data->set.chunk_end = va_arg(param, curl_chunk_end_callback);
+ break;
+ case CURLOPT_FNMATCH_FUNCTION:
+ data->set.fnmatch = va_arg(param, curl_fnmatch_callback);
+ break;
+ case CURLOPT_CHUNK_DATA:
+ data->wildcard.customptr = va_arg(param, void *);
+ break;
+ case CURLOPT_FNMATCH_DATA:
+ data->set.fnmatch_data = va_arg(param, void *);
+ break;
+#endif
+#ifdef USE_TLS_SRP
+ case CURLOPT_TLSAUTH_USERNAME:
+ result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_USERNAME_ORIG],
+ va_arg(param, char *));
+ if(data->set.str[STRING_TLSAUTH_USERNAME_ORIG] && !data->set.ssl.authtype)
+ data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
+ break;
+ case CURLOPT_PROXY_TLSAUTH_USERNAME:
+ result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_USERNAME_PROXY],
+ va_arg(param, char *));
+ if(data->set.str[STRING_TLSAUTH_USERNAME_PROXY] &&
+ !data->set.proxy_ssl.authtype)
+ data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
+ break;
+ case CURLOPT_TLSAUTH_PASSWORD:
+ result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD_ORIG],
+ va_arg(param, char *));
+ if(data->set.str[STRING_TLSAUTH_USERNAME_ORIG] && !data->set.ssl.authtype)
+ data->set.ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
+ break;
+ case CURLOPT_PROXY_TLSAUTH_PASSWORD:
+ result = Curl_setstropt(&data->set.str[STRING_TLSAUTH_PASSWORD_PROXY],
+ va_arg(param, char *));
+ if(data->set.str[STRING_TLSAUTH_USERNAME_PROXY] &&
+ !data->set.proxy_ssl.authtype)
+ data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP; /* default to SRP */
+ break;
+ case CURLOPT_TLSAUTH_TYPE:
+ argptr = va_arg(param, char *);
+ if(!argptr ||
+ strncasecompare(argptr, "SRP", strlen("SRP")))
+ data->set.ssl.authtype = CURL_TLSAUTH_SRP;
+ else
+ data->set.ssl.authtype = CURL_TLSAUTH_NONE;
+ break;
+ case CURLOPT_PROXY_TLSAUTH_TYPE:
+ argptr = va_arg(param, char *);
+ if(!argptr ||
+ strncasecompare(argptr, "SRP", strlen("SRP")))
+ data->set.proxy_ssl.authtype = CURL_TLSAUTH_SRP;
+ else
+ data->set.proxy_ssl.authtype = CURL_TLSAUTH_NONE;
+ break;
+#endif
+#ifdef USE_ARES
+ case CURLOPT_DNS_SERVERS:
+ result = Curl_set_dns_servers(data, va_arg(param, char *));
+ break;
+ case CURLOPT_DNS_INTERFACE:
+ result = Curl_set_dns_interface(data, va_arg(param, char *));
+ break;
+ case CURLOPT_DNS_LOCAL_IP4:
+ result = Curl_set_dns_local_ip4(data, va_arg(param, char *));
+ break;
+ case CURLOPT_DNS_LOCAL_IP6:
+ result = Curl_set_dns_local_ip6(data, va_arg(param, char *));
+ break;
+#endif
+ case CURLOPT_TCP_KEEPALIVE:
+ data->set.tcp_keepalive = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_TCP_KEEPIDLE:
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.tcp_keepidle = arg;
+ break;
+ case CURLOPT_TCP_KEEPINTVL:
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.tcp_keepintvl = arg;
+ break;
+ case CURLOPT_TCP_FASTOPEN:
+#if defined(CONNECT_DATA_IDEMPOTENT) || defined(MSG_FASTOPEN) || \
+ defined(TCP_FASTOPEN_CONNECT)
+ data->set.tcp_fastopen = (0 != va_arg(param, long))?TRUE:FALSE;
+#else
+ result = CURLE_NOT_BUILT_IN;
+#endif
+ break;
+#ifdef USE_NGHTTP2
+ case CURLOPT_SSL_ENABLE_NPN:
+ data->set.ssl_enable_npn = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_SSL_ENABLE_ALPN:
+ data->set.ssl_enable_alpn = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+#endif
+#ifdef USE_UNIX_SOCKETS
+ case CURLOPT_UNIX_SOCKET_PATH:
+ data->set.abstract_unix_socket = FALSE;
+ result = Curl_setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH],
+ va_arg(param, char *));
+ break;
+ case CURLOPT_ABSTRACT_UNIX_SOCKET:
+ data->set.abstract_unix_socket = TRUE;
+ result = Curl_setstropt(&data->set.str[STRING_UNIX_SOCKET_PATH],
+ va_arg(param, char *));
+ break;
+#endif
+
+ case CURLOPT_PATH_AS_IS:
+ data->set.path_as_is = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_PIPEWAIT:
+ data->set.pipewait = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+ case CURLOPT_STREAM_WEIGHT:
+#ifndef USE_NGHTTP2
+ return CURLE_NOT_BUILT_IN;
+#else
+ arg = va_arg(param, long);
+ if((arg >= 1) && (arg <= 256))
+ data->set.stream_weight = (int)arg;
+ break;
+#endif
+ case CURLOPT_STREAM_DEPENDS:
+ case CURLOPT_STREAM_DEPENDS_E:
+ {
+#ifndef USE_NGHTTP2
+ return CURLE_NOT_BUILT_IN;
+#else
+ struct Curl_easy *dep = va_arg(param, struct Curl_easy *);
+ if(!dep || GOOD_EASY_HANDLE(dep)) {
+ if(data->set.stream_depends_on) {
+ Curl_http2_remove_child(data->set.stream_depends_on, data);
+ }
+ Curl_http2_add_child(dep, data, (option == CURLOPT_STREAM_DEPENDS_E));
+ }
+ break;
+#endif
+ }
+ case CURLOPT_CONNECT_TO:
+ data->set.connect_to = va_arg(param, struct curl_slist *);
+ break;
+ case CURLOPT_SUPPRESS_CONNECT_HEADERS:
+ data->set.suppress_connect_headers = (0 != va_arg(param, long))?TRUE:FALSE;
+ break;
+ case CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS:
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.happy_eyeballs_timeout = arg;
+ break;
+#ifndef CURL_DISABLE_SHUFFLE_DNS
+ case CURLOPT_DNS_SHUFFLE_ADDRESSES:
+ data->set.dns_shuffle_addresses = (0 != va_arg(param, long)) ? TRUE:FALSE;
+ break;
+#endif
+ case CURLOPT_DISALLOW_USERNAME_IN_URL:
+ data->set.disallow_username_in_url =
+ (0 != va_arg(param, long)) ? TRUE : FALSE;
+ break;
+#ifndef CURL_DISABLE_DOH
+ case CURLOPT_DOH_URL:
+ result = Curl_setstropt(&data->set.str[STRING_DOH],
+ va_arg(param, char *));
+ data->set.doh = data->set.str[STRING_DOH]?TRUE:FALSE;
+ break;
+#endif
+ case CURLOPT_UPKEEP_INTERVAL_MS:
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.upkeep_interval_ms = arg;
+ break;
+ case CURLOPT_MAXAGE_CONN:
+ arg = va_arg(param, long);
+ if(arg < 0)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+ data->set.maxage_conn = arg;
+ break;
+ case CURLOPT_TRAILERFUNCTION:
+#ifndef CURL_DISABLE_HTTP
+ data->set.trailer_callback = va_arg(param, curl_trailer_callback);
+#endif
+ break;
+ case CURLOPT_TRAILERDATA:
+#ifndef CURL_DISABLE_HTTP
+ data->set.trailer_data = va_arg(param, void *);
+#endif
+ break;
+#ifdef USE_ALTSVC
+ case CURLOPT_ALTSVC:
+ if(!data->asi) {
+ data->asi = Curl_altsvc_init();
+ if(!data->asi)
+ return CURLE_OUT_OF_MEMORY;
+ }
+ argptr = va_arg(param, char *);
+ result = Curl_setstropt(&data->set.str[STRING_ALTSVC], argptr);
+ if(result)
+ return result;
+ (void)Curl_altsvc_load(data->asi, argptr);
+ break;
+ case CURLOPT_ALTSVC_CTRL:
+ if(!data->asi) {
+ data->asi = Curl_altsvc_init();
+ if(!data->asi)
+ return CURLE_OUT_OF_MEMORY;
+ }
+ arg = va_arg(param, long);
+ result = Curl_altsvc_ctrl(data->asi, arg);
+ if(result)
+ return result;
+ break;
+#endif
+ default:
+ /* unknown tag and its companion, just ignore: */
+ result = CURLE_UNKNOWN_OPTION;
+ break;
+ }
+
+ return result;
+}
+
+/*
+ * curl_easy_setopt() is the external interface for setting options on an
+ * easy handle.
+ *
+ * NOTE: This is one of few API functions that are allowed to be called from
+ * within a callback.
+ */
+
+#undef curl_easy_setopt
+CURLcode curl_easy_setopt(struct Curl_easy *data, CURLoption tag, ...)
+{
+ va_list arg;
+ CURLcode result;
+
+ if(!data)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ va_start(arg, tag);
+
+ result = vsetopt(data, tag, arg);
+
+ va_end(arg);
+ return result;
+}
diff --git a/Utilities/cmcurl/lib/setopt.h b/Utilities/cmcurl/lib/setopt.h
new file mode 100644
index 000000000..c658e04ae
--- /dev/null
+++ b/Utilities/cmcurl/lib/setopt.h
@@ -0,0 +1,29 @@
+#ifndef HEADER_CURL_SETOPT_H
+#define HEADER_CURL_SETOPT_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2018, 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.
+ *
+ ***************************************************************************/
+
+CURLcode Curl_setstropt(char **charp, const char *s);
+CURLcode Curl_vsetopt(struct Curl_easy *data, CURLoption option,
+ va_list arg);
+
+#endif /* HEADER_CURL_SETOPT_H */
diff --git a/Utilities/cmcurl/lib/sha256.c b/Utilities/cmcurl/lib/sha256.c
new file mode 100644
index 000000000..f9287af23
--- /dev/null
+++ b/Utilities/cmcurl/lib/sha256.c
@@ -0,0 +1,267 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2018, Florin Petriuc, <petriuc.florin@gmail.com>
+ *
+ * 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"
+
+#ifndef CURL_DISABLE_CRYPTO_AUTH
+
+#include "warnless.h"
+#include "curl_sha256.h"
+
+#if defined(USE_OPENSSL)
+
+#include <openssl/opensslv.h>
+
+#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
+#define USE_OPENSSL_SHA256
+#endif
+
+#endif
+
+#ifdef USE_OPENSSL_SHA256
+/* When OpenSSL is available we use the SHA256-function from OpenSSL */
+#include <openssl/sha.h>
+#else
+
+/* When no other crypto library is available we use this code segment */
+
+/* ===== start - public domain SHA256 implementation ===== */
+/* This is based on SHA256 implementation in LibTomCrypt that was released into
+ * public domain by Tom St Denis. */
+
+#define WPA_GET_BE32(a) ((((unsigned long)(a)[0]) << 24) | \
+ (((unsigned long)(a)[1]) << 16) | \
+ (((unsigned long)(a)[2]) << 8) | \
+ ((unsigned long)(a)[3]))
+#define WPA_PUT_BE32(a, val) \
+do { \
+ (a)[0] = (unsigned char)((((unsigned long) (val)) >> 24) & 0xff); \
+ (a)[1] = (unsigned char)((((unsigned long) (val)) >> 16) & 0xff); \
+ (a)[2] = (unsigned char)((((unsigned long) (val)) >> 8) & 0xff); \
+ (a)[3] = (unsigned char)(((unsigned long) (val)) & 0xff); \
+} while(0)
+
+#ifdef HAVE_LONGLONG
+#define WPA_PUT_BE64(a, val) \
+do { \
+ (a)[0] = (unsigned char)(((unsigned long long)(val)) >> 56); \
+ (a)[1] = (unsigned char)(((unsigned long long)(val)) >> 48); \
+ (a)[2] = (unsigned char)(((unsigned long long)(val)) >> 40); \
+ (a)[3] = (unsigned char)(((unsigned long long)(val)) >> 32); \
+ (a)[4] = (unsigned char)(((unsigned long long)(val)) >> 24); \
+ (a)[5] = (unsigned char)(((unsigned long long)(val)) >> 16); \
+ (a)[6] = (unsigned char)(((unsigned long long)(val)) >> 8); \
+ (a)[7] = (unsigned char)(((unsigned long long)(val)) & 0xff); \
+} while(0)
+#else
+#define WPA_PUT_BE64(a, val) \
+do { \
+ (a)[0] = (unsigned char)(((unsigned __int64)(val)) >> 56); \
+ (a)[1] = (unsigned char)(((unsigned __int64)(val)) >> 48); \
+ (a)[2] = (unsigned char)(((unsigned __int64)(val)) >> 40); \
+ (a)[3] = (unsigned char)(((unsigned __int64)(val)) >> 32); \
+ (a)[4] = (unsigned char)(((unsigned __int64)(val)) >> 24); \
+ (a)[5] = (unsigned char)(((unsigned __int64)(val)) >> 16); \
+ (a)[6] = (unsigned char)(((unsigned __int64)(val)) >> 8); \
+ (a)[7] = (unsigned char)(((unsigned __int64)(val)) & 0xff); \
+} while(0)
+#endif
+
+typedef struct sha256_state {
+#ifdef HAVE_LONGLONG
+ unsigned long long length;
+#else
+ unsigned __int64 length;
+#endif
+ unsigned long state[8], curlen;
+ unsigned char buf[64];
+} SHA256_CTX;
+/* the K array */
+static const unsigned long K[64] = {
+ 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
+ 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
+ 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
+ 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
+ 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
+ 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
+ 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
+ 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
+ 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
+ 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
+ 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
+ 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
+ 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
+};
+/* Various logical functions */
+#define RORc(x, y) \
+(((((unsigned long)(x) & 0xFFFFFFFFUL) >> (unsigned long)((y) & 31)) | \
+ ((unsigned long)(x) << (unsigned long)(32 - ((y) & 31)))) & 0xFFFFFFFFUL)
+#define Ch(x,y,z) (z ^ (x & (y ^ z)))
+#define Maj(x,y,z) (((x | y) & z) | (x & y))
+#define S(x, n) RORc((x), (n))
+#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))
+#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))
+#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))
+#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))
+#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))
+/* compress 512-bits */
+static int sha256_compress(struct sha256_state *md,
+ unsigned char *buf)
+{
+ unsigned long S[8], W[64];
+ int i;
+ /* copy state into S */
+ for(i = 0; i < 8; i++) {
+ S[i] = md->state[i];
+ }
+ /* copy the state into 512-bits into W[0..15] */
+ for(i = 0; i < 16; i++)
+ W[i] = WPA_GET_BE32(buf + (4 * i));
+ /* fill W[16..63] */
+ for(i = 16; i < 64; i++) {
+ W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) +
+ W[i - 16];
+ }
+ /* Compress */
+#define RND(a,b,c,d,e,f,g,h,i) \
+ unsigned long t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \
+ unsigned long t1 = Sigma0(a) + Maj(a, b, c); \
+ d += t0; \
+ h = t0 + t1;
+ for(i = 0; i < 64; ++i) {
+ unsigned long t;
+ RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], i);
+ t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];
+ S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;
+ }
+ /* feedback */
+ for(i = 0; i < 8; i++) {
+ md->state[i] = md->state[i] + S[i];
+ }
+ return 0;
+}
+/* Initialize the hash state */
+static void SHA256_Init(struct sha256_state *md)
+{
+ md->curlen = 0;
+ md->length = 0;
+ md->state[0] = 0x6A09E667UL;
+ md->state[1] = 0xBB67AE85UL;
+ md->state[2] = 0x3C6EF372UL;
+ md->state[3] = 0xA54FF53AUL;
+ md->state[4] = 0x510E527FUL;
+ md->state[5] = 0x9B05688CUL;
+ md->state[6] = 0x1F83D9ABUL;
+ md->state[7] = 0x5BE0CD19UL;
+}
+/**
+ Process a block of memory though the hash
+ @param md The hash state
+ @param in The data to hash
+ @param inlen The length of the data (octets)
+ @return CRYPT_OK if successful
+*/
+static int SHA256_Update(struct sha256_state *md,
+ const unsigned char *in,
+ unsigned long inlen)
+{
+ unsigned long n;
+#define block_size 64
+ if(md->curlen > sizeof(md->buf))
+ return -1;
+ while(inlen > 0) {
+ if(md->curlen == 0 && inlen >= block_size) {
+ if(sha256_compress(md, (unsigned char *)in) < 0)
+ return -1;
+ md->length += block_size * 8;
+ in += block_size;
+ inlen -= block_size;
+ }
+ else {
+ n = CURLMIN(inlen, (block_size - md->curlen));
+ memcpy(md->buf + md->curlen, in, n);
+ md->curlen += n;
+ in += n;
+ inlen -= n;
+ if(md->curlen == block_size) {
+ if(sha256_compress(md, md->buf) < 0)
+ return -1;
+ md->length += 8 * block_size;
+ md->curlen = 0;
+ }
+ }
+ }
+ return 0;
+}
+/**
+ Terminate the hash to get the digest
+ @param md The hash state
+ @param out [out] The destination of the hash (32 bytes)
+ @return CRYPT_OK if successful
+*/
+static int SHA256_Final(unsigned char *out,
+ struct sha256_state *md)
+{
+ int i;
+ if(md->curlen >= sizeof(md->buf))
+ return -1;
+ /* increase the length of the message */
+ md->length += md->curlen * 8;
+ /* append the '1' bit */
+ md->buf[md->curlen++] = (unsigned char)0x80;
+ /* if the length is currently above 56 bytes we append zeros
+ * then compress. Then we can fall back to padding zeros and length
+ * encoding like normal.
+ */
+ if(md->curlen > 56) {
+ while(md->curlen < 64) {
+ md->buf[md->curlen++] = (unsigned char)0;
+ }
+ sha256_compress(md, md->buf);
+ md->curlen = 0;
+ }
+ /* pad up to 56 bytes of zeroes */
+ while(md->curlen < 56) {
+ md->buf[md->curlen++] = (unsigned char)0;
+ }
+ /* store length */
+ WPA_PUT_BE64(md->buf + 56, md->length);
+ sha256_compress(md, md->buf);
+ /* copy output */
+ for(i = 0; i < 8; i++)
+ WPA_PUT_BE32(out + (4 * i), md->state[i]);
+ return 0;
+}
+/* ===== end - public domain SHA256 implementation ===== */
+
+#endif
+
+void Curl_sha256it(unsigned char *outbuffer, /* 32 unsigned chars */
+ const unsigned char *input)
+{
+ SHA256_CTX ctx;
+ SHA256_Init(&ctx);
+ SHA256_Update(&ctx, input, curlx_uztoui(strlen((char *)input)));
+ SHA256_Final(outbuffer, &ctx);
+}
+
+#endif /* CURL_DISABLE_CRYPTO_AUTH */
diff --git a/Utilities/cmcurl/lib/ssh-libssh.c b/Utilities/cmcurl/lib/ssh-libssh.c
new file mode 100644
index 000000000..6cfd6bda8
--- /dev/null
+++ b/Utilities/cmcurl/lib/ssh-libssh.c
@@ -0,0 +1,2740 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2017 - 2019 Red Hat, Inc.
+ *
+ * Authors: Nikos Mavrogiannopoulos, Tomas Mraz, Stanislav Zidek,
+ * Robert Kolcun, Andreas Schneider
+ *
+ * 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"
+
+#ifdef USE_LIBSSH
+
+#include <limits.h>
+
+#include <libssh/libssh.h>
+#include <libssh/sftp.h>
+
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef HAVE_UTSNAME_H
+#include <sys/utsname.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef __VMS
+#include <in.h>
+#include <inet.h>
+#endif
+
+#if (defined(NETWARE) && defined(__NOVELL_LIBC__))
+#undef in_addr_t
+#define in_addr_t unsigned long
+#endif
+
+#include <curl/curl.h>
+#include "urldata.h"
+#include "sendf.h"
+#include "hostip.h"
+#include "progress.h"
+#include "transfer.h"
+#include "escape.h"
+#include "http.h" /* for HTTP proxy tunnel stuff */
+#include "ssh.h"
+#include "url.h"
+#include "speedcheck.h"
+#include "getinfo.h"
+#include "strdup.h"
+#include "strcase.h"
+#include "vtls/vtls.h"
+#include "connect.h"
+#include "strerror.h"
+#include "inet_ntop.h"
+#include "parsedate.h" /* for the week day and month names */
+#include "sockaddr.h" /* required for Curl_sockaddr_storage */
+#include "strtoofft.h"
+#include "multiif.h"
+#include "select.h"
+#include "warnless.h"
+
+/* for permission and open flags */
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+/* The last 3 #include files should be in this order */
+#include "curl_printf.h"
+#include "curl_memory.h"
+#include "memdebug.h"
+#include "curl_path.h"
+
+/* A recent macro provided by libssh. Or make our own. */
+#ifndef SSH_STRING_FREE_CHAR
+/* !checksrc! disable ASSIGNWITHINCONDITION 1 */
+#define SSH_STRING_FREE_CHAR(x) \
+ do { if((x) != NULL) { ssh_string_free_char(x); x = NULL; } } while(0)
+#endif
+
+/* Local functions: */
+static CURLcode myssh_connect(struct connectdata *conn, bool *done);
+static CURLcode myssh_multi_statemach(struct connectdata *conn,
+ bool *done);
+static CURLcode myssh_do_it(struct connectdata *conn, bool *done);
+
+static CURLcode scp_done(struct connectdata *conn,
+ CURLcode, bool premature);
+static CURLcode scp_doing(struct connectdata *conn, bool *dophase_done);
+static CURLcode scp_disconnect(struct connectdata *conn,
+ bool dead_connection);
+
+static CURLcode sftp_done(struct connectdata *conn,
+ CURLcode, bool premature);
+static CURLcode sftp_doing(struct connectdata *conn,
+ bool *dophase_done);
+static CURLcode sftp_disconnect(struct connectdata *conn, bool dead);
+static
+CURLcode sftp_perform(struct connectdata *conn,
+ bool *connected,
+ bool *dophase_done);
+
+static void sftp_quote(struct connectdata *conn);
+static void sftp_quote_stat(struct connectdata *conn);
+
+static int myssh_getsock(struct connectdata *conn, curl_socket_t *sock,
+ int numsocks);
+
+static int myssh_perform_getsock(const struct connectdata *conn,
+ curl_socket_t *sock,
+ int numsocks);
+
+static CURLcode myssh_setup_connection(struct connectdata *conn);
+
+/*
+ * SCP protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_scp = {
+ "SCP", /* scheme */
+ myssh_setup_connection, /* setup_connection */
+ myssh_do_it, /* do_it */
+ scp_done, /* done */
+ ZERO_NULL, /* do_more */
+ myssh_connect, /* connect_it */
+ myssh_multi_statemach, /* connecting */
+ scp_doing, /* doing */
+ myssh_getsock, /* proto_getsock */
+ myssh_getsock, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ myssh_perform_getsock, /* perform_getsock */
+ scp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
+ PORT_SSH, /* defport */
+ CURLPROTO_SCP, /* protocol */
+ PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY /* flags */
+};
+
+/*
+ * SFTP protocol handler.
+ */
+
+const struct Curl_handler Curl_handler_sftp = {
+ "SFTP", /* scheme */
+ myssh_setup_connection, /* setup_connection */
+ myssh_do_it, /* do_it */
+ sftp_done, /* done */
+ ZERO_NULL, /* do_more */
+ myssh_connect, /* connect_it */
+ myssh_multi_statemach, /* connecting */
+ sftp_doing, /* doing */
+ myssh_getsock, /* proto_getsock */
+ myssh_getsock, /* doing_getsock */
+ ZERO_NULL, /* domore_getsock */
+ myssh_perform_getsock, /* perform_getsock */
+ sftp_disconnect, /* disconnect */
+ ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
+ PORT_SSH, /* defport */
+ CURLPROTO_SFTP, /* protocol */
+ PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION
+ | PROTOPT_NOURLQUERY /* flags */
+};
+
+static CURLcode sftp_error_to_CURLE(int err)
+{
+ switch(err) {
+ case SSH_FX_OK:
+ return CURLE_OK;
+
+ case SSH_FX_NO_SUCH_FILE:
+ case SSH_FX_NO_SUCH_PATH:
+ return CURLE_REMOTE_FILE_NOT_FOUND;
+
+ case SSH_FX_PERMISSION_DENIED:
+ case SSH_FX_WRITE_PROTECT:
+ return CURLE_REMOTE_ACCESS_DENIED;
+
+ case SSH_FX_FILE_ALREADY_EXISTS:
+ return CURLE_REMOTE_FILE_EXISTS;
+
+ default:
+ break;
+ }
+
+ return CURLE_SSH;
+}
+
+#ifndef DEBUGBUILD
+#define state(x,y) mystate(x,y)
+#else
+#define state(x,y) mystate(x,y, __LINE__)
+#endif
+
+/*
+ * SSH State machine related code
+ */
+/* This is the ONLY way to change SSH state! */
+static void mystate(struct connectdata *conn, sshstate nowstate
+#ifdef DEBUGBUILD
+ , int lineno
+#endif
+ )
+{
+ struct ssh_conn *sshc = &conn->proto.sshc;
+#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
+ /* for debug purposes */
+ static const char *const names[] = {
+ "SSH_STOP",
+ "SSH_INIT",
+ "SSH_S_STARTUP",
+ "SSH_HOSTKEY",
+ "SSH_AUTHLIST",
+ "SSH_AUTH_PKEY_INIT",
+ "SSH_AUTH_PKEY",
+ "SSH_AUTH_PASS_INIT",
+ "SSH_AUTH_PASS",
+ "SSH_AUTH_AGENT_INIT",
+ "SSH_AUTH_AGENT_LIST",
+ "SSH_AUTH_AGENT",
+ "SSH_AUTH_HOST_INIT",
+ "SSH_AUTH_HOST",
+ "SSH_AUTH_KEY_INIT",
+ "SSH_AUTH_KEY",
+ "SSH_AUTH_GSSAPI",
+ "SSH_AUTH_DONE",
+ "SSH_SFTP_INIT",
+ "SSH_SFTP_REALPATH",
+ "SSH_SFTP_QUOTE_INIT",
+ "SSH_SFTP_POSTQUOTE_INIT",
+ "SSH_SFTP_QUOTE",
+ "SSH_SFTP_NEXT_QUOTE",
+ "SSH_SFTP_QUOTE_STAT",
+ "SSH_SFTP_QUOTE_SETSTAT",
+ "SSH_SFTP_QUOTE_SYMLINK",
+ "SSH_SFTP_QUOTE_MKDIR",
+ "SSH_SFTP_QUOTE_RENAME",
+ "SSH_SFTP_QUOTE_RMDIR",
+ "SSH_SFTP_QUOTE_UNLINK",
+ "SSH_SFTP_QUOTE_STATVFS",
+ "SSH_SFTP_GETINFO",
+ "SSH_SFTP_FILETIME",
+ "SSH_SFTP_TRANS_INIT",
+ "SSH_SFTP_UPLOAD_INIT",
+ "SSH_SFTP_CREATE_DIRS_INIT",
+ "SSH_SFTP_CREATE_DIRS",
+ "SSH_SFTP_CREATE_DIRS_MKDIR",
+ "SSH_SFTP_READDIR_INIT",
+ "SSH_SFTP_READDIR",
+ "SSH_SFTP_READDIR_LINK",
+ "SSH_SFTP_READDIR_BOTTOM",
+ "SSH_SFTP_READDIR_DONE",
+ "SSH_SFTP_DOWNLOAD_INIT",
+ "SSH_SFTP_DOWNLOAD_STAT",
+ "SSH_SFTP_CLOSE",
+ "SSH_SFTP_SHUTDOWN",
+ "SSH_SCP_TRANS_INIT",
+ "SSH_SCP_UPLOAD_INIT",
+ "SSH_SCP_DOWNLOAD_INIT",
+ "SSH_SCP_DOWNLOAD",
+ "SSH_SCP_DONE",
+ "SSH_SCP_SEND_EOF",
+ "SSH_SCP_WAIT_EOF",
+ "SSH_SCP_WAIT_CLOSE",
+ "SSH_SCP_CHANNEL_FREE",
+ "SSH_SESSION_DISCONNECT",
+ "SSH_SESSION_FREE",
+ "QUIT"
+ };
+
+
+ if(sshc->state != nowstate) {
+ infof(conn->data, "SSH %p state change from %s to %s (line %d)\n",
+ (void *) sshc, names[sshc->state], names[nowstate],
+ lineno);
+ }
+#endif
+
+ sshc->state = nowstate;
+}
+
+/* Multiple options:
+ * 1. data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5] is set with an MD5
+ * hash (90s style auth, not sure we should have it here)
+ * 2. data->set.ssh_keyfunc callback is set. Then we do trust on first
+ * use. We even save on knownhosts if CURLKHSTAT_FINE_ADD_TO_FILE
+ * is returned by it.
+ * 3. none of the above. We only accept if it is present on known hosts.
+ *
+ * Returns SSH_OK or SSH_ERROR.
+ */
+static int myssh_is_known(struct connectdata *conn)
+{
+ int rc;
+ struct Curl_easy *data = conn->data;
+ struct ssh_conn *sshc = &conn->proto.sshc;
+ ssh_key pubkey;
+ size_t hlen;
+ unsigned char *hash = NULL;
+ char *base64 = NULL;
+ int vstate;
+ enum curl_khmatch keymatch;
+ struct curl_khkey foundkey;
+ curl_sshkeycallback func =
+ data->set.ssh_keyfunc;
+
+ rc = ssh_get_publickey(sshc->ssh_session, &pubkey);
+ if(rc != SSH_OK)
+ return rc;
+
+ if(data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5]) {
+ rc = ssh_get_publickey_hash(pubkey, SSH_PUBLICKEY_HASH_MD5,
+ &hash, &hlen);
+ if(rc != SSH_OK)
+ goto cleanup;
+
+ if(hlen != strlen(data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5]) ||
+ memcmp(&data->set.str[STRING_SSH_HOST_PUBLIC_KEY_MD5], hash, hlen)) {
+ rc = SSH_ERROR;
+ goto cleanup;
+ }
+
+ rc = SSH_OK;
+ goto cleanup;
+ }
+
+ if(data->set.ssl.primary.verifyhost != TRUE) {
+ rc = SSH_OK;
+ goto cleanup;
+ }
+
+ vstate = ssh_is_server_known(sshc->ssh_session);
+ switch(vstate) {
+ case SSH_SERVER_KNOWN_OK:
+ keymatch = CURLKHMATCH_OK;
+ break;
+ case SSH_SERVER_FILE_NOT_FOUND:
+ /* fallthrough */
+ case SSH_SERVER_NOT_KNOWN:
+ keymatch = CURLKHMATCH_MISSING;
+ break;
+ default:
+ keymatch = CURLKHMATCH_MISMATCH;
+ break;
+ }
+
+ if(func) { /* use callback to determine action */
+ rc = ssh_pki_export_pubkey_base64(pubkey, &base64);
+ if(rc != SSH_OK)
+ goto cleanup;
+
+ foundkey.key = base64;
+ foundkey.len = strlen(base64);
+
+ switch(ssh_key_type(pubkey)) {
+ case SSH_KEYTYPE_RSA:
+ foundkey.keytype = CURLKHTYPE_RSA;
+ break;
+ case SSH_KEYTYPE_RSA1:
+ foundkey.keytype = CURLKHTYPE_RSA1;
+ break;
+ case SSH_KEYTYPE_ECDSA:
+ foundkey.keytype = CURLKHTYPE_ECDSA;
+ break;
+#if LIBSSH_VERSION_INT >= SSH_VERSION_INT(0,7,0)
+ case SSH_KEYTYPE_ED25519:
+ foundkey.keytype = CURLKHTYPE_ED25519;
+ break;
+#endif
+ case SSH_KEYTYPE_DSS:
+ foundkey.keytype = CURLKHTYPE_DSS;
+ break;
+ default:
+ rc = SSH_ERROR;
+ goto cleanup;
+ }
+
+ /* we don't have anything equivalent to knownkey. Always NULL */
+ Curl_set_in_callback(data, true);
+ rc = func(data, NULL, &foundkey, /* from the remote host */
+ keymatch, data->set.ssh_keyfunc_userp);
+ Curl_set_in_callback(data, false);
+
+ switch(rc) {
+ case CURLKHSTAT_FINE_ADD_TO_FILE:
+ rc = ssh_write_knownhost(sshc->ssh_session);
+ if(rc != SSH_OK) {
+ goto cleanup;
+ }
+ break;
+ case CURLKHSTAT_FINE:
+ break;
+ default: /* REJECT/DEFER */
+ rc = SSH_ERROR;
+ goto cleanup;
+ }
+ }
+ else {
+ if(keymatch != CURLKHMATCH_OK) {
+ rc = SSH_ERROR;
+ goto cleanup;
+ }
+ }
+ rc = SSH_OK;
+
+cleanup:
+ if(hash)
+ ssh_clean_pubkey_hash(&hash);
+ ssh_key_free(pubkey);
+ return rc;
+}
+
+#define MOVE_TO_ERROR_STATE(_r) { \
+ state(conn, SSH_SESSION_DISCONNECT); \
+ sshc->actualcode = _r; \
+ rc = SSH_ERROR; \
+ break; \
+}
+
+#define MOVE_TO_SFTP_CLOSE_STATE() { \
+ state(conn, SSH_SFTP_CLOSE); \
+ sshc->actualcode = sftp_error_to_CURLE(sftp_get_error(sshc->sftp_session)); \
+ rc = SSH_ERROR; \
+ break; \
+}
+
+#define MOVE_TO_LAST_AUTH \
+ if(sshc->auth_methods & SSH_AUTH_METHOD_PASSWORD) { \
+ rc = SSH_OK; \
+ state(conn, SSH_AUTH_PASS_INIT); \
+ break; \
+ } \
+ else { \
+ MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED); \
+ }
+
+#define MOVE_TO_TERTIARY_AUTH \
+ if(sshc->auth_methods & SSH_AUTH_METHOD_INTERACTIVE) { \
+ rc = SSH_OK; \
+ state(conn, SSH_AUTH_KEY_INIT); \
+ break; \
+ } \
+ else { \
+ MOVE_TO_LAST_AUTH; \
+ }
+
+#define MOVE_TO_SECONDARY_AUTH \
+ if(sshc->auth_methods & SSH_AUTH_METHOD_GSSAPI_MIC) { \
+ rc = SSH_OK; \
+ state(conn, SSH_AUTH_GSSAPI); \
+ break; \
+ } \
+ else { \
+ MOVE_TO_TERTIARY_AUTH; \
+ }
+
+static
+int myssh_auth_interactive(struct connectdata *conn)
+{
+ int rc;
+ struct ssh_conn *sshc = &conn->proto.sshc;
+ int nprompts;
+
+restart:
+ switch(sshc->kbd_state) {
+ case 0:
+ rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL);
+ if(rc == SSH_AUTH_AGAIN)
+ return SSH_AGAIN;
+
+ if(rc != SSH_AUTH_INFO)
+ return SSH_ERROR;
+
+ nprompts = ssh_userauth_kbdint_getnprompts(sshc->ssh_session);
+ if(nprompts == SSH_ERROR || nprompts != 1)
+ return SSH_ERROR;
+
+ rc = ssh_userauth_kbdint_setanswer(sshc->ssh_session, 0, conn->passwd);
+ if(rc < 0)
+ return SSH_ERROR;
+
+ /* FALLTHROUGH */
+ case 1:
+ sshc->kbd_state = 1;
+
+ rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL);
+ if(rc == SSH_AUTH_AGAIN)
+ return SSH_AGAIN;
+ else if(rc == SSH_AUTH_SUCCESS)
+ rc = SSH_OK;
+ else if(rc == SSH_AUTH_INFO) {
+ nprompts = ssh_userauth_kbdint_getnprompts(sshc->ssh_session);
+ if(nprompts != 0)
+ return SSH_ERROR;
+
+ sshc->kbd_state = 2;
+ goto restart;
+ }
+ else
+ rc = SSH_ERROR;
+ break;
+ case 2:
+ sshc->kbd_state = 2;
+
+ rc = ssh_userauth_kbdint(sshc->ssh_session, NULL, NULL);
+ if(rc == SSH_AUTH_AGAIN)
+ return SSH_AGAIN;
+ else if(rc == SSH_AUTH_SUCCESS)
+ rc = SSH_OK;
+ else
+ rc = SSH_ERROR;
+
+ break;
+ default:
+ return SSH_ERROR;
+ }
+
+ sshc->kbd_state = 0;
+ return rc;
+}
+
+/*
+ * ssh_statemach_act() runs the SSH state machine as far as it can without
+ * blocking and without reaching the end. The data the pointer 'block' points
+ * to will be set to TRUE if the libssh function returns SSH_AGAIN
+ * meaning it wants to be called again when the socket is ready
+ */
+static CURLcode myssh_statemach_act(struct connectdata *conn, bool *block)
+{
+ CURLcode result = CURLE_OK;
+ struct Curl_easy *data = conn->data;
+ struct SSHPROTO *protop = data->req.protop;
+ struct ssh_conn *sshc = &conn->proto.sshc;
+ curl_socket_t sock = conn->sock[FIRSTSOCKET];
+ int rc = SSH_NO_ERROR, err;
+ char *new_readdir_line;
+ int seekerr = CURL_SEEKFUNC_OK;
+ const char *err_msg;
+ *block = 0; /* we're not blocking by default */
+
+ do {
+
+ switch(sshc->state) {
+ case SSH_INIT:
+ sshc->secondCreateDirs = 0;
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_OK;
+
+#if 0
+ ssh_set_log_level(SSH_LOG_PROTOCOL);
+#endif
+
+ /* Set libssh to non-blocking, since everything internally is
+ non-blocking */
+ ssh_set_blocking(sshc->ssh_session, 0);
+
+ state(conn, SSH_S_STARTUP);
+ /* FALLTHROUGH */
+
+ case SSH_S_STARTUP:
+ rc = ssh_connect(sshc->ssh_session);
+ if(rc == SSH_AGAIN)
+ break;
+
+ if(rc != SSH_OK) {
+ failf(data, "Failure establishing ssh session");
+ MOVE_TO_ERROR_STATE(CURLE_FAILED_INIT);
+ }
+
+ state(conn, SSH_HOSTKEY);
+
+ /* FALLTHROUGH */
+ case SSH_HOSTKEY:
+
+ rc = myssh_is_known(conn);
+ if(rc != SSH_OK) {
+ MOVE_TO_ERROR_STATE(CURLE_PEER_FAILED_VERIFICATION);
+ }
+
+ state(conn, SSH_AUTHLIST);
+ /* FALLTHROUGH */
+ case SSH_AUTHLIST:{
+ sshc->authed = FALSE;
+
+ rc = ssh_userauth_none(sshc->ssh_session, NULL);
+ if(rc == SSH_AUTH_AGAIN) {
+ rc = SSH_AGAIN;
+ break;
+ }
+
+ if(rc == SSH_AUTH_SUCCESS) {
+ sshc->authed = TRUE;
+ infof(data, "Authenticated with none\n");
+ state(conn, SSH_AUTH_DONE);
+ break;
+ }
+ else if(rc == SSH_AUTH_ERROR) {
+ MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED);
+ }
+
+ sshc->auth_methods = ssh_userauth_list(sshc->ssh_session, NULL);
+ if(sshc->auth_methods & SSH_AUTH_METHOD_PUBLICKEY) {
+ state(conn, SSH_AUTH_PKEY_INIT);
+ infof(data, "Authentication using SSH public key file\n");
+ }
+ else if(sshc->auth_methods & SSH_AUTH_METHOD_GSSAPI_MIC) {
+ state(conn, SSH_AUTH_GSSAPI);
+ }
+ else if(sshc->auth_methods & SSH_AUTH_METHOD_INTERACTIVE) {
+ state(conn, SSH_AUTH_KEY_INIT);
+ }
+ else if(sshc->auth_methods & SSH_AUTH_METHOD_PASSWORD) {
+ state(conn, SSH_AUTH_PASS_INIT);
+ }
+ else { /* unsupported authentication method */
+ MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED);
+ }
+
+ break;
+ }
+ case SSH_AUTH_PKEY_INIT:
+ if(!(data->set.ssh_auth_types & CURLSSH_AUTH_PUBLICKEY)) {
+ MOVE_TO_SECONDARY_AUTH;
+ }
+
+ /* Two choices, (1) private key was given on CMD,
+ * (2) use the "default" keys. */
+ if(data->set.str[STRING_SSH_PRIVATE_KEY]) {
+ if(sshc->pubkey && !data->set.ssl.key_passwd) {
+ rc = ssh_userauth_try_publickey(sshc->ssh_session, NULL,
+ sshc->pubkey);
+ if(rc == SSH_AUTH_AGAIN) {
+ rc = SSH_AGAIN;
+ break;
+ }
+
+ if(rc != SSH_OK) {
+ MOVE_TO_SECONDARY_AUTH;
+ }
+ }
+
+ rc = ssh_pki_import_privkey_file(data->
+ set.str[STRING_SSH_PRIVATE_KEY],
+ data->set.ssl.key_passwd, NULL,
+ NULL, &sshc->privkey);
+ if(rc != SSH_OK) {
+ failf(data, "Could not load private key file %s",
+ data->set.str[STRING_SSH_PRIVATE_KEY]);
+ MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED);
+ break;
+ }
+
+ state(conn, SSH_AUTH_PKEY);
+ break;
+
+ }
+ else {
+ rc = ssh_userauth_publickey_auto(sshc->ssh_session, NULL,
+ data->set.ssl.key_passwd);
+ if(rc == SSH_AUTH_AGAIN) {
+ rc = SSH_AGAIN;
+ break;
+ }
+ if(rc == SSH_AUTH_SUCCESS) {
+ rc = SSH_OK;
+ sshc->authed = TRUE;
+ infof(data, "Completed public key authentication\n");
+ state(conn, SSH_AUTH_DONE);
+ break;
+ }
+
+ MOVE_TO_SECONDARY_AUTH;
+ }
+ break;
+ case SSH_AUTH_PKEY:
+ rc = ssh_userauth_publickey(sshc->ssh_session, NULL, sshc->privkey);
+ if(rc == SSH_AUTH_AGAIN) {
+ rc = SSH_AGAIN;
+ break;
+ }
+
+ if(rc == SSH_AUTH_SUCCESS) {
+ sshc->authed = TRUE;
+ infof(data, "Completed public key authentication\n");
+ state(conn, SSH_AUTH_DONE);
+ break;
+ }
+ else {
+ infof(data, "Failed public key authentication (rc: %d)\n", rc);
+ MOVE_TO_SECONDARY_AUTH;
+ }
+ break;
+
+ case SSH_AUTH_GSSAPI:
+ if(!(data->set.ssh_auth_types & CURLSSH_AUTH_GSSAPI)) {
+ MOVE_TO_TERTIARY_AUTH;
+ }
+
+ rc = ssh_userauth_gssapi(sshc->ssh_session);
+ if(rc == SSH_AUTH_AGAIN) {
+ rc = SSH_AGAIN;
+ break;
+ }
+
+ if(rc == SSH_AUTH_SUCCESS) {
+ rc = SSH_OK;
+ sshc->authed = TRUE;
+ infof(data, "Completed gssapi authentication\n");
+ state(conn, SSH_AUTH_DONE);
+ break;
+ }
+
+ MOVE_TO_TERTIARY_AUTH;
+ break;
+
+ case SSH_AUTH_KEY_INIT:
+ if(data->set.ssh_auth_types & CURLSSH_AUTH_KEYBOARD) {
+ state(conn, SSH_AUTH_KEY);
+ }
+ else {
+ MOVE_TO_LAST_AUTH;
+ }
+ break;
+
+ case SSH_AUTH_KEY:
+
+ /* Authentication failed. Continue with keyboard-interactive now. */
+ rc = myssh_auth_interactive(conn);
+ if(rc == SSH_AGAIN) {
+ break;
+ }
+ if(rc == SSH_OK) {
+ sshc->authed = TRUE;
+ infof(data, "completed keyboard interactive authentication\n");
+ }
+ state(conn, SSH_AUTH_DONE);
+ break;
+
+ case SSH_AUTH_PASS_INIT:
+ if(!(data->set.ssh_auth_types & CURLSSH_AUTH_PASSWORD)) {
+ /* Host key authentication is intentionally not implemented */
+ MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED);
+ }
+ state(conn, SSH_AUTH_PASS);
+ /* FALLTHROUGH */
+
+ case SSH_AUTH_PASS:
+ rc = ssh_userauth_password(sshc->ssh_session, NULL, conn->passwd);
+ if(rc == SSH_AUTH_AGAIN) {
+ rc = SSH_AGAIN;
+ break;
+ }
+
+ if(rc == SSH_AUTH_SUCCESS) {
+ sshc->authed = TRUE;
+ infof(data, "Completed password authentication\n");
+ state(conn, SSH_AUTH_DONE);
+ }
+ else {
+ MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED);
+ }
+ break;
+
+ case SSH_AUTH_DONE:
+ if(!sshc->authed) {
+ failf(data, "Authentication failure");
+ MOVE_TO_ERROR_STATE(CURLE_LOGIN_DENIED);
+ break;
+ }
+
+ /*
+ * At this point we have an authenticated ssh session.
+ */
+ infof(data, "Authentication complete\n");
+
+ Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSH is connected */
+
+ conn->sockfd = sock;
+ conn->writesockfd = CURL_SOCKET_BAD;
+
+ if(conn->handler->protocol == CURLPROTO_SFTP) {
+ state(conn, SSH_SFTP_INIT);
+ break;
+ }
+ infof(data, "SSH CONNECT phase done\n");
+ state(conn, SSH_STOP);
+ break;
+
+ case SSH_SFTP_INIT:
+ ssh_set_blocking(sshc->ssh_session, 1);
+
+ sshc->sftp_session = sftp_new(sshc->ssh_session);
+ if(!sshc->sftp_session) {
+ failf(data, "Failure initializing sftp session: %s",
+ ssh_get_error(sshc->ssh_session));
+ MOVE_TO_ERROR_STATE(CURLE_COULDNT_CONNECT);
+ break;
+ }
+
+ rc = sftp_init(sshc->sftp_session);
+ if(rc != SSH_OK) {
+ rc = sftp_get_error(sshc->sftp_session);
+ failf(data, "Failure initializing sftp session: %s",
+ ssh_get_error(sshc->ssh_session));
+ MOVE_TO_ERROR_STATE(sftp_error_to_CURLE(rc));
+ break;
+ }
+ state(conn, SSH_SFTP_REALPATH);
+ /* FALLTHROUGH */
+ case SSH_SFTP_REALPATH:
+ /*
+ * Get the "home" directory
+ */
+ sshc->homedir = sftp_canonicalize_path(sshc->sftp_session, ".");
+ if(sshc->homedir == NULL) {
+ MOVE_TO_ERROR_STATE(CURLE_COULDNT_CONNECT);
+ }
+ conn->data->state.most_recent_ftp_entrypath = sshc->homedir;
+
+ /* This is the last step in the SFTP connect phase. Do note that while
+ we get the homedir here, we get the "workingpath" in the DO action
+ since the homedir will remain the same between request but the
+ working path will not. */
+ DEBUGF(infof(data, "SSH CONNECT phase done\n"));
+ state(conn, SSH_STOP);
+ break;
+
+ case SSH_SFTP_QUOTE_INIT:
+
+ result = Curl_getworkingpath(conn, sshc->homedir, &protop->path);
+ if(result) {
+ sshc->actualcode = result;
+ state(conn, SSH_STOP);
+ break;
+ }
+
+ if(data->set.quote) {
+ infof(data, "Sending quote commands\n");
+ sshc->quote_item = data->set.quote;
+ state(conn, SSH_SFTP_QUOTE);
+ }
+ else {
+ state(conn, SSH_SFTP_GETINFO);
+ }
+ break;
+
+ case SSH_SFTP_POSTQUOTE_INIT:
+ if(data->set.postquote) {
+ infof(data, "Sending quote commands\n");
+ sshc->quote_item = data->set.postquote;
+ state(conn, SSH_SFTP_QUOTE);
+ }
+ else {
+ state(conn, SSH_STOP);
+ }
+ break;
+
+ case SSH_SFTP_QUOTE:
+ /* Send any quote commands */
+ sftp_quote(conn);
+ break;
+
+ case SSH_SFTP_NEXT_QUOTE:
+ Curl_safefree(sshc->quote_path1);
+ Curl_safefree(sshc->quote_path2);
+
+ sshc->quote_item = sshc->quote_item->next;
+
+ if(sshc->quote_item) {
+ state(conn, SSH_SFTP_QUOTE);
+ }
+ else {
+ if(sshc->nextstate != SSH_NO_STATE) {
+ state(conn, sshc->nextstate);
+ sshc->nextstate = SSH_NO_STATE;
+ }
+ else {
+ state(conn, SSH_SFTP_GETINFO);
+ }
+ }
+ break;
+
+ case SSH_SFTP_QUOTE_STAT:
+ sftp_quote_stat(conn);
+ break;
+
+ case SSH_SFTP_QUOTE_SETSTAT:
+ rc = sftp_setstat(sshc->sftp_session, sshc->quote_path2,
+ sshc->quote_attrs);
+ if(rc != 0 && !sshc->acceptfail) {
+ Curl_safefree(sshc->quote_path1);
+ Curl_safefree(sshc->quote_path2);
+ failf(data, "Attempt to set SFTP stats failed: %s",
+ ssh_get_error(sshc->ssh_session));
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ /* sshc->actualcode = sftp_error_to_CURLE(err);
+ * we do not send the actual error; we return
+ * the error the libssh2 backend is returning */
+ break;
+ }
+ state(conn, SSH_SFTP_NEXT_QUOTE);
+ break;
+
+ case SSH_SFTP_QUOTE_SYMLINK:
+ rc = sftp_symlink(sshc->sftp_session, sshc->quote_path2,
+ sshc->quote_path1);
+ if(rc != 0 && !sshc->acceptfail) {
+ Curl_safefree(sshc->quote_path1);
+ Curl_safefree(sshc->quote_path2);
+ failf(data, "symlink command failed: %s",
+ ssh_get_error(sshc->ssh_session));
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ break;
+ }
+ state(conn, SSH_SFTP_NEXT_QUOTE);
+ break;
+
+ case SSH_SFTP_QUOTE_MKDIR:
+ rc = sftp_mkdir(sshc->sftp_session, sshc->quote_path1,
+ (mode_t)data->set.new_directory_perms);
+ if(rc != 0 && !sshc->acceptfail) {
+ Curl_safefree(sshc->quote_path1);
+ failf(data, "mkdir command failed: %s",
+ ssh_get_error(sshc->ssh_session));
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ break;
+ }
+ state(conn, SSH_SFTP_NEXT_QUOTE);
+ break;
+
+ case SSH_SFTP_QUOTE_RENAME:
+ rc = sftp_rename(sshc->sftp_session, sshc->quote_path1,
+ sshc->quote_path2);
+ if(rc != 0 && !sshc->acceptfail) {
+ Curl_safefree(sshc->quote_path1);
+ Curl_safefree(sshc->quote_path2);
+ failf(data, "rename command failed: %s",
+ ssh_get_error(sshc->ssh_session));
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ break;
+ }
+ state(conn, SSH_SFTP_NEXT_QUOTE);
+ break;
+
+ case SSH_SFTP_QUOTE_RMDIR:
+ rc = sftp_rmdir(sshc->sftp_session, sshc->quote_path1);
+ if(rc != 0 && !sshc->acceptfail) {
+ Curl_safefree(sshc->quote_path1);
+ failf(data, "rmdir command failed: %s",
+ ssh_get_error(sshc->ssh_session));
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ break;
+ }
+ state(conn, SSH_SFTP_NEXT_QUOTE);
+ break;
+
+ case SSH_SFTP_QUOTE_UNLINK:
+ rc = sftp_unlink(sshc->sftp_session, sshc->quote_path1);
+ if(rc != 0 && !sshc->acceptfail) {
+ Curl_safefree(sshc->quote_path1);
+ failf(data, "rm command failed: %s",
+ ssh_get_error(sshc->ssh_session));
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ break;
+ }
+ state(conn, SSH_SFTP_NEXT_QUOTE);
+ break;
+
+ case SSH_SFTP_QUOTE_STATVFS:
+ {
+ sftp_statvfs_t statvfs;
+
+ statvfs = sftp_statvfs(sshc->sftp_session, sshc->quote_path1);
+ if(!statvfs && !sshc->acceptfail) {
+ Curl_safefree(sshc->quote_path1);
+ failf(data, "statvfs command failed: %s",
+ ssh_get_error(sshc->ssh_session));
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ break;
+ }
+ else if(statvfs) {
+ char *tmp = aprintf("statvfs:\n"
+ "f_bsize: %llu\n" "f_frsize: %llu\n"
+ "f_blocks: %llu\n" "f_bfree: %llu\n"
+ "f_bavail: %llu\n" "f_files: %llu\n"
+ "f_ffree: %llu\n" "f_favail: %llu\n"
+ "f_fsid: %llu\n" "f_flag: %llu\n"
+ "f_namemax: %llu\n",
+ statvfs->f_bsize, statvfs->f_frsize,
+ statvfs->f_blocks, statvfs->f_bfree,
+ statvfs->f_bavail, statvfs->f_files,
+ statvfs->f_ffree, statvfs->f_favail,
+ statvfs->f_fsid, statvfs->f_flag,
+ statvfs->f_namemax);
+ sftp_statvfs_free(statvfs);
+
+ if(!tmp) {
+ result = CURLE_OUT_OF_MEMORY;
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ break;
+ }
+
+ result = Curl_client_write(conn, CLIENTWRITE_HEADER, tmp, strlen(tmp));
+ free(tmp);
+ if(result) {
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = result;
+ }
+ }
+ state(conn, SSH_SFTP_NEXT_QUOTE);
+ break;
+ }
+
+ case SSH_SFTP_GETINFO:
+ if(data->set.get_filetime) {
+ state(conn, SSH_SFTP_FILETIME);
+ }
+ else {
+ state(conn, SSH_SFTP_TRANS_INIT);
+ }
+ break;
+
+ case SSH_SFTP_FILETIME:
+ {
+ sftp_attributes attrs;
+
+ attrs = sftp_stat(sshc->sftp_session, protop->path);
+ if(attrs != 0) {
+ data->info.filetime = attrs->mtime;
+ sftp_attributes_free(attrs);
+ }
+
+ state(conn, SSH_SFTP_TRANS_INIT);
+ break;
+ }
+
+ case SSH_SFTP_TRANS_INIT:
+ if(data->set.upload)
+ state(conn, SSH_SFTP_UPLOAD_INIT);
+ else {
+ if(protop->path[strlen(protop->path)-1] == '/')
+ state(conn, SSH_SFTP_READDIR_INIT);
+ else
+ state(conn, SSH_SFTP_DOWNLOAD_INIT);
+ }
+ break;
+
+ case SSH_SFTP_UPLOAD_INIT:
+ {
+ int flags;
+
+ if(data->state.resume_from != 0) {
+ sftp_attributes attrs;
+
+ if(data->state.resume_from < 0) {
+ attrs = sftp_stat(sshc->sftp_session, protop->path);
+ if(attrs != 0) {
+ curl_off_t size = attrs->size;
+ if(size < 0) {
+ failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size);
+ MOVE_TO_ERROR_STATE(CURLE_BAD_DOWNLOAD_RESUME);
+ }
+ data->state.resume_from = attrs->size;
+
+ sftp_attributes_free(attrs);
+ }
+ else {
+ data->state.resume_from = 0;
+ }
+ }
+ }
+
+ if(data->set.ftp_append)
+ /* Try to open for append, but create if nonexisting */
+ flags = O_WRONLY|O_CREAT|O_APPEND;
+ else if(data->state.resume_from > 0)
+ /* If we have restart position then open for append */
+ flags = O_WRONLY|O_APPEND;
+ else
+ /* Clear file before writing (normal behaviour) */
+ flags = O_WRONLY|O_APPEND|O_CREAT|O_TRUNC;
+
+ if(sshc->sftp_file)
+ sftp_close(sshc->sftp_file);
+ sshc->sftp_file =
+ sftp_open(sshc->sftp_session, protop->path,
+ flags, (mode_t)data->set.new_file_perms);
+ if(!sshc->sftp_file) {
+ err = sftp_get_error(sshc->sftp_session);
+
+ if(((err == SSH_FX_NO_SUCH_FILE || err == SSH_FX_FAILURE ||
+ err == SSH_FX_NO_SUCH_PATH)) &&
+ (data->set.ftp_create_missing_dirs &&
+ (strlen(protop->path) > 1))) {
+ /* try to create the path remotely */
+ rc = 0;
+ sshc->secondCreateDirs = 1;
+ state(conn, SSH_SFTP_CREATE_DIRS_INIT);
+ break;
+ }
+ else {
+ MOVE_TO_SFTP_CLOSE_STATE();
+ }
+ }
+
+ /* If we have a restart point then we need to seek to the correct
+ position. */
+ if(data->state.resume_from > 0) {
+ /* Let's read off the proper amount of bytes from the input. */
+ if(conn->seek_func) {
+ Curl_set_in_callback(data, true);
+ seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
+ SEEK_SET);
+ Curl_set_in_callback(data, false);
+ }
+
+ if(seekerr != CURL_SEEKFUNC_OK) {
+ curl_off_t passed = 0;
+
+ if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
+ failf(data, "Could not seek stream");
+ return CURLE_FTP_COULDNT_USE_REST;
+ }
+ /* seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
+ do {
+ size_t readthisamountnow =
+ (data->state.resume_from - passed > data->set.buffer_size) ?
+ (size_t)data->set.buffer_size :
+ curlx_sotouz(data->state.resume_from - passed);
+
+ size_t actuallyread =
+ data->state.fread_func(data->state.buffer, 1,
+ readthisamountnow, data->state.in);
+
+ passed += actuallyread;
+ if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
+ /* this checks for greater-than only to make sure that the
+ CURL_READFUNC_ABORT return code still aborts */
+ failf(data, "Failed to read data");
+ MOVE_TO_ERROR_STATE(CURLE_FTP_COULDNT_USE_REST);
+ }
+ } while(passed < data->state.resume_from);
+ }
+
+ /* now, decrease the size of the read */
+ if(data->state.infilesize > 0) {
+ data->state.infilesize -= data->state.resume_from;
+ data->req.size = data->state.infilesize;
+ Curl_pgrsSetUploadSize(data, data->state.infilesize);
+ }
+
+ rc = sftp_seek64(sshc->sftp_file, data->state.resume_from);
+ if(rc != 0) {
+ MOVE_TO_SFTP_CLOSE_STATE();
+ }
+ }
+ if(data->state.infilesize > 0) {
+ data->req.size = data->state.infilesize;
+ Curl_pgrsSetUploadSize(data, data->state.infilesize);
+ }
+ /* upload data */
+ Curl_setup_transfer(data, -1, -1, FALSE, FIRSTSOCKET);
+
+ /* not set by Curl_setup_transfer to preserve keepon bits */
+ conn->sockfd = conn->writesockfd;
+
+ /* store this original bitmask setup to use later on if we can't
+ figure out a "real" bitmask */
+ sshc->orig_waitfor = data->req.keepon;
+
+ /* we want to use the _sending_ function even when the socket turns
+ out readable as the underlying libssh sftp send function will deal
+ with both accordingly */
+ conn->cselect_bits = CURL_CSELECT_OUT;
+
+ /* since we don't really wait for anything at this point, we want the
+ state machine to move on as soon as possible so we set a very short
+ timeout here */
+ Curl_expire(data, 0, EXPIRE_RUN_NOW);
+
+ state(conn, SSH_STOP);
+ break;
+ }
+
+ case SSH_SFTP_CREATE_DIRS_INIT:
+ if(strlen(protop->path) > 1) {
+ sshc->slash_pos = protop->path + 1; /* ignore the leading '/' */
+ state(conn, SSH_SFTP_CREATE_DIRS);
+ }
+ else {
+ state(conn, SSH_SFTP_UPLOAD_INIT);
+ }
+ break;
+
+ case SSH_SFTP_CREATE_DIRS:
+ sshc->slash_pos = strchr(sshc->slash_pos, '/');
+ if(sshc->slash_pos) {
+ *sshc->slash_pos = 0;
+
+ infof(data, "Creating directory '%s'\n", protop->path);
+ state(conn, SSH_SFTP_CREATE_DIRS_MKDIR);
+ break;
+ }
+ state(conn, SSH_SFTP_UPLOAD_INIT);
+ break;
+
+ case SSH_SFTP_CREATE_DIRS_MKDIR:
+ /* 'mode' - parameter is preliminary - default to 0644 */
+ rc = sftp_mkdir(sshc->sftp_session, protop->path,
+ (mode_t)data->set.new_directory_perms);
+ *sshc->slash_pos = '/';
+ ++sshc->slash_pos;
+ if(rc < 0) {
+ /*
+ * Abort if failure wasn't that the dir already exists or the
+ * permission was denied (creation might succeed further down the
+ * path) - retry on unspecific FAILURE also
+ */
+ err = sftp_get_error(sshc->sftp_session);
+ if((err != SSH_FX_FILE_ALREADY_EXISTS) &&
+ (err != SSH_FX_FAILURE) &&
+ (err != SSH_FX_PERMISSION_DENIED)) {
+ MOVE_TO_SFTP_CLOSE_STATE();
+ }
+ rc = 0; /* clear rc and continue */
+ }
+ state(conn, SSH_SFTP_CREATE_DIRS);
+ break;
+
+ case SSH_SFTP_READDIR_INIT:
+ Curl_pgrsSetDownloadSize(data, -1);
+ if(data->set.opt_no_body) {
+ state(conn, SSH_STOP);
+ break;
+ }
+
+ /*
+ * This is a directory that we are trying to get, so produce a directory
+ * listing
+ */
+ sshc->sftp_dir = sftp_opendir(sshc->sftp_session,
+ protop->path);
+ if(!sshc->sftp_dir) {
+ failf(data, "Could not open directory for reading: %s",
+ ssh_get_error(sshc->ssh_session));
+ MOVE_TO_SFTP_CLOSE_STATE();
+ }
+ state(conn, SSH_SFTP_READDIR);
+ break;
+
+ case SSH_SFTP_READDIR:
+
+ if(sshc->readdir_attrs)
+ sftp_attributes_free(sshc->readdir_attrs);
+
+ sshc->readdir_attrs = sftp_readdir(sshc->sftp_session, sshc->sftp_dir);
+ if(sshc->readdir_attrs) {
+ sshc->readdir_filename = sshc->readdir_attrs->name;
+ sshc->readdir_longentry = sshc->readdir_attrs->longname;
+ sshc->readdir_len = strlen(sshc->readdir_filename);
+
+ if(data->set.ftp_list_only) {
+ char *tmpLine;
+
+ tmpLine = aprintf("%s\n", sshc->readdir_filename);
+ if(tmpLine == NULL) {
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->actualcode = CURLE_OUT_OF_MEMORY;
+ break;
+ }
+ result = Curl_client_write(conn, CLIENTWRITE_BODY,
+ tmpLine, sshc->readdir_len + 1);
+ free(tmpLine);
+
+ if(result) {
+ state(conn, SSH_STOP);
+ break;
+ }
+ /* since this counts what we send to the client, we include the
+ newline in this counter */
+ data->req.bytecount += sshc->readdir_len + 1;
+
+ /* output debug output if that is requested */
+ if(data->set.verbose) {
+ Curl_debug(data, CURLINFO_DATA_OUT,
+ (char *)sshc->readdir_filename,
+ sshc->readdir_len);
+ }
+ }
+ else {
+ sshc->readdir_currLen = strlen(sshc->readdir_longentry);
+ sshc->readdir_totalLen = 80 + sshc->readdir_currLen;
+ sshc->readdir_line = calloc(sshc->readdir_totalLen, 1);
+ if(!sshc->readdir_line) {
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->actualcode = CURLE_OUT_OF_MEMORY;
+ break;
+ }
+
+ memcpy(sshc->readdir_line, sshc->readdir_longentry,
+ sshc->readdir_currLen);
+ if((sshc->readdir_attrs->flags & SSH_FILEXFER_ATTR_PERMISSIONS) &&
+ ((sshc->readdir_attrs->permissions & S_IFMT) ==
+ S_IFLNK)) {
+ sshc->readdir_linkPath = malloc(PATH_MAX + 1);
+ if(sshc->readdir_linkPath == NULL) {
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->actualcode = CURLE_OUT_OF_MEMORY;
+ break;
+ }
+
+ msnprintf(sshc->readdir_linkPath, PATH_MAX, "%s%s", protop->path,
+ sshc->readdir_filename);
+
+ state(conn, SSH_SFTP_READDIR_LINK);
+ break;
+ }
+ state(conn, SSH_SFTP_READDIR_BOTTOM);
+ break;
+ }
+ }
+ else if(sshc->readdir_attrs == NULL && sftp_dir_eof(sshc->sftp_dir)) {
+ state(conn, SSH_SFTP_READDIR_DONE);
+ break;
+ }
+ else {
+ failf(data, "Could not open remote file for reading: %s",
+ ssh_get_error(sshc->ssh_session));
+ MOVE_TO_SFTP_CLOSE_STATE();
+ break;
+ }
+ break;
+
+ case SSH_SFTP_READDIR_LINK:
+ if(sshc->readdir_link_attrs)
+ sftp_attributes_free(sshc->readdir_link_attrs);
+
+ sshc->readdir_link_attrs = sftp_lstat(sshc->sftp_session,
+ sshc->readdir_linkPath);
+ if(sshc->readdir_link_attrs == 0) {
+ failf(data, "Could not read symlink for reading: %s",
+ ssh_get_error(sshc->ssh_session));
+ MOVE_TO_SFTP_CLOSE_STATE();
+ }
+
+ if(sshc->readdir_link_attrs->name == NULL) {
+ sshc->readdir_tmp = sftp_readlink(sshc->sftp_session,
+ sshc->readdir_linkPath);
+ if(sshc->readdir_filename == NULL)
+ sshc->readdir_len = 0;
+ else
+ sshc->readdir_len = strlen(sshc->readdir_tmp);
+ sshc->readdir_longentry = NULL;
+ sshc->readdir_filename = sshc->readdir_tmp;
+ }
+ else {
+ sshc->readdir_len = strlen(sshc->readdir_link_attrs->name);
+ sshc->readdir_filename = sshc->readdir_link_attrs->name;
+ sshc->readdir_longentry = sshc->readdir_link_attrs->longname;
+ }
+
+ Curl_safefree(sshc->readdir_linkPath);
+
+ /* get room for the filename and extra output */
+ sshc->readdir_totalLen += 4 + sshc->readdir_len;
+ new_readdir_line = Curl_saferealloc(sshc->readdir_line,
+ sshc->readdir_totalLen);
+ if(!new_readdir_line) {
+ sshc->readdir_line = NULL;
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->actualcode = CURLE_OUT_OF_MEMORY;
+ break;
+ }
+ sshc->readdir_line = new_readdir_line;
+
+ sshc->readdir_currLen += msnprintf(sshc->readdir_line +
+ sshc->readdir_currLen,
+ sshc->readdir_totalLen -
+ sshc->readdir_currLen,
+ " -> %s",
+ sshc->readdir_filename);
+
+ sftp_attributes_free(sshc->readdir_link_attrs);
+ sshc->readdir_link_attrs = NULL;
+ sshc->readdir_filename = NULL;
+ sshc->readdir_longentry = NULL;
+
+ state(conn, SSH_SFTP_READDIR_BOTTOM);
+ /* FALLTHROUGH */
+ case SSH_SFTP_READDIR_BOTTOM:
+ sshc->readdir_currLen += msnprintf(sshc->readdir_line +
+ sshc->readdir_currLen,
+ sshc->readdir_totalLen -
+ sshc->readdir_currLen, "\n");
+ result = Curl_client_write(conn, CLIENTWRITE_BODY,
+ sshc->readdir_line,
+ sshc->readdir_currLen);
+
+ if(!result) {
+
+ /* output debug output if that is requested */
+ if(data->set.verbose) {
+ Curl_debug(data, CURLINFO_DATA_OUT, sshc->readdir_line,
+ sshc->readdir_currLen);
+ }
+ data->req.bytecount += sshc->readdir_currLen;
+ }
+ Curl_safefree(sshc->readdir_line);
+ ssh_string_free_char(sshc->readdir_tmp);
+ sshc->readdir_tmp = NULL;
+
+ if(result) {
+ state(conn, SSH_STOP);
+ }
+ else
+ state(conn, SSH_SFTP_READDIR);
+ break;
+
+ case SSH_SFTP_READDIR_DONE:
+ sftp_closedir(sshc->sftp_dir);
+ sshc->sftp_dir = NULL;
+
+ /* no data to transfer */
+ Curl_setup_transfer(data, -1, -1, FALSE, -1);
+ state(conn, SSH_STOP);
+ break;
+
+ case SSH_SFTP_DOWNLOAD_INIT:
+ /*
+ * Work on getting the specified file
+ */
+ if(sshc->sftp_file)
+ sftp_close(sshc->sftp_file);
+
+ sshc->sftp_file = sftp_open(sshc->sftp_session, protop->path,
+ O_RDONLY, (mode_t)data->set.new_file_perms);
+ if(!sshc->sftp_file) {
+ failf(data, "Could not open remote file for reading: %s",
+ ssh_get_error(sshc->ssh_session));
+
+ MOVE_TO_SFTP_CLOSE_STATE();
+ }
+
+ state(conn, SSH_SFTP_DOWNLOAD_STAT);
+ break;
+
+ case SSH_SFTP_DOWNLOAD_STAT:
+ {
+ sftp_attributes attrs;
+ curl_off_t size;
+
+ attrs = sftp_fstat(sshc->sftp_file);
+ if(!attrs ||
+ !(attrs->flags & SSH_FILEXFER_ATTR_SIZE) ||
+ (attrs->size == 0)) {
+ /*
+ * sftp_fstat didn't return an error, so maybe the server
+ * just doesn't support stat()
+ * OR the server doesn't return a file size with a stat()
+ * OR file size is 0
+ */
+ data->req.size = -1;
+ data->req.maxdownload = -1;
+ Curl_pgrsSetDownloadSize(data, -1);
+ size = 0;
+ }
+ else {
+ size = attrs->size;
+
+ sftp_attributes_free(attrs);
+
+ if(size < 0) {
+ failf(data, "Bad file size (%" CURL_FORMAT_CURL_OFF_T ")", size);
+ return CURLE_BAD_DOWNLOAD_RESUME;
+ }
+ if(conn->data->state.use_range) {
+ curl_off_t from, to;
+ char *ptr;
+ char *ptr2;
+ CURLofft to_t;
+ CURLofft from_t;
+
+ 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_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_t) {
+ /* from is relative to end of file */
+ from = size - to;
+ to = size - 1;
+ }
+ if(from > size) {
+ failf(data, "Offset (%"
+ CURL_FORMAT_CURL_OFF_T ") was beyond file size (%"
+ CURL_FORMAT_CURL_OFF_T ")", from, size);
+ return CURLE_BAD_DOWNLOAD_RESUME;
+ }
+ if(from > to) {
+ from = to;
+ size = 0;
+ }
+ else {
+ size = to - from + 1;
+ }
+
+ rc = sftp_seek64(sshc->sftp_file, from);
+ if(rc != 0) {
+ MOVE_TO_SFTP_CLOSE_STATE();
+ }
+ }
+ data->req.size = size;
+ data->req.maxdownload = size;
+ Curl_pgrsSetDownloadSize(data, size);
+ }
+
+ /* We can resume if we can seek to the resume position */
+ if(data->state.resume_from) {
+ if(data->state.resume_from < 0) {
+ /* We're supposed to download the last abs(from) bytes */
+ if((curl_off_t)size < -data->state.resume_from) {
+ failf(data, "Offset (%"
+ CURL_FORMAT_CURL_OFF_T ") was beyond file size (%"
+ CURL_FORMAT_CURL_OFF_T ")",
+ data->state.resume_from, size);
+ return CURLE_BAD_DOWNLOAD_RESUME;
+ }
+ /* download from where? */
+ data->state.resume_from += size;
+ }
+ else {
+ if((curl_off_t)size < data->state.resume_from) {
+ failf(data, "Offset (%" CURL_FORMAT_CURL_OFF_T
+ ") was beyond file size (%" CURL_FORMAT_CURL_OFF_T ")",
+ data->state.resume_from, size);
+ return CURLE_BAD_DOWNLOAD_RESUME;
+ }
+ }
+ /* Does a completed file need to be seeked and started or closed ? */
+ /* Now store the number of bytes we are expected to download */
+ data->req.size = size - data->state.resume_from;
+ data->req.maxdownload = size - data->state.resume_from;
+ Curl_pgrsSetDownloadSize(data,
+ size - data->state.resume_from);
+
+ rc = sftp_seek64(sshc->sftp_file, data->state.resume_from);
+ if(rc != 0) {
+ MOVE_TO_SFTP_CLOSE_STATE();
+ }
+ }
+ }
+
+ /* Setup the actual download */
+ if(data->req.size == 0) {
+ /* no data to transfer */
+ Curl_setup_transfer(data, -1, -1, FALSE, -1);
+ infof(data, "File already completely downloaded\n");
+ state(conn, SSH_STOP);
+ break;
+ }
+ Curl_setup_transfer(data, FIRSTSOCKET, data->req.size, FALSE, -1);
+
+ /* not set by Curl_setup_transfer to preserve keepon bits */
+ conn->writesockfd = conn->sockfd;
+
+ /* we want to use the _receiving_ function even when the socket turns
+ out writableable as the underlying libssh recv function will deal
+ with both accordingly */
+ conn->cselect_bits = CURL_CSELECT_IN;
+
+ if(result) {
+ /* this should never occur; the close state should be entered
+ at the time the error occurs */
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->actualcode = result;
+ }
+ else {
+ sshc->sftp_recv_state = 0;
+ state(conn, SSH_STOP);
+ }
+ break;
+
+ case SSH_SFTP_CLOSE:
+ if(sshc->sftp_file) {
+ sftp_close(sshc->sftp_file);
+ sshc->sftp_file = NULL;
+ }
+ Curl_safefree(protop->path);
+
+ DEBUGF(infof(data, "SFTP DONE done\n"));
+
+ /* Check if nextstate is set and move .nextstate could be POSTQUOTE_INIT
+ After nextstate is executed, the control should come back to
+ SSH_SFTP_CLOSE to pass the correct result back */
+ if(sshc->nextstate != SSH_NO_STATE &&
+ sshc->nextstate != SSH_SFTP_CLOSE) {
+ state(conn, sshc->nextstate);
+ sshc->nextstate = SSH_SFTP_CLOSE;
+ }
+ else {
+ state(conn, SSH_STOP);
+ result = sshc->actualcode;
+ }
+ break;
+
+ case SSH_SFTP_SHUTDOWN:
+ /* during times we get here due to a broken transfer and then the
+ sftp_handle might not have been taken down so make sure that is done
+ before we proceed */
+
+ if(sshc->sftp_file) {
+ sftp_close(sshc->sftp_file);
+ sshc->sftp_file = NULL;
+ }
+
+ if(sshc->sftp_session) {
+ sftp_free(sshc->sftp_session);
+ sshc->sftp_session = NULL;
+ }
+
+ SSH_STRING_FREE_CHAR(sshc->homedir);
+ conn->data->state.most_recent_ftp_entrypath = NULL;
+
+ state(conn, SSH_SESSION_DISCONNECT);
+ break;
+
+
+ case SSH_SCP_TRANS_INIT:
+ result = Curl_getworkingpath(conn, sshc->homedir, &protop->path);
+ if(result) {
+ sshc->actualcode = result;
+ state(conn, SSH_STOP);
+ break;
+ }
+
+ /* Functions from the SCP subsystem cannot handle/return SSH_AGAIN */
+ ssh_set_blocking(sshc->ssh_session, 1);
+
+ if(data->set.upload) {
+ if(data->state.infilesize < 0) {
+ failf(data, "SCP requires a known file size for upload");
+ sshc->actualcode = CURLE_UPLOAD_FAILED;
+ MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED);
+ }
+
+ sshc->scp_session =
+ ssh_scp_new(sshc->ssh_session, SSH_SCP_WRITE, protop->path);
+ state(conn, SSH_SCP_UPLOAD_INIT);
+ }
+ else {
+ sshc->scp_session =
+ ssh_scp_new(sshc->ssh_session, SSH_SCP_READ, protop->path);
+ state(conn, SSH_SCP_DOWNLOAD_INIT);
+ }
+
+ if(!sshc->scp_session) {
+ err_msg = ssh_get_error(sshc->ssh_session);
+ failf(conn->data, "%s", err_msg);
+ MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED);
+ }
+
+ break;
+
+ case SSH_SCP_UPLOAD_INIT:
+
+ rc = ssh_scp_init(sshc->scp_session);
+ if(rc != SSH_OK) {
+ err_msg = ssh_get_error(sshc->ssh_session);
+ failf(conn->data, "%s", err_msg);
+ MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED);
+ }
+
+ rc = ssh_scp_push_file(sshc->scp_session, protop->path,
+ data->state.infilesize,
+ (int)data->set.new_file_perms);
+ if(rc != SSH_OK) {
+ err_msg = ssh_get_error(sshc->ssh_session);
+ failf(conn->data, "%s", err_msg);
+ MOVE_TO_ERROR_STATE(CURLE_UPLOAD_FAILED);
+ }
+
+ /* upload data */
+ Curl_setup_transfer(data, -1, data->req.size, FALSE, FIRSTSOCKET);
+
+ /* not set by Curl_setup_transfer to preserve keepon bits */
+ conn->sockfd = conn->writesockfd;
+
+ /* store this original bitmask setup to use later on if we can't
+ figure out a "real" bitmask */
+ sshc->orig_waitfor = data->req.keepon;
+
+ /* we want to use the _sending_ function even when the socket turns
+ out readable as the underlying libssh scp send function will deal
+ with both accordingly */
+ conn->cselect_bits = CURL_CSELECT_OUT;
+
+ state(conn, SSH_STOP);
+
+ break;
+
+ case SSH_SCP_DOWNLOAD_INIT:
+
+ rc = ssh_scp_init(sshc->scp_session);
+ if(rc != SSH_OK) {
+ err_msg = ssh_get_error(sshc->ssh_session);
+ failf(conn->data, "%s", err_msg);
+ MOVE_TO_ERROR_STATE(CURLE_COULDNT_CONNECT);
+ }
+ state(conn, SSH_SCP_DOWNLOAD);
+ /* FALLTHROUGH */
+
+ case SSH_SCP_DOWNLOAD:{
+ curl_off_t bytecount;
+
+ rc = ssh_scp_pull_request(sshc->scp_session);
+ if(rc != SSH_SCP_REQUEST_NEWFILE) {
+ err_msg = ssh_get_error(sshc->ssh_session);
+ failf(conn->data, "%s", err_msg);
+ MOVE_TO_ERROR_STATE(CURLE_REMOTE_FILE_NOT_FOUND);
+ break;
+ }
+
+ /* download data */
+ bytecount = ssh_scp_request_get_size(sshc->scp_session);
+ data->req.maxdownload = (curl_off_t) bytecount;
+ Curl_setup_transfer(data, FIRSTSOCKET, bytecount, FALSE, -1);
+
+ /* not set by Curl_setup_transfer to preserve keepon bits */
+ conn->writesockfd = conn->sockfd;
+
+ /* we want to use the _receiving_ function even when the socket turns
+ out writableable as the underlying libssh recv function will deal
+ with both accordingly */
+ conn->cselect_bits = CURL_CSELECT_IN;
+
+ state(conn, SSH_STOP);
+ break;
+ }
+ case SSH_SCP_DONE:
+ if(data->set.upload)
+ state(conn, SSH_SCP_SEND_EOF);
+ else
+ state(conn, SSH_SCP_CHANNEL_FREE);
+ break;
+
+ case SSH_SCP_SEND_EOF:
+ if(sshc->scp_session) {
+ rc = ssh_scp_close(sshc->scp_session);
+ if(rc == SSH_AGAIN) {
+ /* Currently the ssh_scp_close handles waiting for EOF in
+ * blocking way.
+ */
+ break;
+ }
+ if(rc != SSH_OK) {
+ infof(data, "Failed to close libssh scp channel: %s\n",
+ ssh_get_error(sshc->ssh_session));
+ }
+ }
+
+ state(conn, SSH_SCP_CHANNEL_FREE);
+ break;
+
+ case SSH_SCP_CHANNEL_FREE:
+ if(sshc->scp_session) {
+ ssh_scp_free(sshc->scp_session);
+ sshc->scp_session = NULL;
+ }
+ DEBUGF(infof(data, "SCP DONE phase complete\n"));
+
+ ssh_set_blocking(sshc->ssh_session, 0);
+
+ state(conn, SSH_SESSION_DISCONNECT);
+ /* FALLTHROUGH */
+
+ case SSH_SESSION_DISCONNECT:
+ /* during weird times when we've been prematurely aborted, the channel
+ is still alive when we reach this state and we MUST kill the channel
+ properly first */
+ if(sshc->scp_session) {
+ ssh_scp_free(sshc->scp_session);
+ sshc->scp_session = NULL;
+ }
+
+ ssh_disconnect(sshc->ssh_session);
+
+ SSH_STRING_FREE_CHAR(sshc->homedir);
+ conn->data->state.most_recent_ftp_entrypath = NULL;
+
+ state(conn, SSH_SESSION_FREE);
+ /* FALLTHROUGH */
+ case SSH_SESSION_FREE:
+ if(sshc->ssh_session) {
+ ssh_free(sshc->ssh_session);
+ sshc->ssh_session = NULL;
+ }
+
+ /* worst-case scenario cleanup */
+
+ DEBUGASSERT(sshc->ssh_session == NULL);
+ DEBUGASSERT(sshc->scp_session == NULL);
+
+ if(sshc->readdir_tmp) {
+ ssh_string_free_char(sshc->readdir_tmp);
+ sshc->readdir_tmp = NULL;
+ }
+
+ if(sshc->quote_attrs)
+ sftp_attributes_free(sshc->quote_attrs);
+
+ if(sshc->readdir_attrs)
+ sftp_attributes_free(sshc->readdir_attrs);
+
+ if(sshc->readdir_link_attrs)
+ sftp_attributes_free(sshc->readdir_link_attrs);
+
+ if(sshc->privkey)
+ ssh_key_free(sshc->privkey);
+ if(sshc->pubkey)
+ ssh_key_free(sshc->pubkey);
+
+ Curl_safefree(sshc->rsa_pub);
+ Curl_safefree(sshc->rsa);
+ Curl_safefree(sshc->quote_path1);
+ Curl_safefree(sshc->quote_path2);
+ Curl_safefree(sshc->readdir_line);
+ Curl_safefree(sshc->readdir_linkPath);
+ SSH_STRING_FREE_CHAR(sshc->homedir);
+
+ /* the code we are about to return */
+ result = sshc->actualcode;
+
+ memset(sshc, 0, sizeof(struct ssh_conn));
+
+ connclose(conn, "SSH session free");
+ sshc->state = SSH_SESSION_FREE; /* current */
+ sshc->nextstate = SSH_NO_STATE;
+ state(conn, SSH_STOP);
+ break;
+
+ case SSH_QUIT:
+ /* fallthrough, just stop! */
+ default:
+ /* internal error */
+ sshc->nextstate = SSH_NO_STATE;
+ state(conn, SSH_STOP);
+ break;
+
+ }
+ } while(!rc && (sshc->state != SSH_STOP));
+
+
+ if(rc == SSH_AGAIN) {
+ /* we would block, we need to wait for the socket to be ready (in the
+ right direction too)! */
+ *block = TRUE;
+ }
+
+ return result;
+}
+
+
+/* called by the multi interface to figure out what socket(s) to wait for and
+ for what actions in the DO_DONE, PERFORM and WAITPERFORM states */
+static int myssh_perform_getsock(const struct connectdata *conn,
+ curl_socket_t *sock, /* points to numsocks
+ number of sockets */
+ int numsocks)
+{
+ int bitmap = GETSOCK_BLANK;
+ (void) numsocks;
+
+ sock[0] = conn->sock[FIRSTSOCKET];
+
+ if(conn->waitfor & KEEP_RECV)
+ bitmap |= GETSOCK_READSOCK(FIRSTSOCKET);
+
+ if(conn->waitfor & KEEP_SEND)
+ bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET);
+
+ return bitmap;
+}
+
+/* Generic function called by the multi interface to figure out what socket(s)
+ to wait for and for what actions during the DOING and PROTOCONNECT states*/
+static int myssh_getsock(struct connectdata *conn,
+ curl_socket_t *sock, /* points to numsocks
+ number of sockets */
+ int numsocks)
+{
+ /* if we know the direction we can use the generic *_getsock() function even
+ for the protocol_connect and doing states */
+ return myssh_perform_getsock(conn, sock, numsocks);
+}
+
+static void myssh_block2waitfor(struct connectdata *conn, bool block)
+{
+ struct ssh_conn *sshc = &conn->proto.sshc;
+
+ /* If it didn't block, or nothing was returned by ssh_get_poll_flags
+ * have the original set */
+ conn->waitfor = sshc->orig_waitfor;
+
+ if(block) {
+ int dir = ssh_get_poll_flags(sshc->ssh_session);
+ if(dir & SSH_READ_PENDING) {
+ /* translate the libssh define bits into our own bit defines */
+ conn->waitfor = KEEP_RECV;
+ }
+ else if(dir & SSH_WRITE_PENDING) {
+ conn->waitfor = KEEP_SEND;
+ }
+ }
+}
+
+/* called repeatedly until done from multi.c */
+static CURLcode myssh_multi_statemach(struct connectdata *conn,
+ bool *done)
+{
+ struct ssh_conn *sshc = &conn->proto.sshc;
+ CURLcode result = CURLE_OK;
+ bool block; /* we store the status and use that to provide a ssh_getsock()
+ implementation */
+
+ result = myssh_statemach_act(conn, &block);
+ *done = (sshc->state == SSH_STOP) ? TRUE : FALSE;
+ myssh_block2waitfor(conn, block);
+
+ return result;
+}
+
+static CURLcode myssh_block_statemach(struct connectdata *conn,
+ bool disconnect)
+{
+ struct ssh_conn *sshc = &conn->proto.sshc;
+ CURLcode result = CURLE_OK;
+ struct Curl_easy *data = conn->data;
+
+ while((sshc->state != SSH_STOP) && !result) {
+ bool block;
+ timediff_t left = 1000;
+ struct curltime now = Curl_now();
+
+ result = myssh_statemach_act(conn, &block);
+ if(result)
+ break;
+
+ if(!disconnect) {
+ if(Curl_pgrsUpdate(conn))
+ return CURLE_ABORTED_BY_CALLBACK;
+
+ result = Curl_speedcheck(data, now);
+ if(result)
+ break;
+
+ left = Curl_timeleft(data, NULL, FALSE);
+ if(left < 0) {
+ failf(data, "Operation timed out");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+ }
+
+ if(!result && block) {
+ curl_socket_t fd_read = conn->sock[FIRSTSOCKET];
+ /* wait for the socket to become ready */
+ (void) Curl_socket_check(fd_read, CURL_SOCKET_BAD,
+ CURL_SOCKET_BAD, left > 1000 ? 1000 : left);
+ }
+
+ }
+
+ return result;
+}
+
+/*
+ * SSH setup connection
+ */
+static CURLcode myssh_setup_connection(struct connectdata *conn)
+{
+ struct SSHPROTO *ssh;
+
+ conn->data->req.protop = ssh = calloc(1, sizeof(struct SSHPROTO));
+ if(!ssh)
+ return CURLE_OUT_OF_MEMORY;
+
+ return CURLE_OK;
+}
+
+static Curl_recv scp_recv, sftp_recv;
+static Curl_send scp_send, sftp_send;
+
+/*
+ * Curl_ssh_connect() gets called from Curl_protocol_connect() to allow us to
+ * do protocol-specific actions at connect-time.
+ */
+static CURLcode myssh_connect(struct connectdata *conn, bool *done)
+{
+ struct ssh_conn *ssh;
+ CURLcode result;
+ curl_socket_t sock = conn->sock[FIRSTSOCKET];
+ struct Curl_easy *data = conn->data;
+
+ /* initialize per-handle data if not already */
+ if(!data->req.protop)
+ myssh_setup_connection(conn);
+
+ /* We default to persistent connections. We set this already in this connect
+ function to make the re-use checks properly be able to check this bit. */
+ connkeep(conn, "SSH default");
+
+ if(conn->handler->protocol & CURLPROTO_SCP) {
+ conn->recv[FIRSTSOCKET] = scp_recv;
+ conn->send[FIRSTSOCKET] = scp_send;
+ }
+ else {
+ conn->recv[FIRSTSOCKET] = sftp_recv;
+ conn->send[FIRSTSOCKET] = sftp_send;
+ }
+
+ ssh = &conn->proto.sshc;
+
+ ssh->ssh_session = ssh_new();
+ if(ssh->ssh_session == NULL) {
+ failf(data, "Failure initialising ssh session");
+ return CURLE_FAILED_INIT;
+ }
+
+ ssh_options_set(ssh->ssh_session, SSH_OPTIONS_FD, &sock);
+
+ if(conn->user) {
+ infof(data, "User: %s\n", conn->user);
+ ssh_options_set(ssh->ssh_session, SSH_OPTIONS_USER, conn->user);
+ }
+
+ if(data->set.str[STRING_SSH_KNOWNHOSTS]) {
+ infof(data, "Known hosts: %s\n", data->set.str[STRING_SSH_KNOWNHOSTS]);
+ ssh_options_set(ssh->ssh_session, SSH_OPTIONS_KNOWNHOSTS,
+ data->set.str[STRING_SSH_KNOWNHOSTS]);
+ }
+
+ ssh_options_set(ssh->ssh_session, SSH_OPTIONS_HOST, conn->host.name);
+ if(conn->remote_port)
+ ssh_options_set(ssh->ssh_session, SSH_OPTIONS_PORT,
+ &conn->remote_port);
+
+ if(data->set.ssh_compression) {
+ ssh_options_set(ssh->ssh_session, SSH_OPTIONS_COMPRESSION,
+ "zlib,zlib@openssh.com,none");
+ }
+
+ ssh->privkey = NULL;
+ ssh->pubkey = NULL;
+
+ if(data->set.str[STRING_SSH_PUBLIC_KEY]) {
+ int rc = ssh_pki_import_pubkey_file(data->set.str[STRING_SSH_PUBLIC_KEY],
+ &ssh->pubkey);
+ if(rc != SSH_OK) {
+ failf(data, "Could not load public key file");
+ /* ignore */
+ }
+ }
+
+ /* we do not verify here, we do it at the state machine,
+ * after connection */
+
+ state(conn, SSH_INIT);
+
+ result = myssh_multi_statemach(conn, done);
+
+ return result;
+}
+
+/* called from multi.c while DOing */
+static CURLcode scp_doing(struct connectdata *conn, bool *dophase_done)
+{
+ CURLcode result;
+
+ result = myssh_multi_statemach(conn, dophase_done);
+
+ if(*dophase_done) {
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+ }
+ return result;
+}
+
+/*
+ ***********************************************************************
+ *
+ * scp_perform()
+ *
+ * This is the actual DO function for SCP. Get a file according to
+ * the options previously setup.
+ */
+
+static
+CURLcode scp_perform(struct connectdata *conn,
+ bool *connected, bool *dophase_done)
+{
+ CURLcode result = CURLE_OK;
+
+ DEBUGF(infof(conn->data, "DO phase starts\n"));
+
+ *dophase_done = FALSE; /* not done yet */
+
+ /* start the first command in the DO phase */
+ state(conn, SSH_SCP_TRANS_INIT);
+
+ result = myssh_multi_statemach(conn, dophase_done);
+
+ *connected = conn->bits.tcpconnect[FIRSTSOCKET];
+
+ if(*dophase_done) {
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+ }
+
+ return result;
+}
+
+static CURLcode myssh_do_it(struct connectdata *conn, bool *done)
+{
+ CURLcode result;
+ bool connected = 0;
+ struct Curl_easy *data = conn->data;
+ struct ssh_conn *sshc = &conn->proto.sshc;
+
+ *done = FALSE; /* default to false */
+
+ 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 */
+
+ Curl_pgrsSetUploadCounter(data, 0);
+ Curl_pgrsSetDownloadCounter(data, 0);
+ Curl_pgrsSetUploadSize(data, -1);
+ Curl_pgrsSetDownloadSize(data, -1);
+
+ if(conn->handler->protocol & CURLPROTO_SCP)
+ result = scp_perform(conn, &connected, done);
+ else
+ result = sftp_perform(conn, &connected, done);
+
+ return result;
+}
+
+/* BLOCKING, but the function is using the state machine so the only reason
+ this is still blocking is that the multi interface code has no support for
+ disconnecting operations that takes a while */
+static CURLcode scp_disconnect(struct connectdata *conn,
+ bool dead_connection)
+{
+ CURLcode result = CURLE_OK;
+ struct ssh_conn *ssh = &conn->proto.sshc;
+ (void) dead_connection;
+
+ if(ssh->ssh_session) {
+ /* only if there's a session still around to use! */
+
+ state(conn, SSH_SESSION_DISCONNECT);
+
+ result = myssh_block_statemach(conn, TRUE);
+ }
+
+ return result;
+}
+
+/* generic done function for both SCP and SFTP called from their specific
+ done functions */
+static CURLcode myssh_done(struct connectdata *conn, CURLcode status)
+{
+ CURLcode result = CURLE_OK;
+ struct SSHPROTO *protop = conn->data->req.protop;
+
+ if(!status) {
+ /* run the state-machine */
+ result = myssh_block_statemach(conn, FALSE);
+ }
+ else
+ result = status;
+
+ if(protop)
+ Curl_safefree(protop->path);
+ if(Curl_pgrsDone(conn))
+ return CURLE_ABORTED_BY_CALLBACK;
+
+ conn->data->req.keepon = 0; /* clear all bits */
+ return result;
+}
+
+
+static CURLcode scp_done(struct connectdata *conn, CURLcode status,
+ bool premature)
+{
+ (void) premature; /* not used */
+
+ if(!status)
+ state(conn, SSH_SCP_DONE);
+
+ return myssh_done(conn, status);
+
+}
+
+static ssize_t scp_send(struct connectdata *conn, int sockindex,
+ const void *mem, size_t len, CURLcode *err)
+{
+ int rc;
+ (void) sockindex; /* we only support SCP on the fixed known primary socket */
+ (void) err;
+
+ rc = ssh_scp_write(conn->proto.sshc.scp_session, mem, len);
+
+#if 0
+ /* The following code is misleading, mostly added as wishful thinking
+ * that libssh at some point will implement non-blocking ssh_scp_write/read.
+ * Currently rc can only be number of bytes read or SSH_ERROR. */
+ myssh_block2waitfor(conn, (rc == SSH_AGAIN) ? TRUE : FALSE);
+
+ if(rc == SSH_AGAIN) {
+ *err = CURLE_AGAIN;
+ return 0;
+ }
+ else
+#endif
+ if(rc != SSH_OK) {
+ *err = CURLE_SSH;
+ return -1;
+ }
+
+ return len;
+}
+
+static ssize_t scp_recv(struct connectdata *conn, int sockindex,
+ char *mem, size_t len, CURLcode *err)
+{
+ ssize_t nread;
+ (void) err;
+ (void) sockindex; /* we only support SCP on the fixed known primary socket */
+
+ /* libssh returns int */
+ nread = ssh_scp_read(conn->proto.sshc.scp_session, mem, len);
+
+#if 0
+ /* The following code is misleading, mostly added as wishful thinking
+ * that libssh at some point will implement non-blocking ssh_scp_write/read.
+ * Currently rc can only be SSH_OK or SSH_ERROR. */
+
+ myssh_block2waitfor(conn, (nread == SSH_AGAIN) ? TRUE : FALSE);
+ if(nread == SSH_AGAIN) {
+ *err = CURLE_AGAIN;
+ nread = -1;
+ }
+#endif
+
+ return nread;
+}
+
+/*
+ * =============== SFTP ===============
+ */
+
+/*
+ ***********************************************************************
+ *
+ * sftp_perform()
+ *
+ * This is the actual DO function for SFTP. Get a file/directory according to
+ * the options previously setup.
+ */
+
+static
+CURLcode sftp_perform(struct connectdata *conn,
+ bool *connected,
+ bool *dophase_done)
+{
+ CURLcode result = CURLE_OK;
+
+ DEBUGF(infof(conn->data, "DO phase starts\n"));
+
+ *dophase_done = FALSE; /* not done yet */
+
+ /* start the first command in the DO phase */
+ state(conn, SSH_SFTP_QUOTE_INIT);
+
+ /* run the state-machine */
+ result = myssh_multi_statemach(conn, dophase_done);
+
+ *connected = conn->bits.tcpconnect[FIRSTSOCKET];
+
+ if(*dophase_done) {
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+ }
+
+ return result;
+}
+
+/* called from multi.c while DOing */
+static CURLcode sftp_doing(struct connectdata *conn,
+ bool *dophase_done)
+{
+ CURLcode result = myssh_multi_statemach(conn, dophase_done);
+ if(*dophase_done) {
+ DEBUGF(infof(conn->data, "DO phase is complete\n"));
+ }
+ return result;
+}
+
+/* BLOCKING, but the function is using the state machine so the only reason
+ this is still blocking is that the multi interface code has no support for
+ disconnecting operations that takes a while */
+static CURLcode sftp_disconnect(struct connectdata *conn, bool dead_connection)
+{
+ CURLcode result = CURLE_OK;
+ (void) dead_connection;
+
+ DEBUGF(infof(conn->data, "SSH DISCONNECT starts now\n"));
+
+ if(conn->proto.sshc.ssh_session) {
+ /* only if there's a session still around to use! */
+ state(conn, SSH_SFTP_SHUTDOWN);
+ result = myssh_block_statemach(conn, TRUE);
+ }
+
+ DEBUGF(infof(conn->data, "SSH DISCONNECT is done\n"));
+
+ return result;
+
+}
+
+static CURLcode sftp_done(struct connectdata *conn, CURLcode status,
+ bool premature)
+{
+ struct ssh_conn *sshc = &conn->proto.sshc;
+
+ if(!status) {
+ /* Post quote commands are executed after the SFTP_CLOSE state to avoid
+ errors that could happen due to open file handles during POSTQUOTE
+ operation */
+ if(!premature && conn->data->set.postquote && !conn->bits.retry)
+ sshc->nextstate = SSH_SFTP_POSTQUOTE_INIT;
+ state(conn, SSH_SFTP_CLOSE);
+ }
+ return myssh_done(conn, status);
+}
+
+/* return number of sent bytes */
+static ssize_t sftp_send(struct connectdata *conn, int sockindex,
+ const void *mem, size_t len, CURLcode *err)
+{
+ ssize_t nwrite;
+ (void)sockindex;
+
+ nwrite = sftp_write(conn->proto.sshc.sftp_file, mem, len);
+
+ myssh_block2waitfor(conn, FALSE);
+
+#if 0 /* not returned by libssh on write */
+ if(nwrite == SSH_AGAIN) {
+ *err = CURLE_AGAIN;
+ nwrite = 0;
+ }
+ else
+#endif
+ if(nwrite < 0) {
+ *err = CURLE_SSH;
+ nwrite = -1;
+ }
+
+ return nwrite;
+}
+
+/*
+ * Return number of received (decrypted) bytes
+ * or <0 on error
+ */
+static ssize_t sftp_recv(struct connectdata *conn, int sockindex,
+ char *mem, size_t len, CURLcode *err)
+{
+ ssize_t nread;
+ (void)sockindex;
+
+ DEBUGASSERT(len < CURL_MAX_READ_SIZE);
+
+ switch(conn->proto.sshc.sftp_recv_state) {
+ case 0:
+ conn->proto.sshc.sftp_file_index =
+ sftp_async_read_begin(conn->proto.sshc.sftp_file,
+ (uint32_t)len);
+ if(conn->proto.sshc.sftp_file_index < 0) {
+ *err = CURLE_RECV_ERROR;
+ return -1;
+ }
+
+ /* FALLTHROUGH */
+ case 1:
+ conn->proto.sshc.sftp_recv_state = 1;
+
+ nread = sftp_async_read(conn->proto.sshc.sftp_file,
+ mem, (uint32_t)len,
+ conn->proto.sshc.sftp_file_index);
+
+ myssh_block2waitfor(conn, (nread == SSH_AGAIN)?TRUE:FALSE);
+
+ if(nread == SSH_AGAIN) {
+ *err = CURLE_AGAIN;
+ return -1;
+ }
+ else if(nread < 0) {
+ *err = CURLE_RECV_ERROR;
+ return -1;
+ }
+
+ conn->proto.sshc.sftp_recv_state = 0;
+ return nread;
+
+ default:
+ /* we never reach here */
+ return -1;
+ }
+}
+
+static void sftp_quote(struct connectdata *conn)
+{
+ const char *cp;
+ struct Curl_easy *data = conn->data;
+ struct SSHPROTO *protop = data->req.protop;
+ struct ssh_conn *sshc = &conn->proto.sshc;
+ CURLcode result;
+
+ /*
+ * Support some of the "FTP" commands
+ */
+ char *cmd = sshc->quote_item->data;
+ sshc->acceptfail = FALSE;
+
+ /* if a command starts with an asterisk, which a legal SFTP command never
+ can, the command will be allowed to fail without it causing any
+ aborts or cancels etc. It will cause libcurl to act as if the command
+ is successful, whatever the server reponds. */
+
+ if(cmd[0] == '*') {
+ cmd++;
+ sshc->acceptfail = TRUE;
+ }
+
+ if(strcasecompare("pwd", cmd)) {
+ /* output debug output if that is requested */
+ char *tmp = aprintf("257 \"%s\" is current directory.\n",
+ protop->path);
+ if(!tmp) {
+ sshc->actualcode = CURLE_OUT_OF_MEMORY;
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ return;
+ }
+ if(data->set.verbose) {
+ Curl_debug(data, CURLINFO_HEADER_OUT, (char *) "PWD\n", 4);
+ Curl_debug(data, CURLINFO_HEADER_IN, tmp, strlen(tmp));
+ }
+ /* this sends an FTP-like "header" to the header callback so that the
+ current directory can be read very similar to how it is read when
+ using ordinary FTP. */
+ result = Curl_client_write(conn, CLIENTWRITE_HEADER, tmp, strlen(tmp));
+ free(tmp);
+ if(result) {
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = result;
+ }
+ else
+ state(conn, SSH_SFTP_NEXT_QUOTE);
+ return;
+ }
+
+ /*
+ * the arguments following the command must be separated from the
+ * command with a space so we can check for it unconditionally
+ */
+ cp = strchr(cmd, ' ');
+ if(cp == NULL) {
+ failf(data, "Syntax error in SFTP command. Supply parameter(s)!");
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ return;
+ }
+
+ /*
+ * also, every command takes at least one argument so we get that
+ * first argument right now
+ */
+ result = Curl_get_pathname(&cp, &sshc->quote_path1, sshc->homedir);
+ if(result) {
+ if(result == CURLE_OUT_OF_MEMORY)
+ failf(data, "Out of memory");
+ else
+ failf(data, "Syntax error: Bad first parameter");
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = result;
+ return;
+ }
+
+ /*
+ * SFTP is a binary protocol, so we don't send text commands
+ * to the server. Instead, we scan for commands used by
+ * OpenSSH's sftp program and call the appropriate libssh
+ * functions.
+ */
+ if(strncasecompare(cmd, "chgrp ", 6) ||
+ strncasecompare(cmd, "chmod ", 6) ||
+ strncasecompare(cmd, "chown ", 6)) {
+ /* attribute change */
+
+ /* sshc->quote_path1 contains the mode to set */
+ /* get the destination */
+ result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir);
+ if(result) {
+ if(result == CURLE_OUT_OF_MEMORY)
+ failf(data, "Out of memory");
+ else
+ failf(data, "Syntax error in chgrp/chmod/chown: "
+ "Bad second parameter");
+ Curl_safefree(sshc->quote_path1);
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = result;
+ return;
+ }
+ sshc->quote_attrs = NULL;
+ state(conn, SSH_SFTP_QUOTE_STAT);
+ return;
+ }
+ if(strncasecompare(cmd, "ln ", 3) ||
+ strncasecompare(cmd, "symlink ", 8)) {
+ /* symbolic linking */
+ /* sshc->quote_path1 is the source */
+ /* get the destination */
+ result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir);
+ if(result) {
+ if(result == CURLE_OUT_OF_MEMORY)
+ failf(data, "Out of memory");
+ else
+ failf(data, "Syntax error in ln/symlink: Bad second parameter");
+ Curl_safefree(sshc->quote_path1);
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = result;
+ return;
+ }
+ state(conn, SSH_SFTP_QUOTE_SYMLINK);
+ return;
+ }
+ else if(strncasecompare(cmd, "mkdir ", 6)) {
+ /* create dir */
+ state(conn, SSH_SFTP_QUOTE_MKDIR);
+ return;
+ }
+ else if(strncasecompare(cmd, "rename ", 7)) {
+ /* rename file */
+ /* first param is the source path */
+ /* second param is the dest. path */
+ result = Curl_get_pathname(&cp, &sshc->quote_path2, sshc->homedir);
+ if(result) {
+ if(result == CURLE_OUT_OF_MEMORY)
+ failf(data, "Out of memory");
+ else
+ failf(data, "Syntax error in rename: Bad second parameter");
+ Curl_safefree(sshc->quote_path1);
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = result;
+ return;
+ }
+ state(conn, SSH_SFTP_QUOTE_RENAME);
+ return;
+ }
+ else if(strncasecompare(cmd, "rmdir ", 6)) {
+ /* delete dir */
+ state(conn, SSH_SFTP_QUOTE_RMDIR);
+ return;
+ }
+ else if(strncasecompare(cmd, "rm ", 3)) {
+ state(conn, SSH_SFTP_QUOTE_UNLINK);
+ return;
+ }
+#ifdef HAS_STATVFS_SUPPORT
+ else if(strncasecompare(cmd, "statvfs ", 8)) {
+ state(conn, SSH_SFTP_QUOTE_STATVFS);
+ return;
+ }
+#endif
+
+ failf(data, "Unknown SFTP command");
+ Curl_safefree(sshc->quote_path1);
+ Curl_safefree(sshc->quote_path2);
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+}
+
+static void sftp_quote_stat(struct connectdata *conn)
+{
+ struct Curl_easy *data = conn->data;
+ struct ssh_conn *sshc = &conn->proto.sshc;
+ char *cmd = sshc->quote_item->data;
+ sshc->acceptfail = FALSE;
+
+ /* if a command starts with an asterisk, which a legal SFTP command never
+ can, the command will be allowed to fail without it causing any
+ aborts or cancels etc. It will cause libcurl to act as if the command
+ is successful, whatever the server reponds. */
+
+ if(cmd[0] == '*') {
+ cmd++;
+ sshc->acceptfail = TRUE;
+ }
+
+ /* We read the file attributes, store them in sshc->quote_attrs
+ * and modify them accordingly to command. Then we switch to
+ * QUOTE_SETSTAT state to write new ones.
+ */
+
+ if(sshc->quote_attrs)
+ sftp_attributes_free(sshc->quote_attrs);
+ sshc->quote_attrs = sftp_stat(sshc->sftp_session, sshc->quote_path2);
+ if(sshc->quote_attrs == NULL) {
+ Curl_safefree(sshc->quote_path1);
+ Curl_safefree(sshc->quote_path2);
+ failf(data, "Attempt to get SFTP stats failed: %d",
+ sftp_get_error(sshc->sftp_session));
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ return;
+ }
+
+ /* Now set the new attributes... */
+ if(strncasecompare(cmd, "chgrp", 5)) {
+ sshc->quote_attrs->gid = (uint32_t)strtoul(sshc->quote_path1, NULL, 10);
+ if(sshc->quote_attrs->gid == 0 && !ISDIGIT(sshc->quote_path1[0]) &&
+ !sshc->acceptfail) {
+ Curl_safefree(sshc->quote_path1);
+ Curl_safefree(sshc->quote_path2);
+ failf(data, "Syntax error: chgrp gid not a number");
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ return;
+ }
+ sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_UIDGID;
+ }
+ else if(strncasecompare(cmd, "chmod", 5)) {
+ mode_t perms;
+ perms = (mode_t)strtoul(sshc->quote_path1, NULL, 8);
+ /* permissions are octal */
+ if(perms == 0 && !ISDIGIT(sshc->quote_path1[0])) {
+ Curl_safefree(sshc->quote_path1);
+ Curl_safefree(sshc->quote_path2);
+ failf(data, "Syntax error: chmod permissions not a number");
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ return;
+ }
+ sshc->quote_attrs->permissions = perms;
+ sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_PERMISSIONS;
+ }
+ else if(strncasecompare(cmd, "chown", 5)) {
+ sshc->quote_attrs->uid = (uint32_t)strtoul(sshc->quote_path1, NULL, 10);
+ if(sshc->quote_attrs->uid == 0 && !ISDIGIT(sshc->quote_path1[0]) &&
+ !sshc->acceptfail) {
+ Curl_safefree(sshc->quote_path1);
+ Curl_safefree(sshc->quote_path2);
+ failf(data, "Syntax error: chown uid not a number");
+ state(conn, SSH_SFTP_CLOSE);
+ sshc->nextstate = SSH_NO_STATE;
+ sshc->actualcode = CURLE_QUOTE_ERROR;
+ return;
+ }
+ sshc->quote_attrs->flags |= SSH_FILEXFER_ATTR_UIDGID;
+ }
+
+ /* Now send the completed structure... */
+ state(conn, SSH_SFTP_QUOTE_SETSTAT);
+ return;
+}
+
+
+#endif /* USE_LIBSSH */
diff --git a/Utilities/cmcurl/lib/urlapi-int.h b/Utilities/cmcurl/lib/urlapi-int.h
new file mode 100644
index 000000000..5f059c203
--- /dev/null
+++ b/Utilities/cmcurl/lib/urlapi-int.h
@@ -0,0 +1,37 @@
+#ifndef HEADER_CURL_URLAPI_INT_H
+#define HEADER_CURL_URLAPI_INT_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2019, 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"
+/* scheme is not URL encoded, the longest libcurl supported ones are... */
+#define MAX_SCHEME_LEN 40
+
+bool Curl_is_absolute_url(const char *url, char *scheme, size_t buflen);
+char *Curl_concat_url(const char *base, const char *relurl);
+size_t Curl_strlen_url(const char *url, bool relative);
+void Curl_strcpy_url(char *output, const char *url, bool relative);
+
+#ifdef DEBUGBUILD
+CURLUcode Curl_parse_port(struct Curl_URL *u, char *hostname);
+#endif
+
+#endif /* HEADER_CURL_URLAPI_INT_H */
diff --git a/Utilities/cmcurl/lib/urlapi.c b/Utilities/cmcurl/lib/urlapi.c
new file mode 100644
index 000000000..d07e4f5df
--- /dev/null
+++ b/Utilities/cmcurl/lib/urlapi.c
@@ -0,0 +1,1440 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2019, 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 "urldata.h"
+#include "urlapi-int.h"
+#include "strcase.h"
+#include "dotdot.h"
+#include "url.h"
+#include "escape.h"
+#include "curl_ctype.h"
+
+/* The last 3 #include files should be in this order */
+#include "curl_printf.h"
+#include "curl_memory.h"
+#include "memdebug.h"
+
+ /* 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] == ':'))
+
+ /* MSDOS/Windows style drive prefix, optionally with
+ * a '|' instead of ':', followed by a slash or NUL */
+#define STARTS_WITH_URL_DRIVE_PREFIX(str) \
+ ((('a' <= (str)[0] && (str)[0] <= 'z') || \
+ ('A' <= (str)[0] && (str)[0] <= 'Z')) && \
+ ((str)[1] == ':' || (str)[1] == '|') && \
+ ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0))
+
+/* Internal representation of CURLU. Point to URL-encoded strings. */
+struct Curl_URL {
+ char *scheme;
+ char *user;
+ char *password;
+ char *options; /* IMAP only? */
+ char *host;
+ char *zoneid; /* for numerical IPv6 addresses */
+ char *port;
+ char *path;
+ char *query;
+ char *fragment;
+
+ char *scratch; /* temporary scratch area */
+ long portnum; /* the numerical version */
+};
+
+#define DEFAULT_SCHEME "https"
+
+static void free_urlhandle(struct Curl_URL *u)
+{
+ free(u->scheme);
+ free(u->user);
+ free(u->password);
+ free(u->options);
+ free(u->host);
+ free(u->zoneid);
+ free(u->port);
+ free(u->path);
+ free(u->query);
+ free(u->fragment);
+ free(u->scratch);
+}
+
+/* move the full contents of one handle onto another and
+ free the original */
+static void mv_urlhandle(struct Curl_URL *from,
+ struct Curl_URL *to)
+{
+ free_urlhandle(to);
+ *to = *from;
+ free(from);
+}
+
+/*
+ * 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;
+}
+
+/*
+ * Decide in an encoding-independent manner whether a character in an
+ * URL must be escaped. The same criterion must be used in strlen_url()
+ * and strcpy_url().
+ */
+static bool urlchar_needs_escaping(int c)
+{
+ return !(ISCNTRL(c) || ISSPACE(c) || ISGRAPH(c));
+}
+
+/*
+ * 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, bool relative)
+{
+ const unsigned char *ptr;
+ 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;
+ }
+
+ switch(*ptr) {
+ case '?':
+ left = FALSE;
+ /* FALLTHROUGH */
+ default:
+ if(urlchar_needs_escaping(*ptr))
+ newlen += 2;
+ newlen++;
+ break;
+ case ' ':
+ if(left)
+ newlen += 3;
+ else
+ newlen++;
+ break;
+ }
+ }
+ return newlen;
+}
+
+/* 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, bool relative)
+{
+ /* we must add this with whitespace-replacing */
+ 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;
+ /* FALLTHROUGH */
+ default:
+ if(urlchar_needs_escaping(*iptr)) {
+ msnprintf(optr, 4, "%%%02x", *iptr);
+ optr += 3;
+ }
+ else
+ *optr++=*iptr;
+ break;
+ case ' ':
+ if(left) {
+ *optr++='%'; /* add a '%' */
+ *optr++='2'; /* add a '2' */
+ *optr++='0'; /* add a '0' */
+ }
+ else
+ *optr++='+'; /* add a '+' here */
+ break;
+ }
+ }
+ *optr = 0; /* zero terminate output buffer */
+
+}
+
+/*
+ * Returns true if the given URL is absolute (as opposed to relative) within
+ * the buffer size. Returns the scheme in the buffer if TRUE and 'buf' is
+ * non-NULL.
+ */
+bool Curl_is_absolute_url(const char *url, char *buf, size_t buflen)
+{
+ size_t i;
+#ifdef WIN32
+ if(STARTS_WITH_DRIVE_PREFIX(url))
+ return FALSE;
+#endif
+ for(i = 0; i < buflen && url[i]; ++i) {
+ char s = url[i];
+ if((s == ':') && (url[i + 1] == '/')) {
+ if(buf)
+ buf[i] = 0;
+ return TRUE;
+ }
+ /* RFC 3986 3.1 explains:
+ scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
+ */
+ else if(ISALNUM(s) || (s == '+') || (s == '-') || (s == '.') ) {
+ if(buf)
+ buf[i] = (char)TOLOWER(s);
+ }
+ else
+ break;
+ }
+ return FALSE;
+}
+
+/*
+ * Concatenate a relative URL to a base URL making it absolute.
+ * URL-encodes any spaces.
+ * The returned pointer must be freed by the caller unless NULL
+ * (returns NULL on out of memory).
+ */
+static char *concat_url(const char *base, const char *relurl)
+{
+ /***
+ TRY to append this new path to the old URL
+ to the right of the host part. Oh crap, this is doomed to cause
+ problems in the future...
+ */
+ char *newest;
+ 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);
+
+ if(!url_clone)
+ return NULL; /* skip out of this NOW */
+
+ /* protsep points to the start of the host name */
+ protsep = strstr(url_clone, "//");
+ if(!protsep)
+ protsep = url_clone;
+ else
+ protsep += 2; /* pass the slashes */
+
+ if('/' != relurl[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;
+
+ /* 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
+ '?') we append the new one at the end of the entire currently worked
+ out URL */
+ if(useurl[0] != '?') {
+ pathsep = strrchr(protsep, '/');
+ if(pathsep)
+ *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;
+ else
+ protsep = NULL;
+
+ /* now deal with one "./" or any amount of "../" in the newurl
+ and act accordingly */
+
+ if((useurl[0] == '.') && (useurl[1] == '/'))
+ useurl += 2; /* just skip the "./" */
+
+ while((useurl[0] == '.') &&
+ (useurl[1] == '.') &&
+ (useurl[2] == '/')) {
+ level++;
+ useurl += 3; /* pass the "../" */
+ }
+
+ if(protsep) {
+ while(level--) {
+ /* cut off one more level from the right of the original URL */
+ pathsep = strrchr(protsep, '/');
+ if(pathsep)
+ *pathsep = 0;
+ else {
+ *protsep = 0;
+ break;
+ }
+ }
+ }
+ }
+ else {
+ /* We got a new absolute path for this server */
+
+ if((relurl[0] == '/') && (relurl[1] == '/')) {
+ /* the new URL starts with //, just keep the protocol part from the
+ original one */
+ *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
+ without slash */
+ pathsep = strchr(protsep, '/');
+ if(pathsep) {
+ /* When people use badly formatted URLs, such as
+ "http://www.url.com?dir=/home/daniel" we must not use the first
+ slash, if there's a ?-letter before it! */
+ char *sep = strchr(protsep, '?');
+ if(sep && (sep < pathsep))
+ pathsep = sep;
+ *pathsep = 0;
+ }
+ else {
+ /* There was no slash. Now, since we might be operating on a badly
+ formatted URL, such as "http://www.url.com?id=2380" which doesn't
+ use a slash separator as it is supposed to, we need to check for a
+ ?-letter as well! */
+ pathsep = strchr(protsep, '?');
+ if(pathsep)
+ *pathsep = 0;
+ }
+ }
+ }
+
+ /* If the new part contains a space, this is a mighty stupid redirect
+ but we still make an effort to do "right". To the left of a '?'
+ letter we replace each space with %20 while it is replaced with '+'
+ on the right side of the '?' letter.
+ */
+ newlen = strlen_url(useurl, !host_changed);
+
+ urllen = strlen(url_clone);
+
+ newest = malloc(urllen + 1 + /* possible slash */
+ newlen + 1 /* zero byte */);
+
+ if(!newest) {
+ free(url_clone); /* don't leak this */
+ return NULL;
+ }
+
+ /* copy over the root url part */
+ memcpy(newest, url_clone, urllen);
+
+ /* check if we need to append a slash */
+ if(('/' == useurl[0]) || (protsep && !*protsep) || ('?' == useurl[0]))
+ ;
+ else
+ newest[urllen++]='/';
+
+ /* then append the new piece on the right side */
+ strcpy_url(&newest[urllen], useurl, !host_changed);
+
+ free(url_clone);
+
+ return newest;
+}
+
+/*
+ * parse_hostname_login()
+ *
+ * Parse the login details (user name, password and options) from the URL and
+ * strip them out of the host name
+ *
+ */
+static CURLUcode parse_hostname_login(struct Curl_URL *u,
+ const struct Curl_handler *h,
+ char **hostname,
+ unsigned int flags)
+{
+ CURLUcode result = CURLUE_OK;
+ CURLcode ccode;
+ char *userp = NULL;
+ char *passwdp = NULL;
+ char *optionsp = NULL;
+
+ /* At this point, we're hoping all the other special cases have
+ * been taken care of, so conn->host.name is at most
+ * [user[:password][;options]]@]hostname
+ *
+ * We need somewhere to put the embedded details, so do that first.
+ */
+
+ char *ptr = strchr(*hostname, '@');
+ char *login = *hostname;
+
+ if(!ptr)
+ goto out;
+
+ /* We will now try to extract the
+ * possible login information in a string like:
+ * ftp://user:password@ftp.my.site:8021/README */
+ *hostname = ++ptr;
+
+ /* We could use the login information in the URL so extract it. Only parse
+ options if the handler says we should. Note that 'h' might be NULL! */
+ ccode = Curl_parse_login_details(login, ptr - login - 1,
+ &userp, &passwdp,
+ (h && (h->flags & PROTOPT_URLOPTIONS)) ?
+ &optionsp:NULL);
+ if(ccode) {
+ result = CURLUE_MALFORMED_INPUT;
+ goto out;
+ }
+
+ if(userp) {
+ if(flags & CURLU_DISALLOW_USER) {
+ /* Option DISALLOW_USER is set and url contains username. */
+ result = CURLUE_USER_NOT_ALLOWED;
+ goto out;
+ }
+
+ u->user = userp;
+ }
+
+ if(passwdp)
+ u->password = passwdp;
+
+ if(optionsp)
+ u->options = optionsp;
+
+ return CURLUE_OK;
+ out:
+
+ free(userp);
+ free(passwdp);
+ free(optionsp);
+
+ return result;
+}
+
+UNITTEST CURLUcode Curl_parse_port(struct Curl_URL *u, char *hostname)
+{
+ char *portptr = NULL;
+ char endbracket;
+ int len;
+
+ /*
+ * Find the end of an IPv6 address, either on the ']' ending bracket or
+ * a percent-encoded zone index.
+ */
+ if(1 == sscanf(hostname, "[%*45[0123456789abcdefABCDEF:.]%c%n",
+ &endbracket, &len)) {
+ if(']' == endbracket)
+ portptr = &hostname[len];
+ else if('%' == endbracket) {
+ int zonelen = len;
+ if(1 == sscanf(hostname + zonelen, "%*[^]]%c%n", &endbracket, &len)) {
+ if(']' != endbracket)
+ return CURLUE_MALFORMED_INPUT;
+ portptr = &hostname[--zonelen + len + 1];
+ }
+ else
+ return CURLUE_MALFORMED_INPUT;
+ }
+ else
+ return CURLUE_MALFORMED_INPUT;
+
+ /* this is a RFC2732-style specified IP-address */
+ if(portptr && *portptr) {
+ if(*portptr != ':')
+ return CURLUE_MALFORMED_INPUT;
+ }
+ else
+ portptr = NULL;
+ }
+ else
+ portptr = strchr(hostname, ':');
+
+ if(portptr) {
+ char *rest;
+ long port;
+ char portbuf[7];
+
+ /* Browser behavior adaptation. If there's a colon with no digits after,
+ just cut off the name there which makes us ignore the colon and just
+ use the default port. Firefox, Chrome and Safari all do that. */
+ if(!portptr[1]) {
+ *portptr = '\0';
+ return CURLUE_OK;
+ }
+
+ if(!ISDIGIT(portptr[1]))
+ return CURLUE_BAD_PORT_NUMBER;
+
+ 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, but we don't
+ treat port zero as OK. */
+ return CURLUE_BAD_PORT_NUMBER;
+
+ if(rest[0])
+ return CURLUE_BAD_PORT_NUMBER;
+
+ *portptr++ = '\0'; /* cut off the name there */
+ *rest = 0;
+ /* generate a new port number string to get rid of leading zeroes etc */
+ msnprintf(portbuf, sizeof(portbuf), "%ld", port);
+ u->portnum = port;
+ u->port = strdup(portbuf);
+ if(!u->port)
+ return CURLUE_OUT_OF_MEMORY;
+ }
+
+ return CURLUE_OK;
+}
+
+/* scan for byte values < 31 or 127 */
+static CURLUcode junkscan(char *part)
+{
+ if(part) {
+ static const char badbytes[]={
+ /* */ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+ 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
+ 0x7f,
+ 0x00 /* zero terminate */
+ };
+ size_t n = strlen(part);
+ size_t nfine = strcspn(part, badbytes);
+ if(nfine != n)
+ /* since we don't know which part is scanned, return a generic error
+ code */
+ return CURLUE_MALFORMED_INPUT;
+ }
+ return CURLUE_OK;
+}
+
+static CURLUcode hostname_check(struct Curl_URL *u, char *hostname)
+{
+ const char *l = NULL; /* accepted characters */
+ size_t len;
+ size_t hlen = strlen(hostname);
+
+ if(hostname[0] == '[') {
+ hostname++;
+ l = "0123456789abcdefABCDEF::.";
+ hlen -= 2;
+ }
+
+ if(l) {
+ /* only valid letters are ok */
+ len = strspn(hostname, l);
+ if(hlen != len) {
+ if(hostname[len] == '%') {
+ /* this could now be '%[zone id]' */
+ char zoneid[16];
+ int i = 0;
+ char *h = &hostname[len + 1];
+ /* pass '25' if present and is a url encoded percent sign */
+ if(!strncmp(h, "25", 2) && h[2] && (h[2] != ']'))
+ h += 2;
+ while(*h && (*h != ']') && (i < 15))
+ zoneid[i++] = *h++;
+ if(!i || (']' != *h))
+ return CURLUE_MALFORMED_INPUT;
+ zoneid[i] = 0;
+ u->zoneid = strdup(zoneid);
+ if(!u->zoneid)
+ return CURLUE_OUT_OF_MEMORY;
+ hostname[len] = ']'; /* insert end bracket */
+ hostname[len + 1] = 0; /* terminate the hostname */
+ }
+ else
+ return CURLUE_MALFORMED_INPUT;
+ /* hostname is fine */
+ }
+ }
+ else {
+ /* letters from the second string is not ok */
+ len = strcspn(hostname, " ");
+ if(hlen != len)
+ /* hostname with bad content */
+ return CURLUE_MALFORMED_INPUT;
+ }
+ if(!hostname[0])
+ return CURLUE_NO_HOST;
+ return CURLUE_OK;
+}
+
+#define HOSTNAME_END(x) (((x) == '/') || ((x) == '?') || ((x) == '#'))
+
+static CURLUcode seturl(const char *url, CURLU *u, unsigned int flags)
+{
+ char *path;
+ bool path_alloced = FALSE;
+ char *hostname;
+ char *query = NULL;
+ char *fragment = NULL;
+ CURLUcode result;
+ bool url_has_scheme = FALSE;
+ char schemebuf[MAX_SCHEME_LEN + 1];
+ char *schemep = NULL;
+ size_t schemelen = 0;
+ size_t urllen;
+ const struct Curl_handler *h = NULL;
+
+ if(!url)
+ return CURLUE_MALFORMED_INPUT;
+
+ /*************************************************************
+ * Parse the URL.
+ ************************************************************/
+ /* allocate scratch area */
+ urllen = strlen(url);
+ if(urllen > CURL_MAX_INPUT_LENGTH)
+ /* excessive input length */
+ return CURLUE_MALFORMED_INPUT;
+
+ path = u->scratch = malloc(urllen * 2 + 2);
+ if(!path)
+ return CURLUE_OUT_OF_MEMORY;
+
+ hostname = &path[urllen + 1];
+ hostname[0] = 0;
+
+ if(Curl_is_absolute_url(url, schemebuf, sizeof(schemebuf))) {
+ url_has_scheme = TRUE;
+ schemelen = strlen(schemebuf);
+ }
+
+ /* handle the file: scheme */
+ if(url_has_scheme && strcasecompare(schemebuf, "file")) {
+ /* path has been allocated large enough to hold this */
+ strcpy(path, &url[5]);
+
+ hostname = NULL; /* no host for file: URLs */
+ u->scheme = strdup("file");
+ if(!u->scheme)
+ return CURLUE_OUT_OF_MEMORY;
+
+ /* Extra handling URLs with an authority component (i.e. that start with
+ * "file://")
+ *
+ * We allow omitted hostname (e.g. file:/<path>) -- valid according to
+ * RFC 8089, but not the (current) WHAT-WG URL spec.
+ */
+ if(path[0] == '/' && path[1] == '/') {
+ /* swallow the two slashes */
+ char *ptr = &path[2];
+
+ /*
+ * According to RFC 8089, a file: URL can be reliably dereferenced if:
+ *
+ * o it has no/blank hostname, or
+ *
+ * o the hostname matches "localhost" (case-insensitively), or
+ *
+ * o the hostname is a FQDN that resolves to this machine.
+ *
+ * For brevity, we only consider URLs with empty, "localhost", or
+ * "127.0.0.1" hostnames as local.
+ *
+ * Additionally, there is an exception for URLs with a Windows drive
+ * letter in the authority (which was accidentally omitted from RFC 8089
+ * Appendix E, but believe me, it was meant to be there. --MK)
+ */
+ if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) {
+ /* the URL includes a host name, it must match "localhost" or
+ "127.0.0.1" to be valid */
+ if(!checkprefix("localhost/", ptr) &&
+ !checkprefix("127.0.0.1/", ptr)) {
+ /* Invalid file://hostname/, expected localhost or 127.0.0.1 or
+ none */
+ return CURLUE_MALFORMED_INPUT;
+ }
+ ptr += 9; /* now points to the slash after the host */
+ }
+
+ path = ptr;
+ }
+
+#if !defined(MSDOS) && !defined(WIN32) && !defined(__CYGWIN__)
+ /* Don't allow Windows drive letters when not in Windows.
+ * This catches both "file:/c:" and "file:c:" */
+ if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
+ STARTS_WITH_URL_DRIVE_PREFIX(path)) {
+ /* File drive letters are only accepted in MSDOS/Windows */
+ return CURLUE_MALFORMED_INPUT;
+ }
+#else
+ /* If the path starts with a slash and a drive letter, ditch the slash */
+ if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) {
+ /* This cannot be done with strcpy, as the memory chunks overlap! */
+ memmove(path, &path[1], strlen(&path[1]) + 1);
+ }
+#endif
+
+ }
+ else {
+ /* clear path */
+ const char *p;
+ const char *hostp;
+ size_t len;
+ path[0] = 0;
+
+ if(url_has_scheme) {
+ int i = 0;
+ p = &url[schemelen + 1];
+ while(p && (*p == '/') && (i < 4)) {
+ p++;
+ i++;
+ }
+ if((i < 1) || (i>3))
+ /* less than one or more than three slashes */
+ return CURLUE_MALFORMED_INPUT;
+
+ schemep = schemebuf;
+ if(!Curl_builtin_scheme(schemep) &&
+ !(flags & CURLU_NON_SUPPORT_SCHEME))
+ return CURLUE_UNSUPPORTED_SCHEME;
+
+ if(junkscan(schemep))
+ return CURLUE_MALFORMED_INPUT;
+ }
+ else {
+ /* no scheme! */
+
+ if(!(flags & (CURLU_DEFAULT_SCHEME|CURLU_GUESS_SCHEME)))
+ return CURLUE_MALFORMED_INPUT;
+ if(flags & CURLU_DEFAULT_SCHEME)
+ schemep = (char *) DEFAULT_SCHEME;
+
+ /*
+ * The URL was badly formatted, let's try without scheme specified.
+ */
+ p = url;
+ }
+ hostp = p; /* host name starts here */
+
+ while(*p && !HOSTNAME_END(*p)) /* find end of host name */
+ p++;
+
+ len = p - hostp;
+ if(!len)
+ return CURLUE_MALFORMED_INPUT;
+
+ memcpy(hostname, hostp, len);
+ hostname[len] = 0;
+
+ if((flags & CURLU_GUESS_SCHEME) && !schemep) {
+ /* legacy curl-style guess based on host name */
+ if(checkprefix("ftp.", hostname))
+ schemep = (char *)"ftp";
+ else if(checkprefix("dict.", hostname))
+ schemep = (char *)"dict";
+ else if(checkprefix("ldap.", hostname))
+ schemep = (char *)"ldap";
+ else if(checkprefix("imap.", hostname))
+ schemep = (char *)"imap";
+ else if(checkprefix("smtp.", hostname))
+ schemep = (char *)"smtp";
+ else if(checkprefix("pop3.", hostname))
+ schemep = (char *)"pop3";
+ else
+ schemep = (char *)"http";
+ }
+
+ len = strlen(p);
+ memcpy(path, p, len);
+ path[len] = 0;
+
+ u->scheme = strdup(schemep);
+ if(!u->scheme)
+ return CURLUE_OUT_OF_MEMORY;
+ }
+
+ /* if this is a known scheme, get some details */
+ h = Curl_builtin_scheme(u->scheme);
+
+ if(junkscan(path))
+ return CURLUE_MALFORMED_INPUT;
+
+ query = strchr(path, '?');
+ if(query)
+ *query++ = 0;
+
+ fragment = strchr(query?query:path, '#');
+ if(fragment)
+ *fragment++ = 0;
+
+ if(!path[0])
+ /* if there's no path set, unset */
+ path = NULL;
+ else if(!(flags & CURLU_PATH_AS_IS)) {
+ /* sanitise paths and remove ../ and ./ sequences according to RFC3986 */
+ char *newp = Curl_dedotdotify(path);
+ if(!newp)
+ return CURLUE_OUT_OF_MEMORY;
+
+ if(strcmp(newp, path)) {
+ /* if we got a new version */
+ path = newp;
+ path_alloced = TRUE;
+ }
+ else
+ free(newp);
+ }
+ if(path) {
+ u->path = path_alloced?path:strdup(path);
+ if(!u->path)
+ return CURLUE_OUT_OF_MEMORY;
+ }
+
+ if(hostname) {
+ /*
+ * Parse the login details and strip them out of the host name.
+ */
+ if(junkscan(hostname))
+ return CURLUE_MALFORMED_INPUT;
+
+ result = parse_hostname_login(u, h, &hostname, flags);
+ if(result)
+ return result;
+
+ result = Curl_parse_port(u, hostname);
+ if(result)
+ return result;
+
+ result = hostname_check(u, hostname);
+ if(result)
+ return result;
+
+ u->host = strdup(hostname);
+ if(!u->host)
+ return CURLUE_OUT_OF_MEMORY;
+ }
+
+ if(query) {
+ u->query = strdup(query);
+ if(!u->query)
+ return CURLUE_OUT_OF_MEMORY;
+ }
+ if(fragment && fragment[0]) {
+ u->fragment = strdup(fragment);
+ if(!u->fragment)
+ return CURLUE_OUT_OF_MEMORY;
+ }
+
+ free(u->scratch);
+ u->scratch = NULL;
+
+ return CURLUE_OK;
+}
+
+/*
+ * Parse the URL and set the relevant members of the Curl_URL struct.
+ */
+static CURLUcode parseurl(const char *url, CURLU *u, unsigned int flags)
+{
+ CURLUcode result = seturl(url, u, flags);
+ if(result) {
+ free_urlhandle(u);
+ memset(u, 0, sizeof(struct Curl_URL));
+ }
+ return result;
+}
+
+/*
+ */
+CURLU *curl_url(void)
+{
+ return calloc(sizeof(struct Curl_URL), 1);
+}
+
+void curl_url_cleanup(CURLU *u)
+{
+ if(u) {
+ free_urlhandle(u);
+ free(u);
+ }
+}
+
+#define DUP(dest, src, name) \
+ if(src->name) { \
+ dest->name = strdup(src->name); \
+ if(!dest->name) \
+ goto fail; \
+ }
+
+CURLU *curl_url_dup(CURLU *in)
+{
+ struct Curl_URL *u = calloc(sizeof(struct Curl_URL), 1);
+ if(u) {
+ DUP(u, in, scheme);
+ DUP(u, in, user);
+ DUP(u, in, password);
+ DUP(u, in, options);
+ DUP(u, in, host);
+ DUP(u, in, port);
+ DUP(u, in, path);
+ DUP(u, in, query);
+ DUP(u, in, fragment);
+ u->portnum = in->portnum;
+ }
+ return u;
+ fail:
+ curl_url_cleanup(u);
+ return NULL;
+}
+
+CURLUcode curl_url_get(CURLU *u, CURLUPart what,
+ char **part, unsigned int flags)
+{
+ char *ptr;
+ CURLUcode ifmissing = CURLUE_UNKNOWN_PART;
+ char portbuf[7];
+ bool urldecode = (flags & CURLU_URLDECODE)?1:0;
+ bool plusdecode = FALSE;
+ (void)flags;
+ if(!u)
+ return CURLUE_BAD_HANDLE;
+ if(!part)
+ return CURLUE_BAD_PARTPOINTER;
+ *part = NULL;
+
+ switch(what) {
+ case CURLUPART_SCHEME:
+ ptr = u->scheme;
+ ifmissing = CURLUE_NO_SCHEME;
+ urldecode = FALSE; /* never for schemes */
+ break;
+ case CURLUPART_USER:
+ ptr = u->user;
+ ifmissing = CURLUE_NO_USER;
+ break;
+ case CURLUPART_PASSWORD:
+ ptr = u->password;
+ ifmissing = CURLUE_NO_PASSWORD;
+ break;
+ case CURLUPART_OPTIONS:
+ ptr = u->options;
+ ifmissing = CURLUE_NO_OPTIONS;
+ break;
+ case CURLUPART_HOST:
+ ptr = u->host;
+ ifmissing = CURLUE_NO_HOST;
+ break;
+ case CURLUPART_ZONEID:
+ ptr = u->zoneid;
+ break;
+ case CURLUPART_PORT:
+ ptr = u->port;
+ ifmissing = CURLUE_NO_PORT;
+ urldecode = FALSE; /* never for port */
+ if(!ptr && (flags & CURLU_DEFAULT_PORT) && u->scheme) {
+ /* there's no stored port number, but asked to deliver
+ a default one for the scheme */
+ const struct Curl_handler *h =
+ Curl_builtin_scheme(u->scheme);
+ if(h) {
+ msnprintf(portbuf, sizeof(portbuf), "%ld", h->defport);
+ ptr = portbuf;
+ }
+ }
+ else if(ptr && u->scheme) {
+ /* there is a stored port number, but ask to inhibit if
+ it matches the default one for the scheme */
+ const struct Curl_handler *h =
+ Curl_builtin_scheme(u->scheme);
+ if(h && (h->defport == u->portnum) &&
+ (flags & CURLU_NO_DEFAULT_PORT))
+ ptr = NULL;
+ }
+ break;
+ case CURLUPART_PATH:
+ ptr = u->path;
+ if(!ptr) {
+ ptr = u->path = strdup("/");
+ if(!u->path)
+ return CURLUE_OUT_OF_MEMORY;
+ }
+ break;
+ case CURLUPART_QUERY:
+ ptr = u->query;
+ ifmissing = CURLUE_NO_QUERY;
+ plusdecode = urldecode;
+ break;
+ case CURLUPART_FRAGMENT:
+ ptr = u->fragment;
+ ifmissing = CURLUE_NO_FRAGMENT;
+ break;
+ case CURLUPART_URL: {
+ char *url;
+ char *scheme;
+ char *options = u->options;
+ char *port = u->port;
+ char *allochost = NULL;
+ if(u->scheme && strcasecompare("file", u->scheme)) {
+ url = aprintf("file://%s%s%s",
+ u->path,
+ u->fragment? "#": "",
+ u->fragment? u->fragment : "");
+ }
+ else if(!u->host)
+ return CURLUE_NO_HOST;
+ else {
+ const struct Curl_handler *h = NULL;
+ if(u->scheme)
+ scheme = u->scheme;
+ else if(flags & CURLU_DEFAULT_SCHEME)
+ scheme = (char *) DEFAULT_SCHEME;
+ else
+ return CURLUE_NO_SCHEME;
+
+ if(scheme) {
+ h = Curl_builtin_scheme(scheme);
+ if(!port && (flags & CURLU_DEFAULT_PORT)) {
+ /* there's no stored port number, but asked to deliver
+ a default one for the scheme */
+ if(h) {
+ msnprintf(portbuf, sizeof(portbuf), "%ld", h->defport);
+ port = portbuf;
+ }
+ }
+ else if(port) {
+ /* there is a stored port number, but asked to inhibit if it matches
+ the default one for the scheme */
+ if(h && (h->defport == u->portnum) &&
+ (flags & CURLU_NO_DEFAULT_PORT))
+ port = NULL;
+ }
+ }
+ if(h && !(h->flags & PROTOPT_URLOPTIONS))
+ options = NULL;
+
+ if((u->host[0] == '[') && u->zoneid) {
+ /* make it '[ host %25 zoneid ]' */
+ size_t hostlen = strlen(u->host);
+ size_t alen = hostlen + 3 + strlen(u->zoneid) + 1;
+ allochost = malloc(alen);
+ if(!allochost)
+ return CURLUE_OUT_OF_MEMORY;
+ memcpy(allochost, u->host, hostlen - 1);
+ msnprintf(&allochost[hostlen - 1], alen - hostlen + 1,
+ "%%25%s]", u->zoneid);
+ }
+
+ url = aprintf("%s://%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
+ scheme,
+ u->user ? u->user : "",
+ u->password ? ":": "",
+ u->password ? u->password : "",
+ options ? ";" : "",
+ options ? options : "",
+ (u->user || u->password || options) ? "@": "",
+ allochost ? allochost : u->host,
+ port ? ":": "",
+ port ? port : "",
+ (u->path && (u->path[0] != '/')) ? "/": "",
+ u->path ? u->path : "/",
+ (u->query && u->query[0]) ? "?": "",
+ (u->query && u->query[0]) ? u->query : "",
+ u->fragment? "#": "",
+ u->fragment? u->fragment : "");
+ free(allochost);
+ }
+ if(!url)
+ return CURLUE_OUT_OF_MEMORY;
+ *part = url;
+ return CURLUE_OK;
+ }
+ default:
+ ptr = NULL;
+ break;
+ }
+ if(ptr) {
+ *part = strdup(ptr);
+ if(!*part)
+ return CURLUE_OUT_OF_MEMORY;
+ if(plusdecode) {
+ /* convert + to space */
+ char *plus;
+ for(plus = *part; *plus; ++plus) {
+ if(*plus == '+')
+ *plus = ' ';
+ }
+ }
+ if(urldecode) {
+ char *decoded;
+ size_t dlen;
+ CURLcode res = Curl_urldecode(NULL, *part, 0, &decoded, &dlen, TRUE);
+ free(*part);
+ if(res) {
+ *part = NULL;
+ return CURLUE_URLDECODE;
+ }
+ *part = decoded;
+ }
+ return CURLUE_OK;
+ }
+ else
+ return ifmissing;
+}
+
+CURLUcode curl_url_set(CURLU *u, CURLUPart what,
+ const char *part, unsigned int flags)
+{
+ char **storep = NULL;
+ long port = 0;
+ bool urlencode = (flags & CURLU_URLENCODE)? 1 : 0;
+ bool plusencode = FALSE;
+ bool urlskipslash = FALSE;
+ bool appendquery = FALSE;
+ bool equalsencode = FALSE;
+
+ if(!u)
+ return CURLUE_BAD_HANDLE;
+ if(!part) {
+ /* setting a part to NULL clears it */
+ switch(what) {
+ case CURLUPART_URL:
+ break;
+ case CURLUPART_SCHEME:
+ storep = &u->scheme;
+ break;
+ case CURLUPART_USER:
+ storep = &u->user;
+ break;
+ case CURLUPART_PASSWORD:
+ storep = &u->password;
+ break;
+ case CURLUPART_OPTIONS:
+ storep = &u->options;
+ break;
+ case CURLUPART_HOST:
+ storep = &u->host;
+ break;
+ case CURLUPART_ZONEID:
+ storep = &u->zoneid;
+ break;
+ case CURLUPART_PORT:
+ u->portnum = 0;
+ storep = &u->port;
+ break;
+ case CURLUPART_PATH:
+ storep = &u->path;
+ break;
+ case CURLUPART_QUERY:
+ storep = &u->query;
+ break;
+ case CURLUPART_FRAGMENT:
+ storep = &u->fragment;
+ break;
+ default:
+ return CURLUE_UNKNOWN_PART;
+ }
+ if(storep && *storep) {
+ free(*storep);
+ *storep = NULL;
+ }
+ return CURLUE_OK;
+ }
+
+ switch(what) {
+ case CURLUPART_SCHEME:
+ if(strlen(part) > MAX_SCHEME_LEN)
+ /* too long */
+ return CURLUE_MALFORMED_INPUT;
+ if(!(flags & CURLU_NON_SUPPORT_SCHEME) &&
+ /* verify that it is a fine scheme */
+ !Curl_builtin_scheme(part))
+ return CURLUE_UNSUPPORTED_SCHEME;
+ storep = &u->scheme;
+ urlencode = FALSE; /* never */
+ break;
+ case CURLUPART_USER:
+ storep = &u->user;
+ break;
+ case CURLUPART_PASSWORD:
+ storep = &u->password;
+ break;
+ case CURLUPART_OPTIONS:
+ storep = &u->options;
+ break;
+ case CURLUPART_HOST:
+ storep = &u->host;
+ free(u->zoneid);
+ u->zoneid = NULL;
+ break;
+ case CURLUPART_ZONEID:
+ storep = &u->zoneid;
+ break;
+ case CURLUPART_PORT:
+ {
+ char *endp;
+ urlencode = FALSE; /* never */
+ port = strtol(part, &endp, 10); /* Port number must be decimal */
+ if((port <= 0) || (port > 0xffff))
+ return CURLUE_BAD_PORT_NUMBER;
+ if(*endp)
+ /* weirdly provided number, not good! */
+ return CURLUE_MALFORMED_INPUT;
+ storep = &u->port;
+ }
+ break;
+ case CURLUPART_PATH:
+ urlskipslash = TRUE;
+ storep = &u->path;
+ break;
+ case CURLUPART_QUERY:
+ plusencode = urlencode;
+ appendquery = (flags & CURLU_APPENDQUERY)?1:0;
+ equalsencode = appendquery;
+ storep = &u->query;
+ break;
+ case CURLUPART_FRAGMENT:
+ storep = &u->fragment;
+ break;
+ case CURLUPART_URL: {
+ /*
+ * Allow a new URL to replace the existing (if any) contents.
+ *
+ * If the existing contents is enough for a URL, allow a relative URL to
+ * replace it.
+ */
+ CURLUcode result;
+ char *oldurl;
+ char *redired_url;
+ CURLU *handle2;
+
+ if(Curl_is_absolute_url(part, NULL, MAX_SCHEME_LEN + 1)) {
+ handle2 = curl_url();
+ if(!handle2)
+ return CURLUE_OUT_OF_MEMORY;
+ result = parseurl(part, handle2, flags);
+ if(!result)
+ mv_urlhandle(handle2, u);
+ else
+ curl_url_cleanup(handle2);
+ return result;
+ }
+ /* extract the full "old" URL to do the redirect on */
+ result = curl_url_get(u, CURLUPART_URL, &oldurl, flags);
+ if(result) {
+ /* couldn't get the old URL, just use the new! */
+ handle2 = curl_url();
+ if(!handle2)
+ return CURLUE_OUT_OF_MEMORY;
+ result = parseurl(part, handle2, flags);
+ if(!result)
+ mv_urlhandle(handle2, u);
+ else
+ curl_url_cleanup(handle2);
+ return result;
+ }
+
+ /* apply the relative part to create a new URL */
+ redired_url = concat_url(oldurl, part);
+ free(oldurl);
+ if(!redired_url)
+ return CURLUE_OUT_OF_MEMORY;
+
+ /* now parse the new URL */
+ handle2 = curl_url();
+ if(!handle2) {
+ free(redired_url);
+ return CURLUE_OUT_OF_MEMORY;
+ }
+ result = parseurl(redired_url, handle2, flags);
+ free(redired_url);
+ if(!result)
+ mv_urlhandle(handle2, u);
+ else
+ curl_url_cleanup(handle2);
+ return result;
+ }
+ default:
+ return CURLUE_UNKNOWN_PART;
+ }
+ if(storep) {
+ const char *newp = part;
+ size_t nalloc = strlen(part);
+
+ if(nalloc > CURL_MAX_INPUT_LENGTH)
+ /* excessive input length */
+ return CURLUE_MALFORMED_INPUT;
+
+ if(urlencode) {
+ const unsigned char *i;
+ char *o;
+ bool free_part = FALSE;
+ char *enc = malloc(nalloc * 3 + 1); /* for worst case! */
+ if(!enc)
+ return CURLUE_OUT_OF_MEMORY;
+ if(plusencode) {
+ /* space to plus */
+ i = (const unsigned char *)part;
+ for(o = enc; *i; ++o, ++i)
+ *o = (*i == ' ') ? '+' : *i;
+ *o = 0; /* zero terminate */
+ part = strdup(enc);
+ if(!part) {
+ free(enc);
+ return CURLUE_OUT_OF_MEMORY;
+ }
+ free_part = TRUE;
+ }
+ for(i = (const unsigned char *)part, o = enc; *i; i++) {
+ if(Curl_isunreserved(*i) ||
+ ((*i == '/') && urlskipslash) ||
+ ((*i == '=') && equalsencode) ||
+ ((*i == '+') && plusencode)) {
+ if((*i == '=') && equalsencode)
+ /* only skip the first equals sign */
+ equalsencode = FALSE;
+ *o = *i;
+ o++;
+ }
+ else {
+ msnprintf(o, 4, "%%%02x", *i);
+ o += 3;
+ }
+ }
+ *o = 0; /* zero terminate */
+ newp = enc;
+ if(free_part)
+ free((char *)part);
+ }
+ else {
+ char *p;
+ newp = strdup(part);
+ if(!newp)
+ return CURLUE_OUT_OF_MEMORY;
+ p = (char *)newp;
+ while(*p) {
+ /* make sure percent encoded are lower case */
+ if((*p == '%') && ISXDIGIT(p[1]) && ISXDIGIT(p[2]) &&
+ (ISUPPER(p[1]) || ISUPPER(p[2]))) {
+ p[1] = (char)TOLOWER(p[1]);
+ p[2] = (char)TOLOWER(p[2]);
+ p += 3;
+ }
+ else
+ p++;
+ }
+ }
+
+ if(appendquery) {
+ /* Append the string onto the old query. Add a '&' separator if none is
+ present at the end of the exsting query already */
+ size_t querylen = u->query ? strlen(u->query) : 0;
+ bool addamperand = querylen && (u->query[querylen -1] != '&');
+ if(querylen) {
+ size_t newplen = strlen(newp);
+ char *p = malloc(querylen + addamperand + newplen + 1);
+ if(!p) {
+ free((char *)newp);
+ return CURLUE_OUT_OF_MEMORY;
+ }
+ strcpy(p, u->query); /* original query */
+ if(addamperand)
+ p[querylen] = '&'; /* ampersand */
+ strcpy(&p[querylen + addamperand], newp); /* new suffix */
+ free((char *)newp);
+ free(*storep);
+ *storep = p;
+ return CURLUE_OK;
+ }
+ }
+
+ if(what == CURLUPART_HOST) {
+ if(hostname_check(u, (char *)newp)) {
+ free((char *)newp);
+ return CURLUE_MALFORMED_INPUT;
+ }
+ }
+
+ free(*storep);
+ *storep = (char *)newp;
+ }
+ /* set after the string, to make it not assigned if the allocation above
+ fails */
+ if(port)
+ u->portnum = port;
+ return CURLUE_OK;
+}
diff --git a/Utilities/cmcurl/lib/vtls/mesalink.c b/Utilities/cmcurl/lib/vtls/mesalink.c
new file mode 100644
index 000000000..718c282ee
--- /dev/null
+++ b/Utilities/cmcurl/lib/vtls/mesalink.c
@@ -0,0 +1,627 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2017 - 2018, Yiming Jing, <jingyiming@baidu.com>
+ * Copyright (C) 1998 - 2018, 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.
+ *
+ ***************************************************************************/
+
+/*
+ * Source file for all MesaLink-specific code for the TLS/SSL layer. No code
+ * but vtls.c should ever call or use these functions.
+ *
+ */
+
+/*
+ * Based upon the CyaSSL implementation in cyassl.c and cyassl.h:
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * Thanks for code and inspiration!
+ */
+
+#include "curl_setup.h"
+
+#ifdef USE_MESALINK
+
+#include <mesalink/options.h>
+#include <mesalink/version.h>
+
+#include "urldata.h"
+#include "sendf.h"
+#include "inet_pton.h"
+#include "vtls.h"
+#include "parsedate.h"
+#include "connect.h" /* for the connect timeout */
+#include "select.h"
+#include "strcase.h"
+#include "x509asn1.h"
+#include "curl_printf.h"
+
+#include "mesalink.h"
+#include <mesalink/openssl/ssl.h>
+#include <mesalink/openssl/err.h>
+
+/* The last #include files should be: */
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#define MESALINK_MAX_ERROR_SZ 80
+
+struct ssl_backend_data
+{
+ SSL_CTX *ctx;
+ SSL *handle;
+};
+
+#define BACKEND connssl->backend
+
+static Curl_recv mesalink_recv;
+static Curl_send mesalink_send;
+
+/*
+ * This function loads all the client/CA certificates and CRLs. Setup the TLS
+ * layer and do all necessary magic.
+ */
+static CURLcode
+mesalink_connect_step1(struct connectdata *conn, int sockindex)
+{
+ char *ciphers;
+ struct Curl_easy *data = conn->data;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
+ const char *const ssl_cafile = SSL_CONN_CONFIG(CAfile);
+ const char *const ssl_capath = SSL_CONN_CONFIG(CApath);
+ struct in_addr addr4;
+#ifdef ENABLE_IPV6
+ struct in6_addr addr6;
+#endif
+ const char *const hostname =
+ SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name;
+ size_t hostname_len = strlen(hostname);
+
+ SSL_METHOD *req_method = NULL;
+ curl_socket_t sockfd = conn->sock[sockindex];
+
+ if(connssl->state == ssl_connection_complete)
+ return CURLE_OK;
+
+ if(SSL_CONN_CONFIG(version_max) != CURL_SSLVERSION_MAX_NONE) {
+ failf(data, "MesaLink does not support to set maximum SSL/TLS version");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+
+ switch(SSL_CONN_CONFIG(version)) {
+ case CURL_SSLVERSION_SSLv3:
+ case CURL_SSLVERSION_TLSv1:
+ case CURL_SSLVERSION_TLSv1_0:
+ case CURL_SSLVERSION_TLSv1_1:
+ failf(data, "MesaLink does not support SSL 3.0, TLS 1.0, or TLS 1.1");
+ return CURLE_NOT_BUILT_IN;
+ case CURL_SSLVERSION_DEFAULT:
+ case CURL_SSLVERSION_TLSv1_2:
+ req_method = TLSv1_2_client_method();
+ break;
+ case CURL_SSLVERSION_TLSv1_3:
+ req_method = TLSv1_3_client_method();
+ break;
+ case CURL_SSLVERSION_SSLv2:
+ failf(data, "MesaLink does not support SSLv2");
+ return CURLE_SSL_CONNECT_ERROR;
+ default:
+ failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+
+ if(!req_method) {
+ failf(data, "SSL: couldn't create a method!");
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ if(BACKEND->ctx)
+ SSL_CTX_free(BACKEND->ctx);
+ BACKEND->ctx = SSL_CTX_new(req_method);
+
+ if(!BACKEND->ctx) {
+ failf(data, "SSL: couldn't create a context!");
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ SSL_CTX_set_verify(
+ BACKEND->ctx, verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
+
+ if(ssl_cafile || ssl_capath) {
+ if(!SSL_CTX_load_verify_locations(BACKEND->ctx, ssl_cafile, ssl_capath)) {
+ if(verifypeer) {
+ failf(data,
+ "error setting certificate verify locations:\n"
+ " CAfile: %s\n CApath: %s",
+ ssl_cafile ? ssl_cafile : "none",
+ ssl_capath ? ssl_capath : "none");
+ return CURLE_SSL_CACERT_BADFILE;
+ }
+ infof(data,
+ "error setting certificate verify locations,"
+ " continuing anyway:\n");
+ }
+ else {
+ infof(data, "successfully set certificate verify locations:\n");
+ }
+ infof(data,
+ " CAfile: %s\n"
+ " CApath: %s\n",
+ ssl_cafile ? ssl_cafile : "none",
+ ssl_capath ? ssl_capath : "none");
+ }
+
+ ciphers = SSL_CONN_CONFIG(cipher_list);
+ if(ciphers) {
+#ifdef MESALINK_HAVE_CIPHER
+ if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) {
+ failf(data, "failed setting cipher list: %s", ciphers);
+ return CURLE_SSL_CIPHER;
+ }
+#endif
+ infof(data, "Cipher selection: %s\n", ciphers);
+ }
+
+ 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;
+ }
+
+ if((hostname_len < USHRT_MAX) &&
+ (0 == Curl_inet_pton(AF_INET, hostname, &addr4))
+#ifdef ENABLE_IPV6
+ && (0 == Curl_inet_pton(AF_INET6, hostname, &addr6))
+#endif
+ ) {
+ /* hostname is not a valid IP address */
+ if(SSL_set_tlsext_host_name(BACKEND->handle, hostname) != SSL_SUCCESS) {
+ failf(data,
+ "WARNING: failed to configure server name indication (SNI) "
+ "TLS extension\n");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ }
+ else {
+#ifdef CURLDEBUG
+ /* Check if the hostname is 127.0.0.1 or [::1];
+ * otherwise reject because MesaLink always wants a valid DNS Name
+ * specified in RFC 5280 Section 7.2 */
+ if(strncmp(hostname, "127.0.0.1", 9) == 0
+#ifdef ENABLE_IPV6
+ || strncmp(hostname, "[::1]", 5) == 0
+#endif
+ ) {
+ SSL_set_tlsext_host_name(BACKEND->handle, "localhost");
+ }
+ else
+#endif
+ {
+ failf(data,
+ "ERROR: MesaLink does not accept an IP address as a hostname\n");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ }
+
+#ifdef MESALINK_HAVE_SESSION
+ if(SSL_SET_OPTION(primary.sessionid)) {
+ void *ssl_sessionid = NULL;
+
+ 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(BACKEND->handle, ssl_sessionid)) {
+ Curl_ssl_sessionid_unlock(conn);
+ failf(
+ data,
+ "SSL: SSL_set_session failed: %s",
+ ERR_error_string(SSL_get_error(BACKEND->handle, 0), error_buffer));
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ /* Informational message */
+ infof(data, "SSL re-using session ID\n");
+ }
+ Curl_ssl_sessionid_unlock(conn);
+ }
+#endif /* MESALINK_HAVE_SESSION */
+
+ if(SSL_set_fd(BACKEND->handle, (int)sockfd) != SSL_SUCCESS) {
+ failf(data, "SSL: SSL_set_fd failed");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+
+ connssl->connecting_state = ssl_connect_2;
+ return CURLE_OK;
+}
+
+static CURLcode
+mesalink_connect_step2(struct connectdata *conn, int sockindex)
+{
+ int ret = -1;
+ struct Curl_easy *data = conn->data;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+
+ conn->recv[sockindex] = mesalink_recv;
+ conn->send[sockindex] = mesalink_send;
+
+ ret = SSL_connect(BACKEND->handle);
+ if(ret != SSL_SUCCESS) {
+ char error_buffer[MESALINK_MAX_ERROR_SZ];
+ int detail = SSL_get_error(BACKEND->handle, ret);
+
+ if(SSL_ERROR_WANT_CONNECT == detail || SSL_ERROR_WANT_READ == detail) {
+ connssl->connecting_state = ssl_connect_2_reading;
+ return CURLE_OK;
+ }
+ else {
+ failf(data,
+ "SSL_connect failed with error %d: %s",
+ detail,
+ ERR_error_string_n(detail, error_buffer, sizeof(error_buffer)));
+ ERR_print_errors_fp(stderr);
+ if(detail && SSL_CONN_CONFIG(verifypeer)) {
+ detail &= ~0xFF;
+ if(detail == TLS_ERROR_WEBPKI_ERRORS) {
+ failf(data, "Cert verify failed");
+ return CURLE_PEER_FAILED_VERIFICATION;
+ }
+ }
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ }
+
+ connssl->connecting_state = ssl_connect_3;
+ infof(data,
+ "SSL connection using %s / %s\n",
+ SSL_get_version(BACKEND->handle),
+ SSL_get_cipher_name(BACKEND->handle));
+
+ return CURLE_OK;
+}
+
+static CURLcode
+mesalink_connect_step3(struct connectdata *conn, int sockindex)
+{
+ CURLcode result = CURLE_OK;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+
+ DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
+
+#ifdef MESALINK_HAVE_SESSION
+ if(SSL_SET_OPTION(primary.sessionid)) {
+ bool incache;
+ SSL_SESSION *our_ssl_sessionid;
+ void *old_ssl_sessionid = NULL;
+
+ our_ssl_sessionid = SSL_get_session(BACKEND->handle);
+
+ Curl_ssl_sessionid_lock(conn);
+ incache =
+ !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL, sockindex));
+ if(incache) {
+ if(old_ssl_sessionid != our_ssl_sessionid) {
+ infof(data, "old SSL session ID is stale, removing\n");
+ Curl_ssl_delsessionid(conn, old_ssl_sessionid);
+ incache = FALSE;
+ }
+ }
+
+ if(!incache) {
+ result = Curl_ssl_addsessionid(
+ conn, our_ssl_sessionid, 0 /* unknown size */, sockindex);
+ if(result) {
+ Curl_ssl_sessionid_unlock(conn);
+ failf(data, "failed to store ssl session");
+ return result;
+ }
+ }
+ Curl_ssl_sessionid_unlock(conn);
+ }
+#endif /* MESALINK_HAVE_SESSION */
+
+ connssl->connecting_state = ssl_connect_done;
+
+ return result;
+}
+
+static ssize_t
+mesalink_send(struct connectdata *conn, int sockindex, const void *mem,
+ size_t len, CURLcode *curlcode)
+{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ char error_buffer[MESALINK_MAX_ERROR_SZ];
+ int memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
+ int rc = SSL_write(BACKEND->handle, mem, memlen);
+
+ if(rc < 0) {
+ int err = SSL_get_error(BACKEND->handle, rc);
+ switch(err) {
+ case SSL_ERROR_WANT_READ:
+ case SSL_ERROR_WANT_WRITE:
+ /* there's data pending, re-invoke SSL_write() */
+ *curlcode = CURLE_AGAIN;
+ return -1;
+ default:
+ failf(conn->data,
+ "SSL write: %s, errno %d",
+ ERR_error_string_n(err, error_buffer, sizeof(error_buffer)),
+ SOCKERRNO);
+ *curlcode = CURLE_SEND_ERROR;
+ return -1;
+ }
+ }
+ return rc;
+}
+
+static void
+Curl_mesalink_close(struct connectdata *conn, int sockindex)
+{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+
+ if(BACKEND->handle) {
+ (void)SSL_shutdown(BACKEND->handle);
+ SSL_free(BACKEND->handle);
+ BACKEND->handle = NULL;
+ }
+ if(BACKEND->ctx) {
+ SSL_CTX_free(BACKEND->ctx);
+ BACKEND->ctx = NULL;
+ }
+}
+
+static ssize_t
+mesalink_recv(struct connectdata *conn, int num, char *buf, size_t buffersize,
+ CURLcode *curlcode)
+{
+ struct ssl_connect_data *connssl = &conn->ssl[num];
+ char error_buffer[MESALINK_MAX_ERROR_SZ];
+ int buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
+ int nread = SSL_read(BACKEND->handle, buf, buffsize);
+
+ if(nread <= 0) {
+ int err = SSL_get_error(BACKEND->handle, nread);
+
+ switch(err) {
+ case SSL_ERROR_ZERO_RETURN: /* no more data */
+ case IO_ERROR_CONNECTION_ABORTED:
+ break;
+ case SSL_ERROR_WANT_READ:
+ case SSL_ERROR_WANT_WRITE:
+ /* there's data pending, re-invoke SSL_read() */
+ *curlcode = CURLE_AGAIN;
+ return -1;
+ default:
+ failf(conn->data,
+ "SSL read: %s, errno %d",
+ ERR_error_string_n(err, error_buffer, sizeof(error_buffer)),
+ SOCKERRNO);
+ *curlcode = CURLE_RECV_ERROR;
+ return -1;
+ }
+ }
+ return nread;
+}
+
+static size_t
+Curl_mesalink_version(char *buffer, size_t size)
+{
+ return msnprintf(buffer, size, "MesaLink/%s", MESALINK_VERSION_STRING);
+}
+
+static int
+Curl_mesalink_init(void)
+{
+ return (SSL_library_init() == SSL_SUCCESS);
+}
+
+/*
+ * This function is called to shut down the SSL layer but keep the
+ * socket open (CCC - Clear Command Channel)
+ */
+static int
+Curl_mesalink_shutdown(struct connectdata *conn, int sockindex)
+{
+ int retval = 0;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+
+ if(BACKEND->handle) {
+ SSL_free(BACKEND->handle);
+ BACKEND->handle = NULL;
+ }
+ return retval;
+}
+
+static CURLcode
+mesalink_connect_common(struct connectdata *conn, int sockindex,
+ bool nonblocking, bool *done)
+{
+ CURLcode result;
+ struct Curl_easy *data = conn->data;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ curl_socket_t sockfd = conn->sock[sockindex];
+ time_t timeout_ms;
+ int what;
+
+ /* check if the connection has already been established */
+ if(ssl_connection_complete == connssl->state) {
+ *done = TRUE;
+ return CURLE_OK;
+ }
+
+ if(ssl_connect_1 == connssl->connecting_state) {
+ /* Find out how much more time we're allowed */
+ timeout_ms = Curl_timeleft(data, NULL, TRUE);
+
+ if(timeout_ms < 0) {
+ /* no need to continue if time already is up */
+ failf(data, "SSL connection timeout");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+
+ result = mesalink_connect_step1(conn, sockindex);
+ if(result)
+ return result;
+ }
+
+ while(ssl_connect_2 == connssl->connecting_state ||
+ ssl_connect_2_reading == connssl->connecting_state ||
+ ssl_connect_2_writing == connssl->connecting_state) {
+
+ /* check allowed time left */
+ timeout_ms = Curl_timeleft(data, NULL, TRUE);
+
+ if(timeout_ms < 0) {
+ /* no need to continue if time already is up */
+ failf(data, "SSL connection timeout");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+
+ /* if ssl is expecting something, check if it's available. */
+ if(connssl->connecting_state == ssl_connect_2_reading ||
+ connssl->connecting_state == 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 == connssl->connecting_state
+ ? sockfd
+ : CURL_SOCKET_BAD;
+
+ what = Curl_socket_check(
+ readfd, CURL_SOCKET_BAD, writefd, nonblocking ? 0 : timeout_ms);
+ if(what < 0) {
+ /* fatal error */
+ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ else if(0 == what) {
+ if(nonblocking) {
+ *done = FALSE;
+ return CURLE_OK;
+ }
+ else {
+ /* timeout */
+ failf(data, "SSL connection timeout");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+ }
+ /* socket is readable or writable */
+ }
+
+ /* Run transaction, and return to the caller if it failed or if
+ * this connection is part of a multi handle and this loop would
+ * execute again. This permits the owner of a multi handle to
+ * abort a connection attempt before step2 has completed while
+ * ensuring that a client using select() or epoll() will always
+ * have a valid fdset to wait on.
+ */
+ result = mesalink_connect_step2(conn, sockindex);
+
+ if(result ||
+ (nonblocking && (ssl_connect_2 == connssl->connecting_state ||
+ ssl_connect_2_reading == connssl->connecting_state ||
+ ssl_connect_2_writing == connssl->connecting_state))) {
+ return result;
+ }
+ } /* repeat step2 until all transactions are done. */
+
+ if(ssl_connect_3 == connssl->connecting_state) {
+ result = mesalink_connect_step3(conn, sockindex);
+ if(result)
+ return result;
+ }
+
+ if(ssl_connect_done == connssl->connecting_state) {
+ connssl->state = ssl_connection_complete;
+ conn->recv[sockindex] = mesalink_recv;
+ conn->send[sockindex] = mesalink_send;
+ *done = TRUE;
+ }
+ else
+ *done = FALSE;
+
+ /* Reset our connect state machine */
+ connssl->connecting_state = ssl_connect_1;
+
+ return CURLE_OK;
+}
+
+static CURLcode
+Curl_mesalink_connect_nonblocking(struct connectdata *conn, int sockindex,
+ bool *done)
+{
+ return mesalink_connect_common(conn, sockindex, TRUE, done);
+}
+
+static CURLcode
+Curl_mesalink_connect(struct connectdata *conn, int sockindex)
+{
+ CURLcode result;
+ bool done = FALSE;
+
+ result = mesalink_connect_common(conn, sockindex, FALSE, &done);
+ if(result)
+ return result;
+
+ DEBUGASSERT(done);
+
+ return CURLE_OK;
+}
+
+static void *
+Curl_mesalink_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
+{
+ (void)info;
+ return BACKEND->handle;
+}
+
+const struct Curl_ssl Curl_ssl_mesalink = {
+ { CURLSSLBACKEND_MESALINK, "MesaLink" }, /* info */
+
+ SSLSUPP_SSL_CTX,
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_mesalink_init, /* init */
+ Curl_none_cleanup, /* cleanup */
+ Curl_mesalink_version, /* version */
+ Curl_none_check_cxn, /* check_cxn */
+ Curl_mesalink_shutdown, /* shutdown */
+ Curl_none_data_pending, /* data_pending */
+ Curl_none_random, /* random */
+ Curl_none_cert_status_request, /* cert_status_request */
+ Curl_mesalink_connect, /* connect */
+ Curl_mesalink_connect_nonblocking, /* connect_nonblocking */
+ Curl_mesalink_get_internals, /* get_internals */
+ Curl_mesalink_close, /* close_one */
+ 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 */
+};
+
+#endif
diff --git a/Utilities/cmcurl/lib/vtls/mesalink.h b/Utilities/cmcurl/lib/vtls/mesalink.h
new file mode 100644
index 000000000..54cb94ad3
--- /dev/null
+++ b/Utilities/cmcurl/lib/vtls/mesalink.h
@@ -0,0 +1,32 @@
+#ifndef HEADER_CURL_MESALINK_H
+#define HEADER_CURL_MESALINK_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2017-2018, Yiming Jing, <jingyiming@baidu.com>
+ * 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"
+
+#ifdef USE_MESALINK
+
+extern const struct Curl_ssl Curl_ssl_mesalink;
+
+#endif /* USE_MESALINK */
+#endif /* HEADER_CURL_MESALINK_H */
diff --git a/Utilities/cmcurl/lib/vtls/schannel_verify.c b/Utilities/cmcurl/lib/vtls/schannel_verify.c
new file mode 100644
index 000000000..5a09e969e
--- /dev/null
+++ b/Utilities/cmcurl/lib/vtls/schannel_verify.c
@@ -0,0 +1,572 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2012 - 2016, Marc Hoersken, <info@marc-hoersken.de>
+ * Copyright (C) 2012, Mark Salisbury, <mark.salisbury@hp.com>
+ * Copyright (C) 2012 - 2019, 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.
+ *
+ ***************************************************************************/
+
+/*
+ * Source file for Schannel-specific certificate verification. This code should
+ * only be invoked by code in schannel.c.
+ */
+
+#include "curl_setup.h"
+
+#ifdef USE_SCHANNEL
+#ifndef USE_WINDOWS_SSPI
+# error "Can't compile SCHANNEL support without SSPI."
+#endif
+
+#define EXPOSE_SCHANNEL_INTERNAL_STRUCTS
+#include "schannel.h"
+
+#ifdef HAS_MANUAL_VERIFY_API
+
+#include "vtls.h"
+#include "sendf.h"
+#include "strerror.h"
+#include "curl_multibyte.h"
+#include "curl_printf.h"
+#include "hostcheck.h"
+#include "system_win32.h"
+
+/* The last #include file should be: */
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#define BACKEND connssl->backend
+
+#define MAX_CAFILE_SIZE 1048576 /* 1 MiB */
+#define BEGIN_CERT "-----BEGIN CERTIFICATE-----"
+#define END_CERT "\n-----END CERTIFICATE-----"
+
+typedef struct {
+ DWORD cbSize;
+ HCERTSTORE hRestrictedRoot;
+ HCERTSTORE hRestrictedTrust;
+ HCERTSTORE hRestrictedOther;
+ DWORD cAdditionalStore;
+ HCERTSTORE *rghAdditionalStore;
+ DWORD dwFlags;
+ DWORD dwUrlRetrievalTimeout;
+ DWORD MaximumCachedCertificates;
+ DWORD CycleDetectionModulus;
+ HCERTSTORE hExclusiveRoot;
+ HCERTSTORE hExclusiveTrustedPeople;
+} CERT_CHAIN_ENGINE_CONFIG_WIN7, *PCERT_CHAIN_ENGINE_CONFIG_WIN7;
+
+static int is_cr_or_lf(char c)
+{
+ return c == '\r' || c == '\n';
+}
+
+static CURLcode add_certs_to_store(HCERTSTORE trust_store,
+ const char *ca_file,
+ struct connectdata *conn)
+{
+ CURLcode result;
+ struct Curl_easy *data = conn->data;
+ HANDLE ca_file_handle = INVALID_HANDLE_VALUE;
+ LARGE_INTEGER file_size;
+ char *ca_file_buffer = NULL;
+ char *current_ca_file_ptr = NULL;
+ TCHAR *ca_file_tstr = NULL;
+ size_t ca_file_bufsize = 0;
+ DWORD total_bytes_read = 0;
+ bool more_certs = 0;
+ int num_certs = 0;
+ size_t END_CERT_LEN;
+
+ ca_file_tstr = Curl_convert_UTF8_to_tchar((char *)ca_file);
+ if(!ca_file_tstr) {
+ char buffer[STRERROR_LEN];
+ failf(data,
+ "schannel: invalid path name for CA file '%s': %s",
+ ca_file, Curl_strerror(GetLastError(), buffer, sizeof(buffer)));
+ result = CURLE_SSL_CACERT_BADFILE;
+ goto cleanup;
+ }
+
+ /*
+ * Read the CA file completely into memory before parsing it. This
+ * optimizes for the common case where the CA file will be relatively
+ * small ( < 1 MiB ).
+ */
+ ca_file_handle = CreateFile(ca_file_tstr,
+ GENERIC_READ,
+ 0,
+ NULL,
+ OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL,
+ NULL);
+ if(ca_file_handle == INVALID_HANDLE_VALUE) {
+ char buffer[STRERROR_LEN];
+ failf(data,
+ "schannel: failed to open CA file '%s': %s",
+ ca_file, Curl_strerror(GetLastError(), buffer, sizeof(buffer)));
+ result = CURLE_SSL_CACERT_BADFILE;
+ goto cleanup;
+ }
+
+ if(!GetFileSizeEx(ca_file_handle, &file_size)) {
+ char buffer[STRERROR_LEN];
+ failf(data,
+ "schannel: failed to determine size of CA file '%s': %s",
+ ca_file, Curl_strerror(GetLastError(), buffer, sizeof(buffer)));
+ result = CURLE_SSL_CACERT_BADFILE;
+ goto cleanup;
+ }
+
+ if(file_size.QuadPart > MAX_CAFILE_SIZE) {
+ failf(data,
+ "schannel: CA file exceeds max size of %u bytes",
+ MAX_CAFILE_SIZE);
+ result = CURLE_SSL_CACERT_BADFILE;
+ goto cleanup;
+ }
+
+ ca_file_bufsize = (size_t)file_size.QuadPart;
+ ca_file_buffer = (char *)malloc(ca_file_bufsize + 1);
+ if(!ca_file_buffer) {
+ result = CURLE_OUT_OF_MEMORY;
+ goto cleanup;
+ }
+
+ result = CURLE_OK;
+ while(total_bytes_read < ca_file_bufsize) {
+ DWORD bytes_to_read = (DWORD)(ca_file_bufsize - total_bytes_read);
+ DWORD bytes_read = 0;
+
+ if(!ReadFile(ca_file_handle, ca_file_buffer + total_bytes_read,
+ bytes_to_read, &bytes_read, NULL)) {
+ char buffer[STRERROR_LEN];
+ failf(data,
+ "schannel: failed to read from CA file '%s': %s",
+ ca_file, Curl_strerror(GetLastError(), buffer, sizeof(buffer)));
+ result = CURLE_SSL_CACERT_BADFILE;
+ goto cleanup;
+ }
+ if(bytes_read == 0) {
+ /* Premature EOF -- adjust the bufsize to the new value */
+ ca_file_bufsize = total_bytes_read;
+ }
+ else {
+ total_bytes_read += bytes_read;
+ }
+ }
+
+ /* Null terminate the buffer */
+ ca_file_buffer[ca_file_bufsize] = '\0';
+
+ if(result != CURLE_OK) {
+ goto cleanup;
+ }
+
+ END_CERT_LEN = strlen(END_CERT);
+
+ more_certs = 1;
+ current_ca_file_ptr = ca_file_buffer;
+ while(more_certs && *current_ca_file_ptr != '\0') {
+ char *begin_cert_ptr = strstr(current_ca_file_ptr, BEGIN_CERT);
+ if(!begin_cert_ptr || !is_cr_or_lf(begin_cert_ptr[strlen(BEGIN_CERT)])) {
+ more_certs = 0;
+ }
+ else {
+ char *end_cert_ptr = strstr(begin_cert_ptr, END_CERT);
+ if(!end_cert_ptr) {
+ failf(data,
+ "schannel: CA file '%s' is not correctly formatted",
+ ca_file);
+ result = CURLE_SSL_CACERT_BADFILE;
+ more_certs = 0;
+ }
+ else {
+ CERT_BLOB cert_blob;
+ CERT_CONTEXT *cert_context = NULL;
+ BOOL add_cert_result = FALSE;
+ DWORD actual_content_type = 0;
+ DWORD cert_size = (DWORD)
+ ((end_cert_ptr + END_CERT_LEN) - begin_cert_ptr);
+
+ cert_blob.pbData = (BYTE *)begin_cert_ptr;
+ cert_blob.cbData = cert_size;
+ if(!CryptQueryObject(CERT_QUERY_OBJECT_BLOB,
+ &cert_blob,
+ CERT_QUERY_CONTENT_FLAG_CERT,
+ CERT_QUERY_FORMAT_FLAG_ALL,
+ 0,
+ NULL,
+ &actual_content_type,
+ NULL,
+ NULL,
+ NULL,
+ (const void **)&cert_context)) {
+ char buffer[STRERROR_LEN];
+ failf(data,
+ "schannel: failed to extract certificate from CA file "
+ "'%s': %s",
+ ca_file,
+ Curl_strerror(GetLastError(), buffer, sizeof(buffer)));
+ result = CURLE_SSL_CACERT_BADFILE;
+ more_certs = 0;
+ }
+ else {
+ current_ca_file_ptr = begin_cert_ptr + cert_size;
+
+ /* Sanity check that the cert_context object is the right type */
+ if(CERT_QUERY_CONTENT_CERT != actual_content_type) {
+ failf(data,
+ "schannel: unexpected content type '%d' when extracting "
+ "certificate from CA file '%s'",
+ actual_content_type, ca_file);
+ result = CURLE_SSL_CACERT_BADFILE;
+ more_certs = 0;
+ }
+ else {
+ add_cert_result =
+ CertAddCertificateContextToStore(trust_store,
+ cert_context,
+ CERT_STORE_ADD_ALWAYS,
+ NULL);
+ CertFreeCertificateContext(cert_context);
+ if(!add_cert_result) {
+ char buffer[STRERROR_LEN];
+ failf(data,
+ "schannel: failed to add certificate from CA file '%s' "
+ "to certificate store: %s",
+ ca_file,
+ Curl_strerror(GetLastError(), buffer, sizeof(buffer)));
+ result = CURLE_SSL_CACERT_BADFILE;
+ more_certs = 0;
+ }
+ else {
+ num_certs++;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if(result == CURLE_OK) {
+ if(!num_certs) {
+ infof(data,
+ "schannel: did not add any certificates from CA file '%s'\n",
+ ca_file);
+ }
+ else {
+ infof(data,
+ "schannel: added %d certificate(s) from CA file '%s'\n",
+ num_certs, ca_file);
+ }
+ }
+
+cleanup:
+ if(ca_file_handle != INVALID_HANDLE_VALUE) {
+ CloseHandle(ca_file_handle);
+ }
+ Curl_safefree(ca_file_buffer);
+ Curl_unicodefree(ca_file_tstr);
+
+ return result;
+}
+
+static CURLcode verify_host(struct Curl_easy *data,
+ CERT_CONTEXT *pCertContextServer,
+ const char * const conn_hostname)
+{
+ CURLcode result = CURLE_PEER_FAILED_VERIFICATION;
+ TCHAR *cert_hostname_buff = NULL;
+ size_t cert_hostname_buff_index = 0;
+ DWORD len = 0;
+ DWORD actual_len = 0;
+
+ /* CertGetNameString will provide the 8-bit character string without
+ * any decoding */
+ DWORD name_flags = CERT_NAME_DISABLE_IE4_UTF8_FLAG;
+
+#ifdef CERT_NAME_SEARCH_ALL_NAMES_FLAG
+ name_flags |= CERT_NAME_SEARCH_ALL_NAMES_FLAG;
+#endif
+
+ /* Determine the size of the string needed for the cert hostname */
+ len = CertGetNameString(pCertContextServer,
+ CERT_NAME_DNS_TYPE,
+ name_flags,
+ NULL,
+ NULL,
+ 0);
+ if(len == 0) {
+ failf(data,
+ "schannel: CertGetNameString() returned no "
+ "certificate name information");
+ result = CURLE_PEER_FAILED_VERIFICATION;
+ goto cleanup;
+ }
+
+ /* CertGetNameString guarantees that the returned name will not contain
+ * embedded null bytes. This appears to be undocumented behavior.
+ */
+ cert_hostname_buff = (LPTSTR)malloc(len * sizeof(TCHAR));
+ if(!cert_hostname_buff) {
+ result = CURLE_OUT_OF_MEMORY;
+ goto cleanup;
+ }
+ actual_len = CertGetNameString(pCertContextServer,
+ CERT_NAME_DNS_TYPE,
+ name_flags,
+ NULL,
+ (LPTSTR) cert_hostname_buff,
+ len);
+
+ /* Sanity check */
+ if(actual_len != len) {
+ failf(data,
+ "schannel: CertGetNameString() returned certificate "
+ "name information of unexpected size");
+ result = CURLE_PEER_FAILED_VERIFICATION;
+ goto cleanup;
+ }
+
+ /* If HAVE_CERT_NAME_SEARCH_ALL_NAMES is available, the output
+ * will contain all DNS names, where each name is null-terminated
+ * and the last DNS name is double null-terminated. Due to this
+ * encoding, use the length of the buffer to iterate over all names.
+ */
+ result = CURLE_PEER_FAILED_VERIFICATION;
+ while(cert_hostname_buff_index < len &&
+ cert_hostname_buff[cert_hostname_buff_index] != TEXT('\0') &&
+ result == CURLE_PEER_FAILED_VERIFICATION) {
+
+ char *cert_hostname;
+
+ /* Comparing the cert name and the connection hostname encoded as UTF-8
+ * is acceptable since both values are assumed to use ASCII
+ * (or some equivalent) encoding
+ */
+ cert_hostname = Curl_convert_tchar_to_UTF8(
+ &cert_hostname_buff[cert_hostname_buff_index]);
+ if(!cert_hostname) {
+ result = CURLE_OUT_OF_MEMORY;
+ }
+ else {
+ int match_result;
+
+ match_result = Curl_cert_hostcheck(cert_hostname, conn_hostname);
+ if(match_result == CURL_HOST_MATCH) {
+ infof(data,
+ "schannel: connection hostname (%s) validated "
+ "against certificate name (%s)\n",
+ conn_hostname, cert_hostname);
+ result = CURLE_OK;
+ }
+ else {
+ size_t cert_hostname_len;
+
+ infof(data,
+ "schannel: connection hostname (%s) did not match "
+ "against certificate name (%s)\n",
+ conn_hostname, cert_hostname);
+
+ cert_hostname_len = _tcslen(
+ &cert_hostname_buff[cert_hostname_buff_index]);
+
+ /* Move on to next cert name */
+ cert_hostname_buff_index += cert_hostname_len + 1;
+
+ result = CURLE_PEER_FAILED_VERIFICATION;
+ }
+ Curl_unicodefree(cert_hostname);
+ }
+ }
+
+ if(result == CURLE_PEER_FAILED_VERIFICATION) {
+ failf(data,
+ "schannel: CertGetNameString() failed to match "
+ "connection hostname (%s) against server certificate names",
+ conn_hostname);
+ }
+ else if(result != CURLE_OK)
+ failf(data, "schannel: server certificate name verification failed");
+
+cleanup:
+ Curl_unicodefree(cert_hostname_buff);
+
+ return result;
+}
+
+CURLcode Curl_verify_certificate(struct connectdata *conn, int sockindex)
+{
+ SECURITY_STATUS sspi_status;
+ struct Curl_easy *data = conn->data;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ CURLcode result = CURLE_OK;
+ CERT_CONTEXT *pCertContextServer = NULL;
+ const CERT_CHAIN_CONTEXT *pChainContext = NULL;
+ HCERTCHAINENGINE cert_chain_engine = NULL;
+ HCERTSTORE trust_store = NULL;
+ const char * const conn_hostname = SSL_IS_PROXY() ?
+ conn->http_proxy.host.name :
+ conn->host.name;
+
+ sspi_status =
+ s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle,
+ SECPKG_ATTR_REMOTE_CERT_CONTEXT,
+ &pCertContextServer);
+
+ if((sspi_status != SEC_E_OK) || (pCertContextServer == NULL)) {
+ char buffer[STRERROR_LEN];
+ failf(data, "schannel: Failed to read remote certificate context: %s",
+ Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
+ result = CURLE_PEER_FAILED_VERIFICATION;
+ }
+
+ if(result == CURLE_OK && SSL_CONN_CONFIG(CAfile) &&
+ BACKEND->use_manual_cred_validation) {
+ /*
+ * Create a chain engine that uses the certificates in the CA file as
+ * trusted certificates. This is only supported on Windows 7+.
+ */
+
+ if(Curl_verify_windows_version(6, 1, PLATFORM_WINNT, VERSION_LESS_THAN)) {
+ failf(data, "schannel: this version of Windows is too old to support "
+ "certificate verification via CA bundle file.");
+ result = CURLE_SSL_CACERT_BADFILE;
+ }
+ else {
+ /* Open the certificate store */
+ trust_store = CertOpenStore(CERT_STORE_PROV_MEMORY,
+ 0,
+ (HCRYPTPROV)NULL,
+ CERT_STORE_CREATE_NEW_FLAG,
+ NULL);
+ if(!trust_store) {
+ char buffer[STRERROR_LEN];
+ failf(data, "schannel: failed to create certificate store: %s",
+ Curl_strerror(GetLastError(), buffer, sizeof(buffer)));
+ result = CURLE_SSL_CACERT_BADFILE;
+ }
+ else {
+ result = add_certs_to_store(trust_store, SSL_CONN_CONFIG(CAfile),
+ conn);
+ }
+ }
+
+ if(result == CURLE_OK) {
+ CERT_CHAIN_ENGINE_CONFIG_WIN7 engine_config;
+ BOOL create_engine_result;
+
+ memset(&engine_config, 0, sizeof(engine_config));
+ engine_config.cbSize = sizeof(engine_config);
+ engine_config.hExclusiveRoot = trust_store;
+
+ /* CertCreateCertificateChainEngine will check the expected size of the
+ * CERT_CHAIN_ENGINE_CONFIG structure and fail if the specified size
+ * does not match the expected size. When this occurs, it indicates that
+ * CAINFO is not supported on the version of Windows in use.
+ */
+ create_engine_result =
+ CertCreateCertificateChainEngine(
+ (CERT_CHAIN_ENGINE_CONFIG *)&engine_config, &cert_chain_engine);
+ if(!create_engine_result) {
+ char buffer[STRERROR_LEN];
+ failf(data,
+ "schannel: failed to create certificate chain engine: %s",
+ Curl_strerror(GetLastError(), buffer, sizeof(buffer)));
+ result = CURLE_SSL_CACERT_BADFILE;
+ }
+ }
+ }
+
+ if(result == CURLE_OK) {
+ CERT_CHAIN_PARA ChainPara;
+
+ memset(&ChainPara, 0, sizeof(ChainPara));
+ ChainPara.cbSize = sizeof(ChainPara);
+
+ if(!CertGetCertificateChain(cert_chain_engine,
+ pCertContextServer,
+ NULL,
+ pCertContextServer->hCertStore,
+ &ChainPara,
+ (data->set.ssl.no_revoke ? 0 :
+ CERT_CHAIN_REVOCATION_CHECK_CHAIN),
+ NULL,
+ &pChainContext)) {
+ char buffer[STRERROR_LEN];
+ failf(data, "schannel: CertGetCertificateChain failed: %s",
+ Curl_strerror(GetLastError(), buffer, sizeof(buffer)));
+ pChainContext = NULL;
+ result = CURLE_PEER_FAILED_VERIFICATION;
+ }
+
+ if(result == CURLE_OK) {
+ CERT_SIMPLE_CHAIN *pSimpleChain = pChainContext->rgpChain[0];
+ DWORD dwTrustErrorMask = ~(DWORD)(CERT_TRUST_IS_NOT_TIME_NESTED);
+ dwTrustErrorMask &= pSimpleChain->TrustStatus.dwErrorStatus;
+ if(dwTrustErrorMask) {
+ if(dwTrustErrorMask & CERT_TRUST_IS_REVOKED)
+ failf(data, "schannel: CertGetCertificateChain trust error"
+ " CERT_TRUST_IS_REVOKED");
+ else if(dwTrustErrorMask & CERT_TRUST_IS_PARTIAL_CHAIN)
+ failf(data, "schannel: CertGetCertificateChain trust error"
+ " CERT_TRUST_IS_PARTIAL_CHAIN");
+ else if(dwTrustErrorMask & CERT_TRUST_IS_UNTRUSTED_ROOT)
+ failf(data, "schannel: CertGetCertificateChain trust error"
+ " CERT_TRUST_IS_UNTRUSTED_ROOT");
+ else if(dwTrustErrorMask & CERT_TRUST_IS_NOT_TIME_VALID)
+ failf(data, "schannel: CertGetCertificateChain trust error"
+ " CERT_TRUST_IS_NOT_TIME_VALID");
+ else if(dwTrustErrorMask & CERT_TRUST_REVOCATION_STATUS_UNKNOWN)
+ failf(data, "schannel: CertGetCertificateChain trust error"
+ " CERT_TRUST_REVOCATION_STATUS_UNKNOWN");
+ else
+ failf(data, "schannel: CertGetCertificateChain error mask: 0x%08x",
+ dwTrustErrorMask);
+ result = CURLE_PEER_FAILED_VERIFICATION;
+ }
+ }
+ }
+
+ if(result == CURLE_OK) {
+ if(SSL_CONN_CONFIG(verifyhost)) {
+ result = verify_host(conn->data, pCertContextServer, conn_hostname);
+ }
+ }
+
+ if(cert_chain_engine) {
+ CertFreeCertificateChainEngine(cert_chain_engine);
+ }
+
+ if(trust_store) {
+ CertCloseStore(trust_store, 0);
+ }
+
+ if(pChainContext)
+ CertFreeCertificateChain(pChainContext);
+
+ if(pCertContextServer)
+ CertFreeCertificateContext(pCertContextServer);
+
+ return result;
+}
+
+#endif /* HAS_MANUAL_VERIFY_API */
+#endif /* USE_SCHANNEL */
diff --git a/Utilities/cmcurl/lib/vtls/sectransp.c b/Utilities/cmcurl/lib/vtls/sectransp.c
new file mode 100644
index 000000000..2fdf662a1
--- /dev/null
+++ b/Utilities/cmcurl/lib/vtls/sectransp.c
@@ -0,0 +1,3264 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2012 - 2017, Nick Zitzmann, <nickzman@gmail.com>.
+ * Copyright (C) 2012 - 2019, 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.
+ *
+ ***************************************************************************/
+
+/*
+ * Source file for all iOS and macOS SecureTransport-specific code for the
+ * TLS/SSL layer. No code but vtls.c should ever call or use these functions.
+ */
+
+#include "curl_setup.h"
+
+#include "urldata.h" /* for the Curl_easy definition */
+#include "curl_base64.h"
+#include "strtok.h"
+#include "multiif.h"
+
+#ifdef USE_SECTRANSP
+
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wtautological-pointer-compare"
+#endif /* __clang__ */
+
+#include <limits.h>
+
+#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>
+
+/* The Security framework has changed greatly between iOS and different macOS
+ versions, and we will try to support as many of them as we can (back to
+ Leopard and iOS 5) by using macros and weak-linking.
+
+ In general, you want to build this using the most recent OS SDK, since some
+ features require curl to be built against the latest SDK. TLS 1.1 and 1.2
+ support, for instance, require the macOS 10.8 SDK or later. TLS 1.3
+ requires the macOS 10.13 or iOS 11 SDK or later. */
+#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
+
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1050
+#error "The Secure Transport back-end requires Leopard or later."
+#endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1050 */
+
+#define CURL_BUILD_IOS 0
+#define CURL_BUILD_IOS_7 0
+#define CURL_BUILD_IOS_9 0
+#define CURL_BUILD_IOS_11 0
+#define CURL_BUILD_MAC 1
+/* This is the maximum API level we are allowed to use when building: */
+#define CURL_BUILD_MAC_10_5 MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
+#define CURL_BUILD_MAC_10_6 MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
+#define CURL_BUILD_MAC_10_7 MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
+#define CURL_BUILD_MAC_10_8 MAC_OS_X_VERSION_MAX_ALLOWED >= 1080
+#define CURL_BUILD_MAC_10_9 MAC_OS_X_VERSION_MAX_ALLOWED >= 1090
+#define CURL_BUILD_MAC_10_11 MAC_OS_X_VERSION_MAX_ALLOWED >= 101100
+#define CURL_BUILD_MAC_10_13 MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
+/* These macros mean "the following code is present to allow runtime backward
+ compatibility with at least this cat or earlier":
+ (You set this at build-time using the compiler command line option
+ "-mmacos-version-min.") */
+#define CURL_SUPPORT_MAC_10_5 MAC_OS_X_VERSION_MIN_REQUIRED <= 1050
+#define CURL_SUPPORT_MAC_10_6 MAC_OS_X_VERSION_MIN_REQUIRED <= 1060
+#define CURL_SUPPORT_MAC_10_7 MAC_OS_X_VERSION_MIN_REQUIRED <= 1070
+#define CURL_SUPPORT_MAC_10_8 MAC_OS_X_VERSION_MIN_REQUIRED <= 1080
+#define CURL_SUPPORT_MAC_10_9 MAC_OS_X_VERSION_MIN_REQUIRED <= 1090
+
+#elif TARGET_OS_EMBEDDED || TARGET_OS_IPHONE
+#define CURL_BUILD_IOS 1
+#define CURL_BUILD_IOS_7 __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
+#define CURL_BUILD_IOS_9 __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
+#define CURL_BUILD_IOS_11 __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000
+#define CURL_BUILD_MAC 0
+#define CURL_BUILD_MAC_10_5 0
+#define CURL_BUILD_MAC_10_6 0
+#define CURL_BUILD_MAC_10_7 0
+#define CURL_BUILD_MAC_10_8 0
+#define CURL_BUILD_MAC_10_9 0
+#define CURL_BUILD_MAC_10_11 0
+#define CURL_BUILD_MAC_10_13 0
+#define CURL_SUPPORT_MAC_10_5 0
+#define CURL_SUPPORT_MAC_10_6 0
+#define CURL_SUPPORT_MAC_10_7 0
+#define CURL_SUPPORT_MAC_10_8 0
+#define CURL_SUPPORT_MAC_10_9 0
+
+#else
+#error "The Secure Transport back-end requires iOS or macOS."
+#endif /* (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) */
+
+#if CURL_BUILD_MAC
+#include <sys/sysctl.h>
+#endif /* CURL_BUILD_MAC */
+
+#include "urldata.h"
+#include "sendf.h"
+#include "inet_pton.h"
+#include "connect.h"
+#include "select.h"
+#include "vtls.h"
+#include "sectransp.h"
+#include "curl_printf.h"
+#include "strdup.h"
+
+#include "curl_memory.h"
+/* The last #include file should be: */
+#include "memdebug.h"
+
+/* From MacTypes.h (which we can't include because it isn't present in iOS: */
+#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 SECTRANSP_PINNEDPUBKEY_V1 1
+#endif
+
+/* version 2 supports MacOSX 10.7+ */
+#if (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070)
+#define SECTRANSP_PINNEDPUBKEY_V2 1
+#endif
+
+#if defined(SECTRANSP_PINNEDPUBKEY_V1) || defined(SECTRANSP_PINNEDPUBKEY_V2)
+/* this backend supports CURLOPT_PINNEDPUBLICKEY */
+#define SECTRANSP_PINNEDPUBKEY 1
+#endif /* SECTRANSP_PINNEDPUBKEY */
+
+#ifdef SECTRANSP_PINNEDPUBKEY
+/* both new and old APIs return rsa keys missing the spki header (not DER) */
+static const unsigned char rsa4096SpkiHeader[] = {
+ 0x30, 0x82, 0x02, 0x22, 0x30, 0x0d,
+ 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
+ 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05,
+ 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00};
+
+static const unsigned char rsa2048SpkiHeader[] = {
+ 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d,
+ 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
+ 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05,
+ 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00};
+#ifdef SECTRANSP_PINNEDPUBKEY_V1
+/* the *new* version doesn't return DER encoded ecdsa certs like the old... */
+static const unsigned char ecDsaSecp256r1SpkiHeader[] = {
+ 0x30, 0x59, 0x30, 0x13, 0x06, 0x07,
+ 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
+ 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48,
+ 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
+ 0x42, 0x00};
+
+static const unsigned char ecDsaSecp384r1SpkiHeader[] = {
+ 0x30, 0x76, 0x30, 0x10, 0x06, 0x07,
+ 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
+ 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04,
+ 0x00, 0x22, 0x03, 0x62, 0x00};
+#endif /* SECTRANSP_PINNEDPUBKEY_V1 */
+#endif /* SECTRANSP_PINNEDPUBKEY */
+
+/* The following two functions were ripped from Apple sample code,
+ * with some modifications: */
+static OSStatus SocketRead(SSLConnectionRef connection,
+ void *data, /* owned by
+ * caller, data
+ * RETURNED */
+ size_t *dataLength) /* IN/OUT */
+{
+ size_t bytesToGo = *dataLength;
+ size_t initLen = bytesToGo;
+ UInt8 *currData = (UInt8 *)data;
+ /*int sock = *(int *)connection;*/
+ struct ssl_connect_data *connssl = (struct ssl_connect_data *)connection;
+ int sock = BACKEND->ssl_sockfd;
+ OSStatus rtn = noErr;
+ size_t bytesRead;
+ ssize_t rrtn;
+ int theErr;
+
+ *dataLength = 0;
+
+ for(;;) {
+ bytesRead = 0;
+ rrtn = read(sock, currData, bytesToGo);
+ if(rrtn <= 0) {
+ /* this is guesswork... */
+ theErr = errno;
+ if(rrtn == 0) { /* EOF = server hung up */
+ /* the framework will turn this into errSSLClosedNoNotify */
+ rtn = errSSLClosedGraceful;
+ }
+ else /* do the switch */
+ switch(theErr) {
+ case ENOENT:
+ /* connection closed */
+ rtn = errSSLClosedGraceful;
+ break;
+ case ECONNRESET:
+ rtn = errSSLClosedAbort;
+ break;
+ case EAGAIN:
+ rtn = errSSLWouldBlock;
+ BACKEND->ssl_direction = false;
+ break;
+ default:
+ rtn = ioErr;
+ break;
+ }
+ break;
+ }
+ else {
+ bytesRead = rrtn;
+ }
+ bytesToGo -= bytesRead;
+ currData += bytesRead;
+
+ if(bytesToGo == 0) {
+ /* filled buffer with incoming data, done */
+ break;
+ }
+ }
+ *dataLength = initLen - bytesToGo;
+
+ return rtn;
+}
+
+static OSStatus SocketWrite(SSLConnectionRef connection,
+ const void *data,
+ size_t *dataLength) /* IN/OUT */
+{
+ size_t bytesSent = 0;
+ /*int sock = *(int *)connection;*/
+ struct ssl_connect_data *connssl = (struct ssl_connect_data *)connection;
+ int sock = BACKEND->ssl_sockfd;
+ ssize_t length;
+ size_t dataLen = *dataLength;
+ const UInt8 *dataPtr = (UInt8 *)data;
+ OSStatus ortn;
+ int theErr;
+
+ *dataLength = 0;
+
+ do {
+ length = write(sock,
+ (char *)dataPtr + bytesSent,
+ dataLen - bytesSent);
+ } while((length > 0) &&
+ ( (bytesSent += length) < dataLen) );
+
+ if(length <= 0) {
+ theErr = errno;
+ if(theErr == EAGAIN) {
+ ortn = errSSLWouldBlock;
+ BACKEND->ssl_direction = true;
+ }
+ else {
+ ortn = ioErr;
+ }
+ }
+ else {
+ ortn = noErr;
+ }
+ *dataLength = bytesSent;
+ return ortn;
+}
+
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
+CF_INLINE const char *SSLCipherNameForNumber(SSLCipherSuite cipher)
+{
+ switch(cipher) {
+ /* SSL version 3.0 */
+ case SSL_RSA_WITH_NULL_MD5:
+ return "SSL_RSA_WITH_NULL_MD5";
+ break;
+ case SSL_RSA_WITH_NULL_SHA:
+ return "SSL_RSA_WITH_NULL_SHA";
+ break;
+ case SSL_RSA_EXPORT_WITH_RC4_40_MD5:
+ return "SSL_RSA_EXPORT_WITH_RC4_40_MD5";
+ break;
+ case SSL_RSA_WITH_RC4_128_MD5:
+ return "SSL_RSA_WITH_RC4_128_MD5";
+ break;
+ case SSL_RSA_WITH_RC4_128_SHA:
+ return "SSL_RSA_WITH_RC4_128_SHA";
+ break;
+ case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
+ return "SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5";
+ break;
+ case SSL_RSA_WITH_IDEA_CBC_SHA:
+ return "SSL_RSA_WITH_IDEA_CBC_SHA";
+ break;
+ case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA:
+ return "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA";
+ break;
+ case SSL_RSA_WITH_DES_CBC_SHA:
+ return "SSL_RSA_WITH_DES_CBC_SHA";
+ break;
+ case SSL_RSA_WITH_3DES_EDE_CBC_SHA:
+ return "SSL_RSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA:
+ return "SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA";
+ break;
+ case SSL_DH_DSS_WITH_DES_CBC_SHA:
+ return "SSL_DH_DSS_WITH_DES_CBC_SHA";
+ break;
+ case SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA:
+ return "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA:
+ return "SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA";
+ break;
+ case SSL_DH_RSA_WITH_DES_CBC_SHA:
+ return "SSL_DH_RSA_WITH_DES_CBC_SHA";
+ break;
+ case SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA:
+ return "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA:
+ return "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA";
+ break;
+ case SSL_DHE_DSS_WITH_DES_CBC_SHA:
+ return "SSL_DHE_DSS_WITH_DES_CBC_SHA";
+ break;
+ case SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
+ return "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA:
+ return "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA";
+ break;
+ case SSL_DHE_RSA_WITH_DES_CBC_SHA:
+ return "SSL_DHE_RSA_WITH_DES_CBC_SHA";
+ break;
+ case SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
+ return "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5:
+ return "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5";
+ break;
+ case SSL_DH_anon_WITH_RC4_128_MD5:
+ return "SSL_DH_anon_WITH_RC4_128_MD5";
+ break;
+ case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA:
+ return "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA";
+ break;
+ case SSL_DH_anon_WITH_DES_CBC_SHA:
+ return "SSL_DH_anon_WITH_DES_CBC_SHA";
+ break;
+ case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA:
+ return "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case SSL_FORTEZZA_DMS_WITH_NULL_SHA:
+ return "SSL_FORTEZZA_DMS_WITH_NULL_SHA";
+ break;
+ case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA:
+ return "SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA";
+ break;
+ /* TLS 1.0 with AES (RFC 3268)
+ (Apparently these are used in SSLv3 implementations as well.) */
+ case TLS_RSA_WITH_AES_128_CBC_SHA:
+ return "TLS_RSA_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DH_DSS_WITH_AES_128_CBC_SHA:
+ return "TLS_DH_DSS_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DH_RSA_WITH_AES_128_CBC_SHA:
+ return "TLS_DH_RSA_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
+ return "TLS_DHE_DSS_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
+ return "TLS_DHE_RSA_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DH_anon_WITH_AES_128_CBC_SHA:
+ return "TLS_DH_anon_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_RSA_WITH_AES_256_CBC_SHA:
+ return "TLS_RSA_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DH_DSS_WITH_AES_256_CBC_SHA:
+ return "TLS_DH_DSS_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DH_RSA_WITH_AES_256_CBC_SHA:
+ return "TLS_DH_RSA_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
+ return "TLS_DHE_DSS_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
+ return "TLS_DHE_RSA_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DH_anon_WITH_AES_256_CBC_SHA:
+ return "TLS_DH_anon_WITH_AES_256_CBC_SHA";
+ break;
+ /* SSL version 2.0 */
+ case SSL_RSA_WITH_RC2_CBC_MD5:
+ return "SSL_RSA_WITH_RC2_CBC_MD5";
+ break;
+ case SSL_RSA_WITH_IDEA_CBC_MD5:
+ return "SSL_RSA_WITH_IDEA_CBC_MD5";
+ break;
+ case SSL_RSA_WITH_DES_CBC_MD5:
+ return "SSL_RSA_WITH_DES_CBC_MD5";
+ break;
+ case SSL_RSA_WITH_3DES_EDE_CBC_MD5:
+ return "SSL_RSA_WITH_3DES_EDE_CBC_MD5";
+ break;
+ }
+ return "SSL_NULL_WITH_NULL_NULL";
+}
+
+CF_INLINE const char *TLSCipherNameForNumber(SSLCipherSuite cipher)
+{
+ switch(cipher) {
+ /* TLS 1.0 with AES (RFC 3268) */
+ case TLS_RSA_WITH_AES_128_CBC_SHA:
+ return "TLS_RSA_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DH_DSS_WITH_AES_128_CBC_SHA:
+ return "TLS_DH_DSS_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DH_RSA_WITH_AES_128_CBC_SHA:
+ return "TLS_DH_RSA_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
+ return "TLS_DHE_DSS_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
+ return "TLS_DHE_RSA_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DH_anon_WITH_AES_128_CBC_SHA:
+ return "TLS_DH_anon_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_RSA_WITH_AES_256_CBC_SHA:
+ return "TLS_RSA_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DH_DSS_WITH_AES_256_CBC_SHA:
+ return "TLS_DH_DSS_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DH_RSA_WITH_AES_256_CBC_SHA:
+ return "TLS_DH_RSA_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
+ return "TLS_DHE_DSS_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
+ return "TLS_DHE_RSA_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DH_anon_WITH_AES_256_CBC_SHA:
+ return "TLS_DH_anon_WITH_AES_256_CBC_SHA";
+ break;
+#if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS
+ /* TLS 1.0 with ECDSA (RFC 4492) */
+ case TLS_ECDH_ECDSA_WITH_NULL_SHA:
+ return "TLS_ECDH_ECDSA_WITH_NULL_SHA";
+ break;
+ case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
+ return "TLS_ECDH_ECDSA_WITH_RC4_128_SHA";
+ break;
+ case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
+ return "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
+ return "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_ECDHE_ECDSA_WITH_NULL_SHA:
+ return "TLS_ECDHE_ECDSA_WITH_NULL_SHA";
+ break;
+ case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
+ return "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA";
+ break;
+ case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
+ return "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
+ return "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_ECDH_RSA_WITH_NULL_SHA:
+ return "TLS_ECDH_RSA_WITH_NULL_SHA";
+ break;
+ case TLS_ECDH_RSA_WITH_RC4_128_SHA:
+ return "TLS_ECDH_RSA_WITH_RC4_128_SHA";
+ break;
+ case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
+ return "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
+ return "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_ECDHE_RSA_WITH_NULL_SHA:
+ return "TLS_ECDHE_RSA_WITH_NULL_SHA";
+ break;
+ case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
+ return "TLS_ECDHE_RSA_WITH_RC4_128_SHA";
+ break;
+ case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
+ return "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
+ return "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_ECDH_anon_WITH_NULL_SHA:
+ return "TLS_ECDH_anon_WITH_NULL_SHA";
+ break;
+ case TLS_ECDH_anon_WITH_RC4_128_SHA:
+ return "TLS_ECDH_anon_WITH_RC4_128_SHA";
+ break;
+ case TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_ECDH_anon_WITH_AES_128_CBC_SHA:
+ return "TLS_ECDH_anon_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_ECDH_anon_WITH_AES_256_CBC_SHA:
+ return "TLS_ECDH_anon_WITH_AES_256_CBC_SHA";
+ break;
+#endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */
+#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
+ /* TLS 1.2 (RFC 5246) */
+ case TLS_RSA_WITH_NULL_MD5:
+ return "TLS_RSA_WITH_NULL_MD5";
+ break;
+ case TLS_RSA_WITH_NULL_SHA:
+ return "TLS_RSA_WITH_NULL_SHA";
+ break;
+ case TLS_RSA_WITH_RC4_128_MD5:
+ return "TLS_RSA_WITH_RC4_128_MD5";
+ break;
+ case TLS_RSA_WITH_RC4_128_SHA:
+ return "TLS_RSA_WITH_RC4_128_SHA";
+ break;
+ case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_RSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_RSA_WITH_NULL_SHA256:
+ return "TLS_RSA_WITH_NULL_SHA256";
+ break;
+ case TLS_RSA_WITH_AES_128_CBC_SHA256:
+ return "TLS_RSA_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_RSA_WITH_AES_256_CBC_SHA256:
+ return "TLS_RSA_WITH_AES_256_CBC_SHA256";
+ break;
+ case TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_DH_DSS_WITH_AES_128_CBC_SHA256:
+ return "TLS_DH_DSS_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_DH_RSA_WITH_AES_128_CBC_SHA256:
+ return "TLS_DH_RSA_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
+ return "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
+ return "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_DH_DSS_WITH_AES_256_CBC_SHA256:
+ return "TLS_DH_DSS_WITH_AES_256_CBC_SHA256";
+ break;
+ case TLS_DH_RSA_WITH_AES_256_CBC_SHA256:
+ return "TLS_DH_RSA_WITH_AES_256_CBC_SHA256";
+ break;
+ case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
+ return "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256";
+ break;
+ case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
+ return "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256";
+ break;
+ case TLS_DH_anon_WITH_RC4_128_MD5:
+ return "TLS_DH_anon_WITH_RC4_128_MD5";
+ break;
+ case TLS_DH_anon_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_DH_anon_WITH_AES_128_CBC_SHA256:
+ return "TLS_DH_anon_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_DH_anon_WITH_AES_256_CBC_SHA256:
+ return "TLS_DH_anon_WITH_AES_256_CBC_SHA256";
+ break;
+ /* TLS 1.2 with AES GCM (RFC 5288) */
+ case TLS_RSA_WITH_AES_128_GCM_SHA256:
+ return "TLS_RSA_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_RSA_WITH_AES_256_GCM_SHA384:
+ return "TLS_RSA_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
+ return "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
+ return "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_DH_RSA_WITH_AES_128_GCM_SHA256:
+ return "TLS_DH_RSA_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_DH_RSA_WITH_AES_256_GCM_SHA384:
+ return "TLS_DH_RSA_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
+ return "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
+ return "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_DH_DSS_WITH_AES_128_GCM_SHA256:
+ return "TLS_DH_DSS_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_DH_DSS_WITH_AES_256_GCM_SHA384:
+ return "TLS_DH_DSS_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_DH_anon_WITH_AES_128_GCM_SHA256:
+ return "TLS_DH_anon_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_DH_anon_WITH_AES_256_GCM_SHA384:
+ return "TLS_DH_anon_WITH_AES_256_GCM_SHA384";
+ break;
+ /* TLS 1.2 with elliptic curve ciphers (RFC 5289) */
+ case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
+ return "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
+ return "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384";
+ break;
+ case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256:
+ return "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384:
+ return "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384";
+ break;
+ case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
+ return "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
+ return "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384";
+ break;
+ case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256:
+ return "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384:
+ return "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384";
+ break;
+ case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
+ return "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
+ return "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256:
+ return "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384:
+ return "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
+ return "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
+ return "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256:
+ return "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384:
+ return "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_EMPTY_RENEGOTIATION_INFO_SCSV:
+ return "TLS_EMPTY_RENEGOTIATION_INFO_SCSV";
+ break;
+#else
+ case SSL_RSA_WITH_NULL_MD5:
+ return "TLS_RSA_WITH_NULL_MD5";
+ break;
+ case SSL_RSA_WITH_NULL_SHA:
+ return "TLS_RSA_WITH_NULL_SHA";
+ break;
+ case SSL_RSA_WITH_RC4_128_MD5:
+ return "TLS_RSA_WITH_RC4_128_MD5";
+ break;
+ case SSL_RSA_WITH_RC4_128_SHA:
+ return "TLS_RSA_WITH_RC4_128_SHA";
+ break;
+ case SSL_RSA_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_RSA_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case SSL_DH_anon_WITH_RC4_128_MD5:
+ return "TLS_DH_anon_WITH_RC4_128_MD5";
+ break;
+ case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA";
+ break;
+#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
+#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7
+ /* TLS PSK (RFC 4279): */
+ case TLS_PSK_WITH_RC4_128_SHA:
+ return "TLS_PSK_WITH_RC4_128_SHA";
+ break;
+ case TLS_PSK_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_PSK_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_PSK_WITH_AES_128_CBC_SHA:
+ return "TLS_PSK_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_PSK_WITH_AES_256_CBC_SHA:
+ return "TLS_PSK_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_DHE_PSK_WITH_RC4_128_SHA:
+ return "TLS_DHE_PSK_WITH_RC4_128_SHA";
+ break;
+ case TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_DHE_PSK_WITH_AES_128_CBC_SHA:
+ return "TLS_DHE_PSK_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_DHE_PSK_WITH_AES_256_CBC_SHA:
+ return "TLS_DHE_PSK_WITH_AES_256_CBC_SHA";
+ break;
+ case TLS_RSA_PSK_WITH_RC4_128_SHA:
+ return "TLS_RSA_PSK_WITH_RC4_128_SHA";
+ break;
+ case TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA:
+ return "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA";
+ break;
+ case TLS_RSA_PSK_WITH_AES_128_CBC_SHA:
+ return "TLS_RSA_PSK_WITH_AES_128_CBC_SHA";
+ break;
+ case TLS_RSA_PSK_WITH_AES_256_CBC_SHA:
+ return "TLS_RSA_PSK_WITH_AES_256_CBC_SHA";
+ break;
+ /* More TLS PSK (RFC 4785): */
+ case TLS_PSK_WITH_NULL_SHA:
+ return "TLS_PSK_WITH_NULL_SHA";
+ break;
+ case TLS_DHE_PSK_WITH_NULL_SHA:
+ return "TLS_DHE_PSK_WITH_NULL_SHA";
+ break;
+ case TLS_RSA_PSK_WITH_NULL_SHA:
+ return "TLS_RSA_PSK_WITH_NULL_SHA";
+ break;
+ /* Even more TLS PSK (RFC 5487): */
+ case TLS_PSK_WITH_AES_128_GCM_SHA256:
+ return "TLS_PSK_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_PSK_WITH_AES_256_GCM_SHA384:
+ return "TLS_PSK_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_DHE_PSK_WITH_AES_128_GCM_SHA256:
+ return "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_DHE_PSK_WITH_AES_256_GCM_SHA384:
+ return "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_RSA_PSK_WITH_AES_128_GCM_SHA256:
+ return "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256";
+ break;
+ case TLS_RSA_PSK_WITH_AES_256_GCM_SHA384:
+ return "TLS_PSK_WITH_AES_256_GCM_SHA384";
+ break;
+ case TLS_PSK_WITH_AES_128_CBC_SHA256:
+ return "TLS_PSK_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_PSK_WITH_AES_256_CBC_SHA384:
+ return "TLS_PSK_WITH_AES_256_CBC_SHA384";
+ break;
+ case TLS_PSK_WITH_NULL_SHA256:
+ return "TLS_PSK_WITH_NULL_SHA256";
+ break;
+ case TLS_PSK_WITH_NULL_SHA384:
+ return "TLS_PSK_WITH_NULL_SHA384";
+ break;
+ case TLS_DHE_PSK_WITH_AES_128_CBC_SHA256:
+ return "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_DHE_PSK_WITH_AES_256_CBC_SHA384:
+ return "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384";
+ break;
+ case TLS_DHE_PSK_WITH_NULL_SHA256:
+ return "TLS_DHE_PSK_WITH_NULL_SHA256";
+ break;
+ case TLS_DHE_PSK_WITH_NULL_SHA384:
+ return "TLS_RSA_PSK_WITH_NULL_SHA384";
+ break;
+ case TLS_RSA_PSK_WITH_AES_128_CBC_SHA256:
+ return "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256";
+ break;
+ case TLS_RSA_PSK_WITH_AES_256_CBC_SHA384:
+ return "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384";
+ break;
+ case TLS_RSA_PSK_WITH_NULL_SHA256:
+ return "TLS_RSA_PSK_WITH_NULL_SHA256";
+ break;
+ case TLS_RSA_PSK_WITH_NULL_SHA384:
+ return "TLS_RSA_PSK_WITH_NULL_SHA384";
+ break;
+#endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */
+#if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11
+ /* New ChaCha20+Poly1305 cipher-suites used by TLS 1.3: */
+ case TLS_AES_128_GCM_SHA256:
+ return "TLS_AES_128_GCM_SHA256";
+ break;
+ case TLS_AES_256_GCM_SHA384:
+ return "TLS_AES_256_GCM_SHA384";
+ break;
+ case TLS_CHACHA20_POLY1305_SHA256:
+ return "TLS_CHACHA20_POLY1305_SHA256";
+ break;
+ case TLS_AES_128_CCM_SHA256:
+ return "TLS_AES_128_CCM_SHA256";
+ break;
+ case TLS_AES_128_CCM_8_SHA256:
+ return "TLS_AES_128_CCM_8_SHA256";
+ break;
+ case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
+ return "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256";
+ break;
+ case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
+ return "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256";
+ break;
+#endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */
+ }
+ return "TLS_NULL_WITH_NULL_NULL";
+}
+#endif /* !CURL_DISABLE_VERBOSE_STRINGS */
+
+#if CURL_BUILD_MAC
+CF_INLINE void GetDarwinVersionNumber(int *major, int *minor)
+{
+ int mib[2];
+ char *os_version;
+ size_t os_version_len;
+ char *os_version_major, *os_version_minor;
+ char *tok_buf;
+
+ /* Get the Darwin kernel version from the kernel using sysctl(): */
+ mib[0] = CTL_KERN;
+ mib[1] = KERN_OSRELEASE;
+ if(sysctl(mib, 2, NULL, &os_version_len, NULL, 0) == -1)
+ return;
+ os_version = malloc(os_version_len*sizeof(char));
+ if(!os_version)
+ return;
+ if(sysctl(mib, 2, os_version, &os_version_len, NULL, 0) == -1) {
+ free(os_version);
+ return;
+ }
+
+ /* Parse the version: */
+ os_version_major = strtok_r(os_version, ".", &tok_buf);
+ os_version_minor = strtok_r(NULL, ".", &tok_buf);
+ *major = atoi(os_version_major);
+ *minor = atoi(os_version_minor);
+ free(os_version);
+}
+#endif /* CURL_BUILD_MAC */
+
+/* Apple provides a myriad of ways of getting information about a certificate
+ 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 getsubject(SecCertificateRef cert)
+{
+ CFStringRef server_cert_summary = CFSTR("(null)");
+
+#if CURL_BUILD_IOS
+ /* iOS: There's only one way to do this. */
+ server_cert_summary = SecCertificateCopySubjectSummary(cert);
+#else
+#if CURL_BUILD_MAC_10_7
+ /* Lion & later: Get the long description if we can. */
+ if(SecCertificateCopyLongDescription != NULL)
+ server_cert_summary =
+ SecCertificateCopyLongDescription(NULL, cert, NULL);
+ else
+#endif /* CURL_BUILD_MAC_10_7 */
+#if CURL_BUILD_MAC_10_6
+ /* Snow Leopard: Get the certificate summary. */
+ if(SecCertificateCopySubjectSummary != NULL)
+ server_cert_summary = SecCertificateCopySubjectSummary(cert);
+ else
+#endif /* CURL_BUILD_MAC_10_6 */
+ /* Leopard is as far back as we go... */
+ (void)SecCertificateCopyCommonName(cert, &server_cert_summary);
+#endif /* CURL_BUILD_IOS */
+ 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_PEER_FAILED_VERIFICATION;
+ }
+
+ /* 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_PEER_FAILED_VERIFICATION;
+ }
+ 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: */
+static OSStatus CopyIdentityWithLabelOldSchool(char *label,
+ SecIdentityRef *out_c_a_k)
+{
+ OSStatus status = errSecItemNotFound;
+ SecKeychainAttributeList attr_list;
+ SecKeychainAttribute attr;
+ SecKeychainSearchRef search = NULL;
+ SecCertificateRef cert = NULL;
+
+ /* Set up the attribute list: */
+ attr_list.count = 1L;
+ attr_list.attr = &attr;
+
+ /* Set up our lone search criterion: */
+ attr.tag = kSecLabelItemAttr;
+ attr.data = label;
+ attr.length = (UInt32)strlen(label);
+
+ /* Start searching: */
+ status = SecKeychainSearchCreateFromAttributes(NULL,
+ kSecCertificateItemClass,
+ &attr_list,
+ &search);
+ if(status == noErr) {
+ status = SecKeychainSearchCopyNext(search,
+ (SecKeychainItemRef *)&cert);
+ if(status == noErr && cert) {
+ /* If we found a certificate, does it have a private key? */
+ status = SecIdentityCreateWithCertificate(NULL, cert, out_c_a_k);
+ CFRelease(cert);
+ }
+ }
+
+ if(search)
+ CFRelease(search);
+ return status;
+}
+#endif /* CURL_SUPPORT_MAC_10_6 */
+
+static OSStatus CopyIdentityWithLabel(char *label,
+ SecIdentityRef *out_cert_and_key)
+{
+ OSStatus status = errSecItemNotFound;
+
+#if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS
+ CFArrayRef keys_list;
+ CFIndex keys_list_count;
+ CFIndex i;
+ CFStringRef common_name;
+
+ /* SecItemCopyMatching() was introduced in iOS and Snow Leopard.
+ kSecClassIdentity was introduced in Lion. If both exist, let's use them
+ to find the certificate. */
+ if(SecItemCopyMatching != NULL && kSecClassIdentity != NULL) {
+ CFTypeRef keys[5];
+ CFTypeRef values[5];
+ CFDictionaryRef query_dict;
+ CFStringRef label_cf = CFStringCreateWithCString(NULL, label,
+ kCFStringEncodingUTF8);
+
+ /* Set up our search criteria and expected results: */
+ values[0] = kSecClassIdentity; /* we want a certificate and a key */
+ keys[0] = kSecClass;
+ values[1] = kCFBooleanTrue; /* we want a reference */
+ keys[1] = kSecReturnRef;
+ values[2] = kSecMatchLimitAll; /* kSecMatchLimitOne would be better if the
+ * label matching below worked correctly */
+ keys[2] = kSecMatchLimit;
+ /* identity searches need a SecPolicyRef in order to work */
+ values[3] = SecPolicyCreateSSL(false, NULL);
+ keys[3] = kSecMatchPolicy;
+ /* match the name of the certificate (doesn't work in macOS 10.12.1) */
+ values[4] = label_cf;
+ keys[4] = kSecAttrLabel;
+ query_dict = CFDictionaryCreate(NULL, (const void **)keys,
+ (const void **)values, 5L,
+ &kCFCopyStringDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks);
+ CFRelease(values[3]);
+
+ /* Do we have a match? */
+ status = SecItemCopyMatching(query_dict, (CFTypeRef *) &keys_list);
+
+ /* Because kSecAttrLabel matching doesn't work with kSecClassIdentity,
+ * we need to find the correct identity ourselves */
+ if(status == noErr) {
+ keys_list_count = CFArrayGetCount(keys_list);
+ *out_cert_and_key = NULL;
+ status = 1;
+ for(i = 0; i<keys_list_count; i++) {
+ OSStatus err = noErr;
+ SecCertificateRef cert = NULL;
+ SecIdentityRef identity =
+ (SecIdentityRef) CFArrayGetValueAtIndex(keys_list, i);
+ err = SecIdentityCopyCertificate(identity, &cert);
+ if(err == noErr) {
+#if CURL_BUILD_IOS
+ common_name = SecCertificateCopySubjectSummary(cert);
+#elif CURL_BUILD_MAC_10_7
+ SecCertificateCopyCommonName(cert, &common_name);
+#endif
+ if(CFStringCompare(common_name, label_cf, 0) == kCFCompareEqualTo) {
+ CFRelease(cert);
+ CFRelease(common_name);
+ CFRetain(identity);
+ *out_cert_and_key = identity;
+ status = noErr;
+ break;
+ }
+ CFRelease(common_name);
+ }
+ CFRelease(cert);
+ }
+ }
+
+ if(keys_list)
+ CFRelease(keys_list);
+ CFRelease(query_dict);
+ CFRelease(label_cf);
+ }
+ else {
+#if CURL_SUPPORT_MAC_10_6
+ /* On Leopard and Snow Leopard, fall back to SecKeychainSearch. */
+ status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key);
+#endif /* CURL_SUPPORT_MAC_10_6 */
+ }
+#elif CURL_SUPPORT_MAC_10_6
+ /* For developers building on older cats, we have no choice but to fall back
+ to SecKeychainSearch. */
+ status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key);
+#endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */
+ return status;
+}
+
+static OSStatus CopyIdentityFromPKCS12File(const char *cPath,
+ const char *cPassword,
+ SecIdentityRef *out_cert_and_key)
+{
+ OSStatus status = errSecItemNotFound;
+ CFURLRef pkcs_url = CFURLCreateFromFileSystemRepresentation(NULL,
+ (const UInt8 *)cPath, strlen(cPath), false);
+ CFStringRef password = cPassword ? CFStringCreateWithCString(NULL,
+ cPassword, kCFStringEncodingUTF8) : NULL;
+ CFDataRef pkcs_data = NULL;
+
+ /* We can import P12 files on iOS or OS X 10.7 or later: */
+ /* These constants are documented as having first appeared in 10.6 but they
+ raise linker errors when used on that cat for some reason. */
+#if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS
+ if(CFURLCreateDataAndPropertiesFromResource(NULL, pkcs_url, &pkcs_data,
+ NULL, NULL, &status)) {
+ CFArrayRef items = NULL;
+
+ /* On iOS SecPKCS12Import will never add the client certificate to the
+ * Keychain.
+ *
+ * It gives us back a SecIdentityRef that we can use directly. */
+#if CURL_BUILD_IOS
+ const void *cKeys[] = {kSecImportExportPassphrase};
+ const void *cValues[] = {password};
+ CFDictionaryRef options = CFDictionaryCreate(NULL, cKeys, cValues,
+ password ? 1L : 0L, NULL, NULL);
+
+ if(options != NULL) {
+ status = SecPKCS12Import(pkcs_data, options, &items);
+ CFRelease(options);
+ }
+
+
+ /* On macOS SecPKCS12Import will always add the client certificate to
+ * the Keychain.
+ *
+ * As this doesn't match iOS, and apps may not want to see their client
+ * certificate saved in the the user's keychain, we use SecItemImport
+ * with a NULL keychain to avoid importing it.
+ *
+ * This returns a SecCertificateRef from which we can construct a
+ * SecIdentityRef.
+ */
+#elif CURL_BUILD_MAC_10_7
+ SecItemImportExportKeyParameters keyParams;
+ SecExternalFormat inputFormat = kSecFormatPKCS12;
+ SecExternalItemType inputType = kSecItemTypeCertificate;
+
+ memset(&keyParams, 0x00, sizeof(keyParams));
+ keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
+ keyParams.passphrase = password;
+
+ status = SecItemImport(pkcs_data, NULL, &inputFormat, &inputType,
+ 0, &keyParams, NULL, &items);
+#endif
+
+
+ /* Extract the SecIdentityRef */
+ if(status == errSecSuccess && items && CFArrayGetCount(items)) {
+ CFIndex i, count;
+ count = CFArrayGetCount(items);
+
+ for(i = 0; i < count; i++) {
+ CFTypeRef item = (CFTypeRef) CFArrayGetValueAtIndex(items, i);
+ CFTypeID itemID = CFGetTypeID(item);
+
+ if(itemID == CFDictionaryGetTypeID()) {
+ CFTypeRef identity = (CFTypeRef) CFDictionaryGetValue(
+ (CFDictionaryRef) item,
+ kSecImportItemIdentity);
+ CFRetain(identity);
+ *out_cert_and_key = (SecIdentityRef) identity;
+ break;
+ }
+#if CURL_BUILD_MAC_10_7
+ else if(itemID == SecCertificateGetTypeID()) {
+ status = SecIdentityCreateWithCertificate(NULL,
+ (SecCertificateRef) item,
+ out_cert_and_key);
+ break;
+ }
+#endif
+ }
+ }
+
+ if(items)
+ CFRelease(items);
+ CFRelease(pkcs_data);
+ }
+#endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */
+ if(password)
+ CFRelease(password);
+ CFRelease(pkcs_url);
+ return status;
+}
+
+/* This code was borrowed from nss.c, with some modifications:
+ * Determine whether the nickname passed in is a filename that needs to
+ * be loaded as a PEM or a regular NSS nickname.
+ *
+ * returns 1 for a file
+ * returns 0 for not a file
+ */
+CF_INLINE bool is_file(const char *filename)
+{
+ struct_stat st;
+
+ if(filename == NULL)
+ return false;
+
+ if(stat(filename, &st) == 0)
+ return S_ISREG(st.st_mode);
+ return false;
+}
+
+#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
+static CURLcode sectransp_version_from_curl(SSLProtocol *darwinver,
+ long ssl_version)
+{
+ switch(ssl_version) {
+ case CURL_SSLVERSION_TLSv1_0:
+ *darwinver = kTLSProtocol1;
+ return CURLE_OK;
+ case CURL_SSLVERSION_TLSv1_1:
+ *darwinver = kTLSProtocol11;
+ return CURLE_OK;
+ case CURL_SSLVERSION_TLSv1_2:
+ *darwinver = kTLSProtocol12;
+ return CURLE_OK;
+ case CURL_SSLVERSION_TLSv1_3:
+ /* TLS 1.3 support first appeared in iOS 11 and macOS 10.13 */
+#if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1
+ if(__builtin_available(macOS 10.13, iOS 11.0, *)) {
+ *darwinver = kTLSProtocol13;
+ return CURLE_OK;
+ }
+#endif /* (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) &&
+ HAVE_BUILTIN_AVAILABLE == 1 */
+ break;
+ }
+ return CURLE_SSL_CONNECT_ERROR;
+}
+#endif
+
+static CURLcode
+set_ssl_version_min_max(struct connectdata *conn, int sockindex)
+{
+ struct Curl_easy *data = conn->data;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ long ssl_version = SSL_CONN_CONFIG(version);
+ long ssl_version_max = SSL_CONN_CONFIG(version_max);
+ long max_supported_version_by_os;
+
+ /* macOS 10.5-10.7 supported TLS 1.0 only.
+ macOS 10.8 and later, and iOS 5 and later, added TLS 1.1 and 1.2.
+ macOS 10.13 and later, and iOS 11 and later, added TLS 1.3. */
+#if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1
+ if(__builtin_available(macOS 10.13, iOS 11.0, *)) {
+ max_supported_version_by_os = CURL_SSLVERSION_MAX_TLSv1_3;
+ }
+ else {
+ max_supported_version_by_os = CURL_SSLVERSION_MAX_TLSv1_2;
+ }
+#else
+ max_supported_version_by_os = CURL_SSLVERSION_MAX_TLSv1_2;
+#endif /* (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) &&
+ HAVE_BUILTIN_AVAILABLE == 1 */
+
+ switch(ssl_version) {
+ case CURL_SSLVERSION_DEFAULT:
+ case CURL_SSLVERSION_TLSv1:
+ ssl_version = CURL_SSLVERSION_TLSv1_0;
+ break;
+ }
+
+ switch(ssl_version_max) {
+ case CURL_SSLVERSION_MAX_NONE:
+ case CURL_SSLVERSION_MAX_DEFAULT:
+ ssl_version_max = max_supported_version_by_os;
+ break;
+ }
+
+#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
+ if(SSLSetProtocolVersionMax != NULL) {
+ SSLProtocol darwin_ver_min = kTLSProtocol1;
+ SSLProtocol darwin_ver_max = kTLSProtocol1;
+ CURLcode result = sectransp_version_from_curl(&darwin_ver_min,
+ ssl_version);
+ if(result) {
+ failf(data, "unsupported min version passed via CURLOPT_SSLVERSION");
+ return result;
+ }
+ result = sectransp_version_from_curl(&darwin_ver_max,
+ ssl_version_max >> 16);
+ if(result) {
+ failf(data, "unsupported max version passed via CURLOPT_SSLVERSION");
+ return result;
+ }
+
+ (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(BACKEND->ssl_ctx,
+ kSSLProtocolAll,
+ false);
+ for(; i <= (ssl_version_max >> 16); i++) {
+ switch(i) {
+ case CURL_SSLVERSION_TLSv1_0:
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kTLSProtocol1,
+ true);
+ break;
+ case CURL_SSLVERSION_TLSv1_1:
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kTLSProtocol11,
+ true);
+ break;
+ case CURL_SSLVERSION_TLSv1_2:
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kTLSProtocol12,
+ true);
+ break;
+ case CURL_SSLVERSION_TLSv1_3:
+ failf(data, "Your version of the OS does not support TLSv1.3");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ }
+ return CURLE_OK;
+#endif /* CURL_SUPPORT_MAC_10_8 */
+ }
+#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
+ failf(data, "Secure Transport: cannot set SSL protocol");
+ return CURLE_SSL_CONNECT_ERROR;
+}
+
+
+static CURLcode sectransp_connect_step1(struct connectdata *conn,
+ int sockindex)
+{
+ struct Curl_easy *data = conn->data;
+ curl_socket_t sockfd = conn->sock[sockindex];
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
+ const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
+ char * const ssl_cert = SSL_SET_OPTION(cert);
+ const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
+ conn->host.name;
+ const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
+#ifdef ENABLE_IPV6
+ struct in6_addr addr;
+#else
+ struct in_addr addr;
+#endif /* ENABLE_IPV6 */
+ size_t all_ciphers_count = 0UL, allowed_ciphers_count = 0UL, i;
+ SSLCipherSuite *all_ciphers = NULL, *allowed_ciphers = NULL;
+ OSStatus err = noErr;
+#if CURL_BUILD_MAC
+ int darwinver_maj = 0, darwinver_min = 0;
+
+ GetDarwinVersionNumber(&darwinver_maj, &darwinver_min);
+#endif /* CURL_BUILD_MAC */
+
+#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
+ if(SSLCreateContext != NULL) { /* use the newer API if available */
+ 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;
+ }
+ }
+ else {
+ /* The old ST API does not exist under iOS, so don't compile it: */
+#if CURL_SUPPORT_MAC_10_8
+ 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_SUPPORT_MAC_10_8 */
+ }
+#else
+ 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 */
+ 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
+ if(SSLSetProtocolVersionMax != NULL) {
+ switch(conn->ssl_config.version) {
+ case CURL_SSLVERSION_TLSv1:
+ (void)SSLSetProtocolVersionMin(BACKEND->ssl_ctx, kTLSProtocol1);
+#if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1
+ if(__builtin_available(macOS 10.13, iOS 11.0, *)) {
+ (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kTLSProtocol13);
+ }
+ else {
+ (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kTLSProtocol12);
+ }
+#else
+ (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kTLSProtocol12);
+#endif /* (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) &&
+ HAVE_BUILTIN_AVAILABLE == 1 */
+ break;
+ case CURL_SSLVERSION_DEFAULT:
+ case CURL_SSLVERSION_TLSv1_0:
+ case CURL_SSLVERSION_TLSv1_1:
+ case CURL_SSLVERSION_TLSv1_2:
+ case CURL_SSLVERSION_TLSv1_3:
+ {
+ CURLcode result = set_ssl_version_min_max(conn, sockindex);
+ if(result != CURLE_OK)
+ return result;
+ break;
+ }
+ case CURL_SSLVERSION_SSLv3:
+ 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(BACKEND->ssl_ctx, kSSLProtocol3);
+ break;
+ case CURL_SSLVERSION_SSLv2:
+ 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(BACKEND->ssl_ctx, kSSLProtocol2);
+ break;
+ default:
+ failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ }
+ else {
+#if CURL_SUPPORT_MAC_10_8
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kSSLProtocolAll,
+ false);
+ switch(conn->ssl_config.version) {
+ case CURL_SSLVERSION_DEFAULT:
+ case CURL_SSLVERSION_TLSv1:
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kTLSProtocol1,
+ true);
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kTLSProtocol11,
+ true);
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kTLSProtocol12,
+ true);
+ break;
+ case CURL_SSLVERSION_TLSv1_0:
+ case CURL_SSLVERSION_TLSv1_1:
+ case CURL_SSLVERSION_TLSv1_2:
+ case CURL_SSLVERSION_TLSv1_3:
+ {
+ CURLcode result = set_ssl_version_min_max(conn, sockindex);
+ if(result != CURLE_OK)
+ return result;
+ break;
+ }
+ case CURL_SSLVERSION_SSLv3:
+ err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kSSLProtocol3,
+ true);
+ if(err != noErr) {
+ failf(data, "Your version of the OS does not support SSLv3");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ break;
+ case CURL_SSLVERSION_SSLv2:
+ err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kSSLProtocol2,
+ true);
+ if(err != noErr) {
+ failf(data, "Your version of the OS does not support SSLv2");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ break;
+ default:
+ failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+#endif /* CURL_SUPPORT_MAC_10_8 */
+ }
+#else
+ if(conn->ssl_config.version_max != CURL_SSLVERSION_MAX_NONE) {
+ failf(data, "Your version of the OS does not support to set maximum"
+ " SSL/TLS version");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ (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(BACKEND->ssl_ctx,
+ kTLSProtocol1,
+ true);
+ break;
+ case CURL_SSLVERSION_TLSv1_1:
+ failf(data, "Your version of the OS does not support TLSv1.1");
+ return CURLE_SSL_CONNECT_ERROR;
+ case CURL_SSLVERSION_TLSv1_2:
+ failf(data, "Your version of the OS does not support TLSv1.2");
+ return CURLE_SSL_CONNECT_ERROR;
+ case CURL_SSLVERSION_TLSv1_3:
+ failf(data, "Your version of the OS does not support TLSv1.3");
+ return CURLE_SSL_CONNECT_ERROR;
+ case CURL_SSLVERSION_SSLv2:
+ err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kSSLProtocol2,
+ true);
+ if(err != noErr) {
+ failf(data, "Your version of the OS does not support SSLv2");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ break;
+ case CURL_SSLVERSION_SSLv3:
+ err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
+ kSSLProtocol3,
+ true);
+ if(err != noErr) {
+ failf(data, "Your version of the OS does not support SSLv3");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ break;
+ default:
+ failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
+
+#if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1
+ if(conn->bits.tls_enable_alpn) {
+ if(__builtin_available(macOS 10.13.4, iOS 11, tvOS 11, *)) {
+ CFMutableArrayRef alpnArr = CFArrayCreateMutable(NULL, 0,
+ &kCFTypeArrayCallBacks);
+
+#ifdef USE_NGHTTP2
+ if(data->set.httpversion >= CURL_HTTP_VERSION_2 &&
+ (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) {
+ CFArrayAppendValue(alpnArr, CFSTR(NGHTTP2_PROTO_VERSION_ID));
+ infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
+ }
+#endif
+
+ CFArrayAppendValue(alpnArr, CFSTR(ALPN_HTTP_1_1));
+ infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
+
+ /* expects length prefixed preference ordered list of protocols in wire
+ * format
+ */
+ err = SSLSetALPNProtocols(BACKEND->ssl_ctx, alpnArr);
+ if(err != noErr)
+ infof(data, "WARNING: failed to set ALPN protocols; OSStatus %d\n",
+ err);
+ CFRelease(alpnArr);
+ }
+ }
+#endif
+
+ if(SSL_SET_OPTION(key)) {
+ infof(data, "WARNING: SSL: CURLOPT_SSLKEY is ignored by Secure "
+ "Transport. The private key must be in the Keychain.\n");
+ }
+
+ if(ssl_cert) {
+ SecIdentityRef cert_and_key = NULL;
+ bool is_cert_file = is_file(ssl_cert);
+
+ /* User wants to authenticate with a client cert. Look for it:
+ If we detect that this is a file on disk, then let's load it.
+ Otherwise, assume that the user wants to use an identity loaded
+ from the Keychain. */
+ if(is_cert_file) {
+ if(!SSL_SET_OPTION(cert_type))
+ infof(data, "WARNING: SSL: Certificate type not set, assuming "
+ "PKCS#12 format.\n");
+ else if(strncmp(SSL_SET_OPTION(cert_type), "P12",
+ strlen(SSL_SET_OPTION(cert_type))) != 0)
+ infof(data, "WARNING: SSL: The Security framework only supports "
+ "loading identities that are in PKCS#12 format.\n");
+
+ err = CopyIdentityFromPKCS12File(ssl_cert,
+ SSL_SET_OPTION(key_passwd), &cert_and_key);
+ }
+ else
+ err = CopyIdentityWithLabel(ssl_cert, &cert_and_key);
+
+ if(err == noErr && cert_and_key) {
+ SecCertificateRef cert = NULL;
+ CFTypeRef certs_c[1];
+ CFArrayRef certs;
+
+ /* If we found one, print it out: */
+ err = SecIdentityCopyCertificate(cert_and_key, &cert);
+ if(err == noErr) {
+ char *certp;
+ CURLcode result = CopyCertSubject(data, cert, &certp);
+ if(!result) {
+ infof(data, "Client certificate: %s\n", certp);
+ free(certp);
+ }
+
+ CFRelease(cert);
+ if(result == CURLE_PEER_FAILED_VERIFICATION)
+ return CURLE_SSL_CERTPROBLEM;
+ if(result)
+ return result;
+ }
+ certs_c[0] = cert_and_key;
+ certs = CFArrayCreate(NULL, (const void **)certs_c, 1L,
+ &kCFTypeArrayCallBacks);
+ err = SSLSetCertificate(BACKEND->ssl_ctx, certs);
+ if(certs)
+ CFRelease(certs);
+ if(err != noErr) {
+ failf(data, "SSL: SSLSetCertificate() failed: OSStatus %d", err);
+ return CURLE_SSL_CERTPROBLEM;
+ }
+ CFRelease(cert_and_key);
+ }
+ else {
+ switch(err) {
+ case errSecAuthFailed: case -25264: /* errSecPkcs12VerifyFailure */
+ failf(data, "SSL: Incorrect password for the certificate \"%s\" "
+ "and its private key.", ssl_cert);
+ break;
+ case -26275: /* errSecDecode */ case -25257: /* errSecUnknownFormat */
+ failf(data, "SSL: Couldn't make sense of the data in the "
+ "certificate \"%s\" and its private key.",
+ ssl_cert);
+ break;
+ case -25260: /* errSecPassphraseRequired */
+ failf(data, "SSL The certificate \"%s\" requires a password.",
+ ssl_cert);
+ break;
+ case errSecItemNotFound:
+ failf(data, "SSL: Can't find the certificate \"%s\" and its private "
+ "key in the Keychain.", ssl_cert);
+ break;
+ default:
+ failf(data, "SSL: Can't load the certificate \"%s\" and its private "
+ "key: OSStatus %d", ssl_cert, err);
+ break;
+ }
+ return CURLE_SSL_CERTPROBLEM;
+ }
+ }
+
+ /* SSL always tries to verify the peer, this only says whether it should
+ * 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. */
+#if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS
+ /* Snow Leopard introduced the SSLSetSessionOption() function, but due to
+ a library bug with the way the kSSLSessionOptionBreakOnServerAuth flag
+ works, it doesn't work as expected under Snow Leopard, Lion or
+ Mountain Lion.
+ So we need to call SSLSetEnableCertVerify() on those older cats in order
+ to disable certificate validation if the user turned that off.
+ (SecureTransport will always validate the certificate chain by
+ default.)
+ Note:
+ Darwin 11.x.x is Lion (10.7)
+ Darwin 12.x.x is Mountain Lion (10.8)
+ Darwin 13.x.x is Mavericks (10.9)
+ Darwin 14.x.x is Yosemite (10.10)
+ Darwin 15.x.x is El Capitan (10.11)
+ */
+#if CURL_BUILD_MAC
+ if(SSLSetSessionOption != NULL && darwinver_maj >= 13) {
+#else
+ if(SSLSetSessionOption != NULL) {
+#endif /* CURL_BUILD_MAC */
+ bool break_on_auth = !conn->ssl_config.verifypeer || ssl_cafile;
+ err = SSLSetSessionOption(BACKEND->ssl_ctx,
+ kSSLSessionOptionBreakOnServerAuth,
+ break_on_auth);
+ if(err != noErr) {
+ failf(data, "SSL: SSLSetSessionOption() failed: OSStatus %d", err);
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ }
+ else {
+#if CURL_SUPPORT_MAC_10_8
+ err = SSLSetEnableCertVerify(BACKEND->ssl_ctx,
+ conn->ssl_config.verifypeer?true:false);
+ if(err != noErr) {
+ failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err);
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+#endif /* CURL_SUPPORT_MAC_10_8 */
+ }
+#else
+ err = SSLSetEnableCertVerify(BACKEND->ssl_ctx,
+ conn->ssl_config.verifypeer?true:false);
+ if(err != noErr) {
+ failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err);
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+#endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */
+
+ if(ssl_cafile && verifypeer) {
+ bool is_cert_file = is_file(ssl_cafile);
+
+ if(!is_cert_file) {
+ failf(data, "SSL: can't load CA certificate file %s", ssl_cafile);
+ return CURLE_SSL_CACERT_BADFILE;
+ }
+ }
+
+ /* Configure hostname check. SNI is used if available.
+ * Both hostname check and SNI require SSLSetPeerDomainName().
+ * Also: the verifyhost setting influences SNI usage */
+ if(conn->ssl_config.verifyhost) {
+ err = SSLSetPeerDomainName(BACKEND->ssl_ctx, hostname,
+ strlen(hostname));
+
+ if(err != noErr) {
+ infof(data, "WARNING: SSL: SSLSetPeerDomainName() failed: OSStatus %d\n",
+ err);
+ }
+
+ if((Curl_inet_pton(AF_INET, hostname, &addr))
+ #ifdef ENABLE_IPV6
+ || (Curl_inet_pton(AF_INET6, hostname, &addr))
+ #endif
+ ) {
+ infof(data, "WARNING: using IP address, SNI is being disabled by "
+ "the OS.\n");
+ }
+ }
+ else {
+ infof(data, "WARNING: disabling hostname validation also disables SNI.\n");
+ }
+
+ /* Disable cipher suites that ST supports but are not safe. These ciphers
+ are unlikely to be used in any case since ST gives other ciphers a much
+ 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.) */
+ err = SSLGetNumberSupportedCiphers(BACKEND->ssl_ctx, &all_ciphers_count);
+ if(err != noErr) {
+ failf(data, "SSL: SSLGetNumberSupportedCiphers() failed: OSStatus %d",
+ err);
+ return CURLE_SSL_CIPHER;
+ }
+ all_ciphers = malloc(all_ciphers_count*sizeof(SSLCipherSuite));
+ if(!all_ciphers) {
+ failf(data, "SSL: Failed to allocate memory for all ciphers");
+ return CURLE_OUT_OF_MEMORY;
+ }
+ allowed_ciphers = malloc(all_ciphers_count*sizeof(SSLCipherSuite));
+ if(!allowed_ciphers) {
+ Curl_safefree(all_ciphers);
+ failf(data, "SSL: Failed to allocate memory for allowed ciphers");
+ return CURLE_OUT_OF_MEMORY;
+ }
+ err = SSLGetSupportedCiphers(BACKEND->ssl_ctx, all_ciphers,
+ &all_ciphers_count);
+ if(err != noErr) {
+ Curl_safefree(all_ciphers);
+ Curl_safefree(allowed_ciphers);
+ return CURLE_SSL_CIPHER;
+ }
+ for(i = 0UL ; i < all_ciphers_count ; i++) {
+#if CURL_BUILD_MAC
+ /* There's a known bug in early versions of Mountain Lion where ST's ECC
+ ciphers (cipher suite 0xC001 through 0xC032) simply do not work.
+ Work around the problem here by disabling those ciphers if we are
+ running in an affected version of OS X. */
+ if(darwinver_maj == 12 && darwinver_min <= 3 &&
+ all_ciphers[i] >= 0xC001 && all_ciphers[i] <= 0xC032) {
+ continue;
+ }
+#endif /* CURL_BUILD_MAC */
+ switch(all_ciphers[i]) {
+ /* Disable NULL ciphersuites: */
+ case SSL_NULL_WITH_NULL_NULL:
+ case SSL_RSA_WITH_NULL_MD5:
+ case SSL_RSA_WITH_NULL_SHA:
+ case 0x003B: /* TLS_RSA_WITH_NULL_SHA256 */
+ case SSL_FORTEZZA_DMS_WITH_NULL_SHA:
+ case 0xC001: /* TLS_ECDH_ECDSA_WITH_NULL_SHA */
+ case 0xC006: /* TLS_ECDHE_ECDSA_WITH_NULL_SHA */
+ case 0xC00B: /* TLS_ECDH_RSA_WITH_NULL_SHA */
+ case 0xC010: /* TLS_ECDHE_RSA_WITH_NULL_SHA */
+ case 0x002C: /* TLS_PSK_WITH_NULL_SHA */
+ case 0x002D: /* TLS_DHE_PSK_WITH_NULL_SHA */
+ case 0x002E: /* TLS_RSA_PSK_WITH_NULL_SHA */
+ case 0x00B0: /* TLS_PSK_WITH_NULL_SHA256 */
+ case 0x00B1: /* TLS_PSK_WITH_NULL_SHA384 */
+ case 0x00B4: /* TLS_DHE_PSK_WITH_NULL_SHA256 */
+ case 0x00B5: /* TLS_DHE_PSK_WITH_NULL_SHA384 */
+ case 0x00B8: /* TLS_RSA_PSK_WITH_NULL_SHA256 */
+ case 0x00B9: /* TLS_RSA_PSK_WITH_NULL_SHA384 */
+ /* Disable anonymous ciphersuites: */
+ case SSL_DH_anon_EXPORT_WITH_RC4_40_MD5:
+ case SSL_DH_anon_WITH_RC4_128_MD5:
+ case SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA:
+ case SSL_DH_anon_WITH_DES_CBC_SHA:
+ case SSL_DH_anon_WITH_3DES_EDE_CBC_SHA:
+ case TLS_DH_anon_WITH_AES_128_CBC_SHA:
+ case TLS_DH_anon_WITH_AES_256_CBC_SHA:
+ case 0xC015: /* TLS_ECDH_anon_WITH_NULL_SHA */
+ case 0xC016: /* TLS_ECDH_anon_WITH_RC4_128_SHA */
+ case 0xC017: /* TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA */
+ case 0xC018: /* TLS_ECDH_anon_WITH_AES_128_CBC_SHA */
+ case 0xC019: /* TLS_ECDH_anon_WITH_AES_256_CBC_SHA */
+ case 0x006C: /* TLS_DH_anon_WITH_AES_128_CBC_SHA256 */
+ case 0x006D: /* TLS_DH_anon_WITH_AES_256_CBC_SHA256 */
+ case 0x00A6: /* TLS_DH_anon_WITH_AES_128_GCM_SHA256 */
+ case 0x00A7: /* TLS_DH_anon_WITH_AES_256_GCM_SHA384 */
+ /* Disable weak key ciphersuites: */
+ case SSL_RSA_EXPORT_WITH_RC4_40_MD5:
+ case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
+ case SSL_RSA_EXPORT_WITH_DES40_CBC_SHA:
+ case SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA:
+ case SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA:
+ case SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA:
+ case SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA:
+ case SSL_RSA_WITH_DES_CBC_SHA:
+ case SSL_DH_DSS_WITH_DES_CBC_SHA:
+ case SSL_DH_RSA_WITH_DES_CBC_SHA:
+ case SSL_DHE_DSS_WITH_DES_CBC_SHA:
+ case SSL_DHE_RSA_WITH_DES_CBC_SHA:
+ /* Disable IDEA: */
+ case SSL_RSA_WITH_IDEA_CBC_SHA:
+ case SSL_RSA_WITH_IDEA_CBC_MD5:
+ /* Disable RC4: */
+ case SSL_RSA_WITH_RC4_128_MD5:
+ case SSL_RSA_WITH_RC4_128_SHA:
+ case 0xC002: /* TLS_ECDH_ECDSA_WITH_RC4_128_SHA */
+ case 0xC007: /* TLS_ECDHE_ECDSA_WITH_RC4_128_SHA*/
+ case 0xC00C: /* TLS_ECDH_RSA_WITH_RC4_128_SHA */
+ case 0xC011: /* TLS_ECDHE_RSA_WITH_RC4_128_SHA */
+ case 0x008A: /* TLS_PSK_WITH_RC4_128_SHA */
+ case 0x008E: /* TLS_DHE_PSK_WITH_RC4_128_SHA */
+ case 0x0092: /* TLS_RSA_PSK_WITH_RC4_128_SHA */
+ break;
+ default: /* enable everything else */
+ allowed_ciphers[allowed_ciphers_count++] = all_ciphers[i];
+ break;
+ }
+ }
+ err = SSLSetEnabledCiphers(BACKEND->ssl_ctx, allowed_ciphers,
+ allowed_ciphers_count);
+ Curl_safefree(all_ciphers);
+ Curl_safefree(allowed_ciphers);
+ if(err != noErr) {
+ failf(data, "SSL: SSLSetEnabledCiphers() failed: OSStatus %d", err);
+ return CURLE_SSL_CIPHER;
+ }
+
+#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7
+ /* We want to enable 1/n-1 when using a CBC cipher unless the user
+ specifically doesn't want us doing that: */
+ if(SSLSetSessionOption != NULL) {
+ SSLSetSessionOption(BACKEND->ssl_ctx, kSSLSessionOptionSendOneByteRecord,
+ !data->set.ssl.enable_beast);
+ SSLSetSessionOption(BACKEND->ssl_ctx, kSSLSessionOptionFalseStart,
+ data->set.ssl.falsestart); /* false start support */
+ }
+#endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */
+
+ /* Check if there's a cached ID we can/should use here! */
+ if(SSL_SET_OPTION(primary.sessionid)) {
+ char *ssl_sessionid;
+ size_t ssl_sessionid_len;
+
+ Curl_ssl_sessionid_lock(conn);
+ if(!Curl_ssl_getsessionid(conn, (void **)&ssl_sessionid,
+ &ssl_sessionid_len, sockindex)) {
+ /* we got a session id, use it! */
+ 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);
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ /* Informational message */
+ infof(data, "SSL re-using session ID\n");
+ }
+ /* If there isn't one, then let's make one up! This has to be done prior
+ to starting the handshake. */
+ else {
+ CURLcode result;
+ ssl_sessionid =
+ aprintf("%s:%d:%d:%s:%hu", ssl_cafile,
+ verifypeer, SSL_CONN_CONFIG(verifyhost), hostname, port);
+ ssl_sessionid_len = strlen(ssl_sessionid);
+
+ 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);
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+
+ result = Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_sessionid_len,
+ sockindex);
+ Curl_ssl_sessionid_unlock(conn);
+ if(result) {
+ failf(data, "failed to store ssl session");
+ return result;
+ }
+ }
+ }
+
+ err = SSLSetIOFuncs(BACKEND->ssl_ctx, SocketRead, SocketWrite);
+ if(err != noErr) {
+ failf(data, "SSL: SSLSetIOFuncs() failed: OSStatus %d", err);
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+
+ /* pass the raw socket into the SSL layers */
+ /* 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. */
+ 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;
+ }
+
+ connssl->connecting_state = ssl_connect_2;
+ return CURLE_OK;
+}
+
+static long pem_to_der(const char *in, unsigned char **out, size_t *outlen)
+{
+ char *sep_start, *sep_end, *cert_start, *cert_end;
+ size_t i, j, err;
+ size_t len;
+ unsigned char *b64;
+
+ /* Jump through the separators at the beginning of the certificate. */
+ sep_start = strstr(in, "-----");
+ if(sep_start == NULL)
+ return 0;
+ cert_start = strstr(sep_start + 1, "-----");
+ if(cert_start == NULL)
+ return -1;
+
+ cert_start += 5;
+
+ /* Find separator after the end of the certificate. */
+ cert_end = strstr(cert_start, "-----");
+ if(cert_end == NULL)
+ return -1;
+
+ sep_end = strstr(cert_end + 1, "-----");
+ if(sep_end == NULL)
+ return -1;
+ sep_end += 5;
+
+ len = cert_end - cert_start;
+ b64 = malloc(len + 1);
+ if(!b64)
+ return -1;
+
+ /* Create base64 string without linefeeds. */
+ for(i = 0, j = 0; i < len; i++) {
+ if(cert_start[i] != '\r' && cert_start[i] != '\n')
+ b64[j++] = cert_start[i];
+ }
+ b64[j] = '\0';
+
+ err = Curl_base64_decode((const char *)b64, out, outlen);
+ free(b64);
+ if(err) {
+ free(*out);
+ return -1;
+ }
+
+ return sep_end - in;
+}
+
+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[512], *data;
+
+ fd = open(file, 0);
+ if(fd < 0)
+ return -1;
+
+ data = malloc(cap);
+ if(!data) {
+ close(fd);
+ return -1;
+ }
+
+ for(;;) {
+ n = read(fd, buf, sizeof(buf));
+ if(n < 0) {
+ close(fd);
+ free(data);
+ return -1;
+ }
+ else if(n == 0) {
+ close(fd);
+ break;
+ }
+
+ if(len + n >= cap) {
+ cap *= 2;
+ data = Curl_saferealloc(data, cap);
+ if(!data) {
+ close(fd);
+ return -1;
+ }
+ }
+
+ memcpy(data + len, buf, n);
+ len += n;
+ }
+ data[len] = '\0';
+
+ *out = data;
+ *outlen = len;
+
+ return 0;
+}
+
+static int append_cert_to_array(struct Curl_easy *data,
+ unsigned char *buf, size_t buflen,
+ 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;
+ }
+
+ SecCertificateRef cacert =
+ SecCertificateCreateWithData(kCFAllocatorDefault, certdata);
+ CFRelease(certdata);
+ if(!cacert) {
+ failf(data, "SSL: failed to create SecCertificate from CA certificate");
+ return CURLE_SSL_CACERT_BADFILE;
+ }
+
+ /* Check if cacert is valid. */
+ result = CopyCertSubject(data, cacert, &certp);
+ switch(result) {
+ case CURLE_OK:
+ break;
+ case CURLE_PEER_FAILED_VERIFICATION:
+ return CURLE_SSL_CACERT_BADFILE;
+ case CURLE_OUT_OF_MEMORY:
+ default:
+ return result;
+ }
+ free(certp);
+
+ CFArrayAppendValue(array, cacert);
+ CFRelease(cacert);
+
+ return CURLE_OK;
+}
+
+static int verify_cert(const char *cafile, struct Curl_easy *data,
+ SSLContextRef ctx)
+{
+ int n = 0, rc;
+ long res;
+ unsigned char *certbuf, *der;
+ size_t buflen, derlen, offset = 0;
+
+ if(read_cert(cafile, &certbuf, &buflen) < 0) {
+ failf(data, "SSL: failed to read or invalid CA certificate");
+ return CURLE_SSL_CACERT_BADFILE;
+ }
+
+ /*
+ * Certbuf now contains the contents of the certificate file, which can be
+ * - a single DER certificate,
+ * - a single PEM certificate or
+ * - a bunch of PEM certificates (certificate bundle).
+ *
+ * Go through certbuf, and convert any PEM certificate in it into DER
+ * format.
+ */
+ CFMutableArrayRef array = CFArrayCreateMutable(kCFAllocatorDefault, 0,
+ &kCFTypeArrayCallBacks);
+ if(array == NULL) {
+ free(certbuf);
+ failf(data, "SSL: out of memory creating CA certificate array");
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ while(offset < buflen) {
+ n++;
+
+ /*
+ * Check if the certificate is in PEM format, and convert it to DER. If
+ * this fails, we assume the certificate is in DER format.
+ */
+ res = pem_to_der((const char *)certbuf + offset, &der, &derlen);
+ if(res < 0) {
+ free(certbuf);
+ CFRelease(array);
+ failf(data, "SSL: invalid CA certificate #%d (offset %d) in bundle",
+ n, offset);
+ return CURLE_SSL_CACERT_BADFILE;
+ }
+ offset += res;
+
+ if(res == 0 && offset == 0) {
+ /* This is not a PEM file, probably a certificate in DER format. */
+ rc = append_cert_to_array(data, certbuf, buflen, array);
+ free(certbuf);
+ if(rc != CURLE_OK) {
+ CFRelease(array);
+ return rc;
+ }
+ break;
+ }
+ else if(res == 0) {
+ /* No more certificates in the bundle. */
+ free(certbuf);
+ break;
+ }
+
+ rc = append_cert_to_array(data, der, derlen, array);
+ free(der);
+ if(rc != CURLE_OK) {
+ free(certbuf);
+ CFRelease(array);
+ return rc;
+ }
+ }
+
+ SecTrustRef trust;
+ OSStatus ret = SSLCopyPeerTrust(ctx, &trust);
+ if(trust == NULL) {
+ failf(data, "SSL: error getting certificate chain");
+ CFRelease(array);
+ return CURLE_PEER_FAILED_VERIFICATION;
+ }
+ else if(ret != noErr) {
+ CFRelease(array);
+ failf(data, "SSLCopyPeerTrust() returned error %d", ret);
+ return CURLE_PEER_FAILED_VERIFICATION;
+ }
+
+ ret = SecTrustSetAnchorCertificates(trust, array);
+ if(ret != noErr) {
+ CFRelease(array);
+ CFRelease(trust);
+ failf(data, "SecTrustSetAnchorCertificates() returned error %d", ret);
+ return CURLE_PEER_FAILED_VERIFICATION;
+ }
+ ret = SecTrustSetAnchorCertificatesOnly(trust, true);
+ if(ret != noErr) {
+ CFRelease(array);
+ CFRelease(trust);
+ failf(data, "SecTrustSetAnchorCertificatesOnly() returned error %d", ret);
+ return CURLE_PEER_FAILED_VERIFICATION;
+ }
+
+ SecTrustResultType trust_eval = 0;
+ ret = SecTrustEvaluate(trust, &trust_eval);
+ CFRelease(array);
+ CFRelease(trust);
+ if(ret != noErr) {
+ failf(data, "SecTrustEvaluate() returned error %d", ret);
+ return CURLE_PEER_FAILED_VERIFICATION;
+ }
+
+ switch(trust_eval) {
+ case kSecTrustResultUnspecified:
+ case kSecTrustResultProceed:
+ return CURLE_OK;
+
+ case kSecTrustResultRecoverableTrustFailure:
+ case kSecTrustResultDeny:
+ default:
+ failf(data, "SSL: certificate verification failed (result: %d)",
+ trust_eval);
+ return CURLE_PEER_FAILED_VERIFICATION;
+ }
+}
+
+#ifdef SECTRANSP_PINNEDPUBKEY
+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;
+ const unsigned char *spkiHeader = NULL;
+ CFDataRef publicKeyBits = NULL;
+
+ /* Result is returned to caller */
+ CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
+
+ /* if a path wasn't specified, don't pin */
+ if(!pinnedpubkey)
+ return CURLE_OK;
+
+
+ if(!ctx)
+ return result;
+
+ do {
+ SecTrustRef trust;
+ OSStatus ret = SSLCopyPeerTrust(ctx, &trust);
+ if(ret != noErr || trust == NULL)
+ break;
+
+ SecKeyRef keyRef = SecTrustCopyPublicKey(trust);
+ CFRelease(trust);
+ if(keyRef == NULL)
+ break;
+
+#ifdef SECTRANSP_PINNEDPUBKEY_V1
+
+ publicKeyBits = SecKeyCopyExternalRepresentation(keyRef, NULL);
+ CFRelease(keyRef);
+ if(publicKeyBits == NULL)
+ break;
+
+#elif SECTRANSP_PINNEDPUBKEY_V2
+
+ OSStatus success = SecItemExport(keyRef, kSecFormatOpenSSL, 0, NULL,
+ &publicKeyBits);
+ CFRelease(keyRef);
+ if(success != errSecSuccess || publicKeyBits == NULL)
+ break;
+
+#endif /* SECTRANSP_PINNEDPUBKEY_V2 */
+
+ pubkeylen = CFDataGetLength(publicKeyBits);
+ pubkey = (unsigned char *)CFDataGetBytePtr(publicKeyBits);
+
+ switch(pubkeylen) {
+ case 526:
+ /* 4096 bit RSA pubkeylen == 526 */
+ spkiHeader = rsa4096SpkiHeader;
+ break;
+ case 270:
+ /* 2048 bit RSA pubkeylen == 270 */
+ spkiHeader = rsa2048SpkiHeader;
+ break;
+#ifdef SECTRANSP_PINNEDPUBKEY_V1
+ case 65:
+ /* ecDSA secp256r1 pubkeylen == 65 */
+ spkiHeader = ecDsaSecp256r1SpkiHeader;
+ spkiHeaderLength = 26;
+ break;
+ case 97:
+ /* ecDSA secp384r1 pubkeylen == 97 */
+ spkiHeader = ecDsaSecp384r1SpkiHeader;
+ spkiHeaderLength = 23;
+ break;
+ default:
+ infof(data, "SSL: unhandled public key length: %d\n", pubkeylen);
+#elif SECTRANSP_PINNEDPUBKEY_V2
+ default:
+ /* ecDSA secp256r1 pubkeylen == 91 header already included?
+ * ecDSA secp384r1 header already included too
+ * we assume rest of algorithms do same, so do nothing
+ */
+ result = Curl_pin_peer_pubkey(data, pinnedpubkey, pubkey,
+ pubkeylen);
+#endif /* SECTRANSP_PINNEDPUBKEY_V2 */
+ continue; /* break from loop */
+ }
+
+ realpubkeylen = pubkeylen + spkiHeaderLength;
+ realpubkey = malloc(realpubkeylen);
+ if(!realpubkey)
+ break;
+
+ memcpy(realpubkey, spkiHeader, spkiHeaderLength);
+ memcpy(realpubkey + spkiHeaderLength, pubkey, pubkeylen);
+
+ result = Curl_pin_peer_pubkey(data, pinnedpubkey, realpubkey,
+ realpubkeylen);
+
+ } while(0);
+
+ Curl_safefree(realpubkey);
+ if(publicKeyBits != NULL)
+ CFRelease(publicKeyBits);
+
+ return result;
+}
+#endif /* SECTRANSP_PINNEDPUBKEY */
+
+static CURLcode
+sectransp_connect_step2(struct connectdata *conn, int sockindex)
+{
+ struct Curl_easy *data = conn->data;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ OSStatus err;
+ SSLCipherSuite cipher;
+ SSLProtocol protocol = 0;
+ const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
+ conn->host.name;
+
+ DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
+ || ssl_connect_2_reading == connssl->connecting_state
+ || ssl_connect_2_writing == connssl->connecting_state);
+
+ /* Here goes nothing: */
+ err = SSLHandshake(BACKEND->ssl_ctx);
+
+ if(err != noErr) {
+ switch(err) {
+ case errSSLWouldBlock: /* they're not done with us yet */
+ connssl->connecting_state = BACKEND->ssl_direction ?
+ ssl_connect_2_writing : ssl_connect_2_reading;
+ return CURLE_OK;
+
+ /* The below is errSSLServerAuthCompleted; it's not defined in
+ Leopard's headers */
+ case -9841:
+ if(SSL_CONN_CONFIG(CAfile) && SSL_CONN_CONFIG(verifypeer)) {
+ int res = verify_cert(SSL_CONN_CONFIG(CAfile), data,
+ BACKEND->ssl_ctx);
+ if(res != CURLE_OK)
+ return res;
+ }
+ /* the documentation says we need to call SSLHandshake() again */
+ return sectransp_connect_step2(conn, sockindex);
+
+ /* Problem with encrypt / decrypt */
+ case errSSLPeerDecodeError:
+ failf(data, "Decode failed");
+ break;
+ case errSSLDecryptionFail:
+ case errSSLPeerDecryptionFail:
+ failf(data, "Decryption failed");
+ break;
+ case errSSLPeerDecryptError:
+ failf(data, "A decryption error occurred");
+ break;
+ case errSSLBadCipherSuite:
+ failf(data, "A bad SSL cipher suite was encountered");
+ break;
+ case errSSLCrypto:
+ failf(data, "An underlying cryptographic error was encountered");
+ break;
+#if CURL_BUILD_MAC_10_11 || CURL_BUILD_IOS_9
+ case errSSLWeakPeerEphemeralDHKey:
+ failf(data, "Indicates a weak ephemeral Diffie-Hellman key");
+ break;
+#endif
+
+ /* Problem with the message record validation */
+ case errSSLBadRecordMac:
+ case errSSLPeerBadRecordMac:
+ failf(data, "A record with a bad message authentication code (MAC) "
+ "was encountered");
+ break;
+ case errSSLRecordOverflow:
+ case errSSLPeerRecordOverflow:
+ failf(data, "A record overflow occurred");
+ break;
+
+ /* Problem with zlib decompression */
+ case errSSLPeerDecompressFail:
+ failf(data, "Decompression failed");
+ break;
+
+ /* Problem with access */
+ case errSSLPeerAccessDenied:
+ failf(data, "Access was denied");
+ break;
+ case errSSLPeerInsufficientSecurity:
+ failf(data, "There is insufficient security for this operation");
+ break;
+
+ /* These are all certificate problems with the server: */
+ case errSSLXCertChainInvalid:
+ failf(data, "SSL certificate problem: Invalid certificate chain");
+ return CURLE_PEER_FAILED_VERIFICATION;
+ case errSSLUnknownRootCert:
+ failf(data, "SSL certificate problem: Untrusted root certificate");
+ return CURLE_PEER_FAILED_VERIFICATION;
+ case errSSLNoRootCert:
+ failf(data, "SSL certificate problem: No root certificate");
+ return CURLE_PEER_FAILED_VERIFICATION;
+ case errSSLCertNotYetValid:
+ failf(data, "SSL certificate problem: The certificate chain had a "
+ "certificate that is not yet valid");
+ return CURLE_PEER_FAILED_VERIFICATION;
+ case errSSLCertExpired:
+ case errSSLPeerCertExpired:
+ failf(data, "SSL certificate problem: Certificate chain had an "
+ "expired certificate");
+ return CURLE_PEER_FAILED_VERIFICATION;
+ case errSSLBadCert:
+ case errSSLPeerBadCert:
+ failf(data, "SSL certificate problem: Couldn't understand the server "
+ "certificate format");
+ return CURLE_PEER_FAILED_VERIFICATION;
+ case errSSLPeerUnsupportedCert:
+ failf(data, "SSL certificate problem: An unsupported certificate "
+ "format was encountered");
+ return CURLE_PEER_FAILED_VERIFICATION;
+ case errSSLPeerCertRevoked:
+ failf(data, "SSL certificate problem: The certificate was revoked");
+ return CURLE_PEER_FAILED_VERIFICATION;
+ case errSSLPeerCertUnknown:
+ failf(data, "SSL certificate problem: The certificate is unknown");
+ return CURLE_PEER_FAILED_VERIFICATION;
+
+ /* These are all certificate problems with the client: */
+ case errSecAuthFailed:
+ failf(data, "SSL authentication failed");
+ break;
+ case errSSLPeerHandshakeFail:
+ failf(data, "SSL peer handshake failed, the server most likely "
+ "requires a client certificate to connect");
+ break;
+ case errSSLPeerUnknownCA:
+ failf(data, "SSL server rejected the client certificate due to "
+ "the certificate being signed by an unknown certificate "
+ "authority");
+ break;
+
+ /* This error is raised if the server's cert didn't match the server's
+ host name: */
+ case errSSLHostNameMismatch:
+ failf(data, "SSL certificate peer verification failed, the "
+ "certificate did not match \"%s\"\n", conn->host.dispname);
+ return CURLE_PEER_FAILED_VERIFICATION;
+
+ /* Problem with SSL / TLS negotiation */
+ case errSSLNegotiation:
+ failf(data, "Could not negotiate an SSL cipher suite with the server");
+ break;
+ case errSSLBadConfiguration:
+ failf(data, "A configuration error occurred");
+ break;
+ case errSSLProtocol:
+ failf(data, "SSL protocol error");
+ break;
+ case errSSLPeerProtocolVersion:
+ failf(data, "A bad protocol version was encountered");
+ break;
+ case errSSLPeerNoRenegotiation:
+ failf(data, "No renegotiation is allowed");
+ break;
+
+ /* Generic handshake errors: */
+ case errSSLConnectionRefused:
+ failf(data, "Server dropped the connection during the SSL handshake");
+ break;
+ case errSSLClosedAbort:
+ failf(data, "Server aborted the SSL handshake");
+ break;
+ case errSSLClosedGraceful:
+ failf(data, "The connection closed gracefully");
+ break;
+ case errSSLClosedNoNotify:
+ failf(data, "The server closed the session with no notification");
+ break;
+ /* Sometimes paramErr happens with buggy ciphers: */
+ case paramErr:
+ case errSSLInternal:
+ case errSSLPeerInternalError:
+ failf(data, "Internal SSL engine error encountered during the "
+ "SSL handshake");
+ break;
+ case errSSLFatalAlert:
+ failf(data, "Fatal SSL engine error encountered during the SSL "
+ "handshake");
+ break;
+ /* Unclassified error */
+ case errSSLBufferOverflow:
+ failf(data, "An insufficient buffer was provided");
+ break;
+ case errSSLIllegalParam:
+ failf(data, "An illegal parameter was encountered");
+ break;
+ case errSSLModuleAttach:
+ failf(data, "Module attach failure");
+ break;
+ case errSSLSessionNotFound:
+ failf(data, "An attempt to restore an unknown session failed");
+ break;
+ case errSSLPeerExportRestriction:
+ failf(data, "An export restriction occurred");
+ break;
+ case errSSLPeerUserCancelled:
+ failf(data, "The user canceled the operation");
+ break;
+ case errSSLPeerUnexpectedMsg:
+ failf(data, "Peer rejected unexpected message");
+ break;
+#if CURL_BUILD_MAC_10_11 || CURL_BUILD_IOS_9
+ /* Treaing non-fatal error as fatal like before */
+ case errSSLClientHelloReceived:
+ failf(data, "A non-fatal result for providing a server name "
+ "indication");
+ break;
+#endif
+
+ /* Error codes defined in the enum but should never be returned.
+ We list them here just in case. */
+#if CURL_BUILD_MAC_10_6
+ /* Only returned when kSSLSessionOptionBreakOnCertRequested is set */
+ case errSSLClientCertRequested:
+ failf(data, "The server has requested a client certificate");
+ break;
+#endif
+#if CURL_BUILD_MAC_10_9
+ /* Alias for errSSLLast, end of error range */
+ case errSSLUnexpectedRecord:
+ failf(data, "Unexpected (skipped) record in DTLS");
+ break;
+#endif
+ default:
+ /* May also return codes listed in Security Framework Result Codes */
+ failf(data, "Unknown SSL protocol error in connection to %s:%d",
+ hostname, err);
+ break;
+ }
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ else {
+ /* we have been connected fine, we're not waiting for anything else. */
+ connssl->connecting_state = ssl_connect_3;
+
+#ifdef SECTRANSP_PINNEDPUBKEY
+ if(data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]) {
+ 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!");
+ return result;
+ }
+ }
+#endif /* SECTRANSP_PINNEDPUBKEY */
+
+ /* Informational message */
+ (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",
+ SSLCipherNameForNumber(cipher));
+ break;
+ case kSSLProtocol3:
+ infof(data, "SSL 3.0 connection using %s\n",
+ SSLCipherNameForNumber(cipher));
+ break;
+ case kTLSProtocol1:
+ infof(data, "TLS 1.0 connection using %s\n",
+ TLSCipherNameForNumber(cipher));
+ break;
+#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
+ case kTLSProtocol11:
+ infof(data, "TLS 1.1 connection using %s\n",
+ TLSCipherNameForNumber(cipher));
+ break;
+ case kTLSProtocol12:
+ infof(data, "TLS 1.2 connection using %s\n",
+ TLSCipherNameForNumber(cipher));
+ break;
+#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
+#if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11
+ case kTLSProtocol13:
+ infof(data, "TLS 1.3 connection using %s\n",
+ TLSCipherNameForNumber(cipher));
+ break;
+#endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */
+ default:
+ infof(data, "Unknown protocol connection\n");
+ break;
+ }
+
+#if(CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && HAVE_BUILTIN_AVAILABLE == 1
+ if(conn->bits.tls_enable_alpn) {
+ if(__builtin_available(macOS 10.13.4, iOS 11, tvOS 11, *)) {
+ CFArrayRef alpnArr = NULL;
+ CFStringRef chosenProtocol = NULL;
+ err = SSLCopyALPNProtocols(BACKEND->ssl_ctx, &alpnArr);
+
+ if(err == noErr && alpnArr && CFArrayGetCount(alpnArr) >= 1)
+ chosenProtocol = CFArrayGetValueAtIndex(alpnArr, 0);
+
+#ifdef USE_NGHTTP2
+ if(chosenProtocol &&
+ !CFStringCompare(chosenProtocol, CFSTR(NGHTTP2_PROTO_VERSION_ID),
+ 0)) {
+ conn->negnpn = CURL_HTTP_VERSION_2;
+ }
+ else
+#endif
+ if(chosenProtocol &&
+ !CFStringCompare(chosenProtocol, CFSTR(ALPN_HTTP_1_1), 0)) {
+ conn->negnpn = CURL_HTTP_VERSION_1_1;
+ }
+ else
+ infof(data, "ALPN, server did not agree to a protocol\n");
+
+ Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ?
+ BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
+
+ /* chosenProtocol is a reference to the string within alpnArr
+ and doesn't need to be freed separately */
+ if(alpnArr)
+ CFRelease(alpnArr);
+ }
+ }
+#endif
+
+ return CURLE_OK;
+ }
+}
+
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
+/* This should be called during step3 of the connection at the earliest */
+static void
+show_verbose_server_cert(struct connectdata *conn,
+ int sockindex)
+{
+ struct Curl_easy *data = conn->data;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ CFArrayRef server_certs = NULL;
+ SecCertificateRef server_cert;
+ OSStatus err;
+ CFIndex i, count;
+ SecTrustRef trust = NULL;
+
+ if(!BACKEND->ssl_ctx)
+ return;
+
+#if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS
+#if CURL_BUILD_IOS
+#pragma unused(server_certs)
+ 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);
+ result = CopyCertSubject(data, server_cert, &certp);
+ if(!result) {
+ infof(data, "Server certificate: %s\n", certp);
+ free(certp);
+ }
+ }
+ CFRelease(trust);
+ }
+#else
+ /* SSLCopyPeerCertificates() is deprecated as of Mountain Lion.
+ The function SecTrustGetCertificateAtIndex() is officially present
+ in Lion, but it is unfortunately also present in Snow Leopard as
+ private API and doesn't work as expected. So we have to look for
+ a different symbol to make sure this code is only executed under
+ Lion or later. */
+ if(SecTrustEvaluateAsync != NULL) {
+#pragma unused(server_certs)
+ 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);
+ result = CopyCertSubject(data, server_cert, &certp);
+ if(!result) {
+ infof(data, "Server certificate: %s\n", certp);
+ free(certp);
+ }
+ }
+ CFRelease(trust);
+ }
+ }
+ else {
+#if CURL_SUPPORT_MAC_10_8
+ 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);
+ result = CopyCertSubject(data, server_cert, &certp);
+ if(!result) {
+ infof(data, "Server certificate: %s\n", certp);
+ free(certp);
+ }
+ }
+ CFRelease(server_certs);
+ }
+#endif /* CURL_SUPPORT_MAC_10_8 */
+ }
+#endif /* CURL_BUILD_IOS */
+#else
+#pragma unused(trust)
+ 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);
+ result = CopyCertSubject(data, server_cert, &certp);
+ if(!result) {
+ infof(data, "Server certificate: %s\n", certp);
+ free(certp);
+ }
+ }
+ CFRelease(server_certs);
+ }
+#endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */
+}
+#endif /* !CURL_DISABLE_VERBOSE_STRINGS */
+
+static CURLcode
+sectransp_connect_step3(struct connectdata *conn,
+ int sockindex)
+{
+ struct Curl_easy *data = conn->data;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+
+ /* There is no step 3!
+ * Well, okay, if verbose mode is on, let's print the details of the
+ * server certificates. */
+#ifndef CURL_DISABLE_VERBOSE_STRINGS
+ if(data->set.verbose)
+ show_verbose_server_cert(conn, sockindex);
+#endif
+
+ connssl->connecting_state = ssl_connect_done;
+ return CURLE_OK;
+}
+
+static Curl_recv sectransp_recv;
+static Curl_send sectransp_send;
+
+static CURLcode
+sectransp_connect_common(struct connectdata *conn,
+ int sockindex,
+ bool nonblocking,
+ bool *done)
+{
+ CURLcode result;
+ struct Curl_easy *data = conn->data;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ curl_socket_t sockfd = conn->sock[sockindex];
+ long timeout_ms;
+ int what;
+
+ /* check if the connection has already been established */
+ if(ssl_connection_complete == connssl->state) {
+ *done = TRUE;
+ return CURLE_OK;
+ }
+
+ if(ssl_connect_1 == connssl->connecting_state) {
+ /* Find out how much more time we're allowed */
+ timeout_ms = Curl_timeleft(data, NULL, TRUE);
+
+ if(timeout_ms < 0) {
+ /* no need to continue if time already is up */
+ failf(data, "SSL connection timeout");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+
+ result = sectransp_connect_step1(conn, sockindex);
+ if(result)
+ return result;
+ }
+
+ while(ssl_connect_2 == connssl->connecting_state ||
+ ssl_connect_2_reading == connssl->connecting_state ||
+ ssl_connect_2_writing == connssl->connecting_state) {
+
+ /* check allowed time left */
+ timeout_ms = Curl_timeleft(data, NULL, TRUE);
+
+ if(timeout_ms < 0) {
+ /* no need to continue if time already is up */
+ failf(data, "SSL connection timeout");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+
+ /* if ssl is expecting something, check if it's available. */
+ if(connssl->connecting_state == ssl_connect_2_reading ||
+ connssl->connecting_state == 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 ==
+ connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
+
+ what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
+ nonblocking?0:timeout_ms);
+ if(what < 0) {
+ /* fatal error */
+ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
+ return CURLE_SSL_CONNECT_ERROR;
+ }
+ else if(0 == what) {
+ if(nonblocking) {
+ *done = FALSE;
+ return CURLE_OK;
+ }
+ else {
+ /* timeout */
+ failf(data, "SSL connection timeout");
+ return CURLE_OPERATION_TIMEDOUT;
+ }
+ }
+ /* socket is readable or writable */
+ }
+
+ /* Run transaction, and return to the caller if it failed or if this
+ * connection is done nonblocking and this loop would execute again. This
+ * permits the owner of a multi handle to abort a connection attempt
+ * before step2 has completed while ensuring that a client using select()
+ * or epoll() will always have a valid fdset to wait on.
+ */
+ result = sectransp_connect_step2(conn, sockindex);
+ if(result || (nonblocking &&
+ (ssl_connect_2 == connssl->connecting_state ||
+ ssl_connect_2_reading == connssl->connecting_state ||
+ ssl_connect_2_writing == connssl->connecting_state)))
+ return result;
+
+ } /* repeat step2 until all transactions are done. */
+
+
+ if(ssl_connect_3 == connssl->connecting_state) {
+ result = sectransp_connect_step3(conn, sockindex);
+ if(result)
+ return result;
+ }
+
+ if(ssl_connect_done == connssl->connecting_state) {
+ connssl->state = ssl_connection_complete;
+ conn->recv[sockindex] = sectransp_recv;
+ conn->send[sockindex] = sectransp_send;
+ *done = TRUE;
+ }
+ else
+ *done = FALSE;
+
+ /* Reset our connect state machine */
+ connssl->connecting_state = ssl_connect_1;
+
+ return CURLE_OK;
+}
+
+static CURLcode Curl_sectransp_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
+{
+ return sectransp_connect_common(conn, sockindex, TRUE, done);
+}
+
+static CURLcode Curl_sectransp_connect(struct connectdata *conn, int sockindex)
+{
+ CURLcode result;
+ bool done = FALSE;
+
+ result = sectransp_connect_common(conn, sockindex, FALSE, &done);
+
+ if(result)
+ return result;
+
+ DEBUGASSERT(done);
+
+ return CURLE_OK;
+}
+
+static void Curl_sectransp_close(struct connectdata *conn, int sockindex)
+{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+
+ if(BACKEND->ssl_ctx) {
+ (void)SSLClose(BACKEND->ssl_ctx);
+#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
+ if(SSLCreateContext != NULL)
+ CFRelease(BACKEND->ssl_ctx);
+#if CURL_SUPPORT_MAC_10_8
+ else
+ (void)SSLDisposeContext(BACKEND->ssl_ctx);
+#endif /* CURL_SUPPORT_MAC_10_8 */
+#else
+ (void)SSLDisposeContext(BACKEND->ssl_ctx);
+#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
+ BACKEND->ssl_ctx = NULL;
+ }
+ BACKEND->ssl_sockfd = 0;
+}
+
+static int Curl_sectransp_shutdown(struct connectdata *conn, int sockindex)
+{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ struct Curl_easy *data = conn->data;
+ ssize_t nread;
+ int what;
+ int rc;
+ char buf[120];
+
+ if(!BACKEND->ssl_ctx)
+ return 0;
+
+#ifndef CURL_DISABLE_FTP
+ if(data->set.ftp_ccc != CURLFTPSSL_CCC_ACTIVE)
+ return 0;
+#endif
+
+ Curl_sectransp_close(conn, sockindex);
+
+ rc = 0;
+
+ what = SOCKET_READABLE(conn->sock[sockindex], SSL_SHUTDOWN_TIMEOUT);
+
+ for(;;) {
+ if(what < 0) {
+ /* anything that gets here is fatally bad */
+ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
+ rc = -1;
+ break;
+ }
+
+ if(!what) { /* timeout */
+ failf(data, "SSL shutdown timeout");
+ break;
+ }
+
+ /* Something to read, let's do it and hope that it is the close
+ notify alert from the server. No way to SSL_Read now, so use read(). */
+
+ nread = read(conn->sock[sockindex], buf, sizeof(buf));
+
+ if(nread < 0) {
+ failf(data, "read: %s", strerror(errno));
+ rc = -1;
+ }
+
+ if(nread <= 0)
+ break;
+
+ what = SOCKET_READABLE(conn->sock[sockindex], 0);
+ }
+
+ return rc;
+}
+
+static void Curl_sectransp_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
+ function that does this, but I don't want to have to explain to you why I
+ got your application rejected from the App Store due to the use of a
+ private API, so the best we can do is free up our own char array that we
+ created way back in sectransp_connect_step1... */
+ Curl_safefree(ptr);
+}
+
+static size_t Curl_sectransp_version(char *buffer, size_t size)
+{
+ return msnprintf(buffer, size, "SecureTransport");
+}
+
+/*
+ * This function uses SSLGetSessionState to determine connection status.
+ *
+ * Return codes:
+ * 1 means the connection is still in place
+ * 0 means the connection has been closed
+ * -1 means the connection status is unknown
+ */
+static int Curl_sectransp_check_cxn(struct connectdata *conn)
+{
+ struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
+ OSStatus err;
+ SSLSessionState state;
+
+ if(BACKEND->ssl_ctx) {
+ err = SSLGetSessionState(BACKEND->ssl_ctx, &state);
+ if(err == noErr)
+ return state == kSSLConnected || state == kSSLHandshake;
+ return -1;
+ }
+ return 0;
+}
+
+static bool Curl_sectransp_data_pending(const struct connectdata *conn,
+ int connindex)
+{
+ const struct ssl_connect_data *connssl = &conn->ssl[connindex];
+ OSStatus err;
+ size_t buffer;
+
+ if(BACKEND->ssl_ctx) { /* SSL is in use */
+ err = SSLGetBufferedReadSize(BACKEND->ssl_ctx, &buffer);
+ if(err == noErr)
+ return buffer > 0UL;
+ return false;
+ }
+ else
+ return false;
+}
+
+static CURLcode Curl_sectransp_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();
+ entropy[i] = random_number & 0xFF;
+ random_number >>= 8;
+ }
+ i = random_number = 0;
+ return CURLE_OK;
+}
+
+static CURLcode Curl_sectransp_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;
+}
+
+static CURLcode Curl_sectransp_sha256sum(const unsigned char *tmp, /* input */
+ size_t tmplen,
+ unsigned char *sha256sum, /* output */
+ size_t sha256len)
+{
+ assert(sha256len >= CURL_SHA256_DIGEST_LENGTH);
+ (void)CC_SHA256(tmp, (CC_LONG)tmplen, sha256sum);
+ return CURLE_OK;
+}
+
+static bool Curl_sectransp_false_start(void)
+{
+#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7
+ if(SSLSetSessionOption != NULL)
+ return TRUE;
+#endif
+ return FALSE;
+}
+
+static ssize_t sectransp_send(struct connectdata *conn,
+ int sockindex,
+ const void *mem,
+ size_t len,
+ CURLcode *curlcode)
+{
+ /*struct Curl_easy *data = conn->data;*/
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ size_t processed = 0UL;
+ OSStatus err;
+
+ /* The SSLWrite() function works a little differently than expected. The
+ fourth argument (processed) is currently documented in Apple's
+ documentation as: "On return, the length, in bytes, of the data actually
+ written."
+
+ Now, one could interpret that as "written to the socket," but actually,
+ it returns the amount of data that was written to a buffer internal to
+ the SSLContextRef instead. So it's possible for SSLWrite() to return
+ errSSLWouldBlock and a number of bytes "written" because those bytes were
+ encrypted and written to a buffer, not to the socket.
+
+ So if this happens, then we need to keep calling SSLWrite() over and
+ 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(BACKEND->ssl_write_buffered_length) {
+ /* Write the buffered data: */
+ 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 = BACKEND->ssl_write_buffered_length;
+ BACKEND->ssl_write_buffered_length = 0UL;
+ break;
+ case errSSLWouldBlock: /* argh, try again */
+ *curlcode = CURLE_AGAIN;
+ return -1L;
+ default:
+ failf(conn->data, "SSLWrite() returned error %d", err);
+ *curlcode = CURLE_SEND_ERROR;
+ return -1L;
+ }
+ }
+ else {
+ /* We've got new data to write: */
+ 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 */
+ BACKEND->ssl_write_buffered_length = len;
+ *curlcode = CURLE_AGAIN;
+ return -1L;
+ default:
+ failf(conn->data, "SSLWrite() returned error %d", err);
+ *curlcode = CURLE_SEND_ERROR;
+ return -1L;
+ }
+ }
+ }
+ return (ssize_t)processed;
+}
+
+static ssize_t sectransp_recv(struct connectdata *conn,
+ int num,
+ char *buf,
+ size_t buffersize,
+ CURLcode *curlcode)
+{
+ /*struct Curl_easy *data = conn->data;*/
+ struct ssl_connect_data *connssl = &conn->ssl[num];
+ size_t processed = 0UL;
+ OSStatus err = SSLRead(BACKEND->ssl_ctx, buf, buffersize, &processed);
+
+ if(err != noErr) {
+ switch(err) {
+ case errSSLWouldBlock: /* return how much we read (if anything) */
+ if(processed)
+ return (ssize_t)processed;
+ *curlcode = CURLE_AGAIN;
+ return -1L;
+ break;
+
+ /* errSSLClosedGraceful - server gracefully shut down the SSL session
+ errSSLClosedNoNotify - server hung up on us instead of sending a
+ closure alert notice, read() is returning 0
+ Either way, inform the caller that the server disconnected. */
+ case errSSLClosedGraceful:
+ case errSSLClosedNoNotify:
+ *curlcode = CURLE_OK;
+ return -1L;
+ break;
+
+ default:
+ failf(conn->data, "SSLRead() return error %d", err);
+ *curlcode = CURLE_RECV_ERROR;
+ return -1L;
+ break;
+ }
+ }
+ return (ssize_t)processed;
+}
+
+static void *Curl_sectransp_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
+{
+ (void)info;
+ return BACKEND->ssl_ctx;
+}
+
+const struct Curl_ssl Curl_ssl_sectransp = {
+ { CURLSSLBACKEND_SECURETRANSPORT, "secure-transport" }, /* info */
+
+#ifdef SECTRANSP_PINNEDPUBKEY
+ SSLSUPP_PINNEDPUBKEY,
+#else
+ 0,
+#endif /* SECTRANSP_PINNEDPUBKEY */
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_none_init, /* init */
+ Curl_none_cleanup, /* cleanup */
+ Curl_sectransp_version, /* version */
+ Curl_sectransp_check_cxn, /* check_cxn */
+ Curl_sectransp_shutdown, /* shutdown */
+ Curl_sectransp_data_pending, /* data_pending */
+ Curl_sectransp_random, /* random */
+ Curl_none_cert_status_request, /* cert_status_request */
+ Curl_sectransp_connect, /* connect */
+ Curl_sectransp_connect_nonblocking, /* connect_nonblocking */
+ Curl_sectransp_get_internals, /* get_internals */
+ Curl_sectransp_close, /* close_one */
+ Curl_none_close_all, /* close_all */
+ Curl_sectransp_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_sectransp_false_start, /* false_start */
+ Curl_sectransp_md5sum, /* md5sum */
+ Curl_sectransp_sha256sum /* sha256sum */
+};
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+
+#endif /* USE_SECTRANSP */
diff --git a/Utilities/cmcurl/lib/vtls/sectransp.h b/Utilities/cmcurl/lib/vtls/sectransp.h
new file mode 100644
index 000000000..5cec797b3
--- /dev/null
+++ b/Utilities/cmcurl/lib/vtls/sectransp.h
@@ -0,0 +1,32 @@
+#ifndef HEADER_CURL_SECTRANSP_H
+#define HEADER_CURL_SECTRANSP_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2012 - 2014, Nick Zitzmann, <nickzman@gmail.com>.
+ * Copyright (C) 2012 - 2019, 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"
+
+#ifdef USE_SECTRANSP
+
+extern const struct Curl_ssl Curl_ssl_sectransp;
+
+#endif /* USE_SECTRANSP */
+#endif /* HEADER_CURL_SECTRANSP_H */
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/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..aba41e5da
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_disk_acl_freebsd.c
@@ -0,0 +1,702 @@
+/*-
+ * 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},
+#ifdef ACL_ENTRY_INHERITED
+ {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACL_ENTRY_INHERITED}
+#endif
+};
+
+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_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_read_support_filter_zstd.c b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_zstd.c
new file mode 100644
index 000000000..451370693
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_zstd.c
@@ -0,0 +1,292 @@
+/*-
+ * Copyright (c) 2009-2011 Sean Purcell
+ * 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$");
+
+#ifdef HAVE_ERRNO_H
+#include <errno.h>
+#endif
+
+#ifdef HAVE_ERRNO_H
+#include <errno.h>
+#endif
+#include <stdio.h>
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#ifdef HAVE_STRING_H
+#include <string.h>
+#endif
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#if HAVE_ZSTD_H
+#include <cm_zstd.h>
+#endif
+
+#include "archive.h"
+#include "archive_endian.h"
+#include "archive_private.h"
+#include "archive_read_private.h"
+
+#if HAVE_ZSTD_H && HAVE_LIBZSTD
+
+struct private_data {
+ ZSTD_DStream *dstream;
+ unsigned char *out_block;
+ size_t out_block_size;
+ int64_t total_out;
+ char in_frame; /* True = in the middle of a zstd frame. */
+ char eof; /* True = found end of compressed data. */
+};
+
+/* Zstd Filter. */
+static ssize_t zstd_filter_read(struct archive_read_filter *, const void**);
+static int zstd_filter_close(struct archive_read_filter *);
+#endif
+
+/*
+ * Note that we can detect zstd compressed files even if we can't decompress
+ * them. (In fact, we like detecting them because we can give better error
+ * messages.) So the bid framework here gets compiled even if no zstd library
+ * is available.
+ */
+static int zstd_bidder_bid(struct archive_read_filter_bidder *,
+ struct archive_read_filter *);
+static int zstd_bidder_init(struct archive_read_filter *);
+
+int
+archive_read_support_filter_zstd(struct archive *_a)
+{
+ struct archive_read *a = (struct archive_read *)_a;
+ struct archive_read_filter_bidder *bidder;
+
+ archive_check_magic(_a, ARCHIVE_READ_MAGIC,
+ ARCHIVE_STATE_NEW, "archive_read_support_filter_zstd");
+
+ if (__archive_read_get_bidder(a, &bidder) != ARCHIVE_OK)
+ return (ARCHIVE_FATAL);
+
+ bidder->data = NULL;
+ bidder->name = "zstd";
+ bidder->bid = zstd_bidder_bid;
+ bidder->init = zstd_bidder_init;
+ bidder->options = NULL;
+ bidder->free = NULL;
+#if HAVE_ZSTD_H && HAVE_LIBZSTD
+ return (ARCHIVE_OK);
+#else
+ archive_set_error(_a, ARCHIVE_ERRNO_MISC,
+ "Using external zstd program for zstd decompression");
+ return (ARCHIVE_WARN);
+#endif
+}
+
+/*
+ * Test whether we can handle this data.
+ */
+static int
+zstd_bidder_bid(struct archive_read_filter_bidder *self,
+ struct archive_read_filter *filter)
+{
+ const unsigned char *buffer;
+ ssize_t avail;
+ unsigned prefix;
+
+ /* Zstd frame magic values */
+ const unsigned zstd_magic = 0xFD2FB528U;
+
+ (void) self; /* UNUSED */
+
+ buffer = __archive_read_filter_ahead(filter, 4, &avail);
+ if (buffer == NULL)
+ return (0);
+
+ prefix = archive_le32dec(buffer);
+ if (prefix == zstd_magic)
+ return (32);
+
+ return (0);
+}
+
+#if !(HAVE_ZSTD_H && HAVE_LIBZSTD)
+
+/*
+ * If we don't have the library on this system, we can't do the
+ * decompression directly. We can, however, try to run "zstd -d"
+ * in case that's available.
+ */
+static int
+zstd_bidder_init(struct archive_read_filter *self)
+{
+ int r;
+
+ r = __archive_read_program(self, "zstd -d -qq");
+ /* Note: We set the format here even if __archive_read_program()
+ * above fails. We do, after all, know what the format is
+ * even if we weren't able to read it. */
+ self->code = ARCHIVE_FILTER_ZSTD;
+ self->name = "zstd";
+ return (r);
+}
+
+#else
+
+/*
+ * Initialize the filter object
+ */
+static int
+zstd_bidder_init(struct archive_read_filter *self)
+{
+ struct private_data *state;
+ const size_t out_block_size = ZSTD_DStreamOutSize();
+ void *out_block;
+ ZSTD_DStream *dstream;
+
+ self->code = ARCHIVE_FILTER_ZSTD;
+ self->name = "zstd";
+
+ state = (struct private_data *)calloc(sizeof(*state), 1);
+ out_block = (unsigned char *)malloc(out_block_size);
+ dstream = ZSTD_createDStream();
+
+ if (state == NULL || out_block == NULL || dstream == NULL) {
+ free(out_block);
+ free(state);
+ ZSTD_freeDStream(dstream); /* supports free on NULL */
+ archive_set_error(&self->archive->archive, ENOMEM,
+ "Can't allocate data for zstd decompression");
+ return (ARCHIVE_FATAL);
+ }
+
+ self->data = state;
+
+ state->out_block_size = out_block_size;
+ state->out_block = out_block;
+ state->dstream = dstream;
+ self->read = zstd_filter_read;
+ self->skip = NULL; /* not supported */
+ self->close = zstd_filter_close;
+
+ state->eof = 0;
+ state->in_frame = 0;
+
+ return (ARCHIVE_OK);
+}
+
+static ssize_t
+zstd_filter_read(struct archive_read_filter *self, const void **p)
+{
+ struct private_data *state;
+ size_t decompressed;
+ ssize_t avail_in;
+ ZSTD_outBuffer out;
+ ZSTD_inBuffer in;
+
+ state = (struct private_data *)self->data;
+
+ out = (ZSTD_outBuffer) { state->out_block, state->out_block_size, 0 };
+
+ /* Try to fill the output buffer. */
+ while (out.pos < out.size && !state->eof) {
+ if (!state->in_frame) {
+ const size_t ret = ZSTD_initDStream(state->dstream);
+ if (ZSTD_isError(ret)) {
+ archive_set_error(&self->archive->archive,
+ ARCHIVE_ERRNO_MISC,
+ "Error initializing zstd decompressor: %s",
+ ZSTD_getErrorName(ret));
+ return (ARCHIVE_FATAL);
+ }
+ }
+ in.src = __archive_read_filter_ahead(self->upstream, 1,
+ &avail_in);
+ if (avail_in < 0) {
+ return avail_in;
+ }
+ if (in.src == NULL && avail_in == 0) {
+ if (!state->in_frame) {
+ /* end of stream */
+ state->eof = 1;
+ break;
+ } else {
+ archive_set_error(&self->archive->archive,
+ ARCHIVE_ERRNO_MISC,
+ "Truncated zstd input");
+ return (ARCHIVE_FATAL);
+ }
+ }
+ in.size = avail_in;
+ in.pos = 0;
+
+ {
+ const size_t ret =
+ ZSTD_decompressStream(state->dstream, &out, &in);
+
+ if (ZSTD_isError(ret)) {
+ archive_set_error(&self->archive->archive,
+ ARCHIVE_ERRNO_MISC,
+ "Zstd decompression failed: %s",
+ ZSTD_getErrorName(ret));
+ return (ARCHIVE_FATAL);
+ }
+
+ /* Decompressor made some progress */
+ __archive_read_filter_consume(self->upstream, in.pos);
+
+ /* ret guaranteed to be > 0 if frame isn't done yet */
+ state->in_frame = (ret != 0);
+ }
+ }
+
+ decompressed = out.pos;
+ state->total_out += decompressed;
+ if (decompressed == 0)
+ *p = NULL;
+ else
+ *p = state->out_block;
+ return (decompressed);
+}
+
+/*
+ * Clean up the decompressor.
+ */
+static int
+zstd_filter_close(struct archive_read_filter *self)
+{
+ struct private_data *state;
+
+ state = (struct private_data *)self->data;
+
+ ZSTD_freeDStream(state->dstream);
+ free(state->out_block);
+ free(state);
+
+ return (ARCHIVE_OK);
+}
+
+#endif /* HAVE_ZLIB_H && HAVE_LIBZSTD */
diff --git a/Utilities/cmlibarchive/libarchive/archive_version_details.c b/Utilities/cmlibarchive/libarchive/archive_version_details.c
new file mode 100644
index 000000000..b9af6d781
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_version_details.c
@@ -0,0 +1,151 @@
+/*-
+ * 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
+#ifdef HAVE_ZSTD_H
+#include <cm_zstd.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();
+ const char *libzstd = archive_libzstd_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);
+ }
+ if (libzstd) {
+ archive_strcat(&str, " libzstd/");
+ archive_strcat(&str, libzstd);
+ }
+ }
+ 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
+}
+
+const char *
+archive_libzstd_version(void)
+{
+#if HAVE_ZSTD_H && HAVE_LIBZSTD
+ return ZSTD_VERSION_STRING;
+#else
+ return NULL;
+#endif
+}
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_zstd.c b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_zstd.c
new file mode 100644
index 000000000..251b17da5
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_zstd.c
@@ -0,0 +1,335 @@
+/*-
+ * Copyright (c) 2017 Sean Purcell
+ * 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$");
+
+
+#ifdef HAVE_ERRNO_H
+#include <errno.h>
+#endif
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#ifdef HAVE_STRING_H
+#include <string.h>
+#endif
+#ifdef HAVE_ZSTD_H
+#include <cm_zstd.h>
+#endif
+
+#include "archive.h"
+#include "archive_private.h"
+#include "archive_string.h"
+#include "archive_write_private.h"
+
+/* Don't compile this if we don't have zstd.h */
+
+struct private_data {
+ int compression_level;
+#if HAVE_ZSTD_H && HAVE_LIBZSTD
+ ZSTD_CStream *cstream;
+ int64_t total_in;
+ ZSTD_outBuffer out;
+#else
+ struct archive_write_program_data *pdata;
+#endif
+};
+
+static int archive_compressor_zstd_options(struct archive_write_filter *,
+ const char *, const char *);
+static int archive_compressor_zstd_open(struct archive_write_filter *);
+static int archive_compressor_zstd_write(struct archive_write_filter *,
+ const void *, size_t);
+static int archive_compressor_zstd_close(struct archive_write_filter *);
+static int archive_compressor_zstd_free(struct archive_write_filter *);
+#if HAVE_ZSTD_H && HAVE_LIBZSTD
+static int drive_compressor(struct archive_write_filter *,
+ struct private_data *, int, const void *, size_t);
+#endif
+
+
+/*
+ * Add a zstd compression filter to this write handle.
+ */
+int
+archive_write_add_filter_zstd(struct archive *_a)
+{
+ struct archive_write *a = (struct archive_write *)_a;
+ struct archive_write_filter *f = __archive_write_allocate_filter(_a);
+ struct private_data *data;
+ archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC,
+ ARCHIVE_STATE_NEW, "archive_write_add_filter_zstd");
+
+ data = calloc(1, sizeof(*data));
+ if (data == NULL) {
+ archive_set_error(&a->archive, ENOMEM, "Out of memory");
+ return (ARCHIVE_FATAL);
+ }
+ f->data = data;
+ f->open = &archive_compressor_zstd_open;
+ f->options = &archive_compressor_zstd_options;
+ f->close = &archive_compressor_zstd_close;
+ f->free = &archive_compressor_zstd_free;
+ f->code = ARCHIVE_FILTER_ZSTD;
+ f->name = "zstd";
+ data->compression_level = 3; /* Default level used by the zstd CLI */
+#if HAVE_ZSTD_H && HAVE_LIBZSTD
+ data->cstream = ZSTD_createCStream();
+ if (data->cstream == NULL) {
+ free(data);
+ archive_set_error(&a->archive, ENOMEM,
+ "Failed to allocate zstd compressor object");
+ return (ARCHIVE_FATAL);
+ }
+
+ return (ARCHIVE_OK);
+#else
+ data->pdata = __archive_write_program_allocate("zstd");
+ if (data->pdata == NULL) {
+ free(data);
+ archive_set_error(&a->archive, ENOMEM, "Out of memory");
+ return (ARCHIVE_FATAL);
+ }
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
+ "Using external zstd program");
+ return (ARCHIVE_WARN);
+#endif
+}
+
+static int
+archive_compressor_zstd_free(struct archive_write_filter *f)
+{
+ struct private_data *data = (struct private_data *)f->data;
+#if HAVE_ZSTD_H && HAVE_LIBZSTD
+ ZSTD_freeCStream(data->cstream);
+ free(data->out.dst);
+#else
+ __archive_write_program_free(data->pdata);
+#endif
+ free(data);
+ f->data = NULL;
+ return (ARCHIVE_OK);
+}
+
+/*
+ * Set write options.
+ */
+static int
+archive_compressor_zstd_options(struct archive_write_filter *f, const char *key,
+ const char *value)
+{
+ struct private_data *data = (struct private_data *)f->data;
+
+ if (strcmp(key, "compression-level") == 0) {
+ int level = atoi(value);
+#if HAVE_ZSTD_H && HAVE_LIBZSTD
+ if (level < 1 || level > ZSTD_maxCLevel()) {
+#else
+ /* If we don't have the library, hard-code the max level */
+ if (level < 1 || level > 22) {
+#endif
+ return (ARCHIVE_WARN);
+ }
+ data->compression_level = level;
+ return (ARCHIVE_OK);
+ }
+
+ /* Note: The "warn" return is just to inform the options
+ * supervisor that we didn't handle it. It will generate
+ * a suitable error if no one used this option. */
+ return (ARCHIVE_WARN);
+}
+
+#if HAVE_ZSTD_H && HAVE_LIBZSTD
+/*
+ * Setup callback.
+ */
+static int
+archive_compressor_zstd_open(struct archive_write_filter *f)
+{
+ struct private_data *data = (struct private_data *)f->data;
+ int ret;
+
+ ret = __archive_write_open_filter(f->next_filter);
+ if (ret != ARCHIVE_OK)
+ return (ret);
+
+ if (data->out.dst == NULL) {
+ size_t bs = ZSTD_CStreamOutSize(), bpb;
+ if (f->archive->magic == ARCHIVE_WRITE_MAGIC) {
+ /* Buffer size should be a multiple number of
+ * the of bytes per block for performance. */
+ bpb = archive_write_get_bytes_per_block(f->archive);
+ if (bpb > bs)
+ bs = bpb;
+ else if (bpb != 0)
+ bs -= bs % bpb;
+ }
+ data->out.size = bs;
+ data->out.pos = 0;
+ data->out.dst
+ = (unsigned char *)malloc(data->out.size);
+ if (data->out.dst == NULL) {
+ archive_set_error(f->archive, ENOMEM,
+ "Can't allocate data for compression buffer");
+ return (ARCHIVE_FATAL);
+ }
+ }
+
+ f->write = archive_compressor_zstd_write;
+
+ if (ZSTD_isError(ZSTD_initCStream(data->cstream,
+ data->compression_level))) {
+ archive_set_error(f->archive, ARCHIVE_ERRNO_MISC,
+ "Internal error initializing zstd compressor object");
+ return (ARCHIVE_FATAL);
+ }
+
+ return (ARCHIVE_OK);
+}
+
+/*
+ * Write data to the compressed stream.
+ */
+static int
+archive_compressor_zstd_write(struct archive_write_filter *f, const void *buff,
+ size_t length)
+{
+ struct private_data *data = (struct private_data *)f->data;
+ int ret;
+
+ /* Update statistics */
+ data->total_in += length;
+
+ if ((ret = drive_compressor(f, data, 0, buff, length)) != ARCHIVE_OK)
+ return (ret);
+
+ return (ARCHIVE_OK);
+}
+
+/*
+ * Finish the compression...
+ */
+static int
+archive_compressor_zstd_close(struct archive_write_filter *f)
+{
+ struct private_data *data = (struct private_data *)f->data;
+ int r1, r2;
+
+ /* Finish zstd frame */
+ r1 = drive_compressor(f, data, 1, NULL, 0);
+
+ r2 = __archive_write_close_filter(f->next_filter);
+
+ return r1 < r2 ? r1 : r2;
+}
+
+/*
+ * Utility function to push input data through compressor,
+ * writing full output blocks as necessary.
+ *
+ * Note that this handles both the regular write case (finishing ==
+ * false) and the end-of-archive case (finishing == true).
+ */
+static int
+drive_compressor(struct archive_write_filter *f,
+ struct private_data *data, int finishing, const void *src, size_t length)
+{
+ ZSTD_inBuffer in = (ZSTD_inBuffer) { src, length, 0 };
+
+ for (;;) {
+ if (data->out.pos == data->out.size) {
+ const int ret = __archive_write_filter(f->next_filter,
+ data->out.dst, data->out.size);
+ if (ret != ARCHIVE_OK)
+ return (ARCHIVE_FATAL);
+ data->out.pos = 0;
+ }
+
+ /* If there's nothing to do, we're done. */
+ if (!finishing && in.pos == in.size)
+ return (ARCHIVE_OK);
+
+ {
+ const size_t zstdret = !finishing ?
+ ZSTD_compressStream(data->cstream, &data->out, &in)
+ : ZSTD_endStream(data->cstream, &data->out);
+
+ if (ZSTD_isError(zstdret)) {
+ archive_set_error(f->archive,
+ ARCHIVE_ERRNO_MISC,
+ "Zstd compression failed: %s",
+ ZSTD_getErrorName(zstdret));
+ return (ARCHIVE_FATAL);
+ }
+
+ /* If we're finishing, 0 means nothing left to flush */
+ if (finishing && zstdret == 0) {
+ const int ret = __archive_write_filter(f->next_filter,
+ data->out.dst, data->out.pos);
+ return (ret);
+ }
+ }
+ }
+}
+
+#else /* HAVE_ZSTD_H && HAVE_LIBZSTD */
+
+static int
+archive_compressor_zstd_open(struct archive_write_filter *f)
+{
+ struct private_data *data = (struct private_data *)f->data;
+ struct archive_string as;
+ int r;
+
+ archive_string_init(&as);
+ archive_string_sprintf(&as, "zstd -%d", data->compression_level);
+
+ f->write = archive_compressor_zstd_write;
+ r = __archive_write_program_open(f, data->pdata, as.s);
+ archive_string_free(&as);
+ return (r);
+}
+
+static int
+archive_compressor_zstd_write(struct archive_write_filter *f, const void *buff,
+ size_t length)
+{
+ struct private_data *data = (struct private_data *)f->data;
+
+ return __archive_write_program_write(f, data->pdata, buff, length);
+}
+
+static int
+archive_compressor_zstd_close(struct archive_write_filter *f)
+{
+ struct private_data *data = (struct private_data *)f->data;
+
+ return __archive_write_program_close(f, data->pdata);
+}
+
+#endif /* HAVE_ZSTD_H && HAVE_LIBZSTD */
diff --git a/Utilities/cmliblzma/liblzma/api/lzma/lzma12.h b/Utilities/cmliblzma/liblzma/api/lzma/lzma12.h
new file mode 100644
index 000000000..4e32fa3a2
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/api/lzma/lzma12.h
@@ -0,0 +1,420 @@
+/**
+ * \file lzma/lzma12.h
+ * \brief LZMA1 and LZMA2 filters
+ */
+
+/*
+ * Author: Lasse Collin
+ *
+ * This file has been put into the public domain.
+ * You can do whatever you want with this file.
+ *
+ * See ../lzma.h for information about liblzma as a whole.
+ */
+
+#ifndef LZMA_H_INTERNAL
+# error Never include this file directly. Use <lzma.h> instead.
+#endif
+
+
+/**
+ * \brief LZMA1 Filter ID
+ *
+ * LZMA1 is the very same thing as what was called just LZMA in LZMA Utils,
+ * 7-Zip, and LZMA SDK. It's called LZMA1 here to prevent developers from
+ * accidentally using LZMA when they actually want LZMA2.
+ *
+ * LZMA1 shouldn't be used for new applications unless you _really_ know
+ * what you are doing. LZMA2 is almost always a better choice.
+ */
+#define LZMA_FILTER_LZMA1 LZMA_VLI_C(0x4000000000000001)
+
+/**
+ * \brief LZMA2 Filter ID
+ *
+ * Usually you want this instead of LZMA1. Compared to LZMA1, LZMA2 adds
+ * support for LZMA_SYNC_FLUSH, uncompressed chunks (smaller expansion
+ * when trying to compress uncompressible data), possibility to change
+ * lc/lp/pb in the middle of encoding, and some other internal improvements.
+ */
+#define LZMA_FILTER_LZMA2 LZMA_VLI_C(0x21)
+
+
+/**
+ * \brief Match finders
+ *
+ * Match finder has major effect on both speed and compression ratio.
+ * Usually hash chains are faster than binary trees.
+ *
+ * If you will use LZMA_SYNC_FLUSH often, the hash chains may be a better
+ * choice, because binary trees get much higher compression ratio penalty
+ * with LZMA_SYNC_FLUSH.
+ *
+ * The memory usage formulas are only rough estimates, which are closest to
+ * reality when dict_size is a power of two. The formulas are more complex
+ * in reality, and can also change a little between liblzma versions. Use
+ * lzma_raw_encoder_memusage() to get more accurate estimate of memory usage.
+ */
+typedef enum {
+ LZMA_MF_HC3 = 0x03,
+ /**<
+ * \brief Hash Chain with 2- and 3-byte hashing
+ *
+ * Minimum nice_len: 3
+ *
+ * Memory usage:
+ * - dict_size <= 16 MiB: dict_size * 7.5
+ * - dict_size > 16 MiB: dict_size * 5.5 + 64 MiB
+ */
+
+ LZMA_MF_HC4 = 0x04,
+ /**<
+ * \brief Hash Chain with 2-, 3-, and 4-byte hashing
+ *
+ * Minimum nice_len: 4
+ *
+ * Memory usage:
+ * - dict_size <= 32 MiB: dict_size * 7.5
+ * - dict_size > 32 MiB: dict_size * 6.5
+ */
+
+ LZMA_MF_BT2 = 0x12,
+ /**<
+ * \brief Binary Tree with 2-byte hashing
+ *
+ * Minimum nice_len: 2
+ *
+ * Memory usage: dict_size * 9.5
+ */
+
+ LZMA_MF_BT3 = 0x13,
+ /**<
+ * \brief Binary Tree with 2- and 3-byte hashing
+ *
+ * Minimum nice_len: 3
+ *
+ * Memory usage:
+ * - dict_size <= 16 MiB: dict_size * 11.5
+ * - dict_size > 16 MiB: dict_size * 9.5 + 64 MiB
+ */
+
+ LZMA_MF_BT4 = 0x14
+ /**<
+ * \brief Binary Tree with 2-, 3-, and 4-byte hashing
+ *
+ * Minimum nice_len: 4
+ *
+ * Memory usage:
+ * - dict_size <= 32 MiB: dict_size * 11.5
+ * - dict_size > 32 MiB: dict_size * 10.5
+ */
+} lzma_match_finder;
+
+
+/**
+ * \brief Test if given match finder is supported
+ *
+ * Return true if the given match finder is supported by this liblzma build.
+ * Otherwise false is returned. It is safe to call this with a value that
+ * isn't listed in lzma_match_finder enumeration; the return value will be
+ * false.
+ *
+ * There is no way to list which match finders are available in this
+ * particular liblzma version and build. It would be useless, because
+ * a new match finder, which the application developer wasn't aware,
+ * could require giving additional options to the encoder that the older
+ * match finders don't need.
+ */
+extern LZMA_API(lzma_bool) lzma_mf_is_supported(lzma_match_finder match_finder)
+ lzma_nothrow lzma_attr_const;
+
+
+/**
+ * \brief Compression modes
+ *
+ * This selects the function used to analyze the data produced by the match
+ * finder.
+ */
+typedef enum {
+ LZMA_MODE_FAST = 1,
+ /**<
+ * \brief Fast compression
+ *
+ * Fast mode is usually at its best when combined with
+ * a hash chain match finder.
+ */
+
+ LZMA_MODE_NORMAL = 2
+ /**<
+ * \brief Normal compression
+ *
+ * This is usually notably slower than fast mode. Use this
+ * together with binary tree match finders to expose the
+ * full potential of the LZMA1 or LZMA2 encoder.
+ */
+} lzma_mode;
+
+
+/**
+ * \brief Test if given compression mode is supported
+ *
+ * Return true if the given compression mode is supported by this liblzma
+ * build. Otherwise false is returned. It is safe to call this with a value
+ * that isn't listed in lzma_mode enumeration; the return value will be false.
+ *
+ * There is no way to list which modes are available in this particular
+ * liblzma version and build. It would be useless, because a new compression
+ * mode, which the application developer wasn't aware, could require giving
+ * additional options to the encoder that the older modes don't need.
+ */
+extern LZMA_API(lzma_bool) lzma_mode_is_supported(lzma_mode mode)
+ lzma_nothrow lzma_attr_const;
+
+
+/**
+ * \brief Options specific to the LZMA1 and LZMA2 filters
+ *
+ * Since LZMA1 and LZMA2 share most of the code, it's simplest to share
+ * the options structure too. For encoding, all but the reserved variables
+ * need to be initialized unless specifically mentioned otherwise.
+ * lzma_lzma_preset() can be used to get a good starting point.
+ *
+ * For raw decoding, both LZMA1 and LZMA2 need dict_size, preset_dict, and
+ * preset_dict_size (if preset_dict != NULL). LZMA1 needs also lc, lp, and pb.
+ */
+typedef struct {
+ /**
+ * \brief Dictionary size in bytes
+ *
+ * Dictionary size indicates how many bytes of the recently processed
+ * uncompressed data is kept in memory. One method to reduce size of
+ * the uncompressed data is to store distance-length pairs, which
+ * indicate what data to repeat from the dictionary buffer. Thus,
+ * the bigger the dictionary, the better the compression ratio
+ * usually is.
+ *
+ * Maximum size of the dictionary depends on multiple things:
+ * - Memory usage limit
+ * - Available address space (not a problem on 64-bit systems)
+ * - Selected match finder (encoder only)
+ *
+ * Currently the maximum dictionary size for encoding is 1.5 GiB
+ * (i.e. (UINT32_C(1) << 30) + (UINT32_C(1) << 29)) even on 64-bit
+ * systems for certain match finder implementation reasons. In the
+ * future, there may be match finders that support bigger
+ * dictionaries.
+ *
+ * Decoder already supports dictionaries up to 4 GiB - 1 B (i.e.
+ * UINT32_MAX), so increasing the maximum dictionary size of the
+ * encoder won't cause problems for old decoders.
+ *
+ * Because extremely small dictionaries sizes would have unneeded
+ * overhead in the decoder, the minimum dictionary size is 4096 bytes.
+ *
+ * \note When decoding, too big dictionary does no other harm
+ * than wasting memory.
+ */
+ uint32_t dict_size;
+# define LZMA_DICT_SIZE_MIN UINT32_C(4096)
+# define LZMA_DICT_SIZE_DEFAULT (UINT32_C(1) << 23)
+
+ /**
+ * \brief Pointer to an initial dictionary
+ *
+ * It is possible to initialize the LZ77 history window using
+ * a preset dictionary. It is useful when compressing many
+ * similar, relatively small chunks of data independently from
+ * each other. The preset dictionary should contain typical
+ * strings that occur in the files being compressed. The most
+ * probable strings should be near the end of the preset dictionary.
+ *
+ * This feature should be used only in special situations. For
+ * now, it works correctly only with raw encoding and decoding.
+ * Currently none of the container formats supported by
+ * liblzma allow preset dictionary when decoding, thus if
+ * you create a .xz or .lzma file with preset dictionary, it
+ * cannot be decoded with the regular decoder functions. In the
+ * future, the .xz format will likely get support for preset
+ * dictionary though.
+ */
+ const uint8_t *preset_dict;
+
+ /**
+ * \brief Size of the preset dictionary
+ *
+ * Specifies the size of the preset dictionary. If the size is
+ * bigger than dict_size, only the last dict_size bytes are
+ * processed.
+ *
+ * This variable is read only when preset_dict is not NULL.
+ * If preset_dict is not NULL but preset_dict_size is zero,
+ * no preset dictionary is used (identical to only setting
+ * preset_dict to NULL).
+ */
+ uint32_t preset_dict_size;
+
+ /**
+ * \brief Number of literal context bits
+ *
+ * How many of the highest bits of the previous uncompressed
+ * eight-bit byte (also known as `literal') are taken into
+ * account when predicting the bits of the next literal.
+ *
+ * E.g. in typical English text, an upper-case letter is
+ * often followed by a lower-case letter, and a lower-case
+ * letter is usually followed by another lower-case letter.
+ * In the US-ASCII character set, the highest three bits are 010
+ * for upper-case letters and 011 for lower-case letters.
+ * When lc is at least 3, the literal coding can take advantage of
+ * this property in the uncompressed data.
+ *
+ * There is a limit that applies to literal context bits and literal
+ * position bits together: lc + lp <= 4. Without this limit the
+ * decoding could become very slow, which could have security related
+ * results in some cases like email servers doing virus scanning.
+ * This limit also simplifies the internal implementation in liblzma.
+ *
+ * There may be LZMA1 streams that have lc + lp > 4 (maximum possible
+ * lc would be 8). It is not possible to decode such streams with
+ * liblzma.
+ */
+ uint32_t lc;
+# define LZMA_LCLP_MIN 0
+# define LZMA_LCLP_MAX 4
+# define LZMA_LC_DEFAULT 3
+
+ /**
+ * \brief Number of literal position bits
+ *
+ * lp affects what kind of alignment in the uncompressed data is
+ * assumed when encoding literals. A literal is a single 8-bit byte.
+ * See pb below for more information about alignment.
+ */
+ uint32_t lp;
+# define LZMA_LP_DEFAULT 0
+
+ /**
+ * \brief Number of position bits
+ *
+ * pb affects what kind of alignment in the uncompressed data is
+ * assumed in general. The default means four-byte alignment
+ * (2^ pb =2^2=4), which is often a good choice when there's
+ * no better guess.
+ *
+ * When the aligment is known, setting pb accordingly may reduce
+ * the file size a little. E.g. with text files having one-byte
+ * alignment (US-ASCII, ISO-8859-*, UTF-8), setting pb=0 can
+ * improve compression slightly. For UTF-16 text, pb=1 is a good
+ * choice. If the alignment is an odd number like 3 bytes, pb=0
+ * might be the best choice.
+ *
+ * Even though the assumed alignment can be adjusted with pb and
+ * lp, LZMA1 and LZMA2 still slightly favor 16-byte alignment.
+ * It might be worth taking into account when designing file formats
+ * that are likely to be often compressed with LZMA1 or LZMA2.
+ */
+ uint32_t pb;
+# define LZMA_PB_MIN 0
+# define LZMA_PB_MAX 4
+# define LZMA_PB_DEFAULT 2
+
+ /** Compression mode */
+ lzma_mode mode;
+
+ /**
+ * \brief Nice length of a match
+ *
+ * This determines how many bytes the encoder compares from the match
+ * candidates when looking for the best match. Once a match of at
+ * least nice_len bytes long is found, the encoder stops looking for
+ * better candidates and encodes the match. (Naturally, if the found
+ * match is actually longer than nice_len, the actual length is
+ * encoded; it's not truncated to nice_len.)
+ *
+ * Bigger values usually increase the compression ratio and
+ * compression time. For most files, 32 to 128 is a good value,
+ * which gives very good compression ratio at good speed.
+ *
+ * The exact minimum value depends on the match finder. The maximum
+ * is 273, which is the maximum length of a match that LZMA1 and
+ * LZMA2 can encode.
+ */
+ uint32_t nice_len;
+
+ /** Match finder ID */
+ lzma_match_finder mf;
+
+ /**
+ * \brief Maximum search depth in the match finder
+ *
+ * For every input byte, match finder searches through the hash chain
+ * or binary tree in a loop, each iteration going one step deeper in
+ * the chain or tree. The searching stops if
+ * - a match of at least nice_len bytes long is found;
+ * - all match candidates from the hash chain or binary tree have
+ * been checked; or
+ * - maximum search depth is reached.
+ *
+ * Maximum search depth is needed to prevent the match finder from
+ * wasting too much time in case there are lots of short match
+ * candidates. On the other hand, stopping the search before all
+ * candidates have been checked can reduce compression ratio.
+ *
+ * Setting depth to zero tells liblzma to use an automatic default
+ * value, that depends on the selected match finder and nice_len.
+ * The default is in the range [4, 200] or so (it may vary between
+ * liblzma versions).
+ *
+ * Using a bigger depth value than the default can increase
+ * compression ratio in some cases. There is no strict maximum value,
+ * but high values (thousands or millions) should be used with care:
+ * the encoder could remain fast enough with typical input, but
+ * malicious input could cause the match finder to slow down
+ * dramatically, possibly creating a denial of service attack.
+ */
+ uint32_t depth;
+
+ /*
+ * Reserved space to allow possible future extensions without
+ * breaking the ABI. You should not touch these, because the names
+ * of these variables may change. These are and will never be used
+ * with the currently supported options, so it is safe to leave these
+ * uninitialized.
+ */
+ uint32_t reserved_int1;
+ uint32_t reserved_int2;
+ uint32_t reserved_int3;
+ uint32_t reserved_int4;
+ uint32_t reserved_int5;
+ uint32_t reserved_int6;
+ uint32_t reserved_int7;
+ uint32_t reserved_int8;
+ lzma_reserved_enum reserved_enum1;
+ lzma_reserved_enum reserved_enum2;
+ lzma_reserved_enum reserved_enum3;
+ lzma_reserved_enum reserved_enum4;
+ void *reserved_ptr1;
+ void *reserved_ptr2;
+
+} lzma_options_lzma;
+
+
+/**
+ * \brief Set a compression preset to lzma_options_lzma structure
+ *
+ * 0 is the fastest and 9 is the slowest. These match the switches -0 .. -9
+ * of the xz command line tool. In addition, it is possible to bitwise-or
+ * flags to the preset. Currently only LZMA_PRESET_EXTREME is supported.
+ * The flags are defined in container.h, because the flags are used also
+ * with lzma_easy_encoder().
+ *
+ * The preset values are subject to changes between liblzma versions.
+ *
+ * This function is available only if LZMA1 or LZMA2 encoder has been enabled
+ * when building liblzma.
+ *
+ * \return On success, false is returned. If the preset is not
+ * supported, true is returned.
+ */
+extern LZMA_API(lzma_bool) lzma_lzma_preset(
+ lzma_options_lzma *options, uint32_t preset) lzma_nothrow;
diff --git a/Utilities/cmliblzma/liblzma/common/block_buffer_encoder.h b/Utilities/cmliblzma/liblzma/common/block_buffer_encoder.h
new file mode 100644
index 000000000..653207f73
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/block_buffer_encoder.h
@@ -0,0 +1,24 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file block_buffer_encoder.h
+/// \brief Single-call .xz Block encoder
+//
+// Author: Lasse Collin
+//
+// This file has been put into the public domain.
+// You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_BLOCK_BUFFER_ENCODER_H
+#define LZMA_BLOCK_BUFFER_ENCODER_H
+
+#include "common.h"
+
+
+/// uint64_t version of lzma_block_buffer_bound(). It is used by
+/// stream_encoder_mt.c. Probably the original lzma_block_buffer_bound()
+/// should have been 64-bit, but fixing it would break the ABI.
+extern uint64_t lzma_block_buffer_bound64(uint64_t uncompressed_size);
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/hardware_cputhreads.c b/Utilities/cmliblzma/liblzma/common/hardware_cputhreads.c
new file mode 100644
index 000000000..f468366a6
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/hardware_cputhreads.c
@@ -0,0 +1,22 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file hardware_cputhreads.c
+/// \brief Get the number of CPU threads or cores
+//
+// Author: Lasse Collin
+//
+// This file has been put into the public domain.
+// You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+#include "tuklib_cpucores.h"
+
+
+extern LZMA_API(uint32_t)
+lzma_cputhreads(void)
+{
+ return tuklib_cpucores();
+}
diff --git a/Utilities/cmliblzma/liblzma/common/memcmplen.h b/Utilities/cmliblzma/liblzma/common/memcmplen.h
new file mode 100644
index 000000000..c1efc9e28
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/memcmplen.h
@@ -0,0 +1,175 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file memcmplen.h
+/// \brief Optimized comparison of two buffers
+//
+// Author: Lasse Collin
+//
+// This file has been put into the public domain.
+// You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef LZMA_MEMCMPLEN_H
+#define LZMA_MEMCMPLEN_H
+
+#include "common.h"
+
+#ifdef HAVE_IMMINTRIN_H
+# include <immintrin.h>
+#endif
+
+
+/// Find out how many equal bytes the two buffers have.
+///
+/// \param buf1 First buffer
+/// \param buf2 Second buffer
+/// \param len How many bytes have already been compared and will
+/// be assumed to match
+/// \param limit How many bytes to compare at most, including the
+/// already-compared bytes. This must be significantly
+/// smaller than UINT32_MAX to avoid integer overflows.
+/// Up to LZMA_MEMCMPLEN_EXTRA bytes may be read past
+/// the specified limit from both buf1 and buf2.
+///
+/// \return Number of equal bytes in the buffers is returned.
+/// This is always at least len and at most limit.
+///
+/// \note LZMA_MEMCMPLEN_EXTRA defines how many extra bytes may be read.
+/// It's rounded up to 2^n. This extra amount needs to be
+/// allocated in the buffers being used. It needs to be
+/// initialized too to keep Valgrind quiet.
+static inline uint32_t lzma_attribute((__always_inline__))
+lzma_memcmplen(const uint8_t *buf1, const uint8_t *buf2,
+ uint32_t len, uint32_t limit)
+{
+ assert(len <= limit);
+ assert(limit <= UINT32_MAX / 2);
+
+#if defined(TUKLIB_FAST_UNALIGNED_ACCESS) \
+ && ((TUKLIB_GNUC_REQ(3, 4) && defined(__x86_64__)) \
+ || (defined(__INTEL_COMPILER) && defined(__x86_64__)) \
+ || (defined(__INTEL_COMPILER) && defined(_M_X64)) \
+ || (defined(_MSC_VER) && defined(_M_X64)))
+ // NOTE: This will use 64-bit unaligned access which
+ // TUKLIB_FAST_UNALIGNED_ACCESS wasn't meant to permit, but
+ // it's convenient here at least as long as it's x86-64 only.
+ //
+ // I keep this x86-64 only for now since that's where I know this
+ // to be a good method. This may be fine on other 64-bit CPUs too.
+ // On big endian one should use xor instead of subtraction and switch
+ // to __builtin_clzll().
+#define LZMA_MEMCMPLEN_EXTRA 8
+ while (len < limit) {
+ const uint64_t x = *(const uint64_t *)(buf1 + len)
+ - *(const uint64_t *)(buf2 + len);
+ if (x != 0) {
+# if defined(_M_X64) // MSVC or Intel C compiler on Windows
+ unsigned long tmp;
+ _BitScanForward64(&tmp, x);
+ len += (uint32_t)tmp >> 3;
+# else // GCC, clang, or Intel C compiler
+ len += (uint32_t)__builtin_ctzll(x) >> 3;
+# endif
+ return my_min(len, limit);
+ }
+
+ len += 8;
+ }
+
+ return limit;
+
+#elif defined(TUKLIB_FAST_UNALIGNED_ACCESS) \
+ && defined(HAVE__MM_MOVEMASK_EPI8) \
+ && ((defined(__GNUC__) && defined(__SSE2_MATH__)) \
+ || (defined(__INTEL_COMPILER) && defined(__SSE2__)) \
+ || (defined(_MSC_VER) && defined(_M_IX86_FP) \
+ && _M_IX86_FP >= 2))
+ // NOTE: Like above, this will use 128-bit unaligned access which
+ // TUKLIB_FAST_UNALIGNED_ACCESS wasn't meant to permit.
+ //
+ // SSE2 version for 32-bit and 64-bit x86. On x86-64 the above
+ // version is sometimes significantly faster and sometimes
+ // slightly slower than this SSE2 version, so this SSE2
+ // version isn't used on x86-64.
+# define LZMA_MEMCMPLEN_EXTRA 16
+ while (len < limit) {
+ const uint32_t x = 0xFFFF ^ _mm_movemask_epi8(_mm_cmpeq_epi8(
+ _mm_loadu_si128((const __m128i *)(buf1 + len)),
+ _mm_loadu_si128((const __m128i *)(buf2 + len))));
+
+ if (x != 0) {
+# if defined(__INTEL_COMPILER)
+ len += _bit_scan_forward(x);
+# elif defined(_MSC_VER)
+ unsigned long tmp;
+ _BitScanForward(&tmp, x);
+ len += tmp;
+# else
+ len += __builtin_ctz(x);
+# endif
+ return my_min(len, limit);
+ }
+
+ len += 16;
+ }
+
+ return limit;
+
+#elif defined(TUKLIB_FAST_UNALIGNED_ACCESS) && !defined(WORDS_BIGENDIAN)
+ // Generic 32-bit little endian method
+# define LZMA_MEMCMPLEN_EXTRA 4
+ while (len < limit) {
+ uint32_t x = *(const uint32_t *)(buf1 + len)
+ - *(const uint32_t *)(buf2 + len);
+ if (x != 0) {
+ if ((x & 0xFFFF) == 0) {
+ len += 2;
+ x >>= 16;
+ }
+
+ if ((x & 0xFF) == 0)
+ ++len;
+
+ return my_min(len, limit);
+ }
+
+ len += 4;
+ }
+
+ return limit;
+
+#elif defined(TUKLIB_FAST_UNALIGNED_ACCESS) && defined(WORDS_BIGENDIAN)
+ // Generic 32-bit big endian method
+# define LZMA_MEMCMPLEN_EXTRA 4
+ while (len < limit) {
+ uint32_t x = *(const uint32_t *)(buf1 + len)
+ ^ *(const uint32_t *)(buf2 + len);
+ if (x != 0) {
+ if ((x & 0xFFFF0000) == 0) {
+ len += 2;
+ x <<= 16;
+ }
+
+ if ((x & 0xFF000000) == 0)
+ ++len;
+
+ return my_min(len, limit);
+ }
+
+ len += 4;
+ }
+
+ return limit;
+
+#else
+ // Simple portable version that doesn't use unaligned access.
+# define LZMA_MEMCMPLEN_EXTRA 0
+ while (len < limit && buf1[len] == buf2[len])
+ ++len;
+
+ return len;
+#endif
+}
+
+#endif
diff --git a/Utilities/cmliblzma/liblzma/common/outqueue.c b/Utilities/cmliblzma/liblzma/common/outqueue.c
new file mode 100644
index 000000000..2dc8a38d1
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/outqueue.c
@@ -0,0 +1,184 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file outqueue.c
+/// \brief Output queue handling in multithreaded coding
+//
+// Author: Lasse Collin
+//
+// This file has been put into the public domain.
+// You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "outqueue.h"
+
+
+/// This is to ease integer overflow checking: We may allocate up to
+/// 2 * LZMA_THREADS_MAX buffers and we need some extra memory for other
+/// data structures (that's the second /2).
+#define BUF_SIZE_MAX (UINT64_MAX / LZMA_THREADS_MAX / 2 / 2)
+
+
+static lzma_ret
+get_options(uint64_t *bufs_alloc_size, uint32_t *bufs_count,
+ uint64_t buf_size_max, uint32_t threads)
+{
+ if (threads > LZMA_THREADS_MAX || buf_size_max > BUF_SIZE_MAX)
+ return LZMA_OPTIONS_ERROR;
+
+ // The number of buffers is twice the number of threads.
+ // This wastes RAM but keeps the threads busy when buffers
+ // finish out of order.
+ //
+ // NOTE: If this is changed, update BUF_SIZE_MAX too.
+ *bufs_count = threads * 2;
+ *bufs_alloc_size = *bufs_count * buf_size_max;
+
+ return LZMA_OK;
+}
+
+
+extern uint64_t
+lzma_outq_memusage(uint64_t buf_size_max, uint32_t threads)
+{
+ uint64_t bufs_alloc_size;
+ uint32_t bufs_count;
+
+ if (get_options(&bufs_alloc_size, &bufs_count, buf_size_max, threads)
+ != LZMA_OK)
+ return UINT64_MAX;
+
+ return sizeof(lzma_outq) + bufs_count * sizeof(lzma_outbuf)
+ + bufs_alloc_size;
+}
+
+
+extern lzma_ret
+lzma_outq_init(lzma_outq *outq, const lzma_allocator *allocator,
+ uint64_t buf_size_max, uint32_t threads)
+{
+ uint64_t bufs_alloc_size;
+ uint32_t bufs_count;
+
+ // Set bufs_count and bufs_alloc_size.
+ return_if_error(get_options(&bufs_alloc_size, &bufs_count,
+ buf_size_max, threads));
+
+ // Allocate memory if needed.
+ if (outq->buf_size_max != buf_size_max
+ || outq->bufs_allocated != bufs_count) {
+ lzma_outq_end(outq, allocator);
+
+#if SIZE_MAX < UINT64_MAX
+ if (bufs_alloc_size > SIZE_MAX)
+ return LZMA_MEM_ERROR;
+#endif
+
+ outq->bufs = lzma_alloc(bufs_count * sizeof(lzma_outbuf),
+ allocator);
+ outq->bufs_mem = lzma_alloc((size_t)(bufs_alloc_size),
+ allocator);
+
+ if (outq->bufs == NULL || outq->bufs_mem == NULL) {
+ lzma_outq_end(outq, allocator);
+ return LZMA_MEM_ERROR;
+ }
+ }
+
+ // Initialize the rest of the main structure. Initialization of
+ // outq->bufs[] is done when they are actually needed.
+ outq->buf_size_max = (size_t)(buf_size_max);
+ outq->bufs_allocated = bufs_count;
+ outq->bufs_pos = 0;
+ outq->bufs_used = 0;
+ outq->read_pos = 0;
+
+ return LZMA_OK;
+}
+
+
+extern void
+lzma_outq_end(lzma_outq *outq, const lzma_allocator *allocator)
+{
+ lzma_free(outq->bufs, allocator);
+ outq->bufs = NULL;
+
+ lzma_free(outq->bufs_mem, allocator);
+ outq->bufs_mem = NULL;
+
+ return;
+}
+
+
+extern lzma_outbuf *
+lzma_outq_get_buf(lzma_outq *outq)
+{
+ // Caller must have checked it with lzma_outq_has_buf().
+ assert(outq->bufs_used < outq->bufs_allocated);
+
+ // Initialize the new buffer.
+ lzma_outbuf *buf = &outq->bufs[outq->bufs_pos];
+ buf->buf = outq->bufs_mem + outq->bufs_pos * outq->buf_size_max;
+ buf->size = 0;
+ buf->finished = false;
+
+ // Update the queue state.
+ if (++outq->bufs_pos == outq->bufs_allocated)
+ outq->bufs_pos = 0;
+
+ ++outq->bufs_used;
+
+ return buf;
+}
+
+
+extern bool
+lzma_outq_is_readable(const lzma_outq *outq)
+{
+ uint32_t i = outq->bufs_pos - outq->bufs_used;
+ if (outq->bufs_pos < outq->bufs_used)
+ i += outq->bufs_allocated;
+
+ return outq->bufs[i].finished;
+}
+
+
+extern lzma_ret
+lzma_outq_read(lzma_outq *restrict outq, uint8_t *restrict out,
+ size_t *restrict out_pos, size_t out_size,
+ lzma_vli *restrict unpadded_size,
+ lzma_vli *restrict uncompressed_size)
+{
+ // There must be at least one buffer from which to read.
+ if (outq->bufs_used == 0)
+ return LZMA_OK;
+
+ // Get the buffer.
+ uint32_t i = outq->bufs_pos - outq->bufs_used;
+ if (outq->bufs_pos < outq->bufs_used)
+ i += outq->bufs_allocated;
+
+ lzma_outbuf *buf = &outq->bufs[i];
+
+ // If it isn't finished yet, we cannot read from it.
+ if (!buf->finished)
+ return LZMA_OK;
+
+ // Copy from the buffer to output.
+ lzma_bufcpy(buf->buf, &outq->read_pos, buf->size,
+ out, out_pos, out_size);
+
+ // Return if we didn't get all the data from the buffer.
+ if (outq->read_pos < buf->size)
+ return LZMA_OK;
+
+ // The buffer was finished. Tell the caller its size information.
+ *unpadded_size = buf->unpadded_size;
+ *uncompressed_size = buf->uncompressed_size;
+
+ // Free this buffer for further use.
+ --outq->bufs_used;
+ outq->read_pos = 0;
+
+ return LZMA_STREAM_END;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/outqueue.h b/Utilities/cmliblzma/liblzma/common/outqueue.h
new file mode 100644
index 000000000..079634de4
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/outqueue.h
@@ -0,0 +1,156 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file outqueue.h
+/// \brief Output queue handling in multithreaded coding
+//
+// Author: Lasse Collin
+//
+// This file has been put into the public domain.
+// You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "common.h"
+
+
+/// Output buffer for a single thread
+typedef struct {
+ /// Pointer to the output buffer of lzma_outq.buf_size_max bytes
+ uint8_t *buf;
+
+ /// Amount of data written to buf
+ size_t size;
+
+ /// Additional size information
+ lzma_vli unpadded_size;
+ lzma_vli uncompressed_size;
+
+ /// True when no more data will be written into this buffer.
+ ///
+ /// \note This is read by another thread and thus access
+ /// to this variable needs a mutex.
+ bool finished;
+
+} lzma_outbuf;
+
+
+typedef struct {
+ /// Array of buffers that are used cyclically.
+ lzma_outbuf *bufs;
+
+ /// Memory allocated for all the buffers
+ uint8_t *bufs_mem;
+
+ /// Amount of buffer space available in each buffer
+ size_t buf_size_max;
+
+ /// Number of buffers allocated
+ uint32_t bufs_allocated;
+
+ /// Position in the bufs array. The next buffer to be taken
+ /// into use is bufs[bufs_pos].
+ uint32_t bufs_pos;
+
+ /// Number of buffers in use
+ uint32_t bufs_used;
+
+ /// Position in the buffer in lzma_outq_read()
+ size_t read_pos;
+
+} lzma_outq;
+
+
+/**
+ * \brief Calculate the memory usage of an output queue
+ *
+ * \return Approximate memory usage in bytes or UINT64_MAX on error.
+ */
+extern uint64_t lzma_outq_memusage(uint64_t buf_size_max, uint32_t threads);
+
+
+/// \brief Initialize an output queue
+///
+/// \param outq Pointer to an output queue. Before calling
+/// this function the first time, *outq should
+/// have been zeroed with memzero() so that this
+/// function knows that there are no previous
+/// allocations to free.
+/// \param allocator Pointer to allocator or NULL
+/// \param buf_size_max Maximum amount of data that a single buffer
+/// in the queue may need to store.
+/// \param threads Number of buffers that may be in use
+/// concurrently. Note that more than this number
+/// of buffers will actually get allocated to
+/// improve performance when buffers finish
+/// out of order.
+///
+/// \return - LZMA_OK
+/// - LZMA_MEM_ERROR
+///
+extern lzma_ret lzma_outq_init(
+ lzma_outq *outq, const lzma_allocator *allocator,
+ uint64_t buf_size_max, uint32_t threads);
+
+
+/// \brief Free the memory associated with the output queue
+extern void lzma_outq_end(lzma_outq *outq, const lzma_allocator *allocator);
+
+
+/// \brief Get a new buffer
+///
+/// lzma_outq_has_buf() must be used to check that there is a buffer
+/// available before calling lzma_outq_get_buf().
+///
+extern lzma_outbuf *lzma_outq_get_buf(lzma_outq *outq);
+
+
+/// \brief Test if there is data ready to be read
+///
+/// Call to this function must be protected with the same mutex that
+/// is used to protect lzma_outbuf.finished.
+///
+extern bool lzma_outq_is_readable(const lzma_outq *outq);
+
+
+/// \brief Read finished data
+///
+/// \param outq Pointer to an output queue
+/// \param out Beginning of the output buffer
+/// \param out_pos The next byte will be written to
+/// out[*out_pos].
+/// \param out_size Size of the out buffer; the first byte into
+/// which no data is written to is out[out_size].
+/// \param unpadded_size Unpadded Size from the Block encoder
+/// \param uncompressed_size Uncompressed Size from the Block encoder
+///
+/// \return - LZMA: All OK. Either no data was available or the buffer
+/// being read didn't become empty yet.
+/// - LZMA_STREAM_END: The buffer being read was finished.
+/// *unpadded_size and *uncompressed_size were set.
+///
+/// \note This reads lzma_outbuf.finished variables and thus call
+/// to this function needs to be protected with a mutex.
+///
+extern lzma_ret lzma_outq_read(lzma_outq *restrict outq,
+ uint8_t *restrict out, size_t *restrict out_pos,
+ size_t out_size, lzma_vli *restrict unpadded_size,
+ lzma_vli *restrict uncompressed_size);
+
+
+/// \brief Test if there is at least one buffer free
+///
+/// This must be used before getting a new buffer with lzma_outq_get_buf().
+///
+static inline bool
+lzma_outq_has_buf(const lzma_outq *outq)
+{
+ return outq->bufs_used < outq->bufs_allocated;
+}
+
+
+/// \brief Test if the queue is completely empty
+static inline bool
+lzma_outq_is_empty(const lzma_outq *outq)
+{
+ return outq->bufs_used == 0;
+}
diff --git a/Utilities/cmliblzma/liblzma/common/stream_encoder_mt.c b/Utilities/cmliblzma/liblzma/common/stream_encoder_mt.c
new file mode 100644
index 000000000..2efe44c25
--- /dev/null
+++ b/Utilities/cmliblzma/liblzma/common/stream_encoder_mt.c
@@ -0,0 +1,1143 @@
+///////////////////////////////////////////////////////////////////////////////
+//
+/// \file stream_encoder_mt.c
+/// \brief Multithreaded .xz Stream encoder
+//
+// Author: Lasse Collin
+//
+// This file has been put into the public domain.
+// You can do whatever you want with this file.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#include "filter_encoder.h"
+#include "easy_preset.h"
+#include "block_encoder.h"
+#include "block_buffer_encoder.h"
+#include "index_encoder.h"
+#include "outqueue.h"
+
+
+/// Maximum supported block size. This makes it simpler to prevent integer
+/// overflows if we are given unusually large block size.
+#define BLOCK_SIZE_MAX (UINT64_MAX / LZMA_THREADS_MAX)
+
+
+typedef enum {
+ /// Waiting for work.
+ THR_IDLE,
+
+ /// Encoding is in progress.
+ THR_RUN,
+
+ /// Encoding is in progress but no more input data will
+ /// be read.
+ THR_FINISH,
+
+ /// The main thread wants the thread to stop whatever it was doing
+ /// but not exit.
+ THR_STOP,
+
+ /// The main thread wants the thread to exit. We could use
+ /// cancellation but since there's stopped anyway, this is lazier.
+ THR_EXIT,
+
+} worker_state;
+
+typedef struct lzma_stream_coder_s lzma_stream_coder;
+
+typedef struct worker_thread_s worker_thread;
+struct worker_thread_s {
+ worker_state state;
+
+ /// Input buffer of coder->block_size bytes. The main thread will
+ /// put new input into this and update in_size accordingly. Once
+ /// no more input is coming, state will be set to THR_FINISH.
+ uint8_t *in;
+
+ /// Amount of data available in the input buffer. This is modified
+ /// only by the main thread.
+ size_t in_size;
+
+ /// Output buffer for this thread. This is set by the main
+ /// thread every time a new Block is started with this thread
+ /// structure.
+ lzma_outbuf *outbuf;
+
+ /// Pointer to the main structure is needed when putting this
+ /// thread back to the stack of free threads.
+ lzma_stream_coder *coder;
+
+ /// The allocator is set by the main thread. Since a copy of the
+ /// pointer is kept here, the application must not change the
+ /// allocator before calling lzma_end().
+ const lzma_allocator *allocator;
+
+ /// Amount of uncompressed data that has already been compressed.
+ uint64_t progress_in;
+
+ /// Amount of compressed data that is ready.
+ uint64_t progress_out;
+
+ /// Block encoder
+ lzma_next_coder block_encoder;
+
+ /// Compression options for this Block
+ lzma_block block_options;
+
+ /// Next structure in the stack of free worker threads.
+ worker_thread *next;
+
+ mythread_mutex mutex;
+ mythread_cond cond;
+
+ /// The ID of this thread is used to join the thread
+ /// when it's not needed anymore.
+ mythread thread_id;
+};
+
+
+struct lzma_stream_coder_s {
+ enum {
+ SEQ_STREAM_HEADER,
+ SEQ_BLOCK,
+ SEQ_INDEX,
+ SEQ_STREAM_FOOTER,
+ } sequence;
+
+ /// Start a new Block every block_size bytes of input unless
+ /// LZMA_FULL_FLUSH or LZMA_FULL_BARRIER is used earlier.
+ size_t block_size;
+
+ /// The filter chain currently in use
+ lzma_filter filters[LZMA_FILTERS_MAX + 1];
+
+
+ /// Index to hold sizes of the Blocks
+ lzma_index *index;
+
+ /// Index encoder
+ lzma_next_coder index_encoder;
+
+
+ /// Stream Flags for encoding the Stream Header and Stream Footer.
+ lzma_stream_flags stream_flags;
+
+ /// Buffer to hold Stream Header and Stream Footer.
+ uint8_t header[LZMA_STREAM_HEADER_SIZE];
+
+ /// Read position in header[]
+ size_t header_pos;
+
+
+ /// Output buffer queue for compressed data
+ lzma_outq outq;
+
+
+ /// Maximum wait time if cannot use all the input and cannot
+ /// fill the output buffer. This is in milliseconds.
+ uint32_t timeout;
+
+
+ /// Error code from a worker thread
+ lzma_ret thread_error;
+
+ /// Array of allocated thread-specific structures
+ worker_thread *threads;
+
+ /// Number of structures in "threads" above. This is also the
+ /// number of threads that will be created at maximum.
+ uint32_t threads_max;
+
+ /// Number of thread structures that have been initialized, and
+ /// thus the number of worker threads actually created so far.
+ uint32_t threads_initialized;
+
+ /// Stack of free threads. When a thread finishes, it puts itself
+ /// back into this stack. This starts as empty because threads
+ /// are created only when actually needed.
+ worker_thread *threads_free;
+
+ /// The most recent worker thread to which the main thread writes
+ /// the new input from the application.
+ worker_thread *thr;
+
+
+ /// Amount of uncompressed data in Blocks that have already
+ /// been finished.
+ uint64_t progress_in;
+
+ /// Amount of compressed data in Stream Header + Blocks that
+ /// have already been finished.
+ uint64_t progress_out;
+
+
+ mythread_mutex mutex;
+ mythread_cond cond;
+};
+
+
+/// Tell the main thread that something has gone wrong.
+static void
+worker_error(worker_thread *thr, lzma_ret ret)
+{
+ assert(ret != LZMA_OK);
+ assert(ret != LZMA_STREAM_END);
+
+ mythread_sync(thr->coder->mutex) {
+ if (thr->coder->thread_error == LZMA_OK)
+ thr->coder->thread_error = ret;
+
+ mythread_cond_signal(&thr->coder->cond);
+ }
+
+ return;
+}
+
+
+static worker_state
+worker_encode(worker_thread *thr, worker_state state)
+{
+ assert(thr->progress_in == 0);
+ assert(thr->progress_out == 0);
+
+ // Set the Block options.
+ thr->block_options = (lzma_block){
+ .version = 0,
+ .check = thr->coder->stream_flags.check,
+ .compressed_size = thr->coder->outq.buf_size_max,
+ .uncompressed_size = thr->coder->block_size,
+
+ // TODO: To allow changing the filter chain, the filters
+ // array must be copied to each worker_thread.
+ .filters = thr->coder->filters,
+ };
+
+ // Calculate maximum size of the Block Header. This amount is
+ // reserved in the beginning of the buffer so that Block Header
+ // along with Compressed Size and Uncompressed Size can be
+ // written there.
+ lzma_ret ret = lzma_block_header_size(&thr->block_options);
+ if (ret != LZMA_OK) {
+ worker_error(thr, ret);
+ return THR_STOP;
+ }
+
+ // Initialize the Block encoder.
+ ret = lzma_block_encoder_init(&thr->block_encoder,
+ thr->allocator, &thr->block_options);
+ if (ret != LZMA_OK) {
+ worker_error(thr, ret);
+ return THR_STOP;
+ }
+
+ size_t in_pos = 0;
+ size_t in_size = 0;
+
+ thr->outbuf->size = thr->block_options.header_size;
+ const size_t out_size = thr->coder->outq.buf_size_max;
+
+ do {
+ mythread_sync(thr->mutex) {
+ // Store in_pos and out_pos into *thr so that
+ // an application may read them via
+ // lzma_get_progress() to get progress information.
+ //
+ // NOTE: These aren't updated when the encoding
+ // finishes. Instead, the final values are taken
+ // later from thr->outbuf.
+ thr->progress_in = in_pos;
+ thr->progress_out = thr->outbuf->size;
+
+ while (in_size == thr->in_size
+ && thr->state == THR_RUN)
+ mythread_cond_wait(&thr->cond, &thr->mutex);
+
+ state = thr->state;
+ in_size = thr->in_size;
+ }
+
+ // Return if we were asked to stop or exit.
+ if (state >= THR_STOP)
+ return state;
+
+ lzma_action action = state == THR_FINISH
+ ? LZMA_FINISH : LZMA_RUN;
+
+ // Limit the amount of input given to the Block encoder
+ // at once. This way this thread can react fairly quickly
+ // if the main thread wants us to stop or exit.
+ static const size_t in_chunk_max = 16384;
+ size_t in_limit = in_size;
+ if (in_size - in_pos > in_chunk_max) {
+ in_limit = in_pos + in_chunk_max;
+ action = LZMA_RUN;
+ }
+
+ ret = thr->block_encoder.code(
+ thr->block_encoder.coder, thr->allocator,
+ thr->in, &in_pos, in_limit, thr->outbuf->buf,
+ &thr->outbuf->size, out_size, action);
+ } while (ret == LZMA_OK && thr->outbuf->size < out_size);
+
+ switch (ret) {
+ case LZMA_STREAM_END:
+ assert(state == THR_FINISH);
+
+ // Encode the Block Header. By doing it after
+ // the compression, we can store the Compressed Size
+ // and Uncompressed Size fields.
+ ret = lzma_block_header_encode(&thr->block_options,
+ thr->outbuf->buf);
+ if (ret != LZMA_OK) {
+ worker_error(thr, ret);
+ return THR_STOP;
+ }
+
+ break;
+
+ case LZMA_OK:
+ // The data was incompressible. Encode it using uncompressed
+ // LZMA2 chunks.
+ //
+ // First wait that we have gotten all the input.
+ mythread_sync(thr->mutex) {
+ while (thr->state == THR_RUN)
+ mythread_cond_wait(&thr->cond, &thr->mutex);
+
+ state = thr->state;
+ in_size = thr->in_size;
+ }
+
+ if (state >= THR_STOP)
+ return state;
+
+ // Do the encoding. This takes care of the Block Header too.
+ thr->outbuf->size = 0;
+ ret = lzma_block_uncomp_encode(&thr->block_options,
+ thr->in, in_size, thr->outbuf->buf,
+ &thr->outbuf->size, out_size);
+
+ // It shouldn't fail.
+ if (ret != LZMA_OK) {
+ worker_error(thr, LZMA_PROG_ERROR);
+ return THR_STOP;
+ }
+
+ break;
+
+ default:
+ worker_error(thr, ret);
+ return THR_STOP;
+ }
+
+ // Set the size information that will be read by the main thread
+ // to write the Index field.
+ thr->outbuf->unpadded_size
+ = lzma_block_unpadded_size(&thr->block_options);
+ assert(thr->outbuf->unpadded_size != 0);
+ thr->outbuf->uncompressed_size = thr->block_options.uncompressed_size;
+
+ return THR_FINISH;
+}
+
+
+static MYTHREAD_RET_TYPE
+worker_start(void *thr_ptr)
+{
+ worker_thread *thr = thr_ptr;
+ worker_state state = THR_IDLE; // Init to silence a warning
+
+ while (true) {
+ // Wait for work.
+ mythread_sync(thr->mutex) {
+ while (true) {
+ // The thread is already idle so if we are
+ // requested to stop, just set the state.
+ if (thr->state == THR_STOP) {
+ thr->state = THR_IDLE;
+ mythread_cond_signal(&thr->cond);
+ }
+
+ state = thr->state;
+ if (state != THR_IDLE)
+ break;
+
+ mythread_cond_wait(&thr->cond, &thr->mutex);
+ }
+ }
+
+ assert(state != THR_IDLE);
+ assert(state != THR_STOP);
+
+ if (state <= THR_FINISH)
+ state = worker_encode(thr, state);
+
+ if (state == THR_EXIT)
+ break;
+
+ // Mark the thread as idle unless the main thread has
+ // told us to exit. Signal is needed for the case
+ // where the main thread is waiting for the threads to stop.
+ mythread_sync(thr->mutex) {
+ if (thr->state != THR_EXIT) {
+ thr->state = THR_IDLE;
+ mythread_cond_signal(&thr->cond);
+ }
+ }
+
+ mythread_sync(thr->coder->mutex) {
+ // Mark the output buffer as finished if
+ // no errors occurred.
+ thr->outbuf->finished = state == THR_FINISH;
+
+ // Update the main progress info.
+ thr->coder->progress_in
+ += thr->outbuf->uncompressed_size;
+ thr->coder->progress_out += thr->outbuf->size;
+ thr->progress_in = 0;
+ thr->progress_out = 0;
+
+ // Return this thread to the stack of free threads.
+ thr->next = thr->coder->threads_free;
+ thr->coder->threads_free = thr;
+
+ mythread_cond_signal(&thr->coder->cond);
+ }
+ }
+
+ // Exiting, free the resources.
+ mythread_mutex_destroy(&thr->mutex);
+ mythread_cond_destroy(&thr->cond);
+
+ lzma_next_end(&thr->block_encoder, thr->allocator);
+ lzma_free(thr->in, thr->allocator);
+ return MYTHREAD_RET_VALUE;
+}
+
+
+/// Make the threads stop but not exit. Optionally wait for them to stop.
+static void
+threads_stop(lzma_stream_coder *coder, bool wait_for_threads)
+{
+ // Tell the threads to stop.
+ for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
+ mythread_sync(coder->threads[i].mutex) {
+ coder->threads[i].state = THR_STOP;
+ mythread_cond_signal(&coder->threads[i].cond);
+ }
+ }
+
+ if (!wait_for_threads)
+ return;
+
+ // Wait for the threads to settle in the idle state.
+ for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
+ mythread_sync(coder->threads[i].mutex) {
+ while (coder->threads[i].state != THR_IDLE)
+ mythread_cond_wait(&coder->threads[i].cond,
+ &coder->threads[i].mutex);
+ }
+ }
+
+ return;
+}
+
+
+/// Stop the threads and free the resources associated with them.
+/// Wait until the threads have exited.
+static void
+threads_end(lzma_stream_coder *coder, const lzma_allocator *allocator)
+{
+ for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
+ mythread_sync(coder->threads[i].mutex) {
+ coder->threads[i].state = THR_EXIT;
+ mythread_cond_signal(&coder->threads[i].cond);
+ }
+ }
+
+ for (uint32_t i = 0; i < coder->threads_initialized; ++i) {
+ int ret = mythread_join(coder->threads[i].thread_id);
+ assert(ret == 0);
+ (void)ret;
+ }
+
+ lzma_free(coder->threads, allocator);
+ return;
+}
+
+
+/// Initialize a new worker_thread structure and create a new thread.
+static lzma_ret
+initialize_new_thread(lzma_stream_coder *coder,
+ const lzma_allocator *allocator)
+{
+ worker_thread *thr = &coder->threads[coder->threads_initialized];
+
+ thr->in = lzma_alloc(coder->block_size, allocator);
+ if (thr->in == NULL)
+ return LZMA_MEM_ERROR;
+
+ if (mythread_mutex_init(&thr->mutex))
+ goto error_mutex;
+
+ if (mythread_cond_init(&thr->cond))
+ goto error_cond;
+
+ thr->state = THR_IDLE;
+ thr->allocator = allocator;
+ thr->coder = coder;
+ thr->progress_in = 0;
+ thr->progress_out = 0;
+ thr->block_encoder = LZMA_NEXT_CODER_INIT;
+
+ if (mythread_create(&thr->thread_id, &worker_start, thr))
+ goto error_thread;
+
+ ++coder->threads_initialized;
+ coder->thr = thr;
+
+ return LZMA_OK;
+
+error_thread:
+ mythread_cond_destroy(&thr->cond);
+
+error_cond:
+ mythread_mutex_destroy(&thr->mutex);
+
+error_mutex:
+ lzma_free(thr->in, allocator);
+ return LZMA_MEM_ERROR;
+}
+
+
+static lzma_ret
+get_thread(lzma_stream_coder *coder, const lzma_allocator *allocator)
+{
+ // If there are no free output subqueues, there is no
+ // point to try getting a thread.
+ if (!lzma_outq_has_buf(&coder->outq))
+ return LZMA_OK;
+
+ // If there is a free structure on the stack, use it.
+ mythread_sync(coder->mutex) {
+ if (coder->threads_free != NULL) {
+ coder->thr = coder->threads_free;
+ coder->threads_free = coder->threads_free->next;
+ }
+ }
+
+ if (coder->thr == NULL) {
+ // If there are no uninitialized structures left, return.
+ if (coder->threads_initialized == coder->threads_max)
+ return LZMA_OK;
+
+ // Initialize a new thread.
+ return_if_error(initialize_new_thread(coder, allocator));
+ }
+
+ // Reset the parts of the thread state that have to be done
+ // in the main thread.
+ mythread_sync(coder->thr->mutex) {
+ coder->thr->state = THR_RUN;
+ coder->thr->in_size = 0;
+ coder->thr->outbuf = lzma_outq_get_buf(&coder->outq);
+ mythread_cond_signal(&coder->thr->cond);
+ }
+
+ return LZMA_OK;
+}
+
+
+static lzma_ret
+stream_encode_in(lzma_stream_coder *coder, const lzma_allocator *allocator,
+ const uint8_t *restrict in, size_t *restrict in_pos,
+ size_t in_size, lzma_action action)
+{
+ while (*in_pos < in_size
+ || (coder->thr != NULL && action != LZMA_RUN)) {
+ if (coder->thr == NULL) {
+ // Get a new thread.
+ const lzma_ret ret = get_thread(coder, allocator);
+ if (coder->thr == NULL)
+ return ret;
+ }
+
+ // Copy the input data to thread's buffer.
+ size_t thr_in_size = coder->thr->in_size;
+ lzma_bufcpy(in, in_pos, in_size, coder->thr->in,
+ &thr_in_size, coder->block_size);
+
+ // Tell the Block encoder to finish if
+ // - it has got block_size bytes of input; or
+ // - all input was used and LZMA_FINISH, LZMA_FULL_FLUSH,
+ // or LZMA_FULL_BARRIER was used.
+ //
+ // TODO: LZMA_SYNC_FLUSH and LZMA_SYNC_BARRIER.
+ const bool finish = thr_in_size == coder->block_size
+ || (*in_pos == in_size && action != LZMA_RUN);
+
+ bool block_error = false;
+
+ mythread_sync(coder->thr->mutex) {
+ if (coder->thr->state == THR_IDLE) {
+ // Something has gone wrong with the Block
+ // encoder. It has set coder->thread_error
+ // which we will read a few lines later.
+ block_error = true;
+ } else {
+ // Tell the Block encoder its new amount
+ // of input and update the state if needed.
+ coder->thr->in_size = thr_in_size;
+
+ if (finish)
+ coder->thr->state = THR_FINISH;
+
+ mythread_cond_signal(&coder->thr->cond);
+ }
+ }
+
+ if (block_error) {
+ lzma_ret ret;
+
+ mythread_sync(coder->mutex) {
+ ret = coder->thread_error;
+ }
+
+ return ret;
+ }
+
+ if (finish)
+ coder->thr = NULL;
+ }
+
+ return LZMA_OK;
+}
+
+
+/// Wait until more input can be consumed, more output can be read, or
+/// an optional timeout is reached.
+static bool
+wait_for_work(lzma_stream_coder *coder, mythread_condtime *wait_abs,
+ bool *has_blocked, bool has_input)
+{
+ if (coder->timeout != 0 && !*has_blocked) {
+ // Every time when stream_encode_mt() is called via
+ // lzma_code(), *has_blocked starts as false. We set it
+ // to true here and calculate the absolute time when
+ // we must return if there's nothing to do.
+ //
+ // The idea of *has_blocked is to avoid unneeded calls
+ // to mythread_condtime_set(), which may do a syscall
+ // depending on the operating system.
+ *has_blocked = true;
+ mythread_condtime_set(wait_abs, &coder->cond, coder->timeout);
+ }
+
+ bool timed_out = false;
+
+ mythread_sync(coder->mutex) {
+ // There are four things that we wait. If one of them
+ // becomes possible, we return.
+ // - If there is input left, we need to get a free
+ // worker thread and an output buffer for it.
+ // - Data ready to be read from the output queue.
+ // - A worker thread indicates an error.
+ // - Time out occurs.
+ while ((!has_input || coder->threads_free == NULL
+ || !lzma_outq_has_buf(&coder->outq))
+ && !lzma_outq_is_readable(&coder->outq)
+ && coder->thread_error == LZMA_OK
+ && !timed_out) {
+ if (coder->timeout != 0)
+ timed_out = mythread_cond_timedwait(
+ &coder->cond, &coder->mutex,
+ wait_abs) != 0;
+ else
+ mythread_cond_wait(&coder->cond,
+ &coder->mutex);
+ }
+ }
+
+ return timed_out;
+}
+
+
+static lzma_ret
+stream_encode_mt(void *coder_ptr, const lzma_allocator *allocator,
+ const uint8_t *restrict in, size_t *restrict in_pos,
+ size_t in_size, uint8_t *restrict out,
+ size_t *restrict out_pos, size_t out_size, lzma_action action)
+{
+ lzma_stream_coder *coder = coder_ptr;
+
+ switch (coder->sequence) {
+ case SEQ_STREAM_HEADER:
+ lzma_bufcpy(coder->header, &coder->header_pos,
+ sizeof(coder->header),
+ out, out_pos, out_size);
+ if (coder->header_pos < sizeof(coder->header))
+ return LZMA_OK;
+
+ coder->header_pos = 0;
+ coder->sequence = SEQ_BLOCK;
+
+ // Fall through
+
+ case SEQ_BLOCK: {
+ // Initialized to silence warnings.
+ lzma_vli unpadded_size = 0;
+ lzma_vli uncompressed_size = 0;
+ lzma_ret ret = LZMA_OK;
+
+ // These are for wait_for_work().
+ bool has_blocked = false;
+ mythread_condtime wait_abs;
+
+ while (true) {
+ mythread_sync(coder->mutex) {
+ // Check for Block encoder errors.
+ ret = coder->thread_error;
+ if (ret != LZMA_OK) {
+ assert(ret != LZMA_STREAM_END);
+ break;
+ }
+
+ // Try to read compressed data to out[].
+ ret = lzma_outq_read(&coder->outq,
+ out, out_pos, out_size,
+ &unpadded_size,
+ &uncompressed_size);
+ }
+
+ if (ret == LZMA_STREAM_END) {
+ // End of Block. Add it to the Index.
+ ret = lzma_index_append(coder->index,
+ allocator, unpadded_size,
+ uncompressed_size);
+
+ // If we didn't fill the output buffer yet,
+ // try to read more data. Maybe the next
+ // outbuf has been finished already too.
+ if (*out_pos < out_size)
+ continue;
+ }
+
+ if (ret != LZMA_OK) {
+ // coder->thread_error was set or
+ // lzma_index_append() failed.
+ threads_stop(coder, false);
+ return ret;
+ }
+
+ // Try to give uncompressed data to a worker thread.
+ ret = stream_encode_in(coder, allocator,
+ in, in_pos, in_size, action);
+ if (ret != LZMA_OK) {
+ threads_stop(coder, false);
+ return ret;
+ }
+
+ // See if we should wait or return.
+ //
+ // TODO: LZMA_SYNC_FLUSH and LZMA_SYNC_BARRIER.
+ if (*in_pos == in_size) {
+ // LZMA_RUN: More data is probably coming
+ // so return to let the caller fill the
+ // input buffer.
+ if (action == LZMA_RUN)
+ return LZMA_OK;
+
+ // LZMA_FULL_BARRIER: The same as with
+ // LZMA_RUN but tell the caller that the
+ // barrier was completed.
+ if (action == LZMA_FULL_BARRIER)
+ return LZMA_STREAM_END;
+
+ // Finishing or flushing isn't completed until
+ // all input data has been encoded and copied
+ // to the output buffer.
+ if (lzma_outq_is_empty(&coder->outq)) {
+ // LZMA_FINISH: Continue to encode
+ // the Index field.
+ if (action == LZMA_FINISH)
+ break;
+
+ // LZMA_FULL_FLUSH: Return to tell
+ // the caller that flushing was
+ // completed.
+ if (action == LZMA_FULL_FLUSH)
+ return LZMA_STREAM_END;
+ }
+ }
+
+ // Return if there is no output space left.
+ // This check must be done after testing the input
+ // buffer, because we might want to use a different
+ // return code.
+ if (*out_pos == out_size)
+ return LZMA_OK;
+
+ // Neither in nor out has been used completely.
+ // Wait until there's something we can do.
+ if (wait_for_work(coder, &wait_abs, &has_blocked,
+ *in_pos < in_size))
+ return LZMA_TIMED_OUT;
+ }
+
+ // All Blocks have been encoded and the threads have stopped.
+ // Prepare to encode the Index field.
+ return_if_error(lzma_index_encoder_init(
+ &coder->index_encoder, allocator,
+ coder->index));
+ coder->sequence = SEQ_INDEX;
+
+ // Update the progress info to take the Index and
+ // Stream Footer into account. Those are very fast to encode
+ // so in terms of progress information they can be thought
+ // to be ready to be copied out.
+ coder->progress_out += lzma_index_size(coder->index)
+ + LZMA_STREAM_HEADER_SIZE;
+ }
+
+ // Fall through
+
+ case SEQ_INDEX: {
+ // Call the Index encoder. It doesn't take any input, so
+ // those pointers can be NULL.
+ const lzma_ret ret = coder->index_encoder.code(
+ coder->index_encoder.coder, allocator,
+ NULL, NULL, 0,
+ out, out_pos, out_size, LZMA_RUN);
+ if (ret != LZMA_STREAM_END)
+ return ret;
+
+ // Encode the Stream Footer into coder->buffer.
+ coder->stream_flags.backward_size
+ = lzma_index_size(coder->index);
+ if (lzma_stream_footer_encode(&coder->stream_flags,
+ coder->header) != LZMA_OK)
+ return LZMA_PROG_ERROR;
+
+ coder->sequence = SEQ_STREAM_FOOTER;
+ }
+
+ // Fall through
+
+ case SEQ_STREAM_FOOTER:
+ lzma_bufcpy(coder->header, &coder->header_pos,
+ sizeof(coder->header),
+ out, out_pos, out_size);
+ return coder->header_pos < sizeof(coder->header)
+ ? LZMA_OK : LZMA_STREAM_END;
+ }
+
+ assert(0);
+ return LZMA_PROG_ERROR;
+}
+
+
+static void
+stream_encoder_mt_end(void *coder_ptr, const lzma_allocator *allocator)
+{
+ lzma_stream_coder *coder = coder_ptr;
+
+ // Threads must be killed before the output queue can be freed.
+ threads_end(coder, allocator);
+ lzma_outq_end(&coder->outq, allocator);
+
+ for (size_t i = 0; coder->filters[i].id != LZMA_VLI_UNKNOWN; ++i)
+ lzma_free(coder->filters[i].options, allocator);
+
+ lzma_next_end(&coder->index_encoder, allocator);
+ lzma_index_end(coder->index, allocator);
+
+ mythread_cond_destroy(&coder->cond);
+ mythread_mutex_destroy(&coder->mutex);
+
+ lzma_free(coder, allocator);
+ return;
+}
+
+
+/// Options handling for lzma_stream_encoder_mt_init() and
+/// lzma_stream_encoder_mt_memusage()
+static lzma_ret
+get_options(const lzma_mt *options, lzma_options_easy *opt_easy,
+ const lzma_filter **filters, uint64_t *block_size,
+ uint64_t *outbuf_size_max)
+{
+ // Validate some of the options.
+ if (options == NULL)
+ return LZMA_PROG_ERROR;
+
+ if (options->flags != 0 || options->threads == 0
+ || options->threads > LZMA_THREADS_MAX)
+ return LZMA_OPTIONS_ERROR;
+
+ if (options->filters != NULL) {
+ // Filter chain was given, use it as is.
+ *filters = options->filters;
+ } else {
+ // Use a preset.
+ if (lzma_easy_preset(opt_easy, options->preset))
+ return LZMA_OPTIONS_ERROR;
+
+ *filters = opt_easy->filters;
+ }
+
+ // Block size
+ if (options->block_size > 0) {
+ if (options->block_size > BLOCK_SIZE_MAX)
+ return LZMA_OPTIONS_ERROR;
+
+ *block_size = options->block_size;
+ } else {
+ // Determine the Block size from the filter chain.
+ *block_size = lzma_mt_block_size(*filters);
+ if (*block_size == 0)
+ return LZMA_OPTIONS_ERROR;
+
+ assert(*block_size <= BLOCK_SIZE_MAX);
+ }
+
+ // Calculate the maximum amount output that a single output buffer
+ // may need to hold. This is the same as the maximum total size of
+ // a Block.
+ *outbuf_size_max = lzma_block_buffer_bound64(*block_size);
+ if (*outbuf_size_max == 0)
+ return LZMA_MEM_ERROR;
+
+ return LZMA_OK;
+}
+
+
+static void
+get_progress(void *coder_ptr, uint64_t *progress_in, uint64_t *progress_out)
+{
+ lzma_stream_coder *coder = coder_ptr;
+
+ // Lock coder->mutex to prevent finishing threads from moving their
+ // progress info from the worker_thread structure to lzma_stream_coder.
+ mythread_sync(coder->mutex) {
+ *progress_in = coder->progress_in;
+ *progress_out = coder->progress_out;
+
+ for (size_t i = 0; i < coder->threads_initialized; ++i) {
+ mythread_sync(coder->threads[i].mutex) {
+ *progress_in += coder->threads[i].progress_in;
+ *progress_out += coder->threads[i]
+ .progress_out;
+ }
+ }
+ }
+
+ return;
+}
+
+
+static lzma_ret
+stream_encoder_mt_init(lzma_next_coder *next, const lzma_allocator *allocator,
+ const lzma_mt *options)
+{
+ lzma_next_coder_init(&stream_encoder_mt_init, next, allocator);
+
+ // Get the filter chain.
+ lzma_options_easy easy;
+ const lzma_filter *filters;
+ uint64_t block_size;
+ uint64_t outbuf_size_max;
+ return_if_error(get_options(options, &easy, &filters,
+ &block_size, &outbuf_size_max));
+
+#if SIZE_MAX < UINT64_MAX
+ if (block_size > SIZE_MAX)
+ return LZMA_MEM_ERROR;
+#endif
+
+ // Validate the filter chain so that we can give an error in this
+ // function instead of delaying it to the first call to lzma_code().
+ // The memory usage calculation verifies the filter chain as
+ // a side effect so we take advatange of that.
+ if (lzma_raw_encoder_memusage(filters) == UINT64_MAX)
+ return LZMA_OPTIONS_ERROR;
+
+ // Validate the Check ID.
+ if ((unsigned int)(options->check) > LZMA_CHECK_ID_MAX)
+ return LZMA_PROG_ERROR;
+
+ if (!lzma_check_is_supported(options->check))
+ return LZMA_UNSUPPORTED_CHECK;
+
+ // Allocate and initialize the base structure if needed.
+ lzma_stream_coder *coder = next->coder;
+ if (coder == NULL) {
+ coder = lzma_alloc(sizeof(lzma_stream_coder), allocator);
+ if (coder == NULL)
+ return LZMA_MEM_ERROR;
+
+ next->coder = coder;
+
+ // For the mutex and condition variable initializations
+ // the error handling has to be done here because
+ // stream_encoder_mt_end() doesn't know if they have
+ // already been initialized or not.
+ if (mythread_mutex_init(&coder->mutex)) {
+ lzma_free(coder, allocator);
+ next->coder = NULL;
+ return LZMA_MEM_ERROR;
+ }
+
+ if (mythread_cond_init(&coder->cond)) {
+ mythread_mutex_destroy(&coder->mutex);
+ lzma_free(coder, allocator);
+ next->coder = NULL;
+ return LZMA_MEM_ERROR;
+ }
+
+ next->code = &stream_encode_mt;
+ next->end = &stream_encoder_mt_end;
+ next->get_progress = &get_progress;
+// next->update = &stream_encoder_mt_update;
+
+ coder->filters[0].id = LZMA_VLI_UNKNOWN;
+ coder->index_encoder = LZMA_NEXT_CODER_INIT;
+ coder->index = NULL;
+ memzero(&coder->outq, sizeof(coder->outq));
+ coder->threads = NULL;
+ coder->threads_max = 0;
+ coder->threads_initialized = 0;
+ }
+
+ // Basic initializations
+ coder->sequence = SEQ_STREAM_HEADER;
+ coder->block_size = (size_t)(block_size);
+ coder->thread_error = LZMA_OK;
+ coder->thr = NULL;
+
+ // Allocate the thread-specific base structures.
+ assert(options->threads > 0);
+ if (coder->threads_max != options->threads) {
+ threads_end(coder, allocator);
+
+ coder->threads = NULL;
+ coder->threads_max = 0;
+
+ coder->threads_initialized = 0;
+ coder->threads_free = NULL;
+
+ coder->threads = lzma_alloc(
+ options->threads * sizeof(worker_thread),
+ allocator);
+ if (coder->threads == NULL)
+ return LZMA_MEM_ERROR;
+
+ coder->threads_max = options->threads;
+ } else {
+ // Reuse the old structures and threads. Tell the running
+ // threads to stop and wait until they have stopped.
+ threads_stop(coder, true);
+ }
+
+ // Output queue
+ return_if_error(lzma_outq_init(&coder->outq, allocator,
+ outbuf_size_max, options->threads));
+
+ // Timeout
+ coder->timeout = options->timeout;
+
+ // Free the old filter chain and copy the new one.
+ for (size_t i = 0; coder->filters[i].id != LZMA_VLI_UNKNOWN; ++i)
+ lzma_free(coder->filters[i].options, allocator);
+
+ return_if_error(lzma_filters_copy(
+ filters, coder->filters, allocator));
+
+ // Index
+ lzma_index_end(coder->index, allocator);
+ coder->index = lzma_index_init(allocator);
+ if (coder->index == NULL)
+ return LZMA_MEM_ERROR;
+
+ // Stream Header
+ coder->stream_flags.version = 0;
+ coder->stream_flags.check = options->check;
+ return_if_error(lzma_stream_header_encode(
+ &coder->stream_flags, coder->header));
+
+ coder->header_pos = 0;
+
+ // Progress info
+ coder->progress_in = 0;
+ coder->progress_out = LZMA_STREAM_HEADER_SIZE;
+
+ return LZMA_OK;
+}
+
+
+extern LZMA_API(lzma_ret)
+lzma_stream_encoder_mt(lzma_stream *strm, const lzma_mt *options)
+{
+ lzma_next_strm_init(stream_encoder_mt_init, strm, options);
+
+ strm->internal->supported_actions[LZMA_RUN] = true;
+// strm->internal->supported_actions[LZMA_SYNC_FLUSH] = true;
+ strm->internal->supported_actions[LZMA_FULL_FLUSH] = true;
+ strm->internal->supported_actions[LZMA_FULL_BARRIER] = true;
+ strm->internal->supported_actions[LZMA_FINISH] = true;
+
+ return LZMA_OK;
+}
+
+
+// This function name is a monster but it's consistent with the older
+// monster names. :-( 31 chars is the max that C99 requires so in that
+// sense it's not too long. ;-)
+extern LZMA_API(uint64_t)
+lzma_stream_encoder_mt_memusage(const lzma_mt *options)
+{
+ lzma_options_easy easy;
+ const lzma_filter *filters;
+ uint64_t block_size;
+ uint64_t outbuf_size_max;
+
+ if (get_options(options, &easy, &filters, &block_size,
+ &outbuf_size_max) != LZMA_OK)
+ return UINT64_MAX;
+
+ // Memory usage of the input buffers
+ const uint64_t inbuf_memusage = options->threads * block_size;
+
+ // Memory usage of the filter encoders
+ uint64_t filters_memusage = lzma_raw_encoder_memusage(filters);
+ if (filters_memusage == UINT64_MAX)
+ return UINT64_MAX;
+
+ filters_memusage *= options->threads;
+
+ // Memory usage of the output queue
+ const uint64_t outq_memusage = lzma_outq_memusage(
+ outbuf_size_max, options->threads);
+ if (outq_memusage == UINT64_MAX)
+ return UINT64_MAX;
+
+ // Sum them with overflow checking.
+ uint64_t total_memusage = LZMA_MEMUSAGE_BASE
+ + sizeof(lzma_stream_coder)
+ + options->threads * sizeof(worker_thread);
+
+ if (UINT64_MAX - total_memusage < inbuf_memusage)
+ return UINT64_MAX;
+
+ total_memusage += inbuf_memusage;
+
+ if (UINT64_MAX - total_memusage < filters_memusage)
+ return UINT64_MAX;
+
+ total_memusage += filters_memusage;
+
+ if (UINT64_MAX - total_memusage < outq_memusage)
+ return UINT64_MAX;
+
+ return total_memusage + outq_memusage;
+}
diff --git a/Utilities/cmlibuv/include/uv/aix.h b/Utilities/cmlibuv/include/uv/aix.h
new file mode 100644
index 000000000..7dc992fa6
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/aix.h
@@ -0,0 +1,32 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef UV_AIX_H
+#define UV_AIX_H
+
+#define UV_PLATFORM_LOOP_FIELDS \
+ int fs_fd; \
+
+#define UV_PLATFORM_FS_EVENT_FIELDS \
+ uv__io_t event_watcher; \
+ char *dir_filename; \
+
+#endif /* UV_AIX_H */
diff --git a/Utilities/cmlibuv/include/uv/android-ifaddrs.h b/Utilities/cmlibuv/include/uv/android-ifaddrs.h
new file mode 100644
index 000000000..9cd19fec1
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/android-ifaddrs.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 1995, 1999
+ * Berkeley Software Design, Inc. 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.
+ *
+ * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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.
+ *
+ * BSDI ifaddrs.h,v 2.5 2000/02/23 14:51:59 dab Exp
+ */
+
+#ifndef _IFADDRS_H_
+#define _IFADDRS_H_
+
+struct ifaddrs {
+ struct ifaddrs *ifa_next;
+ char *ifa_name;
+ unsigned int ifa_flags;
+ struct sockaddr *ifa_addr;
+ struct sockaddr *ifa_netmask;
+ struct sockaddr *ifa_dstaddr;
+ void *ifa_data;
+};
+
+/*
+ * This may have been defined in <net/if.h>. Note that if <net/if.h> is
+ * to be included it must be included before this header file.
+ */
+#ifndef ifa_broadaddr
+#define ifa_broadaddr ifa_dstaddr /* broadcast address interface */
+#endif
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+extern int getifaddrs(struct ifaddrs **ifap);
+extern void freeifaddrs(struct ifaddrs *ifa);
+__END_DECLS
+
+#endif
diff --git a/Utilities/cmlibuv/include/uv/bsd.h b/Utilities/cmlibuv/include/uv/bsd.h
new file mode 100644
index 000000000..2d72b3d77
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/bsd.h
@@ -0,0 +1,34 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef UV_BSD_H
+#define UV_BSD_H
+
+#define UV_PLATFORM_FS_EVENT_FIELDS \
+ uv__io_t event_watcher; \
+
+#define UV_IO_PRIVATE_PLATFORM_FIELDS \
+ int rcount; \
+ int wcount; \
+
+#define UV_HAVE_KQUEUE 1
+
+#endif /* UV_BSD_H */
diff --git a/Utilities/cmlibuv/include/uv/darwin.h b/Utilities/cmlibuv/include/uv/darwin.h
new file mode 100644
index 000000000..d22641582
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/darwin.h
@@ -0,0 +1,61 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef UV_DARWIN_H
+#define UV_DARWIN_H
+
+#if defined(__APPLE__) && defined(__MACH__)
+# include <mach/mach.h>
+# include <mach/task.h>
+# include <mach/semaphore.h>
+# include <TargetConditionals.h>
+# define UV_PLATFORM_SEM_T semaphore_t
+#endif
+
+#define UV_IO_PRIVATE_PLATFORM_FIELDS \
+ int rcount; \
+ int wcount; \
+
+#define UV_PLATFORM_LOOP_FIELDS \
+ uv_thread_t cf_thread; \
+ void* _cf_reserved; \
+ void* cf_state; \
+ uv_mutex_t cf_mutex; \
+ uv_sem_t cf_sem; \
+ void* cf_signals[2]; \
+
+#define UV_PLATFORM_FS_EVENT_FIELDS \
+ uv__io_t event_watcher; \
+ char* realpath; \
+ int realpath_len; \
+ int cf_flags; \
+ uv_async_t* cf_cb; \
+ void* cf_events[2]; \
+ void* cf_member[2]; \
+ int cf_error; \
+ uv_mutex_t cf_mutex; \
+
+#define UV_STREAM_PRIVATE_PLATFORM_FIELDS \
+ void* select; \
+
+#define UV_HAVE_KQUEUE 1
+
+#endif /* UV_DARWIN_H */
diff --git a/Utilities/cmlibuv/include/uv/errno.h b/Utilities/cmlibuv/include/uv/errno.h
new file mode 100644
index 000000000..8eeb95de3
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/errno.h
@@ -0,0 +1,443 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef UV_ERRNO_H_
+#define UV_ERRNO_H_
+
+#include <errno.h>
+#if EDOM > 0
+# define UV__ERR(x) (-(x))
+#else
+# define UV__ERR(x) (x)
+#endif
+
+#define UV__EOF (-4095)
+#define UV__UNKNOWN (-4094)
+
+#define UV__EAI_ADDRFAMILY (-3000)
+#define UV__EAI_AGAIN (-3001)
+#define UV__EAI_BADFLAGS (-3002)
+#define UV__EAI_CANCELED (-3003)
+#define UV__EAI_FAIL (-3004)
+#define UV__EAI_FAMILY (-3005)
+#define UV__EAI_MEMORY (-3006)
+#define UV__EAI_NODATA (-3007)
+#define UV__EAI_NONAME (-3008)
+#define UV__EAI_OVERFLOW (-3009)
+#define UV__EAI_SERVICE (-3010)
+#define UV__EAI_SOCKTYPE (-3011)
+#define UV__EAI_BADHINTS (-3013)
+#define UV__EAI_PROTOCOL (-3014)
+
+/* Only map to the system errno on non-Windows platforms. It's apparently
+ * a fairly common practice for Windows programmers to redefine errno codes.
+ */
+#if defined(E2BIG) && !defined(_WIN32)
+# define UV__E2BIG UV__ERR(E2BIG)
+#else
+# define UV__E2BIG (-4093)
+#endif
+
+#if defined(EACCES) && !defined(_WIN32)
+# define UV__EACCES UV__ERR(EACCES)
+#else
+# define UV__EACCES (-4092)
+#endif
+
+#if defined(EADDRINUSE) && !defined(_WIN32)
+# define UV__EADDRINUSE UV__ERR(EADDRINUSE)
+#else
+# define UV__EADDRINUSE (-4091)
+#endif
+
+#if defined(EADDRNOTAVAIL) && !defined(_WIN32)
+# define UV__EADDRNOTAVAIL UV__ERR(EADDRNOTAVAIL)
+#else
+# define UV__EADDRNOTAVAIL (-4090)
+#endif
+
+#if defined(EAFNOSUPPORT) && !defined(_WIN32)
+# define UV__EAFNOSUPPORT UV__ERR(EAFNOSUPPORT)
+#else
+# define UV__EAFNOSUPPORT (-4089)
+#endif
+
+#if defined(EAGAIN) && !defined(_WIN32)
+# define UV__EAGAIN UV__ERR(EAGAIN)
+#else
+# define UV__EAGAIN (-4088)
+#endif
+
+#if defined(EALREADY) && !defined(_WIN32)
+# define UV__EALREADY UV__ERR(EALREADY)
+#else
+# define UV__EALREADY (-4084)
+#endif
+
+#if defined(EBADF) && !defined(_WIN32)
+# define UV__EBADF UV__ERR(EBADF)
+#else
+# define UV__EBADF (-4083)
+#endif
+
+#if defined(EBUSY) && !defined(_WIN32)
+# define UV__EBUSY UV__ERR(EBUSY)
+#else
+# define UV__EBUSY (-4082)
+#endif
+
+#if defined(ECANCELED) && !defined(_WIN32)
+# define UV__ECANCELED UV__ERR(ECANCELED)
+#else
+# define UV__ECANCELED (-4081)
+#endif
+
+#if defined(ECHARSET) && !defined(_WIN32)
+# define UV__ECHARSET UV__ERR(ECHARSET)
+#else
+# define UV__ECHARSET (-4080)
+#endif
+
+#if defined(ECONNABORTED) && !defined(_WIN32)
+# define UV__ECONNABORTED UV__ERR(ECONNABORTED)
+#else
+# define UV__ECONNABORTED (-4079)
+#endif
+
+#if defined(ECONNREFUSED) && !defined(_WIN32)
+# define UV__ECONNREFUSED UV__ERR(ECONNREFUSED)
+#else
+# define UV__ECONNREFUSED (-4078)
+#endif
+
+#if defined(ECONNRESET) && !defined(_WIN32)
+# define UV__ECONNRESET UV__ERR(ECONNRESET)
+#else
+# define UV__ECONNRESET (-4077)
+#endif
+
+#if defined(EDESTADDRREQ) && !defined(_WIN32)
+# define UV__EDESTADDRREQ UV__ERR(EDESTADDRREQ)
+#else
+# define UV__EDESTADDRREQ (-4076)
+#endif
+
+#if defined(EEXIST) && !defined(_WIN32)
+# define UV__EEXIST UV__ERR(EEXIST)
+#else
+# define UV__EEXIST (-4075)
+#endif
+
+#if defined(EFAULT) && !defined(_WIN32)
+# define UV__EFAULT UV__ERR(EFAULT)
+#else
+# define UV__EFAULT (-4074)
+#endif
+
+#if defined(EHOSTUNREACH) && !defined(_WIN32)
+# define UV__EHOSTUNREACH UV__ERR(EHOSTUNREACH)
+#else
+# define UV__EHOSTUNREACH (-4073)
+#endif
+
+#if defined(EINTR) && !defined(_WIN32)
+# define UV__EINTR UV__ERR(EINTR)
+#else
+# define UV__EINTR (-4072)
+#endif
+
+#if defined(EINVAL) && !defined(_WIN32)
+# define UV__EINVAL UV__ERR(EINVAL)
+#else
+# define UV__EINVAL (-4071)
+#endif
+
+#if defined(EIO) && !defined(_WIN32)
+# define UV__EIO UV__ERR(EIO)
+#else
+# define UV__EIO (-4070)
+#endif
+
+#if defined(EISCONN) && !defined(_WIN32)
+# define UV__EISCONN UV__ERR(EISCONN)
+#else
+# define UV__EISCONN (-4069)
+#endif
+
+#if defined(EISDIR) && !defined(_WIN32)
+# define UV__EISDIR UV__ERR(EISDIR)
+#else
+# define UV__EISDIR (-4068)
+#endif
+
+#if defined(ELOOP) && !defined(_WIN32)
+# define UV__ELOOP UV__ERR(ELOOP)
+#else
+# define UV__ELOOP (-4067)
+#endif
+
+#if defined(EMFILE) && !defined(_WIN32)
+# define UV__EMFILE UV__ERR(EMFILE)
+#else
+# define UV__EMFILE (-4066)
+#endif
+
+#if defined(EMSGSIZE) && !defined(_WIN32)
+# define UV__EMSGSIZE UV__ERR(EMSGSIZE)
+#else
+# define UV__EMSGSIZE (-4065)
+#endif
+
+#if defined(ENAMETOOLONG) && !defined(_WIN32)
+# define UV__ENAMETOOLONG UV__ERR(ENAMETOOLONG)
+#else
+# define UV__ENAMETOOLONG (-4064)
+#endif
+
+#if defined(ENETDOWN) && !defined(_WIN32)
+# define UV__ENETDOWN UV__ERR(ENETDOWN)
+#else
+# define UV__ENETDOWN (-4063)
+#endif
+
+#if defined(ENETUNREACH) && !defined(_WIN32)
+# define UV__ENETUNREACH UV__ERR(ENETUNREACH)
+#else
+# define UV__ENETUNREACH (-4062)
+#endif
+
+#if defined(ENFILE) && !defined(_WIN32)
+# define UV__ENFILE UV__ERR(ENFILE)
+#else
+# define UV__ENFILE (-4061)
+#endif
+
+#if defined(ENOBUFS) && !defined(_WIN32)
+# define UV__ENOBUFS UV__ERR(ENOBUFS)
+#else
+# define UV__ENOBUFS (-4060)
+#endif
+
+#if defined(ENODEV) && !defined(_WIN32)
+# define UV__ENODEV UV__ERR(ENODEV)
+#else
+# define UV__ENODEV (-4059)
+#endif
+
+#if defined(ENOENT) && !defined(_WIN32)
+# define UV__ENOENT UV__ERR(ENOENT)
+#else
+# define UV__ENOENT (-4058)
+#endif
+
+#if defined(ENOMEM) && !defined(_WIN32)
+# define UV__ENOMEM UV__ERR(ENOMEM)
+#else
+# define UV__ENOMEM (-4057)
+#endif
+
+#if defined(ENONET) && !defined(_WIN32)
+# define UV__ENONET UV__ERR(ENONET)
+#else
+# define UV__ENONET (-4056)
+#endif
+
+#if defined(ENOSPC) && !defined(_WIN32)
+# define UV__ENOSPC UV__ERR(ENOSPC)
+#else
+# define UV__ENOSPC (-4055)
+#endif
+
+#if defined(ENOSYS) && !defined(_WIN32)
+# define UV__ENOSYS UV__ERR(ENOSYS)
+#else
+# define UV__ENOSYS (-4054)
+#endif
+
+#if defined(ENOTCONN) && !defined(_WIN32)
+# define UV__ENOTCONN UV__ERR(ENOTCONN)
+#else
+# define UV__ENOTCONN (-4053)
+#endif
+
+#if defined(ENOTDIR) && !defined(_WIN32)
+# define UV__ENOTDIR UV__ERR(ENOTDIR)
+#else
+# define UV__ENOTDIR (-4052)
+#endif
+
+#if defined(ENOTEMPTY) && !defined(_WIN32)
+# define UV__ENOTEMPTY UV__ERR(ENOTEMPTY)
+#else
+# define UV__ENOTEMPTY (-4051)
+#endif
+
+#if defined(ENOTSOCK) && !defined(_WIN32)
+# define UV__ENOTSOCK UV__ERR(ENOTSOCK)
+#else
+# define UV__ENOTSOCK (-4050)
+#endif
+
+#if defined(ENOTSUP) && !defined(_WIN32)
+# define UV__ENOTSUP UV__ERR(ENOTSUP)
+#else
+# define UV__ENOTSUP (-4049)
+#endif
+
+#if defined(EPERM) && !defined(_WIN32)
+# define UV__EPERM UV__ERR(EPERM)
+#else
+# define UV__EPERM (-4048)
+#endif
+
+#if defined(EPIPE) && !defined(_WIN32)
+# define UV__EPIPE UV__ERR(EPIPE)
+#else
+# define UV__EPIPE (-4047)
+#endif
+
+#if defined(EPROTO) && !defined(_WIN32)
+# define UV__EPROTO UV__ERR(EPROTO)
+#else
+# define UV__EPROTO UV__ERR(4046)
+#endif
+
+#if defined(EPROTONOSUPPORT) && !defined(_WIN32)
+# define UV__EPROTONOSUPPORT UV__ERR(EPROTONOSUPPORT)
+#else
+# define UV__EPROTONOSUPPORT (-4045)
+#endif
+
+#if defined(EPROTOTYPE) && !defined(_WIN32)
+# define UV__EPROTOTYPE UV__ERR(EPROTOTYPE)
+#else
+# define UV__EPROTOTYPE (-4044)
+#endif
+
+#if defined(EROFS) && !defined(_WIN32)
+# define UV__EROFS UV__ERR(EROFS)
+#else
+# define UV__EROFS (-4043)
+#endif
+
+#if defined(ESHUTDOWN) && !defined(_WIN32)
+# define UV__ESHUTDOWN UV__ERR(ESHUTDOWN)
+#else
+# define UV__ESHUTDOWN (-4042)
+#endif
+
+#if defined(ESPIPE) && !defined(_WIN32)
+# define UV__ESPIPE UV__ERR(ESPIPE)
+#else
+# define UV__ESPIPE (-4041)
+#endif
+
+#if defined(ESRCH) && !defined(_WIN32)
+# define UV__ESRCH UV__ERR(ESRCH)
+#else
+# define UV__ESRCH (-4040)
+#endif
+
+#if defined(ETIMEDOUT) && !defined(_WIN32)
+# define UV__ETIMEDOUT UV__ERR(ETIMEDOUT)
+#else
+# define UV__ETIMEDOUT (-4039)
+#endif
+
+#if defined(ETXTBSY) && !defined(_WIN32)
+# define UV__ETXTBSY UV__ERR(ETXTBSY)
+#else
+# define UV__ETXTBSY (-4038)
+#endif
+
+#if defined(EXDEV) && !defined(_WIN32)
+# define UV__EXDEV UV__ERR(EXDEV)
+#else
+# define UV__EXDEV (-4037)
+#endif
+
+#if defined(EFBIG) && !defined(_WIN32)
+# define UV__EFBIG UV__ERR(EFBIG)
+#else
+# define UV__EFBIG (-4036)
+#endif
+
+#if defined(ENOPROTOOPT) && !defined(_WIN32)
+# define UV__ENOPROTOOPT UV__ERR(ENOPROTOOPT)
+#else
+# define UV__ENOPROTOOPT (-4035)
+#endif
+
+#if defined(ERANGE) && !defined(_WIN32)
+# define UV__ERANGE UV__ERR(ERANGE)
+#else
+# define UV__ERANGE (-4034)
+#endif
+
+#if defined(ENXIO) && !defined(_WIN32)
+# define UV__ENXIO UV__ERR(ENXIO)
+#else
+# define UV__ENXIO (-4033)
+#endif
+
+#if defined(EMLINK) && !defined(_WIN32)
+# define UV__EMLINK UV__ERR(EMLINK)
+#else
+# define UV__EMLINK (-4032)
+#endif
+
+/* EHOSTDOWN is not visible on BSD-like systems when _POSIX_C_SOURCE is
+ * defined. Fortunately, its value is always 64 so it's possible albeit
+ * icky to hard-code it.
+ */
+#if defined(EHOSTDOWN) && !defined(_WIN32)
+# define UV__EHOSTDOWN UV__ERR(EHOSTDOWN)
+#elif defined(__APPLE__) || \
+ defined(__DragonFly__) || \
+ defined(__FreeBSD__) || \
+ defined(__FreeBSD_kernel__) || \
+ defined(__NetBSD__) || \
+ defined(__OpenBSD__)
+# define UV__EHOSTDOWN (-64)
+#else
+# define UV__EHOSTDOWN (-4031)
+#endif
+
+#if defined(EREMOTEIO) && !defined(_WIN32)
+# define UV__EREMOTEIO UV__ERR(EREMOTEIO)
+#else
+# define UV__EREMOTEIO (-4030)
+#endif
+
+#if defined(ENOTTY) && !defined(_WIN32)
+# define UV__ENOTTY UV__ERR(ENOTTY)
+#else
+# define UV__ENOTTY (-4029)
+#endif
+
+#if defined(EFTYPE) && !defined(_WIN32)
+# define UV__EFTYPE UV__ERR(EFTYPE)
+#else
+# define UV__EFTYPE (-4028)
+#endif
+
+
+#endif /* UV_ERRNO_H_ */
diff --git a/Utilities/cmlibuv/include/uv/linux.h b/Utilities/cmlibuv/include/uv/linux.h
new file mode 100644
index 000000000..9b38405a1
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/linux.h
@@ -0,0 +1,34 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef UV_LINUX_H
+#define UV_LINUX_H
+
+#define UV_PLATFORM_LOOP_FIELDS \
+ uv__io_t inotify_read_watcher; \
+ void* inotify_watchers; \
+ int inotify_fd; \
+
+#define UV_PLATFORM_FS_EVENT_FIELDS \
+ void* watchers[2]; \
+ int wd; \
+
+#endif /* UV_LINUX_H */
diff --git a/Utilities/cmlibuv/include/uv/os390.h b/Utilities/cmlibuv/include/uv/os390.h
new file mode 100644
index 000000000..0267d74cb
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/os390.h
@@ -0,0 +1,33 @@
+/* Copyright libuv project contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef UV_MVS_H
+#define UV_MVS_H
+
+#define UV_PLATFORM_SEM_T long
+
+#define UV_PLATFORM_LOOP_FIELDS \
+ void* ep; \
+
+#define UV_PLATFORM_FS_EVENT_FIELDS \
+ char rfis_rftok[8]; \
+
+#endif /* UV_MVS_H */
diff --git a/Utilities/cmlibuv/include/uv/posix.h b/Utilities/cmlibuv/include/uv/posix.h
new file mode 100644
index 000000000..9a96634db
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/posix.h
@@ -0,0 +1,31 @@
+/* Copyright libuv project contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef UV_POSIX_H
+#define UV_POSIX_H
+
+#define UV_PLATFORM_LOOP_FIELDS \
+ struct pollfd* poll_fds; \
+ size_t poll_fds_used; \
+ size_t poll_fds_size; \
+ unsigned char poll_fds_iterating; \
+
+#endif /* UV_POSIX_H */
diff --git a/Utilities/cmlibuv/include/uv/stdint-msvc2008.h b/Utilities/cmlibuv/include/uv/stdint-msvc2008.h
new file mode 100644
index 000000000..d02608a59
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/stdint-msvc2008.h
@@ -0,0 +1,247 @@
+// ISO C9x compliant stdint.h for Microsoft Visual Studio
+// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
+//
+// Copyright (c) 2006-2008 Alexander Chemeris
+//
+// 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. The name of the author may be used to endorse or promote products
+// derived from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+#ifndef _MSC_VER // [
+#error "Use this header only with Microsoft Visual C++ compilers!"
+#endif // _MSC_VER ]
+
+#ifndef _MSC_STDINT_H_ // [
+#define _MSC_STDINT_H_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif
+
+#include <limits.h>
+
+// For Visual Studio 6 in C++ mode and for many Visual Studio versions when
+// compiling for ARM we should wrap <wchar.h> include with 'extern "C++" {}'
+// or compiler give many errors like this:
+// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
+#ifdef __cplusplus
+extern "C" {
+#endif
+# include <wchar.h>
+#ifdef __cplusplus
+}
+#endif
+
+// Define _W64 macros to mark types changing their size, like intptr_t.
+#ifndef _W64
+# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
+# define _W64 __w64
+# else
+# define _W64
+# endif
+#endif
+
+
+// 7.18.1 Integer types
+
+// 7.18.1.1 Exact-width integer types
+
+// Visual Studio 6 and Embedded Visual C++ 4 doesn't
+// realize that, e.g. char has the same size as __int8
+// so we give up on __intX for them.
+#if (_MSC_VER < 1300)
+ typedef signed char int8_t;
+ typedef signed short int16_t;
+ typedef signed int int32_t;
+ typedef unsigned char uint8_t;
+ typedef unsigned short uint16_t;
+ typedef unsigned int uint32_t;
+#else
+ typedef signed __int8 int8_t;
+ typedef signed __int16 int16_t;
+ typedef signed __int32 int32_t;
+ typedef unsigned __int8 uint8_t;
+ typedef unsigned __int16 uint16_t;
+ typedef unsigned __int32 uint32_t;
+#endif
+typedef signed __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+
+
+// 7.18.1.2 Minimum-width integer types
+typedef int8_t int_least8_t;
+typedef int16_t int_least16_t;
+typedef int32_t int_least32_t;
+typedef int64_t int_least64_t;
+typedef uint8_t uint_least8_t;
+typedef uint16_t uint_least16_t;
+typedef uint32_t uint_least32_t;
+typedef uint64_t uint_least64_t;
+
+// 7.18.1.3 Fastest minimum-width integer types
+typedef int8_t int_fast8_t;
+typedef int16_t int_fast16_t;
+typedef int32_t int_fast32_t;
+typedef int64_t int_fast64_t;
+typedef uint8_t uint_fast8_t;
+typedef uint16_t uint_fast16_t;
+typedef uint32_t uint_fast32_t;
+typedef uint64_t uint_fast64_t;
+
+// 7.18.1.4 Integer types capable of holding object pointers
+#ifdef _WIN64 // [
+ typedef signed __int64 intptr_t;
+ typedef unsigned __int64 uintptr_t;
+#else // _WIN64 ][
+ typedef _W64 signed int intptr_t;
+ typedef _W64 unsigned int uintptr_t;
+#endif // _WIN64 ]
+
+// 7.18.1.5 Greatest-width integer types
+typedef int64_t intmax_t;
+typedef uint64_t uintmax_t;
+
+
+// 7.18.2 Limits of specified-width integer types
+
+#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259
+
+// 7.18.2.1 Limits of exact-width integer types
+#define INT8_MIN ((int8_t)_I8_MIN)
+#define INT8_MAX _I8_MAX
+#define INT16_MIN ((int16_t)_I16_MIN)
+#define INT16_MAX _I16_MAX
+#define INT32_MIN ((int32_t)_I32_MIN)
+#define INT32_MAX _I32_MAX
+#define INT64_MIN ((int64_t)_I64_MIN)
+#define INT64_MAX _I64_MAX
+#define UINT8_MAX _UI8_MAX
+#define UINT16_MAX _UI16_MAX
+#define UINT32_MAX _UI32_MAX
+#define UINT64_MAX _UI64_MAX
+
+// 7.18.2.2 Limits of minimum-width integer types
+#define INT_LEAST8_MIN INT8_MIN
+#define INT_LEAST8_MAX INT8_MAX
+#define INT_LEAST16_MIN INT16_MIN
+#define INT_LEAST16_MAX INT16_MAX
+#define INT_LEAST32_MIN INT32_MIN
+#define INT_LEAST32_MAX INT32_MAX
+#define INT_LEAST64_MIN INT64_MIN
+#define INT_LEAST64_MAX INT64_MAX
+#define UINT_LEAST8_MAX UINT8_MAX
+#define UINT_LEAST16_MAX UINT16_MAX
+#define UINT_LEAST32_MAX UINT32_MAX
+#define UINT_LEAST64_MAX UINT64_MAX
+
+// 7.18.2.3 Limits of fastest minimum-width integer types
+#define INT_FAST8_MIN INT8_MIN
+#define INT_FAST8_MAX INT8_MAX
+#define INT_FAST16_MIN INT16_MIN
+#define INT_FAST16_MAX INT16_MAX
+#define INT_FAST32_MIN INT32_MIN
+#define INT_FAST32_MAX INT32_MAX
+#define INT_FAST64_MIN INT64_MIN
+#define INT_FAST64_MAX INT64_MAX
+#define UINT_FAST8_MAX UINT8_MAX
+#define UINT_FAST16_MAX UINT16_MAX
+#define UINT_FAST32_MAX UINT32_MAX
+#define UINT_FAST64_MAX UINT64_MAX
+
+// 7.18.2.4 Limits of integer types capable of holding object pointers
+#ifdef _WIN64 // [
+# define INTPTR_MIN INT64_MIN
+# define INTPTR_MAX INT64_MAX
+# define UINTPTR_MAX UINT64_MAX
+#else // _WIN64 ][
+# define INTPTR_MIN INT32_MIN
+# define INTPTR_MAX INT32_MAX
+# define UINTPTR_MAX UINT32_MAX
+#endif // _WIN64 ]
+
+// 7.18.2.5 Limits of greatest-width integer types
+#define INTMAX_MIN INT64_MIN
+#define INTMAX_MAX INT64_MAX
+#define UINTMAX_MAX UINT64_MAX
+
+// 7.18.3 Limits of other integer types
+
+#ifdef _WIN64 // [
+# define PTRDIFF_MIN _I64_MIN
+# define PTRDIFF_MAX _I64_MAX
+#else // _WIN64 ][
+# define PTRDIFF_MIN _I32_MIN
+# define PTRDIFF_MAX _I32_MAX
+#endif // _WIN64 ]
+
+#define SIG_ATOMIC_MIN INT_MIN
+#define SIG_ATOMIC_MAX INT_MAX
+
+#ifndef SIZE_MAX // [
+# ifdef _WIN64 // [
+# define SIZE_MAX _UI64_MAX
+# else // _WIN64 ][
+# define SIZE_MAX _UI32_MAX
+# endif // _WIN64 ]
+#endif // SIZE_MAX ]
+
+// WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h>
+#ifndef WCHAR_MIN // [
+# define WCHAR_MIN 0
+#endif // WCHAR_MIN ]
+#ifndef WCHAR_MAX // [
+# define WCHAR_MAX _UI16_MAX
+#endif // WCHAR_MAX ]
+
+#define WINT_MIN 0
+#define WINT_MAX _UI16_MAX
+
+#endif // __STDC_LIMIT_MACROS ]
+
+
+// 7.18.4 Limits of other integer types
+
+#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
+
+// 7.18.4.1 Macros for minimum-width integer constants
+
+#define INT8_C(val) val##i8
+#define INT16_C(val) val##i16
+#define INT32_C(val) val##i32
+#define INT64_C(val) val##i64
+
+#define UINT8_C(val) val##ui8
+#define UINT16_C(val) val##ui16
+#define UINT32_C(val) val##ui32
+#define UINT64_C(val) val##ui64
+
+// 7.18.4.2 Macros for greatest-width integer constants
+#define INTMAX_C INT64_C
+#define UINTMAX_C UINT64_C
+
+#endif // __STDC_CONSTANT_MACROS ]
+
+
+#endif // _MSC_STDINT_H_ ]
diff --git a/Utilities/cmlibuv/include/uv/sunos.h b/Utilities/cmlibuv/include/uv/sunos.h
new file mode 100644
index 000000000..042166424
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/sunos.h
@@ -0,0 +1,44 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef UV_SUNOS_H
+#define UV_SUNOS_H
+
+#include <sys/port.h>
+#include <port.h>
+
+/* For the sake of convenience and reduced #ifdef-ery in src/unix/sunos.c,
+ * add the fs_event fields even when this version of SunOS doesn't support
+ * file watching.
+ */
+#define UV_PLATFORM_LOOP_FIELDS \
+ uv__io_t fs_event_watcher; \
+ int fs_fd; \
+
+#if defined(PORT_SOURCE_FILE)
+
+# define UV_PLATFORM_FS_EVENT_FIELDS \
+ file_obj_t fo; \
+ int fd; \
+
+#endif /* defined(PORT_SOURCE_FILE) */
+
+#endif /* UV_SUNOS_H */
diff --git a/Utilities/cmlibuv/include/uv/threadpool.h b/Utilities/cmlibuv/include/uv/threadpool.h
new file mode 100644
index 000000000..9708ebdd5
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/threadpool.h
@@ -0,0 +1,37 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+/*
+ * This file is private to libuv. It provides common functionality to both
+ * Windows and Unix backends.
+ */
+
+#ifndef UV_THREADPOOL_H_
+#define UV_THREADPOOL_H_
+
+struct uv__work {
+ void (*work)(struct uv__work *w);
+ void (*done)(struct uv__work *w, int status);
+ struct uv_loop_s* loop;
+ void* wq[2];
+};
+
+#endif /* UV_THREADPOOL_H_ */
diff --git a/Utilities/cmlibuv/include/uv/tree.h b/Utilities/cmlibuv/include/uv/tree.h
new file mode 100644
index 000000000..f936416e3
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/tree.h
@@ -0,0 +1,768 @@
+/*-
+ * Copyright 2002 Niels Provos <provos@citi.umich.edu>
+ * 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 ``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 BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef UV_TREE_H_
+#define UV_TREE_H_
+
+#ifndef UV__UNUSED
+# if __GNUC__
+# define UV__UNUSED __attribute__((unused))
+# else
+# define UV__UNUSED
+# endif
+#endif
+
+/*
+ * This file defines data structures for different types of trees:
+ * splay trees and red-black trees.
+ *
+ * A splay tree is a self-organizing data structure. Every operation
+ * on the tree causes a splay to happen. The splay moves the requested
+ * node to the root of the tree and partly rebalances it.
+ *
+ * This has the benefit that request locality causes faster lookups as
+ * the requested nodes move to the top of the tree. On the other hand,
+ * every lookup causes memory writes.
+ *
+ * The Balance Theorem bounds the total access time for m operations
+ * and n inserts on an initially empty tree as O((m + n)lg n). The
+ * amortized cost for a sequence of m accesses to a splay tree is O(lg n);
+ *
+ * A red-black tree is a binary search tree with the node color as an
+ * extra attribute. It fulfills a set of conditions:
+ * - every search path from the root to a leaf consists of the
+ * same number of black nodes,
+ * - each red node (except for the root) has a black parent,
+ * - each leaf node is black.
+ *
+ * Every operation on a red-black tree is bounded as O(lg n).
+ * The maximum height of a red-black tree is 2lg (n+1).
+ */
+
+#define SPLAY_HEAD(name, type) \
+struct name { \
+ struct type *sph_root; /* root of the tree */ \
+}
+
+#define SPLAY_INITIALIZER(root) \
+ { NULL }
+
+#define SPLAY_INIT(root) do { \
+ (root)->sph_root = NULL; \
+} while (/*CONSTCOND*/ 0)
+
+#define SPLAY_ENTRY(type) \
+struct { \
+ struct type *spe_left; /* left element */ \
+ struct type *spe_right; /* right element */ \
+}
+
+#define SPLAY_LEFT(elm, field) (elm)->field.spe_left
+#define SPLAY_RIGHT(elm, field) (elm)->field.spe_right
+#define SPLAY_ROOT(head) (head)->sph_root
+#define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL)
+
+/* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */
+#define SPLAY_ROTATE_RIGHT(head, tmp, field) do { \
+ SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \
+ SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
+ (head)->sph_root = tmp; \
+} while (/*CONSTCOND*/ 0)
+
+#define SPLAY_ROTATE_LEFT(head, tmp, field) do { \
+ SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \
+ SPLAY_LEFT(tmp, field) = (head)->sph_root; \
+ (head)->sph_root = tmp; \
+} while (/*CONSTCOND*/ 0)
+
+#define SPLAY_LINKLEFT(head, tmp, field) do { \
+ SPLAY_LEFT(tmp, field) = (head)->sph_root; \
+ tmp = (head)->sph_root; \
+ (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \
+} while (/*CONSTCOND*/ 0)
+
+#define SPLAY_LINKRIGHT(head, tmp, field) do { \
+ SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
+ tmp = (head)->sph_root; \
+ (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \
+} while (/*CONSTCOND*/ 0)
+
+#define SPLAY_ASSEMBLE(head, node, left, right, field) do { \
+ SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \
+ SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field); \
+ SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \
+ SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \
+} while (/*CONSTCOND*/ 0)
+
+/* Generates prototypes and inline functions */
+
+#define SPLAY_PROTOTYPE(name, type, field, cmp) \
+void name##_SPLAY(struct name *, struct type *); \
+void name##_SPLAY_MINMAX(struct name *, int); \
+struct type *name##_SPLAY_INSERT(struct name *, struct type *); \
+struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \
+ \
+/* Finds the node with the same key as elm */ \
+static __inline struct type * \
+name##_SPLAY_FIND(struct name *head, struct type *elm) \
+{ \
+ if (SPLAY_EMPTY(head)) \
+ return(NULL); \
+ name##_SPLAY(head, elm); \
+ if ((cmp)(elm, (head)->sph_root) == 0) \
+ return (head->sph_root); \
+ return (NULL); \
+} \
+ \
+static __inline struct type * \
+name##_SPLAY_NEXT(struct name *head, struct type *elm) \
+{ \
+ name##_SPLAY(head, elm); \
+ if (SPLAY_RIGHT(elm, field) != NULL) { \
+ elm = SPLAY_RIGHT(elm, field); \
+ while (SPLAY_LEFT(elm, field) != NULL) { \
+ elm = SPLAY_LEFT(elm, field); \
+ } \
+ } else \
+ elm = NULL; \
+ return (elm); \
+} \
+ \
+static __inline struct type * \
+name##_SPLAY_MIN_MAX(struct name *head, int val) \
+{ \
+ name##_SPLAY_MINMAX(head, val); \
+ return (SPLAY_ROOT(head)); \
+}
+
+/* Main splay operation.
+ * Moves node close to the key of elm to top
+ */
+#define SPLAY_GENERATE(name, type, field, cmp) \
+struct type * \
+name##_SPLAY_INSERT(struct name *head, struct type *elm) \
+{ \
+ if (SPLAY_EMPTY(head)) { \
+ SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \
+ } else { \
+ int __comp; \
+ name##_SPLAY(head, elm); \
+ __comp = (cmp)(elm, (head)->sph_root); \
+ if(__comp < 0) { \
+ SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field); \
+ SPLAY_RIGHT(elm, field) = (head)->sph_root; \
+ SPLAY_LEFT((head)->sph_root, field) = NULL; \
+ } else if (__comp > 0) { \
+ SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field); \
+ SPLAY_LEFT(elm, field) = (head)->sph_root; \
+ SPLAY_RIGHT((head)->sph_root, field) = NULL; \
+ } else \
+ return ((head)->sph_root); \
+ } \
+ (head)->sph_root = (elm); \
+ return (NULL); \
+} \
+ \
+struct type * \
+name##_SPLAY_REMOVE(struct name *head, struct type *elm) \
+{ \
+ struct type *__tmp; \
+ if (SPLAY_EMPTY(head)) \
+ return (NULL); \
+ name##_SPLAY(head, elm); \
+ if ((cmp)(elm, (head)->sph_root) == 0) { \
+ if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \
+ (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \
+ } else { \
+ __tmp = SPLAY_RIGHT((head)->sph_root, field); \
+ (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \
+ name##_SPLAY(head, elm); \
+ SPLAY_RIGHT((head)->sph_root, field) = __tmp; \
+ } \
+ return (elm); \
+ } \
+ return (NULL); \
+} \
+ \
+void \
+name##_SPLAY(struct name *head, struct type *elm) \
+{ \
+ struct type __node, *__left, *__right, *__tmp; \
+ int __comp; \
+ \
+ SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL; \
+ __left = __right = &__node; \
+ \
+ while ((__comp = (cmp)(elm, (head)->sph_root)) != 0) { \
+ if (__comp < 0) { \
+ __tmp = SPLAY_LEFT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if ((cmp)(elm, __tmp) < 0){ \
+ SPLAY_ROTATE_RIGHT(head, __tmp, field); \
+ if (SPLAY_LEFT((head)->sph_root, field) == NULL) \
+ break; \
+ } \
+ SPLAY_LINKLEFT(head, __right, field); \
+ } else if (__comp > 0) { \
+ __tmp = SPLAY_RIGHT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if ((cmp)(elm, __tmp) > 0){ \
+ SPLAY_ROTATE_LEFT(head, __tmp, field); \
+ if (SPLAY_RIGHT((head)->sph_root, field) == NULL) \
+ break; \
+ } \
+ SPLAY_LINKRIGHT(head, __left, field); \
+ } \
+ } \
+ SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
+} \
+ \
+/* Splay with either the minimum or the maximum element \
+ * Used to find minimum or maximum element in tree. \
+ */ \
+void name##_SPLAY_MINMAX(struct name *head, int __comp) \
+{ \
+ struct type __node, *__left, *__right, *__tmp; \
+ \
+ SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL; \
+ __left = __right = &__node; \
+ \
+ while (1) { \
+ if (__comp < 0) { \
+ __tmp = SPLAY_LEFT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if (__comp < 0){ \
+ SPLAY_ROTATE_RIGHT(head, __tmp, field); \
+ if (SPLAY_LEFT((head)->sph_root, field) == NULL) \
+ break; \
+ } \
+ SPLAY_LINKLEFT(head, __right, field); \
+ } else if (__comp > 0) { \
+ __tmp = SPLAY_RIGHT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if (__comp > 0) { \
+ SPLAY_ROTATE_LEFT(head, __tmp, field); \
+ if (SPLAY_RIGHT((head)->sph_root, field) == NULL) \
+ break; \
+ } \
+ SPLAY_LINKRIGHT(head, __left, field); \
+ } \
+ } \
+ SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
+}
+
+#define SPLAY_NEGINF -1
+#define SPLAY_INF 1
+
+#define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y)
+#define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y)
+#define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y)
+#define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y)
+#define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL \
+ : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF))
+#define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL \
+ : name##_SPLAY_MIN_MAX(x, SPLAY_INF))
+
+#define SPLAY_FOREACH(x, name, head) \
+ for ((x) = SPLAY_MIN(name, head); \
+ (x) != NULL; \
+ (x) = SPLAY_NEXT(name, head, x))
+
+/* Macros that define a red-black tree */
+#define RB_HEAD(name, type) \
+struct name { \
+ struct type *rbh_root; /* root of the tree */ \
+}
+
+#define RB_INITIALIZER(root) \
+ { NULL }
+
+#define RB_INIT(root) do { \
+ (root)->rbh_root = NULL; \
+} while (/*CONSTCOND*/ 0)
+
+#define RB_BLACK 0
+#define RB_RED 1
+#define RB_ENTRY(type) \
+struct { \
+ struct type *rbe_left; /* left element */ \
+ struct type *rbe_right; /* right element */ \
+ struct type *rbe_parent; /* parent element */ \
+ int rbe_color; /* node color */ \
+}
+
+#define RB_LEFT(elm, field) (elm)->field.rbe_left
+#define RB_RIGHT(elm, field) (elm)->field.rbe_right
+#define RB_PARENT(elm, field) (elm)->field.rbe_parent
+#define RB_COLOR(elm, field) (elm)->field.rbe_color
+#define RB_ROOT(head) (head)->rbh_root
+#define RB_EMPTY(head) (RB_ROOT(head) == NULL)
+
+#define RB_SET(elm, parent, field) do { \
+ RB_PARENT(elm, field) = parent; \
+ RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \
+ RB_COLOR(elm, field) = RB_RED; \
+} while (/*CONSTCOND*/ 0)
+
+#define RB_SET_BLACKRED(black, red, field) do { \
+ RB_COLOR(black, field) = RB_BLACK; \
+ RB_COLOR(red, field) = RB_RED; \
+} while (/*CONSTCOND*/ 0)
+
+#ifndef RB_AUGMENT
+#define RB_AUGMENT(x) do {} while (0)
+#endif
+
+#define RB_ROTATE_LEFT(head, elm, tmp, field) do { \
+ (tmp) = RB_RIGHT(elm, field); \
+ if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field)) != NULL) { \
+ RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \
+ } \
+ RB_AUGMENT(elm); \
+ if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \
+ if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
+ RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
+ else \
+ RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
+ } else \
+ (head)->rbh_root = (tmp); \
+ RB_LEFT(tmp, field) = (elm); \
+ RB_PARENT(elm, field) = (tmp); \
+ RB_AUGMENT(tmp); \
+ if ((RB_PARENT(tmp, field))) \
+ RB_AUGMENT(RB_PARENT(tmp, field)); \
+} while (/*CONSTCOND*/ 0)
+
+#define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \
+ (tmp) = RB_LEFT(elm, field); \
+ if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field)) != NULL) { \
+ RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \
+ } \
+ RB_AUGMENT(elm); \
+ if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \
+ if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
+ RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
+ else \
+ RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
+ } else \
+ (head)->rbh_root = (tmp); \
+ RB_RIGHT(tmp, field) = (elm); \
+ RB_PARENT(elm, field) = (tmp); \
+ RB_AUGMENT(tmp); \
+ if ((RB_PARENT(tmp, field))) \
+ RB_AUGMENT(RB_PARENT(tmp, field)); \
+} while (/*CONSTCOND*/ 0)
+
+/* Generates prototypes and inline functions */
+#define RB_PROTOTYPE(name, type, field, cmp) \
+ RB_PROTOTYPE_INTERNAL(name, type, field, cmp,)
+#define RB_PROTOTYPE_STATIC(name, type, field, cmp) \
+ RB_PROTOTYPE_INTERNAL(name, type, field, cmp, UV__UNUSED static)
+#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr) \
+attr void name##_RB_INSERT_COLOR(struct name *, struct type *); \
+attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\
+attr struct type *name##_RB_REMOVE(struct name *, struct type *); \
+attr struct type *name##_RB_INSERT(struct name *, struct type *); \
+attr struct type *name##_RB_FIND(struct name *, struct type *); \
+attr struct type *name##_RB_NFIND(struct name *, struct type *); \
+attr struct type *name##_RB_NEXT(struct type *); \
+attr struct type *name##_RB_PREV(struct type *); \
+attr struct type *name##_RB_MINMAX(struct name *, int); \
+ \
+
+/* Main rb operation.
+ * Moves node close to the key of elm to top
+ */
+#define RB_GENERATE(name, type, field, cmp) \
+ RB_GENERATE_INTERNAL(name, type, field, cmp,)
+#define RB_GENERATE_STATIC(name, type, field, cmp) \
+ RB_GENERATE_INTERNAL(name, type, field, cmp, UV__UNUSED static)
+#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr) \
+attr void \
+name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \
+{ \
+ struct type *parent, *gparent, *tmp; \
+ while ((parent = RB_PARENT(elm, field)) != NULL && \
+ RB_COLOR(parent, field) == RB_RED) { \
+ gparent = RB_PARENT(parent, field); \
+ if (parent == RB_LEFT(gparent, field)) { \
+ tmp = RB_RIGHT(gparent, field); \
+ if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
+ RB_COLOR(tmp, field) = RB_BLACK; \
+ RB_SET_BLACKRED(parent, gparent, field); \
+ elm = gparent; \
+ continue; \
+ } \
+ if (RB_RIGHT(parent, field) == elm) { \
+ RB_ROTATE_LEFT(head, parent, tmp, field); \
+ tmp = parent; \
+ parent = elm; \
+ elm = tmp; \
+ } \
+ RB_SET_BLACKRED(parent, gparent, field); \
+ RB_ROTATE_RIGHT(head, gparent, tmp, field); \
+ } else { \
+ tmp = RB_LEFT(gparent, field); \
+ if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
+ RB_COLOR(tmp, field) = RB_BLACK; \
+ RB_SET_BLACKRED(parent, gparent, field); \
+ elm = gparent; \
+ continue; \
+ } \
+ if (RB_LEFT(parent, field) == elm) { \
+ RB_ROTATE_RIGHT(head, parent, tmp, field); \
+ tmp = parent; \
+ parent = elm; \
+ elm = tmp; \
+ } \
+ RB_SET_BLACKRED(parent, gparent, field); \
+ RB_ROTATE_LEFT(head, gparent, tmp, field); \
+ } \
+ } \
+ RB_COLOR(head->rbh_root, field) = RB_BLACK; \
+} \
+ \
+attr void \
+name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, \
+ struct type *elm) \
+{ \
+ struct type *tmp; \
+ while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \
+ elm != RB_ROOT(head)) { \
+ if (RB_LEFT(parent, field) == elm) { \
+ tmp = RB_RIGHT(parent, field); \
+ if (RB_COLOR(tmp, field) == RB_RED) { \
+ RB_SET_BLACKRED(tmp, parent, field); \
+ RB_ROTATE_LEFT(head, parent, tmp, field); \
+ tmp = RB_RIGHT(parent, field); \
+ } \
+ if ((RB_LEFT(tmp, field) == NULL || \
+ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) && \
+ (RB_RIGHT(tmp, field) == NULL || \
+ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) { \
+ RB_COLOR(tmp, field) = RB_RED; \
+ elm = parent; \
+ parent = RB_PARENT(elm, field); \
+ } else { \
+ if (RB_RIGHT(tmp, field) == NULL || \
+ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) { \
+ struct type *oleft; \
+ if ((oleft = RB_LEFT(tmp, field)) \
+ != NULL) \
+ RB_COLOR(oleft, field) = RB_BLACK; \
+ RB_COLOR(tmp, field) = RB_RED; \
+ RB_ROTATE_RIGHT(head, tmp, oleft, field); \
+ tmp = RB_RIGHT(parent, field); \
+ } \
+ RB_COLOR(tmp, field) = RB_COLOR(parent, field); \
+ RB_COLOR(parent, field) = RB_BLACK; \
+ if (RB_RIGHT(tmp, field)) \
+ RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK; \
+ RB_ROTATE_LEFT(head, parent, tmp, field); \
+ elm = RB_ROOT(head); \
+ break; \
+ } \
+ } else { \
+ tmp = RB_LEFT(parent, field); \
+ if (RB_COLOR(tmp, field) == RB_RED) { \
+ RB_SET_BLACKRED(tmp, parent, field); \
+ RB_ROTATE_RIGHT(head, parent, tmp, field); \
+ tmp = RB_LEFT(parent, field); \
+ } \
+ if ((RB_LEFT(tmp, field) == NULL || \
+ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) && \
+ (RB_RIGHT(tmp, field) == NULL || \
+ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) { \
+ RB_COLOR(tmp, field) = RB_RED; \
+ elm = parent; \
+ parent = RB_PARENT(elm, field); \
+ } else { \
+ if (RB_LEFT(tmp, field) == NULL || \
+ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) { \
+ struct type *oright; \
+ if ((oright = RB_RIGHT(tmp, field)) \
+ != NULL) \
+ RB_COLOR(oright, field) = RB_BLACK; \
+ RB_COLOR(tmp, field) = RB_RED; \
+ RB_ROTATE_LEFT(head, tmp, oright, field); \
+ tmp = RB_LEFT(parent, field); \
+ } \
+ RB_COLOR(tmp, field) = RB_COLOR(parent, field); \
+ RB_COLOR(parent, field) = RB_BLACK; \
+ if (RB_LEFT(tmp, field)) \
+ RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK; \
+ RB_ROTATE_RIGHT(head, parent, tmp, field); \
+ elm = RB_ROOT(head); \
+ break; \
+ } \
+ } \
+ } \
+ if (elm) \
+ RB_COLOR(elm, field) = RB_BLACK; \
+} \
+ \
+attr struct type * \
+name##_RB_REMOVE(struct name *head, struct type *elm) \
+{ \
+ struct type *child, *parent, *old = elm; \
+ int color; \
+ if (RB_LEFT(elm, field) == NULL) \
+ child = RB_RIGHT(elm, field); \
+ else if (RB_RIGHT(elm, field) == NULL) \
+ child = RB_LEFT(elm, field); \
+ else { \
+ struct type *left; \
+ elm = RB_RIGHT(elm, field); \
+ while ((left = RB_LEFT(elm, field)) != NULL) \
+ elm = left; \
+ child = RB_RIGHT(elm, field); \
+ parent = RB_PARENT(elm, field); \
+ color = RB_COLOR(elm, field); \
+ if (child) \
+ RB_PARENT(child, field) = parent; \
+ if (parent) { \
+ if (RB_LEFT(parent, field) == elm) \
+ RB_LEFT(parent, field) = child; \
+ else \
+ RB_RIGHT(parent, field) = child; \
+ RB_AUGMENT(parent); \
+ } else \
+ RB_ROOT(head) = child; \
+ if (RB_PARENT(elm, field) == old) \
+ parent = elm; \
+ (elm)->field = (old)->field; \
+ if (RB_PARENT(old, field)) { \
+ if (RB_LEFT(RB_PARENT(old, field), field) == old) \
+ RB_LEFT(RB_PARENT(old, field), field) = elm; \
+ else \
+ RB_RIGHT(RB_PARENT(old, field), field) = elm; \
+ RB_AUGMENT(RB_PARENT(old, field)); \
+ } else \
+ RB_ROOT(head) = elm; \
+ RB_PARENT(RB_LEFT(old, field), field) = elm; \
+ if (RB_RIGHT(old, field)) \
+ RB_PARENT(RB_RIGHT(old, field), field) = elm; \
+ if (parent) { \
+ left = parent; \
+ do { \
+ RB_AUGMENT(left); \
+ } while ((left = RB_PARENT(left, field)) != NULL); \
+ } \
+ goto color; \
+ } \
+ parent = RB_PARENT(elm, field); \
+ color = RB_COLOR(elm, field); \
+ if (child) \
+ RB_PARENT(child, field) = parent; \
+ if (parent) { \
+ if (RB_LEFT(parent, field) == elm) \
+ RB_LEFT(parent, field) = child; \
+ else \
+ RB_RIGHT(parent, field) = child; \
+ RB_AUGMENT(parent); \
+ } else \
+ RB_ROOT(head) = child; \
+color: \
+ if (color == RB_BLACK) \
+ name##_RB_REMOVE_COLOR(head, parent, child); \
+ return (old); \
+} \
+ \
+/* Inserts a node into the RB tree */ \
+attr struct type * \
+name##_RB_INSERT(struct name *head, struct type *elm) \
+{ \
+ struct type *tmp; \
+ struct type *parent = NULL; \
+ int comp = 0; \
+ tmp = RB_ROOT(head); \
+ while (tmp) { \
+ parent = tmp; \
+ comp = (cmp)(elm, parent); \
+ if (comp < 0) \
+ tmp = RB_LEFT(tmp, field); \
+ else if (comp > 0) \
+ tmp = RB_RIGHT(tmp, field); \
+ else \
+ return (tmp); \
+ } \
+ RB_SET(elm, parent, field); \
+ if (parent != NULL) { \
+ if (comp < 0) \
+ RB_LEFT(parent, field) = elm; \
+ else \
+ RB_RIGHT(parent, field) = elm; \
+ RB_AUGMENT(parent); \
+ } else \
+ RB_ROOT(head) = elm; \
+ name##_RB_INSERT_COLOR(head, elm); \
+ return (NULL); \
+} \
+ \
+/* Finds the node with the same key as elm */ \
+attr struct type * \
+name##_RB_FIND(struct name *head, struct type *elm) \
+{ \
+ struct type *tmp = RB_ROOT(head); \
+ int comp; \
+ while (tmp) { \
+ comp = cmp(elm, tmp); \
+ if (comp < 0) \
+ tmp = RB_LEFT(tmp, field); \
+ else if (comp > 0) \
+ tmp = RB_RIGHT(tmp, field); \
+ else \
+ return (tmp); \
+ } \
+ return (NULL); \
+} \
+ \
+/* Finds the first node greater than or equal to the search key */ \
+attr struct type * \
+name##_RB_NFIND(struct name *head, struct type *elm) \
+{ \
+ struct type *tmp = RB_ROOT(head); \
+ struct type *res = NULL; \
+ int comp; \
+ while (tmp) { \
+ comp = cmp(elm, tmp); \
+ if (comp < 0) { \
+ res = tmp; \
+ tmp = RB_LEFT(tmp, field); \
+ } \
+ else if (comp > 0) \
+ tmp = RB_RIGHT(tmp, field); \
+ else \
+ return (tmp); \
+ } \
+ return (res); \
+} \
+ \
+/* ARGSUSED */ \
+attr struct type * \
+name##_RB_NEXT(struct type *elm) \
+{ \
+ if (RB_RIGHT(elm, field)) { \
+ elm = RB_RIGHT(elm, field); \
+ while (RB_LEFT(elm, field)) \
+ elm = RB_LEFT(elm, field); \
+ } else { \
+ if (RB_PARENT(elm, field) && \
+ (elm == RB_LEFT(RB_PARENT(elm, field), field))) \
+ elm = RB_PARENT(elm, field); \
+ else { \
+ while (RB_PARENT(elm, field) && \
+ (elm == RB_RIGHT(RB_PARENT(elm, field), field))) \
+ elm = RB_PARENT(elm, field); \
+ elm = RB_PARENT(elm, field); \
+ } \
+ } \
+ return (elm); \
+} \
+ \
+/* ARGSUSED */ \
+attr struct type * \
+name##_RB_PREV(struct type *elm) \
+{ \
+ if (RB_LEFT(elm, field)) { \
+ elm = RB_LEFT(elm, field); \
+ while (RB_RIGHT(elm, field)) \
+ elm = RB_RIGHT(elm, field); \
+ } else { \
+ if (RB_PARENT(elm, field) && \
+ (elm == RB_RIGHT(RB_PARENT(elm, field), field))) \
+ elm = RB_PARENT(elm, field); \
+ else { \
+ while (RB_PARENT(elm, field) && \
+ (elm == RB_LEFT(RB_PARENT(elm, field), field))) \
+ elm = RB_PARENT(elm, field); \
+ elm = RB_PARENT(elm, field); \
+ } \
+ } \
+ return (elm); \
+} \
+ \
+attr struct type * \
+name##_RB_MINMAX(struct name *head, int val) \
+{ \
+ struct type *tmp = RB_ROOT(head); \
+ struct type *parent = NULL; \
+ while (tmp) { \
+ parent = tmp; \
+ if (val < 0) \
+ tmp = RB_LEFT(tmp, field); \
+ else \
+ tmp = RB_RIGHT(tmp, field); \
+ } \
+ return (parent); \
+}
+
+#define RB_NEGINF -1
+#define RB_INF 1
+
+#define RB_INSERT(name, x, y) name##_RB_INSERT(x, y)
+#define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y)
+#define RB_FIND(name, x, y) name##_RB_FIND(x, y)
+#define RB_NFIND(name, x, y) name##_RB_NFIND(x, y)
+#define RB_NEXT(name, x, y) name##_RB_NEXT(y)
+#define RB_PREV(name, x, y) name##_RB_PREV(y)
+#define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF)
+#define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF)
+
+#define RB_FOREACH(x, name, head) \
+ for ((x) = RB_MIN(name, head); \
+ (x) != NULL; \
+ (x) = name##_RB_NEXT(x))
+
+#define RB_FOREACH_FROM(x, name, y) \
+ for ((x) = (y); \
+ ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \
+ (x) = (y))
+
+#define RB_FOREACH_SAFE(x, name, head, y) \
+ for ((x) = RB_MIN(name, head); \
+ ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \
+ (x) = (y))
+
+#define RB_FOREACH_REVERSE(x, name, head) \
+ for ((x) = RB_MAX(name, head); \
+ (x) != NULL; \
+ (x) = name##_RB_PREV(x))
+
+#define RB_FOREACH_REVERSE_FROM(x, name, y) \
+ for ((x) = (y); \
+ ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \
+ (x) = (y))
+
+#define RB_FOREACH_REVERSE_SAFE(x, name, head, y) \
+ for ((x) = RB_MAX(name, head); \
+ ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \
+ (x) = (y))
+
+#endif /* UV_TREE_H_ */
diff --git a/Utilities/cmlibuv/include/uv/unix.h b/Utilities/cmlibuv/include/uv/unix.h
new file mode 100644
index 000000000..3c1b36369
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/unix.h
@@ -0,0 +1,497 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef UV_UNIX_H
+#define UV_UNIX_H
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <dirent.h>
+
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+
+#include <termios.h>
+#include <pwd.h>
+
+#if !defined(__MVS__)
+#include <semaphore.h>
+#endif
+#include <pthread.h>
+#include <signal.h>
+
+#include "threadpool.h"
+
+#ifdef CMAKE_BOOTSTRAP
+# include "posix.h"
+#elif defined(__linux__)
+# include "linux.h"
+#elif defined (__MVS__)
+# include "os390.h"
+#elif defined(__PASE__)
+# include "posix.h"
+#elif defined(_AIX)
+# include "aix.h"
+#elif defined(__sun)
+# include "sunos.h"
+#elif defined(__APPLE__)
+# include "darwin.h"
+#elif defined(__DragonFly__) || \
+ defined(__FreeBSD__) || \
+ defined(__FreeBSD_kernel__) || \
+ defined(__OpenBSD__) || \
+ defined(__NetBSD__)
+# include "bsd.h"
+#elif defined(__CYGWIN__) || defined(__MSYS__)
+# include "posix.h"
+#elif defined(__GNU__)
+# include "posix.h"
+#endif
+
+#ifndef NI_MAXHOST
+# define NI_MAXHOST 1025
+#endif
+
+#ifndef NI_MAXSERV
+# define NI_MAXSERV 32
+#endif
+
+#ifndef UV_IO_PRIVATE_PLATFORM_FIELDS
+# define UV_IO_PRIVATE_PLATFORM_FIELDS /* empty */
+#endif
+
+struct uv__io_s;
+struct uv_loop_s;
+
+typedef void (*uv__io_cb)(struct uv_loop_s* loop,
+ struct uv__io_s* w,
+ unsigned int events);
+typedef struct uv__io_s uv__io_t;
+
+struct uv__io_s {
+ uv__io_cb cb;
+ void* pending_queue[2];
+ void* watcher_queue[2];
+ unsigned int pevents; /* Pending event mask i.e. mask at next tick. */
+ unsigned int events; /* Current event mask. */
+ int fd;
+ UV_IO_PRIVATE_PLATFORM_FIELDS
+};
+
+#ifndef UV_PLATFORM_SEM_T
+# define UV_PLATFORM_SEM_T sem_t
+#endif
+
+#ifndef UV_PLATFORM_LOOP_FIELDS
+# define UV_PLATFORM_LOOP_FIELDS /* empty */
+#endif
+
+#ifndef UV_PLATFORM_FS_EVENT_FIELDS
+# define UV_PLATFORM_FS_EVENT_FIELDS /* empty */
+#endif
+
+#ifndef UV_STREAM_PRIVATE_PLATFORM_FIELDS
+# define UV_STREAM_PRIVATE_PLATFORM_FIELDS /* empty */
+#endif
+
+/* Note: May be cast to struct iovec. See writev(2). */
+typedef struct uv_buf_t {
+ char* base;
+ size_t len;
+} uv_buf_t;
+
+typedef int uv_file;
+typedef int uv_os_sock_t;
+typedef int uv_os_fd_t;
+typedef pid_t uv_pid_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;
+typedef pthread_t uv_thread_t;
+typedef pthread_mutex_t uv_mutex_t;
+typedef pthread_rwlock_t uv_rwlock_t;
+typedef UV_PLATFORM_SEM_T uv_sem_t;
+typedef pthread_cond_t uv_cond_t;
+typedef pthread_key_t uv_key_t;
+
+/* Note: guard clauses should match uv_barrier_init's in src/unix/thread.c. */
+#if defined(_AIX) || !defined(PTHREAD_BARRIER_SERIAL_THREAD)
+/* TODO(bnoordhuis) Merge into uv_barrier_t in v2. */
+struct _uv_barrier {
+ uv_mutex_t mutex;
+ uv_cond_t cond;
+ unsigned threshold;
+ unsigned in;
+ unsigned out;
+};
+
+typedef struct {
+ struct _uv_barrier* b;
+# if defined(PTHREAD_BARRIER_SERIAL_THREAD)
+ /* TODO(bnoordhuis) Remove padding in v2. */
+ char pad[sizeof(pthread_barrier_t) - sizeof(struct _uv_barrier*)];
+# endif
+} uv_barrier_t;
+#else
+typedef pthread_barrier_t uv_barrier_t;
+#endif
+
+#endif
+
+/* Platform-specific definitions for uv_spawn support. */
+typedef gid_t uv_gid_t;
+typedef uid_t uv_uid_t;
+
+typedef struct dirent uv__dirent_t;
+
+#if defined(DT_UNKNOWN)
+# define HAVE_DIRENT_TYPES
+# if defined(DT_REG)
+# define UV__DT_FILE DT_REG
+# else
+# define UV__DT_FILE -1
+# endif
+# if defined(DT_DIR)
+# define UV__DT_DIR DT_DIR
+# else
+# define UV__DT_DIR -2
+# endif
+# if defined(DT_LNK)
+# define UV__DT_LINK DT_LNK
+# else
+# define UV__DT_LINK -3
+# endif
+# if defined(DT_FIFO)
+# define UV__DT_FIFO DT_FIFO
+# else
+# define UV__DT_FIFO -4
+# endif
+# if defined(DT_SOCK)
+# define UV__DT_SOCKET DT_SOCK
+# else
+# define UV__DT_SOCKET -5
+# endif
+# if defined(DT_CHR)
+# define UV__DT_CHAR DT_CHR
+# else
+# define UV__DT_CHAR -6
+# endif
+# if defined(DT_BLK)
+# define UV__DT_BLOCK DT_BLK
+# else
+# define UV__DT_BLOCK -7
+# endif
+#endif
+
+/* Platform-specific definitions for uv_dlopen support. */
+#define UV_DYNAMIC /* empty */
+
+typedef struct {
+ void* handle;
+ char* errmsg;
+} uv_lib_t;
+
+#define UV_LOOP_PRIVATE_FIELDS \
+ unsigned long flags; \
+ int backend_fd; \
+ void* pending_queue[2]; \
+ void* watcher_queue[2]; \
+ uv__io_t** watchers; \
+ unsigned int nwatchers; \
+ unsigned int nfds; \
+ void* wq[2]; \
+ uv_mutex_t wq_mutex; \
+ uv_async_t wq_async; \
+ uv_rwlock_t cloexec_lock; \
+ uv_handle_t* closing_handles; \
+ void* process_handles[2]; \
+ void* prepare_handles[2]; \
+ void* check_handles[2]; \
+ void* idle_handles[2]; \
+ void* async_handles[2]; \
+ void (*async_unused)(void); /* TODO(bnoordhuis) Remove in libuv v2. */ \
+ uv__io_t async_io_watcher; \
+ int async_wfd; \
+ struct { \
+ void* min; \
+ unsigned int nelts; \
+ } timer_heap; \
+ uint64_t timer_counter; \
+ uint64_t time; \
+ int signal_pipefd[2]; \
+ uv__io_t signal_io_watcher; \
+ uv_signal_t child_watcher; \
+ int emfile_fd; \
+ UV_PLATFORM_LOOP_FIELDS \
+
+#define UV_REQ_TYPE_PRIVATE /* empty */
+
+#define UV_REQ_PRIVATE_FIELDS /* empty */
+
+#define UV_PRIVATE_REQ_TYPES /* empty */
+
+#define UV_WRITE_PRIVATE_FIELDS \
+ void* queue[2]; \
+ unsigned int write_index; \
+ uv_buf_t* bufs; \
+ unsigned int nbufs; \
+ int error; \
+ uv_buf_t bufsml[4]; \
+
+#define UV_CONNECT_PRIVATE_FIELDS \
+ void* queue[2]; \
+
+#define UV_SHUTDOWN_PRIVATE_FIELDS /* empty */
+
+#define UV_UDP_SEND_PRIVATE_FIELDS \
+ void* queue[2]; \
+ struct sockaddr_storage addr; \
+ unsigned int nbufs; \
+ uv_buf_t* bufs; \
+ ssize_t status; \
+ uv_udp_send_cb send_cb; \
+ uv_buf_t bufsml[4]; \
+
+#define UV_HANDLE_PRIVATE_FIELDS \
+ uv_handle_t* next_closing; \
+ unsigned int flags; \
+
+#define UV_STREAM_PRIVATE_FIELDS \
+ uv_connect_t *connect_req; \
+ uv_shutdown_t *shutdown_req; \
+ uv__io_t io_watcher; \
+ void* write_queue[2]; \
+ void* write_completed_queue[2]; \
+ uv_connection_cb connection_cb; \
+ int delayed_error; \
+ int accepted_fd; \
+ void* queued_fds; \
+ UV_STREAM_PRIVATE_PLATFORM_FIELDS \
+
+#define UV_TCP_PRIVATE_FIELDS /* empty */
+
+#define UV_UDP_PRIVATE_FIELDS \
+ uv_alloc_cb alloc_cb; \
+ uv_udp_recv_cb recv_cb; \
+ uv__io_t io_watcher; \
+ void* write_queue[2]; \
+ void* write_completed_queue[2]; \
+
+#define UV_PIPE_PRIVATE_FIELDS \
+ const char* pipe_fname; /* strdup'ed */
+
+#define UV_POLL_PRIVATE_FIELDS \
+ uv__io_t io_watcher;
+
+#define UV_PREPARE_PRIVATE_FIELDS \
+ uv_prepare_cb prepare_cb; \
+ void* queue[2]; \
+
+#define UV_CHECK_PRIVATE_FIELDS \
+ uv_check_cb check_cb; \
+ void* queue[2]; \
+
+#define UV_IDLE_PRIVATE_FIELDS \
+ uv_idle_cb idle_cb; \
+ void* queue[2]; \
+
+#define UV_ASYNC_PRIVATE_FIELDS \
+ uv_async_cb async_cb; \
+ void* queue[2]; \
+ int pending; \
+
+#define UV_TIMER_PRIVATE_FIELDS \
+ uv_timer_cb timer_cb; \
+ void* heap_node[3]; \
+ uint64_t timeout; \
+ uint64_t repeat; \
+ uint64_t start_id;
+
+#define UV_GETADDRINFO_PRIVATE_FIELDS \
+ struct uv__work work_req; \
+ uv_getaddrinfo_cb cb; \
+ struct addrinfo* hints; \
+ char* hostname; \
+ char* service; \
+ struct addrinfo* addrinfo; \
+ int retcode;
+
+#define UV_GETNAMEINFO_PRIVATE_FIELDS \
+ struct uv__work work_req; \
+ uv_getnameinfo_cb getnameinfo_cb; \
+ struct sockaddr_storage storage; \
+ int flags; \
+ char host[NI_MAXHOST]; \
+ char service[NI_MAXSERV]; \
+ int retcode;
+
+#define UV_PROCESS_PRIVATE_FIELDS \
+ void* queue[2]; \
+ int status; \
+
+#define UV_FS_PRIVATE_FIELDS \
+ const char *new_path; \
+ uv_file file; \
+ int flags; \
+ mode_t mode; \
+ unsigned int nbufs; \
+ uv_buf_t* bufs; \
+ off_t off; \
+ uv_uid_t uid; \
+ uv_gid_t gid; \
+ double atime; \
+ double mtime; \
+ struct uv__work work_req; \
+ uv_buf_t bufsml[4]; \
+
+#define UV_WORK_PRIVATE_FIELDS \
+ struct uv__work work_req;
+
+#define UV_TTY_PRIVATE_FIELDS \
+ struct termios orig_termios; \
+ int mode;
+
+#define UV_SIGNAL_PRIVATE_FIELDS \
+ /* RB_ENTRY(uv_signal_s) tree_entry; */ \
+ struct { \
+ struct uv_signal_s* rbe_left; \
+ struct uv_signal_s* rbe_right; \
+ struct uv_signal_s* rbe_parent; \
+ int rbe_color; \
+ } tree_entry; \
+ /* Use two counters here so we don have to fiddle with atomics. */ \
+ unsigned int caught_signals; \
+ unsigned int dispatched_signals;
+
+#define UV_FS_EVENT_PRIVATE_FIELDS \
+ uv_fs_event_cb cb; \
+ UV_PLATFORM_FS_EVENT_FIELDS \
+
+/* fs open() flags supported on this platform: */
+#if defined(O_APPEND)
+# define UV_FS_O_APPEND O_APPEND
+#else
+# define UV_FS_O_APPEND 0
+#endif
+#if defined(O_CREAT)
+# define UV_FS_O_CREAT O_CREAT
+#else
+# define UV_FS_O_CREAT 0
+#endif
+#if defined(O_DIRECT)
+# define UV_FS_O_DIRECT O_DIRECT
+#else
+# define UV_FS_O_DIRECT 0
+#endif
+#if defined(O_DIRECTORY)
+# define UV_FS_O_DIRECTORY O_DIRECTORY
+#else
+# define UV_FS_O_DIRECTORY 0
+#endif
+#if defined(O_DSYNC)
+# define UV_FS_O_DSYNC O_DSYNC
+#else
+# define UV_FS_O_DSYNC 0
+#endif
+#if defined(O_EXCL)
+# define UV_FS_O_EXCL O_EXCL
+#else
+# define UV_FS_O_EXCL 0
+#endif
+#if defined(O_EXLOCK)
+# define UV_FS_O_EXLOCK O_EXLOCK
+#else
+# define UV_FS_O_EXLOCK 0
+#endif
+#if defined(O_NOATIME)
+# define UV_FS_O_NOATIME O_NOATIME
+#else
+# define UV_FS_O_NOATIME 0
+#endif
+#if defined(O_NOCTTY)
+# define UV_FS_O_NOCTTY O_NOCTTY
+#else
+# define UV_FS_O_NOCTTY 0
+#endif
+#if defined(O_NOFOLLOW)
+# define UV_FS_O_NOFOLLOW O_NOFOLLOW
+#else
+# define UV_FS_O_NOFOLLOW 0
+#endif
+#if defined(O_NONBLOCK)
+# define UV_FS_O_NONBLOCK O_NONBLOCK
+#else
+# define UV_FS_O_NONBLOCK 0
+#endif
+#if defined(O_RDONLY)
+# define UV_FS_O_RDONLY O_RDONLY
+#else
+# define UV_FS_O_RDONLY 0
+#endif
+#if defined(O_RDWR)
+# define UV_FS_O_RDWR O_RDWR
+#else
+# define UV_FS_O_RDWR 0
+#endif
+#if defined(O_SYMLINK)
+# define UV_FS_O_SYMLINK O_SYMLINK
+#else
+# define UV_FS_O_SYMLINK 0
+#endif
+#if defined(O_SYNC)
+# define UV_FS_O_SYNC O_SYNC
+#else
+# define UV_FS_O_SYNC 0
+#endif
+#if defined(O_TRUNC)
+# define UV_FS_O_TRUNC O_TRUNC
+#else
+# define UV_FS_O_TRUNC 0
+#endif
+#if defined(O_WRONLY)
+# define UV_FS_O_WRONLY O_WRONLY
+#else
+# define UV_FS_O_WRONLY 0
+#endif
+
+/* fs open() flags supported on other platforms: */
+#define UV_FS_O_RANDOM 0
+#define UV_FS_O_SHORT_LIVED 0
+#define UV_FS_O_SEQUENTIAL 0
+#define UV_FS_O_TEMPORARY 0
+
+#endif /* UV_UNIX_H */
diff --git a/Utilities/cmlibuv/include/uv/version.h b/Utilities/cmlibuv/include/uv/version.h
new file mode 100644
index 000000000..abc140a3b
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/version.h
@@ -0,0 +1,43 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef UV_VERSION_H
+#define UV_VERSION_H
+
+ /*
+ * Versions with the same major number are ABI stable. API is allowed to
+ * evolve between minor releases, but only in a backwards compatible way.
+ * Make sure you update the -soname directives in configure.ac
+ * and uv.gyp whenever you bump UV_VERSION_MAJOR or UV_VERSION_MINOR (but
+ * not UV_VERSION_PATCH.)
+ */
+
+#define UV_VERSION_MAJOR 1
+#define UV_VERSION_MINOR 24
+#define UV_VERSION_PATCH 2
+#define UV_VERSION_IS_RELEASE 0
+#define UV_VERSION_SUFFIX "dev"
+
+#define UV_VERSION_HEX ((UV_VERSION_MAJOR << 16) | \
+ (UV_VERSION_MINOR << 8) | \
+ (UV_VERSION_PATCH))
+
+#endif /* UV_VERSION_H */
diff --git a/Utilities/cmlibuv/include/uv/win.h b/Utilities/cmlibuv/include/uv/win.h
new file mode 100644
index 000000000..f3d3809f3
--- /dev/null
+++ b/Utilities/cmlibuv/include/uv/win.h
@@ -0,0 +1,696 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef _WIN32_WINNT
+# define _WIN32_WINNT 0x0600
+#endif
+
+#if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
+typedef intptr_t ssize_t;
+# define SSIZE_MAX INTPTR_MAX
+# define _SSIZE_T_
+# define _SSIZE_T_DEFINED
+#endif
+
+#include <winsock2.h>
+
+#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
+typedef struct pollfd {
+ SOCKET fd;
+ short events;
+ short revents;
+} WSAPOLLFD, *PWSAPOLLFD, *LPWSAPOLLFD;
+#endif
+
+#ifndef LOCALE_INVARIANT
+# define LOCALE_INVARIANT 0x007f
+#endif
+
+#include <mswsock.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+
+#include <process.h>
+#include <signal.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+
+#if defined(_MSC_VER) && _MSC_VER < 1600
+# include "stdint-msvc2008.h"
+#else
+# include <stdint.h>
+#endif
+
+#include "tree.h"
+#include "threadpool.h"
+
+#define MAX_PIPENAME_LEN 256
+
+#ifndef S_IFLNK
+# define S_IFLNK 0xA000
+#endif
+
+/* Additional signals supported by uv_signal and or uv_kill. The CRT defines
+ * the following signals already:
+ *
+ * #define SIGINT 2
+ * #define SIGILL 4
+ * #define SIGABRT_COMPAT 6
+ * #define SIGFPE 8
+ * #define SIGSEGV 11
+ * #define SIGTERM 15
+ * #define SIGBREAK 21
+ * #define SIGABRT 22
+ *
+ * The additional signals have values that are common on other Unix
+ * variants (Linux and Darwin)
+ */
+#define SIGHUP 1
+#define SIGKILL 9
+#define SIGWINCH 28
+
+/* Redefine NSIG to take SIGWINCH into consideration */
+#if defined(NSIG) && NSIG <= SIGWINCH
+# undef NSIG
+#endif
+#ifndef NSIG
+# define NSIG SIGWINCH + 1
+#endif
+
+/* The CRT defines SIGABRT_COMPAT as 6, which equals SIGABRT on many unix-like
+ * platforms. However MinGW doesn't define it, so we do. */
+#ifndef SIGABRT_COMPAT
+# define SIGABRT_COMPAT 6
+#endif
+
+/*
+ * Guids and typedefs for winsock extension functions
+ * Mingw32 doesn't have these :-(
+ */
+#ifndef WSAID_ACCEPTEX
+# define WSAID_ACCEPTEX \
+ {0xb5367df1, 0xcbac, 0x11cf, \
+ {0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}
+#endif
+
+#ifndef WSAID_CONNECTEX
+# define WSAID_CONNECTEX \
+ {0x25a207b9, 0xddf3, 0x4660, \
+ {0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e}}
+#endif
+
+#ifndef WSAID_GETACCEPTEXSOCKADDRS
+# define WSAID_GETACCEPTEXSOCKADDRS \
+ {0xb5367df2, 0xcbac, 0x11cf, \
+ {0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}
+#endif
+
+#ifndef WSAID_DISCONNECTEX
+# define WSAID_DISCONNECTEX \
+ {0x7fda2e11, 0x8630, 0x436f, \
+ {0xa0, 0x31, 0xf5, 0x36, 0xa6, 0xee, 0xc1, 0x57}}
+#endif
+
+#ifndef WSAID_TRANSMITFILE
+# define WSAID_TRANSMITFILE \
+ {0xb5367df0, 0xcbac, 0x11cf, \
+ {0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92}}
+#endif
+
+#if (defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) \
+ || (defined(_MSC_VER) && _MSC_VER < 1500)
+ typedef BOOL (PASCAL *LPFN_ACCEPTEX)
+ (SOCKET sListenSocket,
+ SOCKET sAcceptSocket,
+ PVOID lpOutputBuffer,
+ DWORD dwReceiveDataLength,
+ DWORD dwLocalAddressLength,
+ DWORD dwRemoteAddressLength,
+ LPDWORD lpdwBytesReceived,
+ LPOVERLAPPED lpOverlapped);
+
+ typedef BOOL (PASCAL *LPFN_CONNECTEX)
+ (SOCKET s,
+ const struct sockaddr* name,
+ int namelen,
+ PVOID lpSendBuffer,
+ DWORD dwSendDataLength,
+ LPDWORD lpdwBytesSent,
+ LPOVERLAPPED lpOverlapped);
+
+ typedef void (PASCAL *LPFN_GETACCEPTEXSOCKADDRS)
+ (PVOID lpOutputBuffer,
+ DWORD dwReceiveDataLength,
+ DWORD dwLocalAddressLength,
+ DWORD dwRemoteAddressLength,
+ LPSOCKADDR* LocalSockaddr,
+ LPINT LocalSockaddrLength,
+ LPSOCKADDR* RemoteSockaddr,
+ LPINT RemoteSockaddrLength);
+
+ typedef BOOL (PASCAL *LPFN_DISCONNECTEX)
+ (SOCKET hSocket,
+ LPOVERLAPPED lpOverlapped,
+ DWORD dwFlags,
+ DWORD reserved);
+
+ typedef BOOL (PASCAL *LPFN_TRANSMITFILE)
+ (SOCKET hSocket,
+ HANDLE hFile,
+ DWORD nNumberOfBytesToWrite,
+ DWORD nNumberOfBytesPerSend,
+ LPOVERLAPPED lpOverlapped,
+ LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers,
+ DWORD dwFlags);
+
+ typedef PVOID RTL_SRWLOCK;
+ typedef RTL_SRWLOCK SRWLOCK, *PSRWLOCK;
+#endif
+
+typedef int (WSAAPI* LPFN_WSARECV)
+ (SOCKET socket,
+ LPWSABUF buffers,
+ DWORD buffer_count,
+ LPDWORD bytes,
+ LPDWORD flags,
+ LPWSAOVERLAPPED overlapped,
+ LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine);
+
+typedef int (WSAAPI* LPFN_WSARECVFROM)
+ (SOCKET socket,
+ LPWSABUF buffers,
+ DWORD buffer_count,
+ LPDWORD bytes,
+ LPDWORD flags,
+ struct sockaddr* addr,
+ LPINT addr_len,
+ LPWSAOVERLAPPED overlapped,
+ LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_routine);
+
+#ifndef _NTDEF_
+ typedef LONG NTSTATUS;
+ typedef NTSTATUS *PNTSTATUS;
+#endif
+
+#ifndef RTL_CONDITION_VARIABLE_INIT
+ typedef PVOID CONDITION_VARIABLE, *PCONDITION_VARIABLE;
+#endif
+
+typedef struct _AFD_POLL_HANDLE_INFO {
+ HANDLE Handle;
+ ULONG Events;
+ NTSTATUS Status;
+} AFD_POLL_HANDLE_INFO, *PAFD_POLL_HANDLE_INFO;
+
+typedef struct _AFD_POLL_INFO {
+ LARGE_INTEGER Timeout;
+ ULONG NumberOfHandles;
+ ULONG Exclusive;
+ AFD_POLL_HANDLE_INFO Handles[1];
+} AFD_POLL_INFO, *PAFD_POLL_INFO;
+
+#define UV_MSAFD_PROVIDER_COUNT 3
+
+
+/**
+ * It should be possible to cast uv_buf_t[] to WSABUF[]
+ * see http://msdn.microsoft.com/en-us/library/ms741542(v=vs.85).aspx
+ */
+typedef struct uv_buf_t {
+ ULONG len;
+ char* base;
+} uv_buf_t;
+
+typedef int uv_file;
+typedef SOCKET uv_os_sock_t;
+typedef HANDLE uv_os_fd_t;
+typedef int uv_pid_t;
+
+typedef HANDLE uv_thread_t;
+
+typedef HANDLE uv_sem_t;
+
+typedef CRITICAL_SECTION uv_mutex_t;
+
+/* This condition variable implementation is based on the SetEvent solution
+ * (section 3.2) at http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
+ * We could not use the SignalObjectAndWait solution (section 3.4) because
+ * it want the 2nd argument (type uv_mutex_t) of uv_cond_wait() and
+ * uv_cond_timedwait() to be HANDLEs, but we use CRITICAL_SECTIONs.
+ */
+
+typedef union {
+ CONDITION_VARIABLE cond_var;
+ struct {
+ unsigned int waiters_count;
+ CRITICAL_SECTION waiters_count_lock;
+ HANDLE signal_event;
+ HANDLE broadcast_event;
+ } unused_; /* TODO: retained for ABI compatibility; remove me in v2.x. */
+} uv_cond_t;
+
+typedef union {
+ struct {
+ unsigned int num_readers_;
+ CRITICAL_SECTION num_readers_lock_;
+ HANDLE write_semaphore_;
+ } state_;
+ /* TODO: remove me in v2.x. */
+ struct {
+ SRWLOCK unused_;
+ } unused1_;
+ /* TODO: remove me in v2.x. */
+ struct {
+ uv_mutex_t unused1_;
+ uv_mutex_t unused2_;
+ } unused2_;
+} uv_rwlock_t;
+
+typedef struct {
+ unsigned int n;
+ unsigned int count;
+ uv_mutex_t mutex;
+ uv_sem_t turnstile1;
+ uv_sem_t turnstile2;
+} uv_barrier_t;
+
+typedef struct {
+ DWORD tls_index;
+} uv_key_t;
+
+#define UV_ONCE_INIT { 0, NULL }
+
+typedef struct uv_once_s {
+ unsigned char ran;
+ HANDLE event;
+} uv_once_t;
+
+/* Platform-specific definitions for uv_spawn support. */
+typedef unsigned char uv_uid_t;
+typedef unsigned char uv_gid_t;
+
+typedef struct uv__dirent_s {
+ int d_type;
+ char d_name[1];
+} uv__dirent_t;
+
+#define HAVE_DIRENT_TYPES
+#define UV__DT_DIR UV_DIRENT_DIR
+#define UV__DT_FILE UV_DIRENT_FILE
+#define UV__DT_LINK UV_DIRENT_LINK
+#define UV__DT_FIFO UV_DIRENT_FIFO
+#define UV__DT_SOCKET UV_DIRENT_SOCKET
+#define UV__DT_CHAR UV_DIRENT_CHAR
+#define UV__DT_BLOCK UV_DIRENT_BLOCK
+
+/* Platform-specific definitions for uv_dlopen support. */
+#define UV_DYNAMIC FAR WINAPI
+typedef struct {
+ HMODULE handle;
+ char* errmsg;
+} uv_lib_t;
+
+#define UV_LOOP_PRIVATE_FIELDS \
+ /* The loop's I/O completion port */ \
+ HANDLE iocp; \
+ /* The current time according to the event loop. in msecs. */ \
+ uint64_t time; \
+ /* Tail of a single-linked circular queue of pending reqs. If the queue */ \
+ /* is empty, tail_ is NULL. If there is only one item, */ \
+ /* tail_->next_req == tail_ */ \
+ uv_req_t* pending_reqs_tail; \
+ /* Head of a single-linked list of closed handles */ \
+ uv_handle_t* endgame_handles; \
+ /* TODO(bnoordhuis) Stop heap-allocating |timer_heap| in libuv v2.x. */ \
+ void* timer_heap; \
+ /* Lists of active loop (prepare / check / idle) watchers */ \
+ uv_prepare_t* prepare_handles; \
+ uv_check_t* check_handles; \
+ uv_idle_t* idle_handles; \
+ /* This pointer will refer to the prepare/check/idle handle whose */ \
+ /* callback is scheduled to be called next. This is needed to allow */ \
+ /* safe removal from one of the lists above while that list being */ \
+ /* iterated over. */ \
+ uv_prepare_t* next_prepare_handle; \
+ uv_check_t* next_check_handle; \
+ uv_idle_t* next_idle_handle; \
+ /* This handle holds the peer sockets for the fast variant of uv_poll_t */ \
+ SOCKET poll_peer_sockets[UV_MSAFD_PROVIDER_COUNT]; \
+ /* Counter to keep track of active tcp streams */ \
+ unsigned int active_tcp_streams; \
+ /* Counter to keep track of active udp streams */ \
+ unsigned int active_udp_streams; \
+ /* Counter to started timer */ \
+ uint64_t timer_counter; \
+ /* Threadpool */ \
+ void* wq[2]; \
+ uv_mutex_t wq_mutex; \
+ uv_async_t wq_async;
+
+#define UV_REQ_TYPE_PRIVATE \
+ /* TODO: remove the req suffix */ \
+ UV_ACCEPT, \
+ UV_FS_EVENT_REQ, \
+ UV_POLL_REQ, \
+ UV_PROCESS_EXIT, \
+ UV_READ, \
+ UV_UDP_RECV, \
+ UV_WAKEUP, \
+ UV_SIGNAL_REQ,
+
+#define UV_REQ_PRIVATE_FIELDS \
+ union { \
+ /* Used by I/O operations */ \
+ struct { \
+ OVERLAPPED overlapped; \
+ size_t queued_bytes; \
+ } io; \
+ } u; \
+ struct uv_req_s* next_req;
+
+#define UV_WRITE_PRIVATE_FIELDS \
+ int coalesced; \
+ uv_buf_t write_buffer; \
+ HANDLE event_handle; \
+ HANDLE wait_handle;
+
+#define UV_CONNECT_PRIVATE_FIELDS \
+ /* empty */
+
+#define UV_SHUTDOWN_PRIVATE_FIELDS \
+ /* empty */
+
+#define UV_UDP_SEND_PRIVATE_FIELDS \
+ /* empty */
+
+#define UV_PRIVATE_REQ_TYPES \
+ typedef struct uv_pipe_accept_s { \
+ UV_REQ_FIELDS \
+ HANDLE pipeHandle; \
+ struct uv_pipe_accept_s* next_pending; \
+ } uv_pipe_accept_t; \
+ \
+ typedef struct uv_tcp_accept_s { \
+ UV_REQ_FIELDS \
+ SOCKET accept_socket; \
+ char accept_buffer[sizeof(struct sockaddr_storage) * 2 + 32]; \
+ HANDLE event_handle; \
+ HANDLE wait_handle; \
+ struct uv_tcp_accept_s* next_pending; \
+ } uv_tcp_accept_t; \
+ \
+ typedef struct uv_read_s { \
+ UV_REQ_FIELDS \
+ HANDLE event_handle; \
+ HANDLE wait_handle; \
+ } uv_read_t;
+
+#define uv_stream_connection_fields \
+ unsigned int write_reqs_pending; \
+ uv_shutdown_t* shutdown_req;
+
+#define uv_stream_server_fields \
+ uv_connection_cb connection_cb;
+
+#define UV_STREAM_PRIVATE_FIELDS \
+ unsigned int reqs_pending; \
+ int activecnt; \
+ uv_read_t read_req; \
+ union { \
+ struct { uv_stream_connection_fields } conn; \
+ struct { uv_stream_server_fields } serv; \
+ } stream;
+
+#define uv_tcp_server_fields \
+ uv_tcp_accept_t* accept_reqs; \
+ unsigned int processed_accepts; \
+ uv_tcp_accept_t* pending_accepts; \
+ LPFN_ACCEPTEX func_acceptex;
+
+#define uv_tcp_connection_fields \
+ uv_buf_t read_buffer; \
+ LPFN_CONNECTEX func_connectex;
+
+#define UV_TCP_PRIVATE_FIELDS \
+ SOCKET socket; \
+ int delayed_error; \
+ union { \
+ struct { uv_tcp_server_fields } serv; \
+ struct { uv_tcp_connection_fields } conn; \
+ } tcp;
+
+#define UV_UDP_PRIVATE_FIELDS \
+ SOCKET socket; \
+ unsigned int reqs_pending; \
+ int activecnt; \
+ uv_req_t recv_req; \
+ uv_buf_t recv_buffer; \
+ struct sockaddr_storage recv_from; \
+ int recv_from_len; \
+ uv_udp_recv_cb recv_cb; \
+ uv_alloc_cb alloc_cb; \
+ LPFN_WSARECV func_wsarecv; \
+ LPFN_WSARECVFROM func_wsarecvfrom;
+
+#define uv_pipe_server_fields \
+ int pending_instances; \
+ uv_pipe_accept_t* accept_reqs; \
+ uv_pipe_accept_t* pending_accepts;
+
+#define uv_pipe_connection_fields \
+ uv_timer_t* eof_timer; \
+ uv_write_t dummy; /* TODO: retained for ABI compat; remove this in v2.x. */ \
+ DWORD ipc_remote_pid; \
+ union { \
+ uint32_t payload_remaining; \
+ uint64_t dummy; /* TODO: retained for ABI compat; remove this in v2.x. */ \
+ } ipc_data_frame; \
+ void* ipc_xfer_queue[2]; \
+ int ipc_xfer_queue_length; \
+ uv_write_t* non_overlapped_writes_tail; \
+ CRITICAL_SECTION readfile_thread_lock; \
+ volatile HANDLE readfile_thread_handle;
+
+#define UV_PIPE_PRIVATE_FIELDS \
+ HANDLE handle; \
+ WCHAR* name; \
+ union { \
+ struct { uv_pipe_server_fields } serv; \
+ struct { uv_pipe_connection_fields } conn; \
+ } pipe;
+
+/* TODO: put the parser states in an union - TTY handles are always half-duplex
+ * so read-state can safely overlap write-state. */
+#define UV_TTY_PRIVATE_FIELDS \
+ HANDLE handle; \
+ union { \
+ struct { \
+ /* Used for readable TTY handles */ \
+ /* TODO: remove me in v2.x. */ \
+ HANDLE unused_; \
+ uv_buf_t read_line_buffer; \
+ HANDLE read_raw_wait; \
+ /* Fields used for translating win keystrokes into vt100 characters */ \
+ char last_key[8]; \
+ unsigned char last_key_offset; \
+ unsigned char last_key_len; \
+ WCHAR last_utf16_high_surrogate; \
+ INPUT_RECORD last_input_record; \
+ } rd; \
+ struct { \
+ /* Used for writable TTY handles */ \
+ /* utf8-to-utf16 conversion state */ \
+ unsigned int utf8_codepoint; \
+ unsigned char utf8_bytes_left; \
+ /* eol conversion state */ \
+ unsigned char previous_eol; \
+ /* ansi parser state */ \
+ unsigned char ansi_parser_state; \
+ unsigned char ansi_csi_argc; \
+ unsigned short ansi_csi_argv[4]; \
+ COORD saved_position; \
+ WORD saved_attributes; \
+ } wr; \
+ } tty;
+
+#define UV_POLL_PRIVATE_FIELDS \
+ SOCKET socket; \
+ /* Used in fast mode */ \
+ SOCKET peer_socket; \
+ AFD_POLL_INFO afd_poll_info_1; \
+ AFD_POLL_INFO afd_poll_info_2; \
+ /* Used in fast and slow mode. */ \
+ uv_req_t poll_req_1; \
+ uv_req_t poll_req_2; \
+ unsigned char submitted_events_1; \
+ unsigned char submitted_events_2; \
+ unsigned char mask_events_1; \
+ unsigned char mask_events_2; \
+ unsigned char events;
+
+#define UV_TIMER_PRIVATE_FIELDS \
+ void* heap_node[3]; \
+ int unused; \
+ uint64_t timeout; \
+ uint64_t repeat; \
+ uint64_t start_id; \
+ uv_timer_cb timer_cb;
+
+#define UV_ASYNC_PRIVATE_FIELDS \
+ struct uv_req_s async_req; \
+ uv_async_cb async_cb; \
+ /* char to avoid alignment issues */ \
+ char volatile async_sent;
+
+#define UV_PREPARE_PRIVATE_FIELDS \
+ uv_prepare_t* prepare_prev; \
+ uv_prepare_t* prepare_next; \
+ uv_prepare_cb prepare_cb;
+
+#define UV_CHECK_PRIVATE_FIELDS \
+ uv_check_t* check_prev; \
+ uv_check_t* check_next; \
+ uv_check_cb check_cb;
+
+#define UV_IDLE_PRIVATE_FIELDS \
+ uv_idle_t* idle_prev; \
+ uv_idle_t* idle_next; \
+ uv_idle_cb idle_cb;
+
+#define UV_HANDLE_PRIVATE_FIELDS \
+ uv_handle_t* endgame_next; \
+ unsigned int flags;
+
+#define UV_GETADDRINFO_PRIVATE_FIELDS \
+ struct uv__work work_req; \
+ uv_getaddrinfo_cb getaddrinfo_cb; \
+ void* alloc; \
+ WCHAR* node; \
+ WCHAR* service; \
+ /* The addrinfoW field is used to store a pointer to the hints, and */ \
+ /* later on to store the result of GetAddrInfoW. The final result will */ \
+ /* be converted to struct addrinfo* and stored in the addrinfo field. */ \
+ struct addrinfoW* addrinfow; \
+ struct addrinfo* addrinfo; \
+ int retcode;
+
+#define UV_GETNAMEINFO_PRIVATE_FIELDS \
+ struct uv__work work_req; \
+ uv_getnameinfo_cb getnameinfo_cb; \
+ struct sockaddr_storage storage; \
+ int flags; \
+ char host[NI_MAXHOST]; \
+ char service[NI_MAXSERV]; \
+ int retcode;
+
+#define UV_PROCESS_PRIVATE_FIELDS \
+ struct uv_process_exit_s { \
+ UV_REQ_FIELDS \
+ } exit_req; \
+ BYTE* child_stdio_buffer; \
+ int exit_signal; \
+ HANDLE wait_handle; \
+ HANDLE process_handle; \
+ volatile char exit_cb_pending;
+
+#define UV_FS_PRIVATE_FIELDS \
+ struct uv__work work_req; \
+ int flags; \
+ DWORD sys_errno_; \
+ union { \
+ /* TODO: remove me in 0.9. */ \
+ WCHAR* pathw; \
+ int fd; \
+ } file; \
+ union { \
+ struct { \
+ int mode; \
+ WCHAR* new_pathw; \
+ int file_flags; \
+ int fd_out; \
+ unsigned int nbufs; \
+ uv_buf_t* bufs; \
+ int64_t offset; \
+ uv_buf_t bufsml[4]; \
+ } info; \
+ struct { \
+ double atime; \
+ double mtime; \
+ } time; \
+ } fs;
+
+#define UV_WORK_PRIVATE_FIELDS \
+ struct uv__work work_req;
+
+#define UV_FS_EVENT_PRIVATE_FIELDS \
+ struct uv_fs_event_req_s { \
+ UV_REQ_FIELDS \
+ } req; \
+ HANDLE dir_handle; \
+ int req_pending; \
+ uv_fs_event_cb cb; \
+ WCHAR* filew; \
+ WCHAR* short_filew; \
+ WCHAR* dirw; \
+ char* buffer;
+
+#define UV_SIGNAL_PRIVATE_FIELDS \
+ RB_ENTRY(uv_signal_s) tree_entry; \
+ struct uv_req_s signal_req; \
+ unsigned long pending_signum;
+
+#ifndef F_OK
+#define F_OK 0
+#endif
+#ifndef R_OK
+#define R_OK 4
+#endif
+#ifndef W_OK
+#define W_OK 2
+#endif
+#ifndef X_OK
+#define X_OK 1
+#endif
+
+/* fs open() flags supported on this platform: */
+#define UV_FS_O_APPEND _O_APPEND
+#define UV_FS_O_CREAT _O_CREAT
+#define UV_FS_O_EXCL _O_EXCL
+#define UV_FS_O_RANDOM _O_RANDOM
+#define UV_FS_O_RDONLY _O_RDONLY
+#define UV_FS_O_RDWR _O_RDWR
+#define UV_FS_O_SEQUENTIAL _O_SEQUENTIAL
+#define UV_FS_O_SHORT_LIVED _O_SHORT_LIVED
+#define UV_FS_O_TEMPORARY _O_TEMPORARY
+#define UV_FS_O_TRUNC _O_TRUNC
+#define UV_FS_O_WRONLY _O_WRONLY
+
+/* fs open() flags supported on other platforms (or mapped on this platform): */
+#define UV_FS_O_DIRECT 0x02000000 /* FILE_FLAG_NO_BUFFERING */
+#define UV_FS_O_DIRECTORY 0
+#define UV_FS_O_DSYNC 0x04000000 /* FILE_FLAG_WRITE_THROUGH */
+#define UV_FS_O_EXLOCK 0x10000000 /* EXCLUSIVE SHARING MODE */
+#define UV_FS_O_NOATIME 0
+#define UV_FS_O_NOCTTY 0
+#define UV_FS_O_NOFOLLOW 0
+#define UV_FS_O_NONBLOCK 0
+#define UV_FS_O_SYMLINK 0
+#define UV_FS_O_SYNC 0x08000000 /* FILE_FLAG_WRITE_THROUGH */
diff --git a/Utilities/cmlibuv/src/idna.c b/Utilities/cmlibuv/src/idna.c
new file mode 100644
index 000000000..13ffac6be
--- /dev/null
+++ b/Utilities/cmlibuv/src/idna.c
@@ -0,0 +1,291 @@
+/* Copyright (c) 2011, 2018 Ben Noordhuis <info@bnoordhuis.nl>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+/* Derived from https://github.com/bnoordhuis/punycode
+ * but updated to support IDNA 2008.
+ */
+
+#include "uv.h"
+#include "idna.h"
+#include <string.h>
+
+static unsigned uv__utf8_decode1_slow(const char** p,
+ const char* pe,
+ unsigned a) {
+ unsigned b;
+ unsigned c;
+ unsigned d;
+ unsigned min;
+
+ if (a > 0xF7)
+ return -1;
+
+ switch (*p - pe) {
+ default:
+ if (a > 0xEF) {
+ min = 0x10000;
+ a = a & 7;
+ b = (unsigned char) *(*p)++;
+ c = (unsigned char) *(*p)++;
+ d = (unsigned char) *(*p)++;
+ break;
+ }
+ /* Fall through. */
+ case 2:
+ if (a > 0xDF) {
+ min = 0x800;
+ b = 0x80 | (a & 15);
+ c = (unsigned char) *(*p)++;
+ d = (unsigned char) *(*p)++;
+ a = 0;
+ break;
+ }
+ /* Fall through. */
+ case 1:
+ if (a > 0xBF) {
+ min = 0x80;
+ b = 0x80;
+ c = 0x80 | (a & 31);
+ d = (unsigned char) *(*p)++;
+ a = 0;
+ break;
+ }
+ return -1; /* Invalid continuation byte. */
+ }
+
+ if (0x80 != (0xC0 & (b ^ c ^ d)))
+ return -1; /* Invalid sequence. */
+
+ b &= 63;
+ c &= 63;
+ d &= 63;
+ a = (a << 18) | (b << 12) | (c << 6) | d;
+
+ if (a < min)
+ return -1; /* Overlong sequence. */
+
+ if (a > 0x10FFFF)
+ return -1; /* Four-byte sequence > U+10FFFF. */
+
+ if (a >= 0xD800 && a <= 0xDFFF)
+ return -1; /* Surrogate pair. */
+
+ return a;
+}
+
+unsigned uv__utf8_decode1(const char** p, const char* pe) {
+ unsigned a;
+
+ a = (unsigned char) *(*p)++;
+
+ if (a < 128)
+ return a; /* ASCII, common case. */
+
+ return uv__utf8_decode1_slow(p, pe, a);
+}
+
+#define foreach_codepoint(c, p, pe) \
+ for (; (void) (*p <= pe && (c = uv__utf8_decode1(p, pe))), *p <= pe;)
+
+static int uv__idna_toascii_label(const char* s, const char* se,
+ char** d, char* de) {
+ static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz0123456789";
+ const char* ss;
+ unsigned c;
+ unsigned h;
+ unsigned k;
+ unsigned n;
+ unsigned m;
+ unsigned q;
+ unsigned t;
+ unsigned x;
+ unsigned y;
+ unsigned bias;
+ unsigned delta;
+ unsigned todo;
+ int first;
+
+ h = 0;
+ ss = s;
+ todo = 0;
+
+ foreach_codepoint(c, &s, se) {
+ if (c < 128)
+ h++;
+ else if (c == (unsigned) -1)
+ return UV_EINVAL;
+ else
+ todo++;
+ }
+
+ if (todo > 0) {
+ if (*d < de) *(*d)++ = 'x';
+ if (*d < de) *(*d)++ = 'n';
+ if (*d < de) *(*d)++ = '-';
+ if (*d < de) *(*d)++ = '-';
+ }
+
+ x = 0;
+ s = ss;
+ foreach_codepoint(c, &s, se) {
+ if (c > 127)
+ continue;
+
+ if (*d < de)
+ *(*d)++ = c;
+
+ if (++x == h)
+ break; /* Visited all ASCII characters. */
+ }
+
+ if (todo == 0)
+ return h;
+
+ /* Only write separator when we've written ASCII characters first. */
+ if (h > 0)
+ if (*d < de)
+ *(*d)++ = '-';
+
+ n = 128;
+ bias = 72;
+ delta = 0;
+ first = 1;
+
+ while (todo > 0) {
+ m = -1;
+ s = ss;
+ foreach_codepoint(c, &s, se)
+ if (c >= n)
+ if (c < m)
+ m = c;
+
+ x = m - n;
+ y = h + 1;
+
+ if (x > ~delta / y)
+ return UV_E2BIG; /* Overflow. */
+
+ delta += x * y;
+ n = m;
+
+ s = ss;
+ foreach_codepoint(c, &s, se) {
+ if (c < n)
+ if (++delta == 0)
+ return UV_E2BIG; /* Overflow. */
+
+ if (c != n)
+ continue;
+
+ for (k = 36, q = delta; /* empty */; k += 36) {
+ t = 1;
+
+ if (k > bias)
+ t = k - bias;
+
+ if (t > 26)
+ t = 26;
+
+ if (q < t)
+ break;
+
+ /* TODO(bnoordhuis) Since 1 <= t <= 26 and therefore
+ * 10 <= y <= 35, we can optimize the long division
+ * into a table-based reciprocal multiplication.
+ */
+ x = q - t;
+ y = 36 - t; /* 10 <= y <= 35 since 1 <= t <= 26. */
+ q = x / y;
+ t = t + x % y; /* 1 <= t <= 35 because of y. */
+
+ if (*d < de)
+ *(*d)++ = alphabet[t];
+ }
+
+ if (*d < de)
+ *(*d)++ = alphabet[q];
+
+ delta /= 2;
+
+ if (first) {
+ delta /= 350;
+ first = 0;
+ }
+
+ /* No overflow check is needed because |delta| was just
+ * divided by 2 and |delta+delta >= delta + delta/h|.
+ */
+ h++;
+ delta += delta / h;
+
+ for (bias = 0; delta > 35 * 26 / 2; bias += 36)
+ delta /= 35;
+
+ bias += 36 * delta / (delta + 38);
+ delta = 0;
+ todo--;
+ }
+
+ delta++;
+ n++;
+ }
+
+ return 0;
+}
+
+#undef foreach_codepoint
+
+long uv__idna_toascii(const char* s, const char* se, char* d, char* de) {
+ const char* si;
+ const char* st;
+ unsigned c;
+ char* ds;
+ int rc;
+
+ ds = d;
+
+ for (si = s; si < se; /* empty */) {
+ st = si;
+ c = uv__utf8_decode1(&si, se);
+
+ if (c != '.')
+ if (c != 0x3002) /* 。 */
+ if (c != 0xFF0E) /* . */
+ if (c != 0xFF61) /* 。 */
+ continue;
+
+ rc = uv__idna_toascii_label(s, st, &d, de);
+
+ if (rc < 0)
+ return rc;
+
+ if (d < de)
+ *d++ = '.';
+
+ s = si;
+ }
+
+ if (s < se) {
+ rc = uv__idna_toascii_label(s, se, &d, de);
+
+ if (rc < 0)
+ return rc;
+ }
+
+ if (d < de)
+ *d++ = '\0';
+
+ return d - ds; /* Number of bytes written. */
+}
diff --git a/Utilities/cmlibuv/src/idna.h b/Utilities/cmlibuv/src/idna.h
new file mode 100644
index 000000000..8e0c592fe
--- /dev/null
+++ b/Utilities/cmlibuv/src/idna.h
@@ -0,0 +1,31 @@
+/* Copyright (c) 2011, 2018 Ben Noordhuis <info@bnoordhuis.nl>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifndef UV_SRC_IDNA_H_
+#define UV_SRC_IDNA_H_
+
+/* Decode a single codepoint. Returns the codepoint or UINT32_MAX on error.
+ * |p| is updated on success _and_ error, i.e., bad multi-byte sequences are
+ * skipped in their entirety, not just the first bad byte.
+ */
+unsigned uv__utf8_decode1(const char** p, const char* pe);
+
+/* Convert a UTF-8 domain name to IDNA 2008 / Punycode. A return value >= 0
+ * is the number of bytes written to |d|, including the trailing nul byte.
+ * A return value < 0 is a libuv error code. |s| and |d| can not overlap.
+ */
+long uv__idna_toascii(const char* s, const char* se, char* d, char* de);
+
+#endif /* UV_SRC_IDNA_H_ */
diff --git a/Utilities/cmlibuv/src/strscpy.c b/Utilities/cmlibuv/src/strscpy.c
new file mode 100644
index 000000000..2a2bdce74
--- /dev/null
+++ b/Utilities/cmlibuv/src/strscpy.c
@@ -0,0 +1,17 @@
+#include "strscpy.h"
+#include <limits.h> /* SSIZE_MAX */
+
+ssize_t uv__strscpy(char* d, const char* s, size_t n) {
+ size_t i;
+
+ for (i = 0; i < n; i++)
+ if ('\0' == (d[i] = s[i]))
+ return i > SSIZE_MAX ? UV_E2BIG : (ssize_t) i;
+
+ if (i == 0)
+ return 0;
+
+ d[--i] = '\0';
+
+ return UV_E2BIG;
+}
diff --git a/Utilities/cmlibuv/src/strscpy.h b/Utilities/cmlibuv/src/strscpy.h
new file mode 100644
index 000000000..fbe0a393f
--- /dev/null
+++ b/Utilities/cmlibuv/src/strscpy.h
@@ -0,0 +1,18 @@
+#ifndef UV_STRSCPY_H_
+#define UV_STRSCPY_H_
+
+/* Include uv.h for its definitions of size_t and ssize_t.
+ * size_t can be obtained directly from <stddef.h> but ssize_t requires
+ * some hoop jumping on Windows that I didn't want to duplicate here.
+ */
+#include "uv.h"
+
+/* Copies up to |n-1| bytes from |d| to |s| and always zero-terminates
+ * the result, except when |n==0|. Returns the number of bytes copied
+ * or UV_E2BIG if |d| is too small.
+ *
+ * See https://www.kernel.org/doc/htmldocs/kernel-api/API-strscpy.html
+ */
+ssize_t uv__strscpy(char* d, const char* s, size_t n);
+
+#endif /* UV_STRSCPY_H_ */
diff --git a/Utilities/cmlibuv/src/timer.c b/Utilities/cmlibuv/src/timer.c
new file mode 100644
index 000000000..dd78bcbad
--- /dev/null
+++ b/Utilities/cmlibuv/src/timer.c
@@ -0,0 +1,181 @@
+/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#include "uv.h"
+#include "uv-common.h"
+#include "heap-inl.h"
+
+#include <assert.h>
+#include <limits.h>
+
+
+static struct heap *timer_heap(const uv_loop_t* loop) {
+#ifdef _WIN32
+ return (struct heap*) loop->timer_heap;
+#else
+ return (struct heap*) &loop->timer_heap;
+#endif
+}
+
+
+static int timer_less_than(const struct heap_node* ha,
+ const struct heap_node* hb) {
+ const uv_timer_t* a;
+ const uv_timer_t* b;
+
+ a = container_of(ha, uv_timer_t, heap_node);
+ b = container_of(hb, uv_timer_t, heap_node);
+
+ if (a->timeout < b->timeout)
+ return 1;
+ if (b->timeout < a->timeout)
+ return 0;
+
+ /* Compare start_id when both have the same timeout. start_id is
+ * allocated with loop->timer_counter in uv_timer_start().
+ */
+ if (a->start_id < b->start_id)
+ return 1;
+ if (b->start_id < a->start_id)
+ return 0;
+
+ return 0;
+}
+
+
+int uv_timer_init(uv_loop_t* loop, uv_timer_t* handle) {
+ uv__handle_init(loop, (uv_handle_t*)handle, UV_TIMER);
+ handle->timer_cb = NULL;
+ handle->repeat = 0;
+ return 0;
+}
+
+
+int uv_timer_start(uv_timer_t* handle,
+ uv_timer_cb cb,
+ uint64_t timeout,
+ uint64_t repeat) {
+ uint64_t clamped_timeout;
+
+ if (cb == NULL)
+ return UV_EINVAL;
+
+ if (uv__is_active(handle))
+ uv_timer_stop(handle);
+
+ clamped_timeout = handle->loop->time + timeout;
+ if (clamped_timeout < timeout)
+ clamped_timeout = (uint64_t) -1;
+
+ handle->timer_cb = cb;
+ handle->timeout = clamped_timeout;
+ handle->repeat = repeat;
+ /* start_id is the second index to be compared in uv__timer_cmp() */
+ handle->start_id = handle->loop->timer_counter++;
+
+ heap_insert(timer_heap(handle->loop),
+ (struct heap_node*) &handle->heap_node,
+ timer_less_than);
+ uv__handle_start(handle);
+
+ return 0;
+}
+
+
+int uv_timer_stop(uv_timer_t* handle) {
+ if (!uv__is_active(handle))
+ return 0;
+
+ heap_remove(timer_heap(handle->loop),
+ (struct heap_node*) &handle->heap_node,
+ timer_less_than);
+ uv__handle_stop(handle);
+
+ return 0;
+}
+
+
+int uv_timer_again(uv_timer_t* handle) {
+ if (handle->timer_cb == NULL)
+ return UV_EINVAL;
+
+ if (handle->repeat) {
+ uv_timer_stop(handle);
+ uv_timer_start(handle, handle->timer_cb, handle->repeat, handle->repeat);
+ }
+
+ return 0;
+}
+
+
+void uv_timer_set_repeat(uv_timer_t* handle, uint64_t repeat) {
+ handle->repeat = repeat;
+}
+
+
+uint64_t uv_timer_get_repeat(const uv_timer_t* handle) {
+ return handle->repeat;
+}
+
+
+int uv__next_timeout(const uv_loop_t* loop) {
+ const struct heap_node* heap_node;
+ const uv_timer_t* handle;
+ uint64_t diff;
+
+ heap_node = heap_min(timer_heap(loop));
+ if (heap_node == NULL)
+ return -1; /* block indefinitely */
+
+ handle = container_of(heap_node, uv_timer_t, heap_node);
+ if (handle->timeout <= loop->time)
+ return 0;
+
+ diff = handle->timeout - loop->time;
+ if (diff > INT_MAX)
+ diff = INT_MAX;
+
+ return (int) diff;
+}
+
+
+void uv__run_timers(uv_loop_t* loop) {
+ struct heap_node* heap_node;
+ uv_timer_t* handle;
+
+ for (;;) {
+ heap_node = heap_min(timer_heap(loop));
+ if (heap_node == NULL)
+ break;
+
+ handle = container_of(heap_node, uv_timer_t, heap_node);
+ if (handle->timeout > loop->time)
+ break;
+
+ uv_timer_stop(handle);
+ uv_timer_again(handle);
+ handle->timer_cb(handle);
+ }
+}
+
+
+void uv__timer_close(uv_timer_t* handle) {
+ uv_timer_stop(handle);
+}
diff --git a/Utilities/cmlibuv/src/unix/aix-common.c b/Utilities/cmlibuv/src/unix/aix-common.c
new file mode 100644
index 000000000..e9697e9c2
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/aix-common.c
@@ -0,0 +1,298 @@
+/* Copyright libuv project contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#include "uv.h"
+#include "internal.h"
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <sys/time.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <utmp.h>
+#include <libgen.h>
+
+#include <sys/protosw.h>
+#include <procinfo.h>
+#include <sys/proc.h>
+#include <sys/procfs.h>
+
+#include <sys/poll.h>
+
+#include <sys/pollset.h>
+#include <ctype.h>
+
+#include <sys/mntctl.h>
+#include <sys/vmount.h>
+#include <limits.h>
+#include <strings.h>
+#include <sys/vnode.h>
+
+uint64_t uv__hrtime(uv_clocktype_t type) {
+ uint64_t G = 1000000000;
+ timebasestruct_t t;
+ read_wall_time(&t, TIMEBASE_SZ);
+ time_base_to_time(&t, TIMEBASE_SZ);
+ return (uint64_t) t.tb_high * G + t.tb_low;
+}
+
+
+/*
+ * We could use a static buffer for the path manipulations that we need outside
+ * of the function, but this function could be called by multiple consumers and
+ * we don't want to potentially create a race condition in the use of snprintf.
+ * There is no direct way of getting the exe path in AIX - either through /procfs
+ * or through some libc APIs. The below approach is to parse the argv[0]'s pattern
+ * and use it in conjunction with PATH environment variable to craft one.
+ */
+int uv_exepath(char* buffer, size_t* size) {
+ int res;
+ char args[PATH_MAX];
+ char abspath[PATH_MAX];
+ size_t abspath_size;
+ struct procsinfo pi;
+
+ if (buffer == NULL || size == NULL || *size == 0)
+ return UV_EINVAL;
+
+ pi.pi_pid = getpid();
+ res = getargs(&pi, sizeof(pi), args, sizeof(args));
+ if (res < 0)
+ return UV_EINVAL;
+
+ /*
+ * Possibilities for args:
+ * i) an absolute path such as: /home/user/myprojects/nodejs/node
+ * ii) a relative path such as: ./node or ../myprojects/nodejs/node
+ * iii) a bare filename such as "node", after exporting PATH variable
+ * to its location.
+ */
+
+ /* Case i) and ii) absolute or relative paths */
+ if (strchr(args, '/') != NULL) {
+ if (realpath(args, abspath) != abspath)
+ return UV__ERR(errno);
+
+ abspath_size = strlen(abspath);
+
+ *size -= 1;
+ if (*size > abspath_size)
+ *size = abspath_size;
+
+ memcpy(buffer, abspath, *size);
+ buffer[*size] = '\0';
+
+ return 0;
+ } else {
+ /* Case iii). Search PATH environment variable */
+ char trypath[PATH_MAX];
+ char *clonedpath = NULL;
+ char *token = NULL;
+ char *path = getenv("PATH");
+
+ if (path == NULL)
+ return UV_EINVAL;
+
+ clonedpath = uv__strdup(path);
+ if (clonedpath == NULL)
+ return UV_ENOMEM;
+
+ token = strtok(clonedpath, ":");
+ while (token != NULL) {
+ snprintf(trypath, sizeof(trypath) - 1, "%s/%s", token, args);
+ if (realpath(trypath, abspath) == abspath) {
+ /* Check the match is executable */
+ if (access(abspath, X_OK) == 0) {
+ abspath_size = strlen(abspath);
+
+ *size -= 1;
+ if (*size > abspath_size)
+ *size = abspath_size;
+
+ memcpy(buffer, abspath, *size);
+ buffer[*size] = '\0';
+
+ uv__free(clonedpath);
+ return 0;
+ }
+ }
+ token = strtok(NULL, ":");
+ }
+ uv__free(clonedpath);
+
+ /* Out of tokens (path entries), and no match found */
+ return UV_EINVAL;
+ }
+}
+
+void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) {
+ int i;
+
+ for (i = 0; i < count; ++i) {
+ uv__free(cpu_infos[i].model);
+ }
+
+ uv__free(cpu_infos);
+}
+
+
+int uv_interface_addresses(uv_interface_address_t** addresses, int* count) {
+ uv_interface_address_t* address;
+ int sockfd, inet6, size = 1;
+ struct ifconf ifc;
+ struct ifreq *ifr, *p, flg;
+ struct sockaddr_dl* sa_addr;
+
+ *count = 0;
+ *addresses = NULL;
+
+ if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP))) {
+ return UV__ERR(errno);
+ }
+
+ if (ioctl(sockfd, SIOCGSIZIFCONF, &size) == -1) {
+ uv__close(sockfd);
+ return UV__ERR(errno);
+ }
+
+ ifc.ifc_req = (struct ifreq*)uv__malloc(size);
+ ifc.ifc_len = size;
+ if (ioctl(sockfd, SIOCGIFCONF, &ifc) == -1) {
+ uv__close(sockfd);
+ return UV__ERR(errno);
+ }
+
+#define ADDR_SIZE(p) MAX((p).sa_len, sizeof(p))
+
+ /* Count all up and running ipv4/ipv6 addresses */
+ ifr = ifc.ifc_req;
+ while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) {
+ p = ifr;
+ ifr = (struct ifreq*)
+ ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr));
+
+ if (!(p->ifr_addr.sa_family == AF_INET6 ||
+ p->ifr_addr.sa_family == AF_INET))
+ continue;
+
+ memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name));
+ if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) {
+ uv__close(sockfd);
+ return UV__ERR(errno);
+ }
+
+ if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING))
+ continue;
+
+ (*count)++;
+ }
+
+ if (*count == 0) {
+ uv__close(sockfd);
+ return 0;
+ }
+
+ /* Alloc the return interface structs */
+ *addresses = uv__malloc(*count * sizeof(uv_interface_address_t));
+ if (!(*addresses)) {
+ uv__close(sockfd);
+ return UV_ENOMEM;
+ }
+ address = *addresses;
+
+ ifr = ifc.ifc_req;
+ while ((char*)ifr < (char*)ifc.ifc_req + ifc.ifc_len) {
+ p = ifr;
+ ifr = (struct ifreq*)
+ ((char*)ifr + sizeof(ifr->ifr_name) + ADDR_SIZE(ifr->ifr_addr));
+
+ if (!(p->ifr_addr.sa_family == AF_INET6 ||
+ p->ifr_addr.sa_family == AF_INET))
+ continue;
+
+ inet6 = (p->ifr_addr.sa_family == AF_INET6);
+
+ memcpy(flg.ifr_name, p->ifr_name, sizeof(flg.ifr_name));
+ if (ioctl(sockfd, SIOCGIFFLAGS, &flg) == -1) {
+ uv__close(sockfd);
+ return UV_ENOSYS;
+ }
+
+ if (!(flg.ifr_flags & IFF_UP && flg.ifr_flags & IFF_RUNNING))
+ continue;
+
+ /* All conditions above must match count loop */
+
+ address->name = uv__strdup(p->ifr_name);
+
+ if (inet6)
+ address->address.address6 = *((struct sockaddr_in6*) &p->ifr_addr);
+ else
+ address->address.address4 = *((struct sockaddr_in*) &p->ifr_addr);
+
+ sa_addr = (struct sockaddr_dl*) &p->ifr_addr;
+ memcpy(address->phys_addr, LLADDR(sa_addr), sizeof(address->phys_addr));
+
+ if (ioctl(sockfd, SIOCGIFNETMASK, p) == -1) {
+ uv__close(sockfd);
+ return UV_ENOSYS;
+ }
+
+ if (inet6)
+ address->netmask.netmask6 = *((struct sockaddr_in6*) &p->ifr_addr);
+ else
+ address->netmask.netmask4 = *((struct sockaddr_in*) &p->ifr_addr);
+
+ address->is_internal = flg.ifr_flags & IFF_LOOPBACK ? 1 : 0;
+
+ address++;
+ }
+
+#undef ADDR_SIZE
+
+ uv__close(sockfd);
+ return 0;
+}
+
+
+void uv_free_interface_addresses(uv_interface_address_t* addresses,
+ int count) {
+ int i;
+
+ for (i = 0; i < count; ++i) {
+ uv__free(addresses[i].name);
+ }
+
+ uv__free(addresses);
+}
+
diff --git a/Utilities/cmlibuv/src/unix/bsd-proctitle.c b/Utilities/cmlibuv/src/unix/bsd-proctitle.c
new file mode 100644
index 000000000..0ce47c8f6
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/bsd-proctitle.c
@@ -0,0 +1,93 @@
+/* Copyright libuv project contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#include "uv.h"
+#include "internal.h"
+
+#include <sys/types.h>
+#include <unistd.h>
+
+
+static uv_mutex_t process_title_mutex;
+static uv_once_t process_title_mutex_once = UV_ONCE_INIT;
+static char* process_title;
+
+
+static void init_process_title_mutex_once(void) {
+ if (uv_mutex_init(&process_title_mutex))
+ abort();
+}
+
+
+char** uv_setup_args(int argc, char** argv) {
+ process_title = argc > 0 ? uv__strdup(argv[0]) : NULL;
+ return argv;
+}
+
+
+int uv_set_process_title(const char* title) {
+ char* new_title;
+
+ new_title = uv__strdup(title);
+ if (new_title == NULL)
+ return UV_ENOMEM;
+
+ uv_once(&process_title_mutex_once, init_process_title_mutex_once);
+ uv_mutex_lock(&process_title_mutex);
+
+ uv__free(process_title);
+ process_title = new_title;
+ setproctitle("%s", title);
+
+ uv_mutex_unlock(&process_title_mutex);
+
+ return 0;
+}
+
+
+int uv_get_process_title(char* buffer, size_t size) {
+ size_t len;
+
+ if (buffer == NULL || size == 0)
+ return UV_EINVAL;
+
+ uv_once(&process_title_mutex_once, init_process_title_mutex_once);
+ uv_mutex_lock(&process_title_mutex);
+
+ if (process_title != NULL) {
+ len = strlen(process_title) + 1;
+
+ if (size < len) {
+ uv_mutex_unlock(&process_title_mutex);
+ return UV_ENOBUFS;
+ }
+
+ memcpy(buffer, process_title, len);
+ } else {
+ len = 0;
+ }
+
+ uv_mutex_unlock(&process_title_mutex);
+
+ buffer[len] = '\0';
+
+ return 0;
+}
diff --git a/Utilities/cmlibuv/src/unix/cmake-bootstrap.c b/Utilities/cmlibuv/src/unix/cmake-bootstrap.c
new file mode 100644
index 000000000..309ec79ce
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/cmake-bootstrap.c
@@ -0,0 +1,140 @@
+#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,
+ enum uv__work_kind kind,
+ 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/ibmi.c b/Utilities/cmlibuv/src/unix/ibmi.c
new file mode 100644
index 000000000..13fed6cc0
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/ibmi.c
@@ -0,0 +1,113 @@
+/* Copyright libuv project contributors. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#include "uv.h"
+#include "internal.h"
+
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <errno.h>
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <net/if.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+
+#include <sys/time.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <utmp.h>
+#include <libgen.h>
+
+#include <sys/protosw.h>
+#include <procinfo.h>
+#include <sys/proc.h>
+#include <sys/procfs.h>
+
+#include <ctype.h>
+
+#include <sys/mntctl.h>
+#include <sys/vmount.h>
+#include <limits.h>
+#include <strings.h>
+#include <sys/vnode.h>
+
+uint64_t uv_get_free_memory(void) {
+ return (uint64_t) sysconf(_SC_PAGESIZE) * sysconf(_SC_AVPHYS_PAGES);
+}
+
+
+uint64_t uv_get_total_memory(void) {
+ return (uint64_t) sysconf(_SC_PAGESIZE) * sysconf(_SC_PHYS_PAGES);
+}
+
+
+void uv_loadavg(double avg[3]) {
+ avg[0] = avg[1] = avg[2] = 0;
+ return;
+}
+
+
+int uv_resident_set_memory(size_t* rss) {
+ *rss = 0;
+ return 0;
+}
+
+
+int uv_uptime(double* uptime) {
+ return UV_ENOSYS;
+}
+
+
+int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
+ unsigned int numcpus, idx = 0;
+ uv_cpu_info_t* cpu_info;
+
+ *cpu_infos = NULL;
+ *count = 0;
+
+ numcpus = sysconf(_SC_NPROCESSORS_ONLN);
+
+ *cpu_infos = uv__malloc(numcpus * sizeof(uv_cpu_info_t));
+ if (!*cpu_infos) {
+ return UV_ENOMEM;
+ }
+
+ cpu_info = *cpu_infos;
+ for (idx = 0; idx < numcpus; idx++) {
+ cpu_info->speed = 0;
+ cpu_info->model = uv__strdup("unknown");
+ cpu_info->cpu_times.user = 0;
+ cpu_info->cpu_times.sys = 0;
+ cpu_info->cpu_times.idle = 0;
+ cpu_info->cpu_times.irq = 0;
+ cpu_info->cpu_times.nice = 0;
+ cpu_info++;
+ }
+ *count = numcpus;
+
+ return 0;
+}
diff --git a/Utilities/cmlibuv/src/uv-data-getter-setters.c b/Utilities/cmlibuv/src/uv-data-getter-setters.c
new file mode 100644
index 000000000..b7fcd4a7f
--- /dev/null
+++ b/Utilities/cmlibuv/src/uv-data-getter-setters.c
@@ -0,0 +1,98 @@
+#include "uv.h"
+
+const char* uv_handle_type_name(uv_handle_type type) {
+ switch (type) {
+#define XX(uc,lc) case UV_##uc: return #lc;
+ UV_HANDLE_TYPE_MAP(XX)
+#undef XX
+ case UV_FILE: return "file";
+ case UV_HANDLE_TYPE_MAX:
+ case UV_UNKNOWN_HANDLE: return NULL;
+ }
+ return NULL;
+}
+
+uv_handle_type uv_handle_get_type(const uv_handle_t* handle) {
+ return handle->type;
+}
+
+void* uv_handle_get_data(const uv_handle_t* handle) {
+ return handle->data;
+}
+
+uv_loop_t* uv_handle_get_loop(const uv_handle_t* handle) {
+ return handle->loop;
+}
+
+void uv_handle_set_data(uv_handle_t* handle, void* data) {
+ handle->data = data;
+}
+
+const char* uv_req_type_name(uv_req_type type) {
+ switch (type) {
+#define XX(uc,lc) case UV_##uc: return #lc;
+ UV_REQ_TYPE_MAP(XX)
+#undef XX
+ case UV_REQ_TYPE_MAX:
+ case UV_UNKNOWN_REQ:
+ default: /* UV_REQ_TYPE_PRIVATE */
+ return NULL;
+ }
+ return NULL;
+}
+
+uv_req_type uv_req_get_type(const uv_req_t* req) {
+ return req->type;
+}
+
+void* uv_req_get_data(const uv_req_t* req) {
+ return req->data;
+}
+
+void uv_req_set_data(uv_req_t* req, void* data) {
+ req->data = data;
+}
+
+size_t uv_stream_get_write_queue_size(const uv_stream_t* stream) {
+ return stream->write_queue_size;
+}
+
+size_t uv_udp_get_send_queue_size(const uv_udp_t* handle) {
+ return handle->send_queue_size;
+}
+
+size_t uv_udp_get_send_queue_count(const uv_udp_t* handle) {
+ return handle->send_queue_count;
+}
+
+uv_pid_t uv_process_get_pid(const uv_process_t* proc) {
+ return proc->pid;
+}
+
+uv_fs_type uv_fs_get_type(const uv_fs_t* req) {
+ return req->fs_type;
+}
+
+ssize_t uv_fs_get_result(const uv_fs_t* req) {
+ return req->result;
+}
+
+void* uv_fs_get_ptr(const uv_fs_t* req) {
+ return req->ptr;
+}
+
+const char* uv_fs_get_path(const uv_fs_t* req) {
+ return req->path;
+}
+
+uv_stat_t* uv_fs_get_statbuf(uv_fs_t* req) {
+ return &req->statbuf;
+}
+
+void* uv_loop_get_data(const uv_loop_t* loop) {
+ return loop->data;
+}
+
+void uv_loop_set_data(uv_loop_t* loop, void* data) {
+ loop->data = data;
+}
diff --git a/Utilities/cmzstd/CMakeLists.txt b/Utilities/cmzstd/CMakeLists.txt
new file mode 100644
index 000000000..8ed04d8d1
--- /dev/null
+++ b/Utilities/cmzstd/CMakeLists.txt
@@ -0,0 +1,47 @@
+project(zstd C)
+
+# Disable warnings to avoid changing 3rd party code.
+if(CMAKE_C_COMPILER_ID MATCHES
+ "^(GNU|Clang|AppleClang|XLClang|XL|VisualAge|SunPro|HP|Intel)$")
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w")
+elseif(CMAKE_C_COMPILER_ID STREQUAL "PathScale")
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -woffall")
+endif()
+
+include_directories(lib lib/common)
+
+add_library(cmzstd STATIC
+ lib/common/entropy_common.c
+ lib/common/error_private.c
+ lib/common/fse_decompress.c
+ lib/common/pool.c
+ lib/common/threading.c
+ lib/common/xxhash.c
+ lib/common/zstd_common.c
+ lib/compress/fse_compress.c
+ lib/compress/hist.c
+ lib/compress/huf_compress.c
+ lib/compress/zstd_compress.c
+ lib/compress/zstd_double_fast.c
+ lib/compress/zstd_fast.c
+ lib/compress/zstd_lazy.c
+ lib/compress/zstd_ldm.c
+ lib/compress/zstdmt_compress.c
+ lib/compress/zstd_opt.c
+ lib/decompress/huf_decompress.c
+ lib/decompress/zstd_ddict.c
+ lib/decompress/zstd_decompress_block.c
+ lib/decompress/zstd_decompress.c
+ lib/deprecated/zbuff_common.c
+ lib/deprecated/zbuff_compress.c
+ lib/deprecated/zbuff_decompress.c
+ lib/dictBuilder/cover.c
+ lib/dictBuilder/divsufsort.c
+ lib/dictBuilder/fastcover.c
+ lib/dictBuilder/zdict.c
+ )
+
+# BMI2 instructions are not supported in older environments.
+set_property(TARGET cmzstd PROPERTY COMPILE_DEFINITIONS DYNAMIC_BMI2=0)
+
+install(FILES LICENSE DESTINATION ${CMAKE_DOC_DIR}/cmzstd)
diff --git a/Utilities/cmzstd/LICENSE b/Utilities/cmzstd/LICENSE
new file mode 100644
index 000000000..a793a8028
--- /dev/null
+++ b/Utilities/cmzstd/LICENSE
@@ -0,0 +1,30 @@
+BSD License
+
+For Zstandard software
+
+Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * 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.
+
+ * Neither the name Facebook 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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.
diff --git a/Utilities/cmzstd/README.md b/Utilities/cmzstd/README.md
new file mode 100644
index 000000000..4b6d19e7e
--- /dev/null
+++ b/Utilities/cmzstd/README.md
@@ -0,0 +1,167 @@
+<p align="center"><img src="https://raw.githubusercontent.com/facebook/zstd/dev/doc/images/zstd_logo86.png" alt="Zstandard"></p>
+
+__Zstandard__, or `zstd` as short version, is a fast lossless compression algorithm,
+targeting real-time compression scenarios at zlib-level and better compression ratios.
+It's backed by a very fast entropy stage, provided by [Huff0 and FSE library](https://github.com/Cyan4973/FiniteStateEntropy).
+
+The project is provided as an open-source dual [BSD](LICENSE) and [GPLv2](COPYING) licensed **C** library,
+and a command line utility producing and decoding `.zst`, `.gz`, `.xz` and `.lz4` files.
+Should your project require another programming language,
+a list of known ports and bindings is provided on [Zstandard homepage](http://www.zstd.net/#other-languages).
+
+**Development branch status:**
+
+[![Build Status][travisDevBadge]][travisLink]
+[![Build status][AppveyorDevBadge]][AppveyorLink]
+[![Build status][CircleDevBadge]][CircleLink]
+
+[travisDevBadge]: https://travis-ci.org/facebook/zstd.svg?branch=dev "Continuous Integration test suite"
+[travisLink]: https://travis-ci.org/facebook/zstd
+[AppveyorDevBadge]: https://ci.appveyor.com/api/projects/status/xt38wbdxjk5mrbem/branch/dev?svg=true "Windows test suite"
+[AppveyorLink]: https://ci.appveyor.com/project/YannCollet/zstd-p0yf0
+[CircleDevBadge]: https://circleci.com/gh/facebook/zstd/tree/dev.svg?style=shield "Short test suite"
+[CircleLink]: https://circleci.com/gh/facebook/zstd
+
+## Benchmarks
+
+For reference, several fast compression algorithms were tested and compared
+on a server running Linux Debian (`Linux version 4.14.0-3-amd64`),
+with a Core i7-6700K CPU @ 4.0GHz,
+using [lzbench], an open-source in-memory benchmark by @inikep
+compiled with [gcc] 7.3.0,
+on the [Silesia compression corpus].
+
+[lzbench]: https://github.com/inikep/lzbench
+[Silesia compression corpus]: http://sun.aei.polsl.pl/~sdeor/index.php?page=silesia
+[gcc]: https://gcc.gnu.org/
+
+| Compressor name | Ratio | Compression| Decompress.|
+| --------------- | ------| -----------| ---------- |
+| **zstd 1.3.4 -1** | 2.877 | 470 MB/s | 1380 MB/s |
+| zlib 1.2.11 -1 | 2.743 | 110 MB/s | 400 MB/s |
+| brotli 1.0.2 -0 | 2.701 | 410 MB/s | 430 MB/s |
+| quicklz 1.5.0 -1 | 2.238 | 550 MB/s | 710 MB/s |
+| lzo1x 2.09 -1 | 2.108 | 650 MB/s | 830 MB/s |
+| lz4 1.8.1 | 2.101 | 750 MB/s | 3700 MB/s |
+| snappy 1.1.4 | 2.091 | 530 MB/s | 1800 MB/s |
+| lzf 3.6 -1 | 2.077 | 400 MB/s | 860 MB/s |
+
+[zlib]: http://www.zlib.net/
+[LZ4]: http://www.lz4.org/
+
+Zstd can also offer stronger compression ratios at the cost of compression speed.
+Speed vs Compression trade-off is configurable by small increments.
+Decompression speed is preserved and remains roughly the same at all settings,
+a property shared by most LZ compression algorithms, such as [zlib] or lzma.
+
+The following tests were run
+on a server running Linux Debian (`Linux version 4.14.0-3-amd64`)
+with a Core i7-6700K CPU @ 4.0GHz,
+using [lzbench], an open-source in-memory benchmark by @inikep
+compiled with [gcc] 7.3.0,
+on the [Silesia compression corpus].
+
+Compression Speed vs Ratio | Decompression Speed
+---------------------------|--------------------
+![Compression Speed vs Ratio](doc/images/CSpeed2.png "Compression Speed vs Ratio") | ![Decompression Speed](doc/images/DSpeed3.png "Decompression Speed")
+
+A few other algorithms can produce higher compression ratios at slower speeds, falling outside of the graph.
+For a larger picture including slow modes, [click on this link](doc/images/DCspeed5.png).
+
+
+## The case for Small Data compression
+
+Previous charts provide results applicable to typical file and stream scenarios (several MB). Small data comes with different perspectives.
+
+The smaller the amount of data to compress, the more difficult it is to compress. This problem is common to all compression algorithms, and reason is, compression algorithms learn from past data how to compress future data. But at the beginning of a new data set, there is no "past" to build upon.
+
+To solve this situation, Zstd offers a __training mode__, which can be used to tune the algorithm for a selected type of data.
+Training Zstandard is achieved by providing it with a few samples (one file per sample). The result of this training is stored in a file called "dictionary", which must be loaded before compression and decompression.
+Using this dictionary, the compression ratio achievable on small data improves dramatically.
+
+The following example uses the `github-users` [sample set](https://github.com/facebook/zstd/releases/tag/v1.1.3), created from [github public API](https://developer.github.com/v3/users/#get-all-users).
+It consists of roughly 10K records weighing about 1KB each.
+
+Compression Ratio | Compression Speed | Decompression Speed
+------------------|-------------------|--------------------
+![Compression Ratio](doc/images/dict-cr.png "Compression Ratio") | ![Compression Speed](doc/images/dict-cs.png "Compression Speed") | ![Decompression Speed](doc/images/dict-ds.png "Decompression Speed")
+
+
+These compression gains are achieved while simultaneously providing _faster_ compression and decompression speeds.
+
+Training works if there is some correlation in a family of small data samples. The more data-specific a dictionary is, the more efficient it is (there is no _universal dictionary_).
+Hence, deploying one dictionary per type of data will provide the greatest benefits.
+Dictionary gains are mostly effective in the first few KB. Then, the compression algorithm will gradually use previously decoded content to better compress the rest of the file.
+
+### Dictionary compression How To:
+
+1. Create the dictionary
+
+ `zstd --train FullPathToTrainingSet/* -o dictionaryName`
+
+2. Compress with dictionary
+
+ `zstd -D dictionaryName FILE`
+
+3. Decompress with dictionary
+
+ `zstd -D dictionaryName --decompress FILE.zst`
+
+
+## Build instructions
+
+### Makefile
+
+If your system is compatible with standard `make` (or `gmake`),
+invoking `make` in root directory will generate `zstd` cli in root directory.
+
+Other available options include:
+- `make install` : create and install zstd cli, library and man pages
+- `make check` : create and run `zstd`, tests its behavior on local platform
+
+### cmake
+
+A `cmake` project generator is provided within `build/cmake`.
+It can generate Makefiles or other build scripts
+to create `zstd` binary, and `libzstd` dynamic and static libraries.
+
+By default, `CMAKE_BUILD_TYPE` is set to `Release`.
+
+### Meson
+
+A Meson project is provided within [`build/meson`](build/meson). Follow
+build instructions in that directory.
+
+You can also take a look at [`.travis.yml`](.travis.yml) file for an
+example about how Meson is used to build this project.
+
+Note that default build type is **release**.
+
+### Visual Studio (Windows)
+
+Going into `build` directory, you will find additional possibilities:
+- Projects for Visual Studio 2005, 2008 and 2010.
+ + VS2010 project is compatible with VS2012, VS2013, VS2015 and VS2017.
+- Automated build scripts for Visual compiler by [@KrzysFR](https://github.com/KrzysFR), in `build/VS_scripts`,
+ which will build `zstd` cli and `libzstd` library without any need to open Visual Studio solution.
+
+### Buck
+
+You can build the zstd binary via buck by executing: `buck build programs:zstd` from the root of the repo.
+The output binary will be in `buck-out/gen/programs/`.
+
+## Status
+
+Zstandard is currently deployed within Facebook. It is used continuously to compress large amounts of data in multiple formats and use cases.
+Zstandard is considered safe for production environments.
+
+## License
+
+Zstandard is dual-licensed under [BSD](LICENSE) and [GPLv2](COPYING).
+
+## Contributing
+
+The "dev" branch is the one where all contributions are merged before reaching "master".
+If you plan to propose a patch, please commit into the "dev" branch, or its own feature branch.
+Direct commit to "master" are not permitted.
+For more information, please read [CONTRIBUTING](CONTRIBUTING.md).
diff --git a/Utilities/cmzstd/lib/common/bitstream.h b/Utilities/cmzstd/lib/common/bitstream.h
new file mode 100644
index 000000000..d955bd677
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/bitstream.h
@@ -0,0 +1,455 @@
+/* ******************************************************************
+ bitstream
+ Part of FSE library
+ Copyright (C) 2013-present, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
+****************************************************************** */
+#ifndef BITSTREAM_H_MODULE
+#define BITSTREAM_H_MODULE
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+/*
+* This API consists of small unitary functions, which must be inlined for best performance.
+* Since link-time-optimization is not available for all compilers,
+* these functions are defined into a .h to be included.
+*/
+
+/*-****************************************
+* Dependencies
+******************************************/
+#include "mem.h" /* unaligned access routines */
+#include "debug.h" /* assert(), DEBUGLOG(), RAWLOG() */
+#include "error_private.h" /* error codes and messages */
+
+
+/*=========================================
+* Target specific
+=========================================*/
+#if defined(__BMI__) && defined(__GNUC__)
+# include <immintrin.h> /* support for bextr (experimental) */
+#endif
+
+#define STREAM_ACCUMULATOR_MIN_32 25
+#define STREAM_ACCUMULATOR_MIN_64 57
+#define STREAM_ACCUMULATOR_MIN ((U32)(MEM_32bits() ? STREAM_ACCUMULATOR_MIN_32 : STREAM_ACCUMULATOR_MIN_64))
+
+
+/*-******************************************
+* bitStream encoding API (write forward)
+********************************************/
+/* bitStream can mix input from multiple sources.
+ * A critical property of these streams is that they encode and decode in **reverse** direction.
+ * So the first bit sequence you add will be the last to be read, like a LIFO stack.
+ */
+typedef struct {
+ size_t bitContainer;
+ unsigned bitPos;
+ char* startPtr;
+ char* ptr;
+ char* endPtr;
+} BIT_CStream_t;
+
+MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, void* dstBuffer, size_t dstCapacity);
+MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC, size_t value, unsigned nbBits);
+MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC);
+MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC);
+
+/* Start with initCStream, providing the size of buffer to write into.
+* bitStream will never write outside of this buffer.
+* `dstCapacity` must be >= sizeof(bitD->bitContainer), otherwise @return will be an error code.
+*
+* bits are first added to a local register.
+* Local register is size_t, hence 64-bits on 64-bits systems, or 32-bits on 32-bits systems.
+* Writing data into memory is an explicit operation, performed by the flushBits function.
+* Hence keep track how many bits are potentially stored into local register to avoid register overflow.
+* After a flushBits, a maximum of 7 bits might still be stored into local register.
+*
+* Avoid storing elements of more than 24 bits if you want compatibility with 32-bits bitstream readers.
+*
+* Last operation is to close the bitStream.
+* The function returns the final size of CStream in bytes.
+* If data couldn't fit into `dstBuffer`, it will return a 0 ( == not storable)
+*/
+
+
+/*-********************************************
+* bitStream decoding API (read backward)
+**********************************************/
+typedef struct {
+ size_t bitContainer;
+ unsigned bitsConsumed;
+ const char* ptr;
+ const char* start;
+ const char* limitPtr;
+} BIT_DStream_t;
+
+typedef enum { BIT_DStream_unfinished = 0,
+ BIT_DStream_endOfBuffer = 1,
+ BIT_DStream_completed = 2,
+ BIT_DStream_overflow = 3 } BIT_DStream_status; /* result of BIT_reloadDStream() */
+ /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */
+
+MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
+MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits);
+MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD);
+MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD);
+
+
+/* Start by invoking BIT_initDStream().
+* A chunk of the bitStream is then stored into a local register.
+* Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
+* You can then retrieve bitFields stored into the local register, **in reverse order**.
+* Local register is explicitly reloaded from memory by the BIT_reloadDStream() method.
+* A reload guarantee a minimum of ((8*sizeof(bitD->bitContainer))-7) bits when its result is BIT_DStream_unfinished.
+* Otherwise, it can be less than that, so proceed accordingly.
+* Checking if DStream has reached its end can be performed with BIT_endOfDStream().
+*/
+
+
+/*-****************************************
+* unsafe API
+******************************************/
+MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, size_t value, unsigned nbBits);
+/* faster, but works only if value is "clean", meaning all high bits above nbBits are 0 */
+
+MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC);
+/* unsafe version; does not check buffer overflow */
+
+MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits);
+/* faster, but works only if nbBits >= 1 */
+
+
+
+/*-**************************************************************
+* Internal functions
+****************************************************************/
+MEM_STATIC unsigned BIT_highbit32 (U32 val)
+{
+ assert(val != 0);
+ {
+# if defined(_MSC_VER) /* Visual */
+ unsigned long r=0;
+ _BitScanReverse ( &r, val );
+ return (unsigned) r;
+# elif defined(__GNUC__) && (__GNUC__ >= 3) /* Use GCC Intrinsic */
+ return 31 - __builtin_clz (val);
+# else /* Software version */
+ static const unsigned DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29,
+ 11, 14, 16, 18, 22, 25, 3, 30,
+ 8, 12, 20, 28, 15, 17, 24, 7,
+ 19, 27, 23, 6, 26, 5, 4, 31 };
+ U32 v = val;
+ v |= v >> 1;
+ v |= v >> 2;
+ v |= v >> 4;
+ v |= v >> 8;
+ v |= v >> 16;
+ return DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
+# endif
+ }
+}
+
+/*===== Local Constants =====*/
+static const unsigned BIT_mask[] = {
+ 0, 1, 3, 7, 0xF, 0x1F,
+ 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF,
+ 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF, 0x1FFFF,
+ 0x3FFFF, 0x7FFFF, 0xFFFFF, 0x1FFFFF, 0x3FFFFF, 0x7FFFFF,
+ 0xFFFFFF, 0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF, 0x1FFFFFFF,
+ 0x3FFFFFFF, 0x7FFFFFFF}; /* up to 31 bits */
+#define BIT_MASK_SIZE (sizeof(BIT_mask) / sizeof(BIT_mask[0]))
+
+/*-**************************************************************
+* bitStream encoding
+****************************************************************/
+/*! BIT_initCStream() :
+ * `dstCapacity` must be > sizeof(size_t)
+ * @return : 0 if success,
+ * otherwise an error code (can be tested using ERR_isError()) */
+MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC,
+ void* startPtr, size_t dstCapacity)
+{
+ bitC->bitContainer = 0;
+ bitC->bitPos = 0;
+ bitC->startPtr = (char*)startPtr;
+ bitC->ptr = bitC->startPtr;
+ bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer);
+ if (dstCapacity <= sizeof(bitC->bitContainer)) return ERROR(dstSize_tooSmall);
+ return 0;
+}
+
+/*! BIT_addBits() :
+ * can add up to 31 bits into `bitC`.
+ * Note : does not check for register overflow ! */
+MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC,
+ size_t value, unsigned nbBits)
+{
+ MEM_STATIC_ASSERT(BIT_MASK_SIZE == 32);
+ assert(nbBits < BIT_MASK_SIZE);
+ assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8);
+ bitC->bitContainer |= (value & BIT_mask[nbBits]) << bitC->bitPos;
+ bitC->bitPos += nbBits;
+}
+
+/*! BIT_addBitsFast() :
+ * works only if `value` is _clean_,
+ * meaning all high bits above nbBits are 0 */
+MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC,
+ size_t value, unsigned nbBits)
+{
+ assert((value>>nbBits) == 0);
+ assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8);
+ bitC->bitContainer |= value << bitC->bitPos;
+ bitC->bitPos += nbBits;
+}
+
+/*! BIT_flushBitsFast() :
+ * assumption : bitContainer has not overflowed
+ * unsafe version; does not check buffer overflow */
+MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC)
+{
+ size_t const nbBytes = bitC->bitPos >> 3;
+ assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8);
+ MEM_writeLEST(bitC->ptr, bitC->bitContainer);
+ bitC->ptr += nbBytes;
+ assert(bitC->ptr <= bitC->endPtr);
+ bitC->bitPos &= 7;
+ bitC->bitContainer >>= nbBytes*8;
+}
+
+/*! BIT_flushBits() :
+ * assumption : bitContainer has not overflowed
+ * safe version; check for buffer overflow, and prevents it.
+ * note : does not signal buffer overflow.
+ * overflow will be revealed later on using BIT_closeCStream() */
+MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC)
+{
+ size_t const nbBytes = bitC->bitPos >> 3;
+ assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8);
+ MEM_writeLEST(bitC->ptr, bitC->bitContainer);
+ bitC->ptr += nbBytes;
+ if (bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr;
+ bitC->bitPos &= 7;
+ bitC->bitContainer >>= nbBytes*8;
+}
+
+/*! BIT_closeCStream() :
+ * @return : size of CStream, in bytes,
+ * or 0 if it could not fit into dstBuffer */
+MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC)
+{
+ BIT_addBitsFast(bitC, 1, 1); /* endMark */
+ BIT_flushBits(bitC);
+ if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */
+ return (bitC->ptr - bitC->startPtr) + (bitC->bitPos > 0);
+}
+
+
+/*-********************************************************
+* bitStream decoding
+**********************************************************/
+/*! BIT_initDStream() :
+ * Initialize a BIT_DStream_t.
+ * `bitD` : a pointer to an already allocated BIT_DStream_t structure.
+ * `srcSize` must be the *exact* size of the bitStream, in bytes.
+ * @return : size of stream (== srcSize), or an errorCode if a problem is detected
+ */
+MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
+{
+ if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }
+
+ bitD->start = (const char*)srcBuffer;
+ bitD->limitPtr = bitD->start + sizeof(bitD->bitContainer);
+
+ if (srcSize >= sizeof(bitD->bitContainer)) { /* normal case */
+ bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(bitD->bitContainer);
+ bitD->bitContainer = MEM_readLEST(bitD->ptr);
+ { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
+ bitD->bitsConsumed = lastByte ? 8 - BIT_highbit32(lastByte) : 0; /* ensures bitsConsumed is always set */
+ if (lastByte == 0) return ERROR(GENERIC); /* endMark not present */ }
+ } else {
+ bitD->ptr = bitD->start;
+ bitD->bitContainer = *(const BYTE*)(bitD->start);
+ switch(srcSize)
+ {
+ case 7: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16);
+ /* fall-through */
+
+ case 6: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24);
+ /* fall-through */
+
+ case 5: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32);
+ /* fall-through */
+
+ case 4: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[3]) << 24;
+ /* fall-through */
+
+ case 3: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[2]) << 16;
+ /* fall-through */
+
+ case 2: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[1]) << 8;
+ /* fall-through */
+
+ default: break;
+ }
+ { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
+ bitD->bitsConsumed = lastByte ? 8 - BIT_highbit32(lastByte) : 0;
+ if (lastByte == 0) return ERROR(corruption_detected); /* endMark not present */
+ }
+ bitD->bitsConsumed += (U32)(sizeof(bitD->bitContainer) - srcSize)*8;
+ }
+
+ return srcSize;
+}
+
+MEM_STATIC size_t BIT_getUpperBits(size_t bitContainer, U32 const start)
+{
+ return bitContainer >> start;
+}
+
+MEM_STATIC size_t BIT_getMiddleBits(size_t bitContainer, U32 const start, U32 const nbBits)
+{
+ U32 const regMask = sizeof(bitContainer)*8 - 1;
+ /* if start > regMask, bitstream is corrupted, and result is undefined */
+ assert(nbBits < BIT_MASK_SIZE);
+ return (bitContainer >> (start & regMask)) & BIT_mask[nbBits];
+}
+
+MEM_STATIC size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits)
+{
+ assert(nbBits < BIT_MASK_SIZE);
+ return bitContainer & BIT_mask[nbBits];
+}
+
+/*! BIT_lookBits() :
+ * Provides next n bits from local register.
+ * local register is not modified.
+ * On 32-bits, maxNbBits==24.
+ * On 64-bits, maxNbBits==56.
+ * @return : value extracted */
+MEM_STATIC size_t BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits)
+{
+ /* arbitrate between double-shift and shift+mask */
+#if 1
+ /* if bitD->bitsConsumed + nbBits > sizeof(bitD->bitContainer)*8,
+ * bitstream is likely corrupted, and result is undefined */
+ return BIT_getMiddleBits(bitD->bitContainer, (sizeof(bitD->bitContainer)*8) - bitD->bitsConsumed - nbBits, nbBits);
+#else
+ /* this code path is slower on my os-x laptop */
+ U32 const regMask = sizeof(bitD->bitContainer)*8 - 1;
+ return ((bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> 1) >> ((regMask-nbBits) & regMask);
+#endif
+}
+
+/*! BIT_lookBitsFast() :
+ * unsafe version; only works if nbBits >= 1 */
+MEM_STATIC size_t BIT_lookBitsFast(const BIT_DStream_t* bitD, U32 nbBits)
+{
+ U32 const regMask = sizeof(bitD->bitContainer)*8 - 1;
+ assert(nbBits >= 1);
+ return (bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> (((regMask+1)-nbBits) & regMask);
+}
+
+MEM_STATIC void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits)
+{
+ bitD->bitsConsumed += nbBits;
+}
+
+/*! BIT_readBits() :
+ * Read (consume) next n bits from local register and update.
+ * Pay attention to not read more than nbBits contained into local register.
+ * @return : extracted value. */
+MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits)
+{
+ size_t const value = BIT_lookBits(bitD, nbBits);
+ BIT_skipBits(bitD, nbBits);
+ return value;
+}
+
+/*! BIT_readBitsFast() :
+ * unsafe version; only works only if nbBits >= 1 */
+MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits)
+{
+ size_t const value = BIT_lookBitsFast(bitD, nbBits);
+ assert(nbBits >= 1);
+ BIT_skipBits(bitD, nbBits);
+ return value;
+}
+
+/*! BIT_reloadDStream() :
+ * Refill `bitD` from buffer previously set in BIT_initDStream() .
+ * This function is safe, it guarantees it will not read beyond src buffer.
+ * @return : status of `BIT_DStream_t` internal register.
+ * when status == BIT_DStream_unfinished, internal register is filled with at least 25 or 57 bits */
+MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD)
+{
+ if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* overflow detected, like end of stream */
+ return BIT_DStream_overflow;
+
+ if (bitD->ptr >= bitD->limitPtr) {
+ bitD->ptr -= bitD->bitsConsumed >> 3;
+ bitD->bitsConsumed &= 7;
+ bitD->bitContainer = MEM_readLEST(bitD->ptr);
+ return BIT_DStream_unfinished;
+ }
+ if (bitD->ptr == bitD->start) {
+ if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer;
+ return BIT_DStream_completed;
+ }
+ /* start < ptr < limitPtr */
+ { U32 nbBytes = bitD->bitsConsumed >> 3;
+ BIT_DStream_status result = BIT_DStream_unfinished;
+ if (bitD->ptr - nbBytes < bitD->start) {
+ nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
+ result = BIT_DStream_endOfBuffer;
+ }
+ bitD->ptr -= nbBytes;
+ bitD->bitsConsumed -= nbBytes*8;
+ bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD->bitContainer), otherwise bitD->ptr == bitD->start */
+ return result;
+ }
+}
+
+/*! BIT_endOfDStream() :
+ * @return : 1 if DStream has _exactly_ reached its end (all bits consumed).
+ */
+MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream)
+{
+ return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
+}
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* BITSTREAM_H_MODULE */
diff --git a/Utilities/cmzstd/lib/common/compiler.h b/Utilities/cmzstd/lib/common/compiler.h
new file mode 100644
index 000000000..7f561282c
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/compiler.h
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef ZSTD_COMPILER_H
+#define ZSTD_COMPILER_H
+
+/*-*******************************************************
+* Compiler specifics
+*********************************************************/
+/* force inlining */
+
+#if !defined(ZSTD_NO_INLINE)
+#if defined (__GNUC__) || defined(__cplusplus) || defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
+# define INLINE_KEYWORD inline
+#else
+# define INLINE_KEYWORD
+#endif
+
+#if defined(__GNUC__)
+# define FORCE_INLINE_ATTR __attribute__((always_inline))
+#elif defined(_MSC_VER)
+# define FORCE_INLINE_ATTR __forceinline
+#else
+# define FORCE_INLINE_ATTR
+#endif
+
+#else
+
+#define INLINE_KEYWORD
+#define FORCE_INLINE_ATTR
+
+#endif
+
+/**
+ * FORCE_INLINE_TEMPLATE is used to define C "templates", which take constant
+ * parameters. They must be inlined for the compiler to elimininate the constant
+ * branches.
+ */
+#define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR
+/**
+ * HINT_INLINE is used to help the compiler generate better code. It is *not*
+ * used for "templates", so it can be tweaked based on the compilers
+ * performance.
+ *
+ * gcc-4.8 and gcc-4.9 have been shown to benefit from leaving off the
+ * always_inline attribute.
+ *
+ * clang up to 5.0.0 (trunk) benefit tremendously from the always_inline
+ * attribute.
+ */
+#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 && __GNUC__ < 5
+# define HINT_INLINE static INLINE_KEYWORD
+#else
+# define HINT_INLINE static INLINE_KEYWORD FORCE_INLINE_ATTR
+#endif
+
+/* force no inlining */
+#ifdef _MSC_VER
+# define FORCE_NOINLINE static __declspec(noinline)
+#else
+# ifdef __GNUC__
+# define FORCE_NOINLINE static __attribute__((__noinline__))
+# else
+# define FORCE_NOINLINE static
+# endif
+#endif
+
+/* target attribute */
+#ifndef __has_attribute
+ #define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
+#endif
+#if defined(__GNUC__)
+# define TARGET_ATTRIBUTE(target) __attribute__((__target__(target)))
+#else
+# define TARGET_ATTRIBUTE(target)
+#endif
+
+/* Enable runtime BMI2 dispatch based on the CPU.
+ * Enabled for clang & gcc >=4.8 on x86 when BMI2 isn't enabled by default.
+ */
+#ifndef DYNAMIC_BMI2
+ #if ((defined(__clang__) && __has_attribute(__target__)) \
+ || (defined(__GNUC__) \
+ && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))) \
+ && (defined(__x86_64__) || defined(_M_X86)) \
+ && !defined(__BMI2__)
+ # define DYNAMIC_BMI2 1
+ #else
+ # define DYNAMIC_BMI2 0
+ #endif
+#endif
+
+/* prefetch
+ * can be disabled, by declaring NO_PREFETCH build macro */
+#if defined(NO_PREFETCH)
+# define PREFETCH_L1(ptr) (void)(ptr) /* disabled */
+# define PREFETCH_L2(ptr) (void)(ptr) /* disabled */
+#else
+# if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86)) /* _mm_prefetch() is not defined outside of x86/x64 */
+# include <mmintrin.h> /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */
+# define PREFETCH_L1(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T0)
+# define PREFETCH_L2(ptr) _mm_prefetch((const char*)(ptr), _MM_HINT_T1)
+# elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) )
+# define PREFETCH_L1(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */)
+# define PREFETCH_L2(ptr) __builtin_prefetch((ptr), 0 /* rw==read */, 2 /* locality */)
+# else
+# define PREFETCH_L1(ptr) (void)(ptr) /* disabled */
+# define PREFETCH_L2(ptr) (void)(ptr) /* disabled */
+# endif
+#endif /* NO_PREFETCH */
+
+#define CACHELINE_SIZE 64
+
+#define PREFETCH_AREA(p, s) { \
+ const char* const _ptr = (const char*)(p); \
+ size_t const _size = (size_t)(s); \
+ size_t _pos; \
+ for (_pos=0; _pos<_size; _pos+=CACHELINE_SIZE) { \
+ PREFETCH_L2(_ptr + _pos); \
+ } \
+}
+
+/* disable warnings */
+#ifdef _MSC_VER /* Visual Studio */
+# include <intrin.h> /* For Visual 2005 */
+# pragma warning(disable : 4100) /* disable: C4100: unreferenced formal parameter */
+# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
+# pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
+# pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
+# pragma warning(disable : 4324) /* disable: C4324: padded structure */
+#endif
+
+#endif /* ZSTD_COMPILER_H */
diff --git a/Utilities/cmzstd/lib/common/cpu.h b/Utilities/cmzstd/lib/common/cpu.h
new file mode 100644
index 000000000..5f0923fc9
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/cpu.h
@@ -0,0 +1,215 @@
+/*
+ * Copyright (c) 2018-present, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef ZSTD_COMMON_CPU_H
+#define ZSTD_COMMON_CPU_H
+
+/**
+ * Implementation taken from folly/CpuId.h
+ * https://github.com/facebook/folly/blob/master/folly/CpuId.h
+ */
+
+#include <string.h>
+
+#include "mem.h"
+
+#ifdef _MSC_VER
+#include <intrin.h>
+#endif
+
+typedef struct {
+ U32 f1c;
+ U32 f1d;
+ U32 f7b;
+ U32 f7c;
+} ZSTD_cpuid_t;
+
+MEM_STATIC ZSTD_cpuid_t ZSTD_cpuid(void) {
+ U32 f1c = 0;
+ U32 f1d = 0;
+ U32 f7b = 0;
+ U32 f7c = 0;
+#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))
+ int reg[4];
+ __cpuid((int*)reg, 0);
+ {
+ int const n = reg[0];
+ if (n >= 1) {
+ __cpuid((int*)reg, 1);
+ f1c = (U32)reg[2];
+ f1d = (U32)reg[3];
+ }
+ if (n >= 7) {
+ __cpuidex((int*)reg, 7, 0);
+ f7b = (U32)reg[1];
+ f7c = (U32)reg[2];
+ }
+ }
+#elif defined(__i386__) && defined(__PIC__) && !defined(__clang__) && defined(__GNUC__)
+ /* The following block like the normal cpuid branch below, but gcc
+ * reserves ebx for use of its pic register so we must specially
+ * handle the save and restore to avoid clobbering the register
+ */
+ U32 n;
+ __asm__(
+ "pushl %%ebx\n\t"
+ "cpuid\n\t"
+ "popl %%ebx\n\t"
+ : "=a"(n)
+ : "a"(0)
+ : "ecx", "edx");
+ if (n >= 1) {
+ U32 f1a;
+ __asm__(
+ "pushl %%ebx\n\t"
+ "cpuid\n\t"
+ "popl %%ebx\n\t"
+ : "=a"(f1a), "=c"(f1c), "=d"(f1d)
+ : "a"(1));
+ }
+ if (n >= 7) {
+ __asm__(
+ "pushl %%ebx\n\t"
+ "cpuid\n\t"
+ "movl %%ebx, %%eax\n\t"
+ "popl %%ebx"
+ : "=a"(f7b), "=c"(f7c)
+ : "a"(7), "c"(0)
+ : "edx");
+ }
+#elif defined(__x86_64__) || defined(_M_X64) || defined(__i386__)
+ U32 n;
+ __asm__("cpuid" : "=a"(n) : "a"(0) : "ebx", "ecx", "edx");
+ if (n >= 1) {
+ U32 f1a;
+ __asm__("cpuid" : "=a"(f1a), "=c"(f1c), "=d"(f1d) : "a"(1) : "ebx");
+ }
+ if (n >= 7) {
+ U32 f7a;
+ __asm__("cpuid"
+ : "=a"(f7a), "=b"(f7b), "=c"(f7c)
+ : "a"(7), "c"(0)
+ : "edx");
+ }
+#endif
+ {
+ ZSTD_cpuid_t cpuid;
+ cpuid.f1c = f1c;
+ cpuid.f1d = f1d;
+ cpuid.f7b = f7b;
+ cpuid.f7c = f7c;
+ return cpuid;
+ }
+}
+
+#define X(name, r, bit) \
+ MEM_STATIC int ZSTD_cpuid_##name(ZSTD_cpuid_t const cpuid) { \
+ return ((cpuid.r) & (1U << bit)) != 0; \
+ }
+
+/* cpuid(1): Processor Info and Feature Bits. */
+#define C(name, bit) X(name, f1c, bit)
+ C(sse3, 0)
+ C(pclmuldq, 1)
+ C(dtes64, 2)
+ C(monitor, 3)
+ C(dscpl, 4)
+ C(vmx, 5)
+ C(smx, 6)
+ C(eist, 7)
+ C(tm2, 8)
+ C(ssse3, 9)
+ C(cnxtid, 10)
+ C(fma, 12)
+ C(cx16, 13)
+ C(xtpr, 14)
+ C(pdcm, 15)
+ C(pcid, 17)
+ C(dca, 18)
+ C(sse41, 19)
+ C(sse42, 20)
+ C(x2apic, 21)
+ C(movbe, 22)
+ C(popcnt, 23)
+ C(tscdeadline, 24)
+ C(aes, 25)
+ C(xsave, 26)
+ C(osxsave, 27)
+ C(avx, 28)
+ C(f16c, 29)
+ C(rdrand, 30)
+#undef C
+#define D(name, bit) X(name, f1d, bit)
+ D(fpu, 0)
+ D(vme, 1)
+ D(de, 2)
+ D(pse, 3)
+ D(tsc, 4)
+ D(msr, 5)
+ D(pae, 6)
+ D(mce, 7)
+ D(cx8, 8)
+ D(apic, 9)
+ D(sep, 11)
+ D(mtrr, 12)
+ D(pge, 13)
+ D(mca, 14)
+ D(cmov, 15)
+ D(pat, 16)
+ D(pse36, 17)
+ D(psn, 18)
+ D(clfsh, 19)
+ D(ds, 21)
+ D(acpi, 22)
+ D(mmx, 23)
+ D(fxsr, 24)
+ D(sse, 25)
+ D(sse2, 26)
+ D(ss, 27)
+ D(htt, 28)
+ D(tm, 29)
+ D(pbe, 31)
+#undef D
+
+/* cpuid(7): Extended Features. */
+#define B(name, bit) X(name, f7b, bit)
+ B(bmi1, 3)
+ B(hle, 4)
+ B(avx2, 5)
+ B(smep, 7)
+ B(bmi2, 8)
+ B(erms, 9)
+ B(invpcid, 10)
+ B(rtm, 11)
+ B(mpx, 14)
+ B(avx512f, 16)
+ B(avx512dq, 17)
+ B(rdseed, 18)
+ B(adx, 19)
+ B(smap, 20)
+ B(avx512ifma, 21)
+ B(pcommit, 22)
+ B(clflushopt, 23)
+ B(clwb, 24)
+ B(avx512pf, 26)
+ B(avx512er, 27)
+ B(avx512cd, 28)
+ B(sha, 29)
+ B(avx512bw, 30)
+ B(avx512vl, 31)
+#undef B
+#define C(name, bit) X(name, f7c, bit)
+ C(prefetchwt1, 0)
+ C(avx512vbmi, 1)
+#undef C
+
+#undef X
+
+#endif /* ZSTD_COMMON_CPU_H */
diff --git a/Utilities/cmzstd/lib/common/debug.c b/Utilities/cmzstd/lib/common/debug.c
new file mode 100644
index 000000000..3ebdd1cb1
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/debug.c
@@ -0,0 +1,44 @@
+/* ******************************************************************
+ debug
+ Part of FSE library
+ Copyright (C) 2013-present, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
+****************************************************************** */
+
+
+/*
+ * This module only hosts one global variable
+ * which can be used to dynamically influence the verbosity of traces,
+ * such as DEBUGLOG and RAWLOG
+ */
+
+#include "debug.h"
+
+int g_debuglevel = DEBUGLEVEL;
diff --git a/Utilities/cmzstd/lib/common/debug.h b/Utilities/cmzstd/lib/common/debug.h
new file mode 100644
index 000000000..b4fc89d49
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/debug.h
@@ -0,0 +1,134 @@
+/* ******************************************************************
+ debug
+ Part of FSE library
+ Copyright (C) 2013-present, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
+****************************************************************** */
+
+
+/*
+ * The purpose of this header is to enable debug functions.
+ * They regroup assert(), DEBUGLOG() and RAWLOG() for run-time,
+ * and DEBUG_STATIC_ASSERT() for compile-time.
+ *
+ * By default, DEBUGLEVEL==0, which means run-time debug is disabled.
+ *
+ * Level 1 enables assert() only.
+ * Starting level 2, traces can be generated and pushed to stderr.
+ * The higher the level, the more verbose the traces.
+ *
+ * It's possible to dynamically adjust level using variable g_debug_level,
+ * which is only declared if DEBUGLEVEL>=2,
+ * and is a global variable, not multi-thread protected (use with care)
+ */
+
+#ifndef DEBUG_H_12987983217
+#define DEBUG_H_12987983217
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+
+/* static assert is triggered at compile time, leaving no runtime artefact.
+ * static assert only works with compile-time constants.
+ * Also, this variant can only be used inside a function. */
+#define DEBUG_STATIC_ASSERT(c) (void)sizeof(char[(c) ? 1 : -1])
+
+
+/* DEBUGLEVEL is expected to be defined externally,
+ * typically through compiler command line.
+ * Value must be a number. */
+#ifndef DEBUGLEVEL
+# define DEBUGLEVEL 0
+#endif
+
+
+/* DEBUGFILE can be defined externally,
+ * typically through compiler command line.
+ * note : currently useless.
+ * Value must be stderr or stdout */
+#ifndef DEBUGFILE
+# define DEBUGFILE stderr
+#endif
+
+
+/* recommended values for DEBUGLEVEL :
+ * 0 : release mode, no debug, all run-time checks disabled
+ * 1 : enables assert() only, no display
+ * 2 : reserved, for currently active debug path
+ * 3 : events once per object lifetime (CCtx, CDict, etc.)
+ * 4 : events once per frame
+ * 5 : events once per block
+ * 6 : events once per sequence (verbose)
+ * 7+: events at every position (*very* verbose)
+ *
+ * It's generally inconvenient to output traces > 5.
+ * In which case, it's possible to selectively trigger high verbosity levels
+ * by modifying g_debug_level.
+ */
+
+#if (DEBUGLEVEL>=1)
+# include <assert.h>
+#else
+# ifndef assert /* assert may be already defined, due to prior #include <assert.h> */
+# define assert(condition) ((void)0) /* disable assert (default) */
+# endif
+#endif
+
+#if (DEBUGLEVEL>=2)
+# include <stdio.h>
+extern int g_debuglevel; /* the variable is only declared,
+ it actually lives in debug.c,
+ and is shared by the whole process.
+ It's not thread-safe.
+ It's useful when enabling very verbose levels
+ on selective conditions (such as position in src) */
+
+# define RAWLOG(l, ...) { \
+ if (l<=g_debuglevel) { \
+ fprintf(stderr, __VA_ARGS__); \
+ } }
+# define DEBUGLOG(l, ...) { \
+ if (l<=g_debuglevel) { \
+ fprintf(stderr, __FILE__ ": " __VA_ARGS__); \
+ fprintf(stderr, " \n"); \
+ } }
+#else
+# define RAWLOG(l, ...) {} /* disabled */
+# define DEBUGLOG(l, ...) {} /* disabled */
+#endif
+
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* DEBUG_H_12987983217 */
diff --git a/Utilities/cmzstd/lib/common/entropy_common.c b/Utilities/cmzstd/lib/common/entropy_common.c
new file mode 100644
index 000000000..b12944e1d
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/entropy_common.c
@@ -0,0 +1,236 @@
+/*
+ Common functions of New Generation Entropy library
+ Copyright (C) 2016, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
+ - Public forum : https://groups.google.com/forum/#!forum/lz4c
+*************************************************************************** */
+
+/* *************************************
+* Dependencies
+***************************************/
+#include "mem.h"
+#include "error_private.h" /* ERR_*, ERROR */
+#define FSE_STATIC_LINKING_ONLY /* FSE_MIN_TABLELOG */
+#include "fse.h"
+#define HUF_STATIC_LINKING_ONLY /* HUF_TABLELOG_ABSOLUTEMAX */
+#include "huf.h"
+
+
+/*=== Version ===*/
+unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; }
+
+
+/*=== Error Management ===*/
+unsigned FSE_isError(size_t code) { return ERR_isError(code); }
+const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); }
+
+unsigned HUF_isError(size_t code) { return ERR_isError(code); }
+const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); }
+
+
+/*-**************************************************************
+* FSE NCount encoding-decoding
+****************************************************************/
+size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
+ const void* headerBuffer, size_t hbSize)
+{
+ const BYTE* const istart = (const BYTE*) headerBuffer;
+ const BYTE* const iend = istart + hbSize;
+ const BYTE* ip = istart;
+ int nbBits;
+ int remaining;
+ int threshold;
+ U32 bitStream;
+ int bitCount;
+ unsigned charnum = 0;
+ int previous0 = 0;
+
+ if (hbSize < 4) {
+ /* This function only works when hbSize >= 4 */
+ char buffer[4];
+ memset(buffer, 0, sizeof(buffer));
+ memcpy(buffer, headerBuffer, hbSize);
+ { size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
+ buffer, sizeof(buffer));
+ if (FSE_isError(countSize)) return countSize;
+ if (countSize > hbSize) return ERROR(corruption_detected);
+ return countSize;
+ } }
+ assert(hbSize >= 4);
+
+ /* init */
+ memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */
+ bitStream = MEM_readLE32(ip);
+ nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
+ if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
+ bitStream >>= 4;
+ bitCount = 4;
+ *tableLogPtr = nbBits;
+ remaining = (1<<nbBits)+1;
+ threshold = 1<<nbBits;
+ nbBits++;
+
+ while ((remaining>1) & (charnum<=*maxSVPtr)) {
+ if (previous0) {
+ unsigned n0 = charnum;
+ while ((bitStream & 0xFFFF) == 0xFFFF) {
+ n0 += 24;
+ if (ip < iend-5) {
+ ip += 2;
+ bitStream = MEM_readLE32(ip) >> bitCount;
+ } else {
+ bitStream >>= 16;
+ bitCount += 16;
+ } }
+ while ((bitStream & 3) == 3) {
+ n0 += 3;
+ bitStream >>= 2;
+ bitCount += 2;
+ }
+ n0 += bitStream & 3;
+ bitCount += 2;
+ if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
+ while (charnum < n0) normalizedCounter[charnum++] = 0;
+ if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
+ assert((bitCount >> 3) <= 3); /* For first condition to work */
+ ip += bitCount>>3;
+ bitCount &= 7;
+ bitStream = MEM_readLE32(ip) >> bitCount;
+ } else {
+ bitStream >>= 2;
+ } }
+ { int const max = (2*threshold-1) - remaining;
+ int count;
+
+ if ((bitStream & (threshold-1)) < (U32)max) {
+ count = bitStream & (threshold-1);
+ bitCount += nbBits-1;
+ } else {
+ count = bitStream & (2*threshold-1);
+ if (count >= threshold) count -= max;
+ bitCount += nbBits;
+ }
+
+ count--; /* extra accuracy */
+ remaining -= count < 0 ? -count : count; /* -1 means +1 */
+ normalizedCounter[charnum++] = (short)count;
+ previous0 = !count;
+ while (remaining < threshold) {
+ nbBits--;
+ threshold >>= 1;
+ }
+
+ if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
+ ip += bitCount>>3;
+ bitCount &= 7;
+ } else {
+ bitCount -= (int)(8 * (iend - 4 - ip));
+ ip = iend - 4;
+ }
+ bitStream = MEM_readLE32(ip) >> (bitCount & 31);
+ } } /* while ((remaining>1) & (charnum<=*maxSVPtr)) */
+ if (remaining != 1) return ERROR(corruption_detected);
+ if (bitCount > 32) return ERROR(corruption_detected);
+ *maxSVPtr = charnum-1;
+
+ ip += (bitCount+7)>>3;
+ return ip-istart;
+}
+
+
+/*! HUF_readStats() :
+ Read compact Huffman tree, saved by HUF_writeCTable().
+ `huffWeight` is destination buffer.
+ `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
+ @return : size read from `src` , or an error Code .
+ Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
+*/
+size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
+ U32* nbSymbolsPtr, U32* tableLogPtr,
+ const void* src, size_t srcSize)
+{
+ U32 weightTotal;
+ const BYTE* ip = (const BYTE*) src;
+ size_t iSize;
+ size_t oSize;
+
+ if (!srcSize) return ERROR(srcSize_wrong);
+ iSize = ip[0];
+ /* memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */
+
+ if (iSize >= 128) { /* special header */
+ oSize = iSize - 127;
+ iSize = ((oSize+1)/2);
+ if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
+ if (oSize >= hwSize) return ERROR(corruption_detected);
+ ip += 1;
+ { U32 n;
+ for (n=0; n<oSize; n+=2) {
+ huffWeight[n] = ip[n/2] >> 4;
+ huffWeight[n+1] = ip[n/2] & 15;
+ } } }
+ else { /* header compressed with FSE (normal case) */
+ FSE_DTable fseWorkspace[FSE_DTABLE_SIZE_U32(6)]; /* 6 is max possible tableLog for HUF header (maybe even 5, to be tested) */
+ if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
+ oSize = FSE_decompress_wksp(huffWeight, hwSize-1, ip+1, iSize, fseWorkspace, 6); /* max (hwSize-1) values decoded, as last one is implied */
+ if (FSE_isError(oSize)) return oSize;
+ }
+
+ /* collect weight stats */
+ memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
+ weightTotal = 0;
+ { U32 n; for (n=0; n<oSize; n++) {
+ if (huffWeight[n] >= HUF_TABLELOG_MAX) return ERROR(corruption_detected);
+ rankStats[huffWeight[n]]++;
+ weightTotal += (1 << huffWeight[n]) >> 1;
+ } }
+ if (weightTotal == 0) return ERROR(corruption_detected);
+
+ /* get last non-null symbol weight (implied, total must be 2^n) */
+ { U32 const tableLog = BIT_highbit32(weightTotal) + 1;
+ if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
+ *tableLogPtr = tableLog;
+ /* determine last weight */
+ { U32 const total = 1 << tableLog;
+ U32 const rest = total - weightTotal;
+ U32 const verif = 1 << BIT_highbit32(rest);
+ U32 const lastWeight = BIT_highbit32(rest) + 1;
+ if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
+ huffWeight[oSize] = (BYTE)lastWeight;
+ rankStats[lastWeight]++;
+ } }
+
+ /* check tree construction validity */
+ if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
+
+ /* results */
+ *nbSymbolsPtr = (U32)(oSize+1);
+ return iSize+1;
+}
diff --git a/Utilities/cmzstd/lib/common/error_private.c b/Utilities/cmzstd/lib/common/error_private.c
new file mode 100644
index 000000000..7c1bb67a2
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/error_private.c
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+/* The purpose of this file is to have a single list of error strings embedded in binary */
+
+#include "error_private.h"
+
+const char* ERR_getErrorString(ERR_enum code)
+{
+#ifdef ZSTD_STRIP_ERROR_STRINGS
+ (void)code;
+ return "Error strings stripped";
+#else
+ static const char* const notErrorCode = "Unspecified error code";
+ switch( code )
+ {
+ case PREFIX(no_error): return "No error detected";
+ case PREFIX(GENERIC): return "Error (generic)";
+ case PREFIX(prefix_unknown): return "Unknown frame descriptor";
+ case PREFIX(version_unsupported): return "Version not supported";
+ case PREFIX(frameParameter_unsupported): return "Unsupported frame parameter";
+ case PREFIX(frameParameter_windowTooLarge): return "Frame requires too much memory for decoding";
+ case PREFIX(corruption_detected): return "Corrupted block detected";
+ case PREFIX(checksum_wrong): return "Restored data doesn't match checksum";
+ case PREFIX(parameter_unsupported): return "Unsupported parameter";
+ case PREFIX(parameter_outOfBound): return "Parameter is out of bound";
+ case PREFIX(init_missing): return "Context should be init first";
+ case PREFIX(memory_allocation): return "Allocation error : not enough memory";
+ case PREFIX(workSpace_tooSmall): return "workSpace buffer is not large enough";
+ case PREFIX(stage_wrong): return "Operation not authorized at current processing stage";
+ case PREFIX(tableLog_tooLarge): return "tableLog requires too much memory : unsupported";
+ case PREFIX(maxSymbolValue_tooLarge): return "Unsupported max Symbol Value : too large";
+ case PREFIX(maxSymbolValue_tooSmall): return "Specified maxSymbolValue is too small";
+ case PREFIX(dictionary_corrupted): return "Dictionary is corrupted";
+ case PREFIX(dictionary_wrong): return "Dictionary mismatch";
+ case PREFIX(dictionaryCreation_failed): return "Cannot create Dictionary from provided samples";
+ case PREFIX(dstSize_tooSmall): return "Destination buffer is too small";
+ case PREFIX(srcSize_wrong): return "Src size is incorrect";
+ case PREFIX(dstBuffer_null): return "Operation on NULL destination buffer";
+ /* following error codes are not stable and may be removed or changed in a future version */
+ case PREFIX(frameIndex_tooLarge): return "Frame index is too large";
+ case PREFIX(seekableIO): return "An I/O error occurred when reading/seeking";
+ case PREFIX(maxCode):
+ default: return notErrorCode;
+ }
+#endif
+}
diff --git a/Utilities/cmzstd/lib/common/error_private.h b/Utilities/cmzstd/lib/common/error_private.h
new file mode 100644
index 000000000..0d2fa7e34
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/error_private.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+/* Note : this module is expected to remain private, do not expose it */
+
+#ifndef ERROR_H_MODULE
+#define ERROR_H_MODULE
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+
+/* ****************************************
+* Dependencies
+******************************************/
+#include <stddef.h> /* size_t */
+#include "zstd_errors.h" /* enum list */
+
+
+/* ****************************************
+* Compiler-specific
+******************************************/
+#if defined(__GNUC__)
+# define ERR_STATIC static __attribute__((unused))
+#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
+# define ERR_STATIC static inline
+#elif defined(_MSC_VER)
+# define ERR_STATIC static __inline
+#else
+# define ERR_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */
+#endif
+
+
+/*-****************************************
+* Customization (error_public.h)
+******************************************/
+typedef ZSTD_ErrorCode ERR_enum;
+#define PREFIX(name) ZSTD_error_##name
+
+
+/*-****************************************
+* Error codes handling
+******************************************/
+#undef ERROR /* reported already defined on VS 2015 (Rich Geldreich) */
+#define ERROR(name) ZSTD_ERROR(name)
+#define ZSTD_ERROR(name) ((size_t)-PREFIX(name))
+
+ERR_STATIC unsigned ERR_isError(size_t code) { return (code > ERROR(maxCode)); }
+
+ERR_STATIC ERR_enum ERR_getErrorCode(size_t code) { if (!ERR_isError(code)) return (ERR_enum)0; return (ERR_enum) (0-code); }
+
+
+/*-****************************************
+* Error Strings
+******************************************/
+
+const char* ERR_getErrorString(ERR_enum code); /* error_private.c */
+
+ERR_STATIC const char* ERR_getErrorName(size_t code)
+{
+ return ERR_getErrorString(ERR_getErrorCode(code));
+}
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* ERROR_H_MODULE */
diff --git a/Utilities/cmzstd/lib/common/fse.h b/Utilities/cmzstd/lib/common/fse.h
new file mode 100644
index 000000000..f72c519b2
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/fse.h
@@ -0,0 +1,708 @@
+/* ******************************************************************
+ FSE : Finite State Entropy codec
+ Public Prototypes declaration
+ Copyright (C) 2013-2016, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
+****************************************************************** */
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#ifndef FSE_H
+#define FSE_H
+
+
+/*-*****************************************
+* Dependencies
+******************************************/
+#include <stddef.h> /* size_t, ptrdiff_t */
+
+
+/*-*****************************************
+* FSE_PUBLIC_API : control library symbols visibility
+******************************************/
+#if defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) && defined(__GNUC__) && (__GNUC__ >= 4)
+# define FSE_PUBLIC_API __attribute__ ((visibility ("default")))
+#elif defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) /* Visual expected */
+# define FSE_PUBLIC_API __declspec(dllexport)
+#elif defined(FSE_DLL_IMPORT) && (FSE_DLL_IMPORT==1)
+# define FSE_PUBLIC_API __declspec(dllimport) /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
+#else
+# define FSE_PUBLIC_API
+#endif
+
+/*------ Version ------*/
+#define FSE_VERSION_MAJOR 0
+#define FSE_VERSION_MINOR 9
+#define FSE_VERSION_RELEASE 0
+
+#define FSE_LIB_VERSION FSE_VERSION_MAJOR.FSE_VERSION_MINOR.FSE_VERSION_RELEASE
+#define FSE_QUOTE(str) #str
+#define FSE_EXPAND_AND_QUOTE(str) FSE_QUOTE(str)
+#define FSE_VERSION_STRING FSE_EXPAND_AND_QUOTE(FSE_LIB_VERSION)
+
+#define FSE_VERSION_NUMBER (FSE_VERSION_MAJOR *100*100 + FSE_VERSION_MINOR *100 + FSE_VERSION_RELEASE)
+FSE_PUBLIC_API unsigned FSE_versionNumber(void); /**< library version number; to be used when checking dll version */
+
+
+/*-****************************************
+* FSE simple functions
+******************************************/
+/*! FSE_compress() :
+ Compress content of buffer 'src', of size 'srcSize', into destination buffer 'dst'.
+ 'dst' buffer must be already allocated. Compression runs faster is dstCapacity >= FSE_compressBound(srcSize).
+ @return : size of compressed data (<= dstCapacity).
+ Special values : if return == 0, srcData is not compressible => Nothing is stored within dst !!!
+ if return == 1, srcData is a single byte symbol * srcSize times. Use RLE compression instead.
+ if FSE_isError(return), compression failed (more details using FSE_getErrorName())
+*/
+FSE_PUBLIC_API size_t FSE_compress(void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize);
+
+/*! FSE_decompress():
+ Decompress FSE data from buffer 'cSrc', of size 'cSrcSize',
+ into already allocated destination buffer 'dst', of size 'dstCapacity'.
+ @return : size of regenerated data (<= maxDstSize),
+ or an error code, which can be tested using FSE_isError() .
+
+ ** Important ** : FSE_decompress() does not decompress non-compressible nor RLE data !!!
+ Why ? : making this distinction requires a header.
+ Header management is intentionally delegated to the user layer, which can better manage special cases.
+*/
+FSE_PUBLIC_API size_t FSE_decompress(void* dst, size_t dstCapacity,
+ const void* cSrc, size_t cSrcSize);
+
+
+/*-*****************************************
+* Tool functions
+******************************************/
+FSE_PUBLIC_API size_t FSE_compressBound(size_t size); /* maximum compressed size */
+
+/* Error Management */
+FSE_PUBLIC_API unsigned FSE_isError(size_t code); /* tells if a return value is an error code */
+FSE_PUBLIC_API const char* FSE_getErrorName(size_t code); /* provides error code string (useful for debugging) */
+
+
+/*-*****************************************
+* FSE advanced functions
+******************************************/
+/*! FSE_compress2() :
+ Same as FSE_compress(), but allows the selection of 'maxSymbolValue' and 'tableLog'
+ Both parameters can be defined as '0' to mean : use default value
+ @return : size of compressed data
+ Special values : if return == 0, srcData is not compressible => Nothing is stored within cSrc !!!
+ if return == 1, srcData is a single byte symbol * srcSize times. Use RLE compression.
+ if FSE_isError(return), it's an error code.
+*/
+FSE_PUBLIC_API size_t FSE_compress2 (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog);
+
+
+/*-*****************************************
+* FSE detailed API
+******************************************/
+/*!
+FSE_compress() does the following:
+1. count symbol occurrence from source[] into table count[] (see hist.h)
+2. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog)
+3. save normalized counters to memory buffer using writeNCount()
+4. build encoding table 'CTable' from normalized counters
+5. encode the data stream using encoding table 'CTable'
+
+FSE_decompress() does the following:
+1. read normalized counters with readNCount()
+2. build decoding table 'DTable' from normalized counters
+3. decode the data stream using decoding table 'DTable'
+
+The following API allows targeting specific sub-functions for advanced tasks.
+For example, it's possible to compress several blocks using the same 'CTable',
+or to save and provide normalized distribution using external method.
+*/
+
+/* *** COMPRESSION *** */
+
+/*! FSE_optimalTableLog():
+ dynamically downsize 'tableLog' when conditions are met.
+ It saves CPU time, by using smaller tables, while preserving or even improving compression ratio.
+ @return : recommended tableLog (necessarily <= 'maxTableLog') */
+FSE_PUBLIC_API unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue);
+
+/*! FSE_normalizeCount():
+ normalize counts so that sum(count[]) == Power_of_2 (2^tableLog)
+ 'normalizedCounter' is a table of short, of minimum size (maxSymbolValue+1).
+ @return : tableLog,
+ or an errorCode, which can be tested using FSE_isError() */
+FSE_PUBLIC_API size_t FSE_normalizeCount(short* normalizedCounter, unsigned tableLog,
+ const unsigned* count, size_t srcSize, unsigned maxSymbolValue);
+
+/*! FSE_NCountWriteBound():
+ Provides the maximum possible size of an FSE normalized table, given 'maxSymbolValue' and 'tableLog'.
+ Typically useful for allocation purpose. */
+FSE_PUBLIC_API size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog);
+
+/*! FSE_writeNCount():
+ Compactly save 'normalizedCounter' into 'buffer'.
+ @return : size of the compressed table,
+ or an errorCode, which can be tested using FSE_isError(). */
+FSE_PUBLIC_API size_t FSE_writeNCount (void* buffer, size_t bufferSize,
+ const short* normalizedCounter,
+ unsigned maxSymbolValue, unsigned tableLog);
+
+/*! Constructor and Destructor of FSE_CTable.
+ Note that FSE_CTable size depends on 'tableLog' and 'maxSymbolValue' */
+typedef unsigned FSE_CTable; /* don't allocate that. It's only meant to be more restrictive than void* */
+FSE_PUBLIC_API FSE_CTable* FSE_createCTable (unsigned maxSymbolValue, unsigned tableLog);
+FSE_PUBLIC_API void FSE_freeCTable (FSE_CTable* ct);
+
+/*! FSE_buildCTable():
+ Builds `ct`, which must be already allocated, using FSE_createCTable().
+ @return : 0, or an errorCode, which can be tested using FSE_isError() */
+FSE_PUBLIC_API size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
+
+/*! FSE_compress_usingCTable():
+ Compress `src` using `ct` into `dst` which must be already allocated.
+ @return : size of compressed data (<= `dstCapacity`),
+ or 0 if compressed data could not fit into `dst`,
+ or an errorCode, which can be tested using FSE_isError() */
+FSE_PUBLIC_API size_t FSE_compress_usingCTable (void* dst, size_t dstCapacity, const void* src, size_t srcSize, const FSE_CTable* ct);
+
+/*!
+Tutorial :
+----------
+The first step is to count all symbols. FSE_count() does this job very fast.
+Result will be saved into 'count', a table of unsigned int, which must be already allocated, and have 'maxSymbolValuePtr[0]+1' cells.
+'src' is a table of bytes of size 'srcSize'. All values within 'src' MUST be <= maxSymbolValuePtr[0]
+maxSymbolValuePtr[0] will be updated, with its real value (necessarily <= original value)
+FSE_count() will return the number of occurrence of the most frequent symbol.
+This can be used to know if there is a single symbol within 'src', and to quickly evaluate its compressibility.
+If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).
+
+The next step is to normalize the frequencies.
+FSE_normalizeCount() will ensure that sum of frequencies is == 2 ^'tableLog'.
+It also guarantees a minimum of 1 to any Symbol with frequency >= 1.
+You can use 'tableLog'==0 to mean "use default tableLog value".
+If you are unsure of which tableLog value to use, you can ask FSE_optimalTableLog(),
+which will provide the optimal valid tableLog given sourceSize, maxSymbolValue, and a user-defined maximum (0 means "default").
+
+The result of FSE_normalizeCount() will be saved into a table,
+called 'normalizedCounter', which is a table of signed short.
+'normalizedCounter' must be already allocated, and have at least 'maxSymbolValue+1' cells.
+The return value is tableLog if everything proceeded as expected.
+It is 0 if there is a single symbol within distribution.
+If there is an error (ex: invalid tableLog value), the function will return an ErrorCode (which can be tested using FSE_isError()).
+
+'normalizedCounter' can be saved in a compact manner to a memory area using FSE_writeNCount().
+'buffer' must be already allocated.
+For guaranteed success, buffer size must be at least FSE_headerBound().
+The result of the function is the number of bytes written into 'buffer'.
+If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError(); ex : buffer size too small).
+
+'normalizedCounter' can then be used to create the compression table 'CTable'.
+The space required by 'CTable' must be already allocated, using FSE_createCTable().
+You can then use FSE_buildCTable() to fill 'CTable'.
+If there is an error, both functions will return an ErrorCode (which can be tested using FSE_isError()).
+
+'CTable' can then be used to compress 'src', with FSE_compress_usingCTable().
+Similar to FSE_count(), the convention is that 'src' is assumed to be a table of char of size 'srcSize'
+The function returns the size of compressed data (without header), necessarily <= `dstCapacity`.
+If it returns '0', compressed data could not fit into 'dst'.
+If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).
+*/
+
+
+/* *** DECOMPRESSION *** */
+
+/*! FSE_readNCount():
+ Read compactly saved 'normalizedCounter' from 'rBuffer'.
+ @return : size read from 'rBuffer',
+ or an errorCode, which can be tested using FSE_isError().
+ maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */
+FSE_PUBLIC_API size_t FSE_readNCount (short* normalizedCounter,
+ unsigned* maxSymbolValuePtr, unsigned* tableLogPtr,
+ const void* rBuffer, size_t rBuffSize);
+
+/*! Constructor and Destructor of FSE_DTable.
+ Note that its size depends on 'tableLog' */
+typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */
+FSE_PUBLIC_API FSE_DTable* FSE_createDTable(unsigned tableLog);
+FSE_PUBLIC_API void FSE_freeDTable(FSE_DTable* dt);
+
+/*! FSE_buildDTable():
+ Builds 'dt', which must be already allocated, using FSE_createDTable().
+ return : 0, or an errorCode, which can be tested using FSE_isError() */
+FSE_PUBLIC_API size_t FSE_buildDTable (FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
+
+/*! FSE_decompress_usingDTable():
+ Decompress compressed source `cSrc` of size `cSrcSize` using `dt`
+ into `dst` which must be already allocated.
+ @return : size of regenerated data (necessarily <= `dstCapacity`),
+ or an errorCode, which can be tested using FSE_isError() */
+FSE_PUBLIC_API size_t FSE_decompress_usingDTable(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, const FSE_DTable* dt);
+
+/*!
+Tutorial :
+----------
+(Note : these functions only decompress FSE-compressed blocks.
+ If block is uncompressed, use memcpy() instead
+ If block is a single repeated byte, use memset() instead )
+
+The first step is to obtain the normalized frequencies of symbols.
+This can be performed by FSE_readNCount() if it was saved using FSE_writeNCount().
+'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short.
+In practice, that means it's necessary to know 'maxSymbolValue' beforehand,
+or size the table to handle worst case situations (typically 256).
+FSE_readNCount() will provide 'tableLog' and 'maxSymbolValue'.
+The result of FSE_readNCount() is the number of bytes read from 'rBuffer'.
+Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that.
+If there is an error, the function will return an error code, which can be tested using FSE_isError().
+
+The next step is to build the decompression tables 'FSE_DTable' from 'normalizedCounter'.
+This is performed by the function FSE_buildDTable().
+The space required by 'FSE_DTable' must be already allocated using FSE_createDTable().
+If there is an error, the function will return an error code, which can be tested using FSE_isError().
+
+`FSE_DTable` can then be used to decompress `cSrc`, with FSE_decompress_usingDTable().
+`cSrcSize` must be strictly correct, otherwise decompression will fail.
+FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`).
+If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small)
+*/
+
+#endif /* FSE_H */
+
+#if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY)
+#define FSE_H_FSE_STATIC_LINKING_ONLY
+
+/* *** Dependency *** */
+#include "bitstream.h"
+
+
+/* *****************************************
+* Static allocation
+*******************************************/
+/* FSE buffer bounds */
+#define FSE_NCOUNTBOUND 512
+#define FSE_BLOCKBOUND(size) (size + (size>>7))
+#define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size)) /* Macro version, useful for static allocation */
+
+/* It is possible to statically allocate FSE CTable/DTable as a table of FSE_CTable/FSE_DTable using below macros */
+#define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) (1 + (1<<(maxTableLog-1)) + ((maxSymbolValue+1)*2))
+#define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1<<maxTableLog))
+
+/* or use the size to malloc() space directly. Pay attention to alignment restrictions though */
+#define FSE_CTABLE_SIZE(maxTableLog, maxSymbolValue) (FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) * sizeof(FSE_CTable))
+#define FSE_DTABLE_SIZE(maxTableLog) (FSE_DTABLE_SIZE_U32(maxTableLog) * sizeof(FSE_DTable))
+
+
+/* *****************************************
+ * FSE advanced API
+ ***************************************** */
+
+unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus);
+/**< same as FSE_optimalTableLog(), which used `minus==2` */
+
+/* FSE_compress_wksp() :
+ * Same as FSE_compress2(), but using an externally allocated scratch buffer (`workSpace`).
+ * FSE_WKSP_SIZE_U32() provides the minimum size required for `workSpace` as a table of FSE_CTable.
+ */
+#define FSE_WKSP_SIZE_U32(maxTableLog, maxSymbolValue) ( FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) + ((maxTableLog > 12) ? (1 << (maxTableLog - 2)) : 1024) )
+size_t FSE_compress_wksp (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);
+
+size_t FSE_buildCTable_raw (FSE_CTable* ct, unsigned nbBits);
+/**< build a fake FSE_CTable, designed for a flat distribution, where each symbol uses nbBits */
+
+size_t FSE_buildCTable_rle (FSE_CTable* ct, unsigned char symbolValue);
+/**< build a fake FSE_CTable, designed to compress always the same symbolValue */
+
+/* FSE_buildCTable_wksp() :
+ * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
+ * `wkspSize` must be >= `(1<<tableLog)`.
+ */
+size_t FSE_buildCTable_wksp(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);
+
+size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits);
+/**< build a fake FSE_DTable, designed to read a flat distribution where each symbol uses nbBits */
+
+size_t FSE_buildDTable_rle (FSE_DTable* dt, unsigned char symbolValue);
+/**< build a fake FSE_DTable, designed to always generate the same symbolValue */
+
+size_t FSE_decompress_wksp(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, FSE_DTable* workSpace, unsigned maxLog);
+/**< same as FSE_decompress(), using an externally allocated `workSpace` produced with `FSE_DTABLE_SIZE_U32(maxLog)` */
+
+typedef enum {
+ FSE_repeat_none, /**< Cannot use the previous table */
+ FSE_repeat_check, /**< Can use the previous table but it must be checked */
+ FSE_repeat_valid /**< Can use the previous table and it is asumed to be valid */
+ } FSE_repeat;
+
+/* *****************************************
+* FSE symbol compression API
+*******************************************/
+/*!
+ This API consists of small unitary functions, which highly benefit from being inlined.
+ Hence their body are included in next section.
+*/
+typedef struct {
+ ptrdiff_t value;
+ const void* stateTable;
+ const void* symbolTT;
+ unsigned stateLog;
+} FSE_CState_t;
+
+static void FSE_initCState(FSE_CState_t* CStatePtr, const FSE_CTable* ct);
+
+static void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* CStatePtr, unsigned symbol);
+
+static void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* CStatePtr);
+
+/**<
+These functions are inner components of FSE_compress_usingCTable().
+They allow the creation of custom streams, mixing multiple tables and bit sources.
+
+A key property to keep in mind is that encoding and decoding are done **in reverse direction**.
+So the first symbol you will encode is the last you will decode, like a LIFO stack.
+
+You will need a few variables to track your CStream. They are :
+
+FSE_CTable ct; // Provided by FSE_buildCTable()
+BIT_CStream_t bitStream; // bitStream tracking structure
+FSE_CState_t state; // State tracking structure (can have several)
+
+
+The first thing to do is to init bitStream and state.
+ size_t errorCode = BIT_initCStream(&bitStream, dstBuffer, maxDstSize);
+ FSE_initCState(&state, ct);
+
+Note that BIT_initCStream() can produce an error code, so its result should be tested, using FSE_isError();
+You can then encode your input data, byte after byte.
+FSE_encodeSymbol() outputs a maximum of 'tableLog' bits at a time.
+Remember decoding will be done in reverse direction.
+ FSE_encodeByte(&bitStream, &state, symbol);
+
+At any time, you can also add any bit sequence.
+Note : maximum allowed nbBits is 25, for compatibility with 32-bits decoders
+ BIT_addBits(&bitStream, bitField, nbBits);
+
+The above methods don't commit data to memory, they just store it into local register, for speed.
+Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
+Writing data to memory is a manual operation, performed by the flushBits function.
+ BIT_flushBits(&bitStream);
+
+Your last FSE encoding operation shall be to flush your last state value(s).
+ FSE_flushState(&bitStream, &state);
+
+Finally, you must close the bitStream.
+The function returns the size of CStream in bytes.
+If data couldn't fit into dstBuffer, it will return a 0 ( == not compressible)
+If there is an error, it returns an errorCode (which can be tested using FSE_isError()).
+ size_t size = BIT_closeCStream(&bitStream);
+*/
+
+
+/* *****************************************
+* FSE symbol decompression API
+*******************************************/
+typedef struct {
+ size_t state;
+ const void* table; /* precise table may vary, depending on U16 */
+} FSE_DState_t;
+
+
+static void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt);
+
+static unsigned char FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
+
+static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr);
+
+/**<
+Let's now decompose FSE_decompress_usingDTable() into its unitary components.
+You will decode FSE-encoded symbols from the bitStream,
+and also any other bitFields you put in, **in reverse order**.
+
+You will need a few variables to track your bitStream. They are :
+
+BIT_DStream_t DStream; // Stream context
+FSE_DState_t DState; // State context. Multiple ones are possible
+FSE_DTable* DTablePtr; // Decoding table, provided by FSE_buildDTable()
+
+The first thing to do is to init the bitStream.
+ errorCode = BIT_initDStream(&DStream, srcBuffer, srcSize);
+
+You should then retrieve your initial state(s)
+(in reverse flushing order if you have several ones) :
+ errorCode = FSE_initDState(&DState, &DStream, DTablePtr);
+
+You can then decode your data, symbol after symbol.
+For information the maximum number of bits read by FSE_decodeSymbol() is 'tableLog'.
+Keep in mind that symbols are decoded in reverse order, like a LIFO stack (last in, first out).
+ unsigned char symbol = FSE_decodeSymbol(&DState, &DStream);
+
+You can retrieve any bitfield you eventually stored into the bitStream (in reverse order)
+Note : maximum allowed nbBits is 25, for 32-bits compatibility
+ size_t bitField = BIT_readBits(&DStream, nbBits);
+
+All above operations only read from local register (which size depends on size_t).
+Refueling the register from memory is manually performed by the reload method.
+ endSignal = FSE_reloadDStream(&DStream);
+
+BIT_reloadDStream() result tells if there is still some more data to read from DStream.
+BIT_DStream_unfinished : there is still some data left into the DStream.
+BIT_DStream_endOfBuffer : Dstream reached end of buffer. Its container may no longer be completely filled.
+BIT_DStream_completed : Dstream reached its exact end, corresponding in general to decompression completed.
+BIT_DStream_tooFar : Dstream went too far. Decompression result is corrupted.
+
+When reaching end of buffer (BIT_DStream_endOfBuffer), progress slowly, notably if you decode multiple symbols per loop,
+to properly detect the exact end of stream.
+After each decoded symbol, check if DStream is fully consumed using this simple test :
+ BIT_reloadDStream(&DStream) >= BIT_DStream_completed
+
+When it's done, verify decompression is fully completed, by checking both DStream and the relevant states.
+Checking if DStream has reached its end is performed by :
+ BIT_endOfDStream(&DStream);
+Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible.
+ FSE_endOfDState(&DState);
+*/
+
+
+/* *****************************************
+* FSE unsafe API
+*******************************************/
+static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
+/* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */
+
+
+/* *****************************************
+* Implementation of inlined functions
+*******************************************/
+typedef struct {
+ int deltaFindState;
+ U32 deltaNbBits;
+} FSE_symbolCompressionTransform; /* total 8 bytes */
+
+MEM_STATIC void FSE_initCState(FSE_CState_t* statePtr, const FSE_CTable* ct)
+{
+ const void* ptr = ct;
+ const U16* u16ptr = (const U16*) ptr;
+ const U32 tableLog = MEM_read16(ptr);
+ statePtr->value = (ptrdiff_t)1<<tableLog;
+ statePtr->stateTable = u16ptr+2;
+ statePtr->symbolTT = ct + 1 + (tableLog ? (1<<(tableLog-1)) : 1);
+ statePtr->stateLog = tableLog;
+}
+
+
+/*! FSE_initCState2() :
+* Same as FSE_initCState(), but the first symbol to include (which will be the last to be read)
+* uses the smallest state value possible, saving the cost of this symbol */
+MEM_STATIC void FSE_initCState2(FSE_CState_t* statePtr, const FSE_CTable* ct, U32 symbol)
+{
+ FSE_initCState(statePtr, ct);
+ { const FSE_symbolCompressionTransform symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];
+ const U16* stateTable = (const U16*)(statePtr->stateTable);
+ U32 nbBitsOut = (U32)((symbolTT.deltaNbBits + (1<<15)) >> 16);
+ statePtr->value = (nbBitsOut << 16) - symbolTT.deltaNbBits;
+ statePtr->value = stateTable[(statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
+ }
+}
+
+MEM_STATIC void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* statePtr, unsigned symbol)
+{
+ FSE_symbolCompressionTransform const symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];
+ const U16* const stateTable = (const U16*)(statePtr->stateTable);
+ U32 const nbBitsOut = (U32)((statePtr->value + symbolTT.deltaNbBits) >> 16);
+ BIT_addBits(bitC, statePtr->value, nbBitsOut);
+ statePtr->value = stateTable[ (statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
+}
+
+MEM_STATIC void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* statePtr)
+{
+ BIT_addBits(bitC, statePtr->value, statePtr->stateLog);
+ BIT_flushBits(bitC);
+}
+
+
+/* FSE_getMaxNbBits() :
+ * Approximate maximum cost of a symbol, in bits.
+ * Fractional get rounded up (i.e : a symbol with a normalized frequency of 3 gives the same result as a frequency of 2)
+ * note 1 : assume symbolValue is valid (<= maxSymbolValue)
+ * note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */
+MEM_STATIC U32 FSE_getMaxNbBits(const void* symbolTTPtr, U32 symbolValue)
+{
+ const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr;
+ return (symbolTT[symbolValue].deltaNbBits + ((1<<16)-1)) >> 16;
+}
+
+/* FSE_bitCost() :
+ * Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits)
+ * note 1 : assume symbolValue is valid (<= maxSymbolValue)
+ * note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */
+MEM_STATIC U32 FSE_bitCost(const void* symbolTTPtr, U32 tableLog, U32 symbolValue, U32 accuracyLog)
+{
+ const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr;
+ U32 const minNbBits = symbolTT[symbolValue].deltaNbBits >> 16;
+ U32 const threshold = (minNbBits+1) << 16;
+ assert(tableLog < 16);
+ assert(accuracyLog < 31-tableLog); /* ensure enough room for renormalization double shift */
+ { U32 const tableSize = 1 << tableLog;
+ U32 const deltaFromThreshold = threshold - (symbolTT[symbolValue].deltaNbBits + tableSize);
+ U32 const normalizedDeltaFromThreshold = (deltaFromThreshold << accuracyLog) >> tableLog; /* linear interpolation (very approximate) */
+ U32 const bitMultiplier = 1 << accuracyLog;
+ assert(symbolTT[symbolValue].deltaNbBits + tableSize <= threshold);
+ assert(normalizedDeltaFromThreshold <= bitMultiplier);
+ return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold;
+ }
+}
+
+
+/* ====== Decompression ====== */
+
+typedef struct {
+ U16 tableLog;
+ U16 fastMode;
+} FSE_DTableHeader; /* sizeof U32 */
+
+typedef struct
+{
+ unsigned short newState;
+ unsigned char symbol;
+ unsigned char nbBits;
+} FSE_decode_t; /* size == U32 */
+
+MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt)
+{
+ const void* ptr = dt;
+ const FSE_DTableHeader* const DTableH = (const FSE_DTableHeader*)ptr;
+ DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
+ BIT_reloadDStream(bitD);
+ DStatePtr->table = dt + 1;
+}
+
+MEM_STATIC BYTE FSE_peekSymbol(const FSE_DState_t* DStatePtr)
+{
+ FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
+ return DInfo.symbol;
+}
+
+MEM_STATIC void FSE_updateState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
+{
+ FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
+ U32 const nbBits = DInfo.nbBits;
+ size_t const lowBits = BIT_readBits(bitD, nbBits);
+ DStatePtr->state = DInfo.newState + lowBits;
+}
+
+MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
+{
+ FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
+ U32 const nbBits = DInfo.nbBits;
+ BYTE const symbol = DInfo.symbol;
+ size_t const lowBits = BIT_readBits(bitD, nbBits);
+
+ DStatePtr->state = DInfo.newState + lowBits;
+ return symbol;
+}
+
+/*! FSE_decodeSymbolFast() :
+ unsafe, only works if no symbol has a probability > 50% */
+MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
+{
+ FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
+ U32 const nbBits = DInfo.nbBits;
+ BYTE const symbol = DInfo.symbol;
+ size_t const lowBits = BIT_readBitsFast(bitD, nbBits);
+
+ DStatePtr->state = DInfo.newState + lowBits;
+ return symbol;
+}
+
+MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
+{
+ return DStatePtr->state == 0;
+}
+
+
+
+#ifndef FSE_COMMONDEFS_ONLY
+
+/* **************************************************************
+* Tuning parameters
+****************************************************************/
+/*!MEMORY_USAGE :
+* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
+* Increasing memory usage improves compression ratio
+* Reduced memory usage can improve speed, due to cache effect
+* Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
+#ifndef FSE_MAX_MEMORY_USAGE
+# define FSE_MAX_MEMORY_USAGE 14
+#endif
+#ifndef FSE_DEFAULT_MEMORY_USAGE
+# define FSE_DEFAULT_MEMORY_USAGE 13
+#endif
+
+/*!FSE_MAX_SYMBOL_VALUE :
+* Maximum symbol value authorized.
+* Required for proper stack allocation */
+#ifndef FSE_MAX_SYMBOL_VALUE
+# define FSE_MAX_SYMBOL_VALUE 255
+#endif
+
+/* **************************************************************
+* template functions type & suffix
+****************************************************************/
+#define FSE_FUNCTION_TYPE BYTE
+#define FSE_FUNCTION_EXTENSION
+#define FSE_DECODE_TYPE FSE_decode_t
+
+
+#endif /* !FSE_COMMONDEFS_ONLY */
+
+
+/* ***************************************************************
+* Constants
+*****************************************************************/
+#define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2)
+#define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)
+#define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)
+#define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)
+#define FSE_MIN_TABLELOG 5
+
+#define FSE_TABLELOG_ABSOLUTE_MAX 15
+#if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
+# error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
+#endif
+
+#define FSE_TABLESTEP(tableSize) ((tableSize>>1) + (tableSize>>3) + 3)
+
+
+#endif /* FSE_STATIC_LINKING_ONLY */
+
+
+#if defined (__cplusplus)
+}
+#endif
diff --git a/Utilities/cmzstd/lib/common/fse_decompress.c b/Utilities/cmzstd/lib/common/fse_decompress.c
new file mode 100644
index 000000000..72bbead5b
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/fse_decompress.c
@@ -0,0 +1,309 @@
+/* ******************************************************************
+ FSE : Finite State Entropy decoder
+ Copyright (C) 2013-2015, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
+ - Public forum : https://groups.google.com/forum/#!forum/lz4c
+****************************************************************** */
+
+
+/* **************************************************************
+* Includes
+****************************************************************/
+#include <stdlib.h> /* malloc, free, qsort */
+#include <string.h> /* memcpy, memset */
+#include "bitstream.h"
+#include "compiler.h"
+#define FSE_STATIC_LINKING_ONLY
+#include "fse.h"
+#include "error_private.h"
+
+
+/* **************************************************************
+* Error Management
+****************************************************************/
+#define FSE_isError ERR_isError
+#define FSE_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c) /* use only *after* variable declarations */
+
+/* check and forward error code */
+#define CHECK_F(f) { size_t const e = f; if (FSE_isError(e)) return e; }
+
+
+/* **************************************************************
+* Templates
+****************************************************************/
+/*
+ designed to be included
+ for type-specific functions (template emulation in C)
+ Objective is to write these functions only once, for improved maintenance
+*/
+
+/* safety checks */
+#ifndef FSE_FUNCTION_EXTENSION
+# error "FSE_FUNCTION_EXTENSION must be defined"
+#endif
+#ifndef FSE_FUNCTION_TYPE
+# error "FSE_FUNCTION_TYPE must be defined"
+#endif
+
+/* Function names */
+#define FSE_CAT(X,Y) X##Y
+#define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
+#define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
+
+
+/* Function templates */
+FSE_DTable* FSE_createDTable (unsigned tableLog)
+{
+ if (tableLog > FSE_TABLELOG_ABSOLUTE_MAX) tableLog = FSE_TABLELOG_ABSOLUTE_MAX;
+ return (FSE_DTable*)malloc( FSE_DTABLE_SIZE_U32(tableLog) * sizeof (U32) );
+}
+
+void FSE_freeDTable (FSE_DTable* dt)
+{
+ free(dt);
+}
+
+size_t FSE_buildDTable(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
+{
+ void* const tdPtr = dt+1; /* because *dt is unsigned, 32-bits aligned on 32-bits */
+ FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*) (tdPtr);
+ U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1];
+
+ U32 const maxSV1 = maxSymbolValue + 1;
+ U32 const tableSize = 1 << tableLog;
+ U32 highThreshold = tableSize-1;
+
+ /* Sanity Checks */
+ if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
+ if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
+
+ /* Init, lay down lowprob symbols */
+ { FSE_DTableHeader DTableH;
+ DTableH.tableLog = (U16)tableLog;
+ DTableH.fastMode = 1;
+ { S16 const largeLimit= (S16)(1 << (tableLog-1));
+ U32 s;
+ for (s=0; s<maxSV1; s++) {
+ if (normalizedCounter[s]==-1) {
+ tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
+ symbolNext[s] = 1;
+ } else {
+ if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
+ symbolNext[s] = normalizedCounter[s];
+ } } }
+ memcpy(dt, &DTableH, sizeof(DTableH));
+ }
+
+ /* Spread symbols */
+ { U32 const tableMask = tableSize-1;
+ U32 const step = FSE_TABLESTEP(tableSize);
+ U32 s, position = 0;
+ for (s=0; s<maxSV1; s++) {
+ int i;
+ for (i=0; i<normalizedCounter[s]; i++) {
+ tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
+ position = (position + step) & tableMask;
+ while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
+ } }
+ if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
+ }
+
+ /* Build Decoding table */
+ { U32 u;
+ for (u=0; u<tableSize; u++) {
+ FSE_FUNCTION_TYPE const symbol = (FSE_FUNCTION_TYPE)(tableDecode[u].symbol);
+ U32 const nextState = symbolNext[symbol]++;
+ tableDecode[u].nbBits = (BYTE) (tableLog - BIT_highbit32(nextState) );
+ tableDecode[u].newState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
+ } }
+
+ return 0;
+}
+
+
+#ifndef FSE_COMMONDEFS_ONLY
+
+/*-*******************************************************
+* Decompression (Byte symbols)
+*********************************************************/
+size_t FSE_buildDTable_rle (FSE_DTable* dt, BYTE symbolValue)
+{
+ void* ptr = dt;
+ FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
+ void* dPtr = dt + 1;
+ FSE_decode_t* const cell = (FSE_decode_t*)dPtr;
+
+ DTableH->tableLog = 0;
+ DTableH->fastMode = 0;
+
+ cell->newState = 0;
+ cell->symbol = symbolValue;
+ cell->nbBits = 0;
+
+ return 0;
+}
+
+
+size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits)
+{
+ void* ptr = dt;
+ FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
+ void* dPtr = dt + 1;
+ FSE_decode_t* const dinfo = (FSE_decode_t*)dPtr;
+ const unsigned tableSize = 1 << nbBits;
+ const unsigned tableMask = tableSize - 1;
+ const unsigned maxSV1 = tableMask+1;
+ unsigned s;
+
+ /* Sanity checks */
+ if (nbBits < 1) return ERROR(GENERIC); /* min size */
+
+ /* Build Decoding Table */
+ DTableH->tableLog = (U16)nbBits;
+ DTableH->fastMode = 1;
+ for (s=0; s<maxSV1; s++) {
+ dinfo[s].newState = 0;
+ dinfo[s].symbol = (BYTE)s;
+ dinfo[s].nbBits = (BYTE)nbBits;
+ }
+
+ return 0;
+}
+
+FORCE_INLINE_TEMPLATE size_t FSE_decompress_usingDTable_generic(
+ void* dst, size_t maxDstSize,
+ const void* cSrc, size_t cSrcSize,
+ const FSE_DTable* dt, const unsigned fast)
+{
+ BYTE* const ostart = (BYTE*) dst;
+ BYTE* op = ostart;
+ BYTE* const omax = op + maxDstSize;
+ BYTE* const olimit = omax-3;
+
+ BIT_DStream_t bitD;
+ FSE_DState_t state1;
+ FSE_DState_t state2;
+
+ /* Init */
+ CHECK_F(BIT_initDStream(&bitD, cSrc, cSrcSize));
+
+ FSE_initDState(&state1, &bitD, dt);
+ FSE_initDState(&state2, &bitD, dt);
+
+#define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)
+
+ /* 4 symbols per loop */
+ for ( ; (BIT_reloadDStream(&bitD)==BIT_DStream_unfinished) & (op<olimit) ; op+=4) {
+ op[0] = FSE_GETSYMBOL(&state1);
+
+ if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
+ BIT_reloadDStream(&bitD);
+
+ op[1] = FSE_GETSYMBOL(&state2);
+
+ if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
+ { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } }
+
+ op[2] = FSE_GETSYMBOL(&state1);
+
+ if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
+ BIT_reloadDStream(&bitD);
+
+ op[3] = FSE_GETSYMBOL(&state2);
+ }
+
+ /* tail */
+ /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */
+ while (1) {
+ if (op>(omax-2)) return ERROR(dstSize_tooSmall);
+ *op++ = FSE_GETSYMBOL(&state1);
+ if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) {
+ *op++ = FSE_GETSYMBOL(&state2);
+ break;
+ }
+
+ if (op>(omax-2)) return ERROR(dstSize_tooSmall);
+ *op++ = FSE_GETSYMBOL(&state2);
+ if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) {
+ *op++ = FSE_GETSYMBOL(&state1);
+ break;
+ } }
+
+ return op-ostart;
+}
+
+
+size_t FSE_decompress_usingDTable(void* dst, size_t originalSize,
+ const void* cSrc, size_t cSrcSize,
+ const FSE_DTable* dt)
+{
+ const void* ptr = dt;
+ const FSE_DTableHeader* DTableH = (const FSE_DTableHeader*)ptr;
+ const U32 fastMode = DTableH->fastMode;
+
+ /* select fast mode (static) */
+ if (fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
+ return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
+}
+
+
+size_t FSE_decompress_wksp(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, FSE_DTable* workSpace, unsigned maxLog)
+{
+ const BYTE* const istart = (const BYTE*)cSrc;
+ const BYTE* ip = istart;
+ short counting[FSE_MAX_SYMBOL_VALUE+1];
+ unsigned tableLog;
+ unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
+
+ /* normal FSE decoding mode */
+ size_t const NCountLength = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
+ if (FSE_isError(NCountLength)) return NCountLength;
+ //if (NCountLength >= cSrcSize) return ERROR(srcSize_wrong); /* too small input size; supposed to be already checked in NCountLength, only remaining case : NCountLength==cSrcSize */
+ if (tableLog > maxLog) return ERROR(tableLog_tooLarge);
+ ip += NCountLength;
+ cSrcSize -= NCountLength;
+
+ CHECK_F( FSE_buildDTable (workSpace, counting, maxSymbolValue, tableLog) );
+
+ return FSE_decompress_usingDTable (dst, dstCapacity, ip, cSrcSize, workSpace); /* always return, even if it is an error code */
+}
+
+
+typedef FSE_DTable DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)];
+
+size_t FSE_decompress(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize)
+{
+ DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */
+ return FSE_decompress_wksp(dst, dstCapacity, cSrc, cSrcSize, dt, FSE_MAX_TABLELOG);
+}
+
+
+
+#endif /* FSE_COMMONDEFS_ONLY */
diff --git a/Utilities/cmzstd/lib/common/huf.h b/Utilities/cmzstd/lib/common/huf.h
new file mode 100644
index 000000000..6b572c448
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/huf.h
@@ -0,0 +1,358 @@
+/* ******************************************************************
+ huff0 huffman codec,
+ part of Finite State Entropy library
+ Copyright (C) 2013-present, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
+****************************************************************** */
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#ifndef HUF_H_298734234
+#define HUF_H_298734234
+
+/* *** Dependencies *** */
+#include <stddef.h> /* size_t */
+
+
+/* *** library symbols visibility *** */
+/* Note : when linking with -fvisibility=hidden on gcc, or by default on Visual,
+ * HUF symbols remain "private" (internal symbols for library only).
+ * Set macro FSE_DLL_EXPORT to 1 if you want HUF symbols visible on DLL interface */
+#if defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) && defined(__GNUC__) && (__GNUC__ >= 4)
+# define HUF_PUBLIC_API __attribute__ ((visibility ("default")))
+#elif defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) /* Visual expected */
+# define HUF_PUBLIC_API __declspec(dllexport)
+#elif defined(FSE_DLL_IMPORT) && (FSE_DLL_IMPORT==1)
+# define HUF_PUBLIC_API __declspec(dllimport) /* not required, just to generate faster code (saves a function pointer load from IAT and an indirect jump) */
+#else
+# define HUF_PUBLIC_API
+#endif
+
+
+/* ========================== */
+/* *** simple functions *** */
+/* ========================== */
+
+/** HUF_compress() :
+ * Compress content from buffer 'src', of size 'srcSize', into buffer 'dst'.
+ * 'dst' buffer must be already allocated.
+ * Compression runs faster if `dstCapacity` >= HUF_compressBound(srcSize).
+ * `srcSize` must be <= `HUF_BLOCKSIZE_MAX` == 128 KB.
+ * @return : size of compressed data (<= `dstCapacity`).
+ * Special values : if return == 0, srcData is not compressible => Nothing is stored within dst !!!
+ * if HUF_isError(return), compression failed (more details using HUF_getErrorName())
+ */
+HUF_PUBLIC_API size_t HUF_compress(void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize);
+
+/** HUF_decompress() :
+ * Decompress HUF data from buffer 'cSrc', of size 'cSrcSize',
+ * into already allocated buffer 'dst', of minimum size 'dstSize'.
+ * `originalSize` : **must** be the ***exact*** size of original (uncompressed) data.
+ * Note : in contrast with FSE, HUF_decompress can regenerate
+ * RLE (cSrcSize==1) and uncompressed (cSrcSize==dstSize) data,
+ * because it knows size to regenerate (originalSize).
+ * @return : size of regenerated data (== originalSize),
+ * or an error code, which can be tested using HUF_isError()
+ */
+HUF_PUBLIC_API size_t HUF_decompress(void* dst, size_t originalSize,
+ const void* cSrc, size_t cSrcSize);
+
+
+/* *** Tool functions *** */
+#define HUF_BLOCKSIZE_MAX (128 * 1024) /**< maximum input size for a single block compressed with HUF_compress */
+HUF_PUBLIC_API size_t HUF_compressBound(size_t size); /**< maximum compressed size (worst case) */
+
+/* Error Management */
+HUF_PUBLIC_API unsigned HUF_isError(size_t code); /**< tells if a return value is an error code */
+HUF_PUBLIC_API const char* HUF_getErrorName(size_t code); /**< provides error code string (useful for debugging) */
+
+
+/* *** Advanced function *** */
+
+/** HUF_compress2() :
+ * Same as HUF_compress(), but offers control over `maxSymbolValue` and `tableLog`.
+ * `maxSymbolValue` must be <= HUF_SYMBOLVALUE_MAX .
+ * `tableLog` must be `<= HUF_TABLELOG_MAX` . */
+HUF_PUBLIC_API size_t HUF_compress2 (void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned tableLog);
+
+/** HUF_compress4X_wksp() :
+ * Same as HUF_compress2(), but uses externally allocated `workSpace`.
+ * `workspace` must have minimum alignment of 4, and be at least as large as HUF_WORKSPACE_SIZE */
+#define HUF_WORKSPACE_SIZE (6 << 10)
+#define HUF_WORKSPACE_SIZE_U32 (HUF_WORKSPACE_SIZE / sizeof(U32))
+HUF_PUBLIC_API size_t HUF_compress4X_wksp (void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned tableLog,
+ void* workSpace, size_t wkspSize);
+
+#endif /* HUF_H_298734234 */
+
+/* ******************************************************************
+ * WARNING !!
+ * The following section contains advanced and experimental definitions
+ * which shall never be used in the context of a dynamic library,
+ * because they are not guaranteed to remain stable in the future.
+ * Only consider them in association with static linking.
+ * *****************************************************************/
+#if defined(HUF_STATIC_LINKING_ONLY) && !defined(HUF_H_HUF_STATIC_LINKING_ONLY)
+#define HUF_H_HUF_STATIC_LINKING_ONLY
+
+/* *** Dependencies *** */
+#include "mem.h" /* U32 */
+
+
+/* *** Constants *** */
+#define HUF_TABLELOG_MAX 12 /* max runtime value of tableLog (due to static allocation); can be modified up to HUF_ABSOLUTEMAX_TABLELOG */
+#define HUF_TABLELOG_DEFAULT 11 /* default tableLog value when none specified */
+#define HUF_SYMBOLVALUE_MAX 255
+
+#define HUF_TABLELOG_ABSOLUTEMAX 15 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */
+#if (HUF_TABLELOG_MAX > HUF_TABLELOG_ABSOLUTEMAX)
+# error "HUF_TABLELOG_MAX is too large !"
+#endif
+
+
+/* ****************************************
+* Static allocation
+******************************************/
+/* HUF buffer bounds */
+#define HUF_CTABLEBOUND 129
+#define HUF_BLOCKBOUND(size) (size + (size>>8) + 8) /* only true when incompressible is pre-filtered with fast heuristic */
+#define HUF_COMPRESSBOUND(size) (HUF_CTABLEBOUND + HUF_BLOCKBOUND(size)) /* Macro version, useful for static allocation */
+
+/* static allocation of HUF's Compression Table */
+#define HUF_CTABLE_SIZE_U32(maxSymbolValue) ((maxSymbolValue)+1) /* Use tables of U32, for proper alignment */
+#define HUF_CTABLE_SIZE(maxSymbolValue) (HUF_CTABLE_SIZE_U32(maxSymbolValue) * sizeof(U32))
+#define HUF_CREATE_STATIC_CTABLE(name, maxSymbolValue) \
+ U32 name##hb[HUF_CTABLE_SIZE_U32(maxSymbolValue)]; \
+ void* name##hv = &(name##hb); \
+ HUF_CElt* name = (HUF_CElt*)(name##hv) /* no final ; */
+
+/* static allocation of HUF's DTable */
+typedef U32 HUF_DTable;
+#define HUF_DTABLE_SIZE(maxTableLog) (1 + (1<<(maxTableLog)))
+#define HUF_CREATE_STATIC_DTABLEX1(DTable, maxTableLog) \
+ HUF_DTable DTable[HUF_DTABLE_SIZE((maxTableLog)-1)] = { ((U32)((maxTableLog)-1) * 0x01000001) }
+#define HUF_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \
+ HUF_DTable DTable[HUF_DTABLE_SIZE(maxTableLog)] = { ((U32)(maxTableLog) * 0x01000001) }
+
+
+/* ****************************************
+* Advanced decompression functions
+******************************************/
+size_t HUF_decompress4X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< single-symbol decoder */
+#ifndef HUF_FORCE_DECOMPRESS_X1
+size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< double-symbols decoder */
+#endif
+
+size_t HUF_decompress4X_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< decodes RLE and uncompressed */
+size_t HUF_decompress4X_hufOnly(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< considers RLE and uncompressed as errors */
+size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< considers RLE and uncompressed as errors */
+size_t HUF_decompress4X1_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< single-symbol decoder */
+size_t HUF_decompress4X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< single-symbol decoder */
+#ifndef HUF_FORCE_DECOMPRESS_X1
+size_t HUF_decompress4X2_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< double-symbols decoder */
+size_t HUF_decompress4X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< double-symbols decoder */
+#endif
+
+
+/* ****************************************
+ * HUF detailed API
+ * ****************************************/
+
+/*! HUF_compress() does the following:
+ * 1. count symbol occurrence from source[] into table count[] using FSE_count() (exposed within "fse.h")
+ * 2. (optional) refine tableLog using HUF_optimalTableLog()
+ * 3. build Huffman table from count using HUF_buildCTable()
+ * 4. save Huffman table to memory buffer using HUF_writeCTable()
+ * 5. encode the data stream using HUF_compress4X_usingCTable()
+ *
+ * The following API allows targeting specific sub-functions for advanced tasks.
+ * For example, it's possible to compress several blocks using the same 'CTable',
+ * or to save and regenerate 'CTable' using external methods.
+ */
+unsigned HUF_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue);
+typedef struct HUF_CElt_s HUF_CElt; /* incomplete type */
+size_t HUF_buildCTable (HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue, unsigned maxNbBits); /* @return : maxNbBits; CTable and count can overlap. In which case, CTable will overwrite count content */
+size_t HUF_writeCTable (void* dst, size_t maxDstSize, const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog);
+size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable);
+
+typedef enum {
+ HUF_repeat_none, /**< Cannot use the previous table */
+ HUF_repeat_check, /**< Can use the previous table but it must be checked. Note : The previous table must have been constructed by HUF_compress{1, 4}X_repeat */
+ HUF_repeat_valid /**< Can use the previous table and it is assumed to be valid */
+ } HUF_repeat;
+/** HUF_compress4X_repeat() :
+ * Same as HUF_compress4X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none.
+ * If it uses hufTable it does not modify hufTable or repeat.
+ * If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used.
+ * If preferRepeat then the old table will always be used if valid. */
+size_t HUF_compress4X_repeat(void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned tableLog,
+ void* workSpace, size_t wkspSize, /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */
+ HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2);
+
+/** HUF_buildCTable_wksp() :
+ * Same as HUF_buildCTable(), but using externally allocated scratch buffer.
+ * `workSpace` must be aligned on 4-bytes boundaries, and its size must be >= HUF_CTABLE_WORKSPACE_SIZE.
+ */
+#define HUF_CTABLE_WORKSPACE_SIZE_U32 (2*HUF_SYMBOLVALUE_MAX +1 +1)
+#define HUF_CTABLE_WORKSPACE_SIZE (HUF_CTABLE_WORKSPACE_SIZE_U32 * sizeof(unsigned))
+size_t HUF_buildCTable_wksp (HUF_CElt* tree,
+ const unsigned* count, U32 maxSymbolValue, U32 maxNbBits,
+ void* workSpace, size_t wkspSize);
+
+/*! HUF_readStats() :
+ * Read compact Huffman tree, saved by HUF_writeCTable().
+ * `huffWeight` is destination buffer.
+ * @return : size read from `src` , or an error Code .
+ * Note : Needed by HUF_readCTable() and HUF_readDTableXn() . */
+size_t HUF_readStats(BYTE* huffWeight, size_t hwSize,
+ U32* rankStats, U32* nbSymbolsPtr, U32* tableLogPtr,
+ const void* src, size_t srcSize);
+
+/** HUF_readCTable() :
+ * Loading a CTable saved with HUF_writeCTable() */
+size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize);
+
+/** HUF_getNbBits() :
+ * Read nbBits from CTable symbolTable, for symbol `symbolValue` presumed <= HUF_SYMBOLVALUE_MAX
+ * Note 1 : is not inlined, as HUF_CElt definition is private
+ * Note 2 : const void* used, so that it can provide a statically allocated table as argument (which uses type U32) */
+U32 HUF_getNbBits(const void* symbolTable, U32 symbolValue);
+
+/*
+ * HUF_decompress() does the following:
+ * 1. select the decompression algorithm (X1, X2) based on pre-computed heuristics
+ * 2. build Huffman table from save, using HUF_readDTableX?()
+ * 3. decode 1 or 4 segments in parallel using HUF_decompress?X?_usingDTable()
+ */
+
+/** HUF_selectDecoder() :
+ * Tells which decoder is likely to decode faster,
+ * based on a set of pre-computed metrics.
+ * @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 .
+ * Assumption : 0 < dstSize <= 128 KB */
+U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize);
+
+/**
+ * The minimum workspace size for the `workSpace` used in
+ * HUF_readDTableX1_wksp() and HUF_readDTableX2_wksp().
+ *
+ * The space used depends on HUF_TABLELOG_MAX, ranging from ~1500 bytes when
+ * HUF_TABLE_LOG_MAX=12 to ~1850 bytes when HUF_TABLE_LOG_MAX=15.
+ * Buffer overflow errors may potentially occur if code modifications result in
+ * a required workspace size greater than that specified in the following
+ * macro.
+ */
+#define HUF_DECOMPRESS_WORKSPACE_SIZE (2 << 10)
+#define HUF_DECOMPRESS_WORKSPACE_SIZE_U32 (HUF_DECOMPRESS_WORKSPACE_SIZE / sizeof(U32))
+
+#ifndef HUF_FORCE_DECOMPRESS_X2
+size_t HUF_readDTableX1 (HUF_DTable* DTable, const void* src, size_t srcSize);
+size_t HUF_readDTableX1_wksp (HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize);
+#endif
+#ifndef HUF_FORCE_DECOMPRESS_X1
+size_t HUF_readDTableX2 (HUF_DTable* DTable, const void* src, size_t srcSize);
+size_t HUF_readDTableX2_wksp (HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize);
+#endif
+
+size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);
+#ifndef HUF_FORCE_DECOMPRESS_X2
+size_t HUF_decompress4X1_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);
+#endif
+#ifndef HUF_FORCE_DECOMPRESS_X1
+size_t HUF_decompress4X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);
+#endif
+
+
+/* ====================== */
+/* single stream variants */
+/* ====================== */
+
+size_t HUF_compress1X (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog);
+size_t HUF_compress1X_wksp (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize); /**< `workSpace` must be a table of at least HUF_WORKSPACE_SIZE_U32 unsigned */
+size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable);
+/** HUF_compress1X_repeat() :
+ * Same as HUF_compress1X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none.
+ * If it uses hufTable it does not modify hufTable or repeat.
+ * If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used.
+ * If preferRepeat then the old table will always be used if valid. */
+size_t HUF_compress1X_repeat(void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned tableLog,
+ void* workSpace, size_t wkspSize, /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */
+ HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2);
+
+size_t HUF_decompress1X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* single-symbol decoder */
+#ifndef HUF_FORCE_DECOMPRESS_X1
+size_t HUF_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* double-symbol decoder */
+#endif
+
+size_t HUF_decompress1X_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
+size_t HUF_decompress1X_DCtx_wksp (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize);
+#ifndef HUF_FORCE_DECOMPRESS_X2
+size_t HUF_decompress1X1_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< single-symbol decoder */
+size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< single-symbol decoder */
+#endif
+#ifndef HUF_FORCE_DECOMPRESS_X1
+size_t HUF_decompress1X2_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< double-symbols decoder */
+size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< double-symbols decoder */
+#endif
+
+size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable); /**< automatic selection of sing or double symbol decoder, based on DTable */
+#ifndef HUF_FORCE_DECOMPRESS_X2
+size_t HUF_decompress1X1_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);
+#endif
+#ifndef HUF_FORCE_DECOMPRESS_X1
+size_t HUF_decompress1X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);
+#endif
+
+/* BMI2 variants.
+ * If the CPU has BMI2 support, pass bmi2=1, otherwise pass bmi2=0.
+ */
+size_t HUF_decompress1X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2);
+#ifndef HUF_FORCE_DECOMPRESS_X2
+size_t HUF_decompress1X1_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2);
+#endif
+size_t HUF_decompress4X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2);
+size_t HUF_decompress4X_hufOnly_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2);
+
+#endif /* HUF_STATIC_LINKING_ONLY */
+
+#if defined (__cplusplus)
+}
+#endif
diff --git a/Utilities/cmzstd/lib/common/mem.h b/Utilities/cmzstd/lib/common/mem.h
new file mode 100644
index 000000000..5da248756
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/mem.h
@@ -0,0 +1,380 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef MEM_H_MODULE
+#define MEM_H_MODULE
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+/*-****************************************
+* Dependencies
+******************************************/
+#include <stddef.h> /* size_t, ptrdiff_t */
+#include <string.h> /* memcpy */
+
+
+/*-****************************************
+* Compiler specifics
+******************************************/
+#if defined(_MSC_VER) /* Visual Studio */
+# include <stdlib.h> /* _byteswap_ulong */
+# include <intrin.h> /* _byteswap_* */
+#endif
+#if defined(__GNUC__)
+# define MEM_STATIC static __inline __attribute__((unused))
+#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
+# define MEM_STATIC static inline
+#elif defined(_MSC_VER)
+# define MEM_STATIC static __inline
+#else
+# define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */
+#endif
+
+#ifndef __has_builtin
+# define __has_builtin(x) 0 /* compat. with non-clang compilers */
+#endif
+
+/* code only tested on 32 and 64 bits systems */
+#define MEM_STATIC_ASSERT(c) { enum { MEM_static_assert = 1/(int)(!!(c)) }; }
+MEM_STATIC void MEM_check(void) { MEM_STATIC_ASSERT((sizeof(size_t)==4) || (sizeof(size_t)==8)); }
+
+
+/*-**************************************************************
+* Basic Types
+*****************************************************************/
+#if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
+# include <stdint.h>
+ typedef uint8_t BYTE;
+ typedef uint16_t U16;
+ typedef int16_t S16;
+ typedef uint32_t U32;
+ typedef int32_t S32;
+ typedef uint64_t U64;
+ typedef int64_t S64;
+#else
+# include <limits.h>
+#if CHAR_BIT != 8
+# error "this implementation requires char to be exactly 8-bit type"
+#endif
+ typedef unsigned char BYTE;
+#if USHRT_MAX != 65535
+# error "this implementation requires short to be exactly 16-bit type"
+#endif
+ typedef unsigned short U16;
+ typedef signed short S16;
+#if UINT_MAX != 4294967295
+# error "this implementation requires int to be exactly 32-bit type"
+#endif
+ typedef unsigned int U32;
+ typedef signed int S32;
+/* note : there are no limits defined for long long type in C90.
+ * limits exist in C99, however, in such case, <stdint.h> is preferred */
+ typedef unsigned long long U64;
+ typedef signed long long S64;
+#endif
+
+
+/*-**************************************************************
+* Memory I/O
+*****************************************************************/
+/* MEM_FORCE_MEMORY_ACCESS :
+ * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
+ * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
+ * The below switch allow to select different access method for improved performance.
+ * Method 0 (default) : use `memcpy()`. Safe and portable.
+ * Method 1 : `__packed` statement. It depends on compiler extension (i.e., not portable).
+ * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
+ * Method 2 : direct access. This method is portable but violate C standard.
+ * It can generate buggy code on targets depending on alignment.
+ * In some circumstances, it's the only known way to get the most performance (i.e. GCC + ARMv6)
+ * See http://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
+ * Prefer these methods in priority order (0 > 1 > 2)
+ */
+#ifndef MEM_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */
+# if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
+# define MEM_FORCE_MEMORY_ACCESS 2
+# elif defined(__INTEL_COMPILER) || defined(__GNUC__)
+# define MEM_FORCE_MEMORY_ACCESS 1
+# endif
+#endif
+
+MEM_STATIC unsigned MEM_32bits(void) { return sizeof(size_t)==4; }
+MEM_STATIC unsigned MEM_64bits(void) { return sizeof(size_t)==8; }
+
+MEM_STATIC unsigned MEM_isLittleEndian(void)
+{
+ const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
+ return one.c[0];
+}
+
+#if defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==2)
+
+/* violates C standard, by lying on structure alignment.
+Only use if no other choice to achieve best performance on target platform */
+MEM_STATIC U16 MEM_read16(const void* memPtr) { return *(const U16*) memPtr; }
+MEM_STATIC U32 MEM_read32(const void* memPtr) { return *(const U32*) memPtr; }
+MEM_STATIC U64 MEM_read64(const void* memPtr) { return *(const U64*) memPtr; }
+MEM_STATIC size_t MEM_readST(const void* memPtr) { return *(const size_t*) memPtr; }
+
+MEM_STATIC void MEM_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
+MEM_STATIC void MEM_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
+MEM_STATIC void MEM_write64(void* memPtr, U64 value) { *(U64*)memPtr = value; }
+
+#elif defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==1)
+
+/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
+/* currently only defined for gcc and icc */
+#if defined(_MSC_VER) || (defined(__INTEL_COMPILER) && defined(WIN32))
+ __pragma( pack(push, 1) )
+ typedef struct { U16 v; } unalign16;
+ typedef struct { U32 v; } unalign32;
+ typedef struct { U64 v; } unalign64;
+ typedef struct { size_t v; } unalignArch;
+ __pragma( pack(pop) )
+#else
+ typedef struct { U16 v; } __attribute__((packed)) unalign16;
+ typedef struct { U32 v; } __attribute__((packed)) unalign32;
+ typedef struct { U64 v; } __attribute__((packed)) unalign64;
+ typedef struct { size_t v; } __attribute__((packed)) unalignArch;
+#endif
+
+MEM_STATIC U16 MEM_read16(const void* ptr) { return ((const unalign16*)ptr)->v; }
+MEM_STATIC U32 MEM_read32(const void* ptr) { return ((const unalign32*)ptr)->v; }
+MEM_STATIC U64 MEM_read64(const void* ptr) { return ((const unalign64*)ptr)->v; }
+MEM_STATIC size_t MEM_readST(const void* ptr) { return ((const unalignArch*)ptr)->v; }
+
+MEM_STATIC void MEM_write16(void* memPtr, U16 value) { ((unalign16*)memPtr)->v = value; }
+MEM_STATIC void MEM_write32(void* memPtr, U32 value) { ((unalign32*)memPtr)->v = value; }
+MEM_STATIC void MEM_write64(void* memPtr, U64 value) { ((unalign64*)memPtr)->v = value; }
+
+#else
+
+/* default method, safe and standard.
+ can sometimes prove slower */
+
+MEM_STATIC U16 MEM_read16(const void* memPtr)
+{
+ U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+MEM_STATIC U32 MEM_read32(const void* memPtr)
+{
+ U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+MEM_STATIC U64 MEM_read64(const void* memPtr)
+{
+ U64 val; memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+MEM_STATIC size_t MEM_readST(const void* memPtr)
+{
+ size_t val; memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+MEM_STATIC void MEM_write16(void* memPtr, U16 value)
+{
+ memcpy(memPtr, &value, sizeof(value));
+}
+
+MEM_STATIC void MEM_write32(void* memPtr, U32 value)
+{
+ memcpy(memPtr, &value, sizeof(value));
+}
+
+MEM_STATIC void MEM_write64(void* memPtr, U64 value)
+{
+ memcpy(memPtr, &value, sizeof(value));
+}
+
+#endif /* MEM_FORCE_MEMORY_ACCESS */
+
+MEM_STATIC U32 MEM_swap32(U32 in)
+{
+#if defined(_MSC_VER) /* Visual Studio */
+ return _byteswap_ulong(in);
+#elif (defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) \
+ || (defined(__clang__) && __has_builtin(__builtin_bswap32))
+ return __builtin_bswap32(in);
+#else
+ return ((in << 24) & 0xff000000 ) |
+ ((in << 8) & 0x00ff0000 ) |
+ ((in >> 8) & 0x0000ff00 ) |
+ ((in >> 24) & 0x000000ff );
+#endif
+}
+
+MEM_STATIC U64 MEM_swap64(U64 in)
+{
+#if defined(_MSC_VER) /* Visual Studio */
+ return _byteswap_uint64(in);
+#elif (defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) \
+ || (defined(__clang__) && __has_builtin(__builtin_bswap64))
+ return __builtin_bswap64(in);
+#else
+ return ((in << 56) & 0xff00000000000000ULL) |
+ ((in << 40) & 0x00ff000000000000ULL) |
+ ((in << 24) & 0x0000ff0000000000ULL) |
+ ((in << 8) & 0x000000ff00000000ULL) |
+ ((in >> 8) & 0x00000000ff000000ULL) |
+ ((in >> 24) & 0x0000000000ff0000ULL) |
+ ((in >> 40) & 0x000000000000ff00ULL) |
+ ((in >> 56) & 0x00000000000000ffULL);
+#endif
+}
+
+MEM_STATIC size_t MEM_swapST(size_t in)
+{
+ if (MEM_32bits())
+ return (size_t)MEM_swap32((U32)in);
+ else
+ return (size_t)MEM_swap64((U64)in);
+}
+
+/*=== Little endian r/w ===*/
+
+MEM_STATIC U16 MEM_readLE16(const void* memPtr)
+{
+ if (MEM_isLittleEndian())
+ return MEM_read16(memPtr);
+ else {
+ const BYTE* p = (const BYTE*)memPtr;
+ return (U16)(p[0] + (p[1]<<8));
+ }
+}
+
+MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val)
+{
+ if (MEM_isLittleEndian()) {
+ MEM_write16(memPtr, val);
+ } else {
+ BYTE* p = (BYTE*)memPtr;
+ p[0] = (BYTE)val;
+ p[1] = (BYTE)(val>>8);
+ }
+}
+
+MEM_STATIC U32 MEM_readLE24(const void* memPtr)
+{
+ return MEM_readLE16(memPtr) + (((const BYTE*)memPtr)[2] << 16);
+}
+
+MEM_STATIC void MEM_writeLE24(void* memPtr, U32 val)
+{
+ MEM_writeLE16(memPtr, (U16)val);
+ ((BYTE*)memPtr)[2] = (BYTE)(val>>16);
+}
+
+MEM_STATIC U32 MEM_readLE32(const void* memPtr)
+{
+ if (MEM_isLittleEndian())
+ return MEM_read32(memPtr);
+ else
+ return MEM_swap32(MEM_read32(memPtr));
+}
+
+MEM_STATIC void MEM_writeLE32(void* memPtr, U32 val32)
+{
+ if (MEM_isLittleEndian())
+ MEM_write32(memPtr, val32);
+ else
+ MEM_write32(memPtr, MEM_swap32(val32));
+}
+
+MEM_STATIC U64 MEM_readLE64(const void* memPtr)
+{
+ if (MEM_isLittleEndian())
+ return MEM_read64(memPtr);
+ else
+ return MEM_swap64(MEM_read64(memPtr));
+}
+
+MEM_STATIC void MEM_writeLE64(void* memPtr, U64 val64)
+{
+ if (MEM_isLittleEndian())
+ MEM_write64(memPtr, val64);
+ else
+ MEM_write64(memPtr, MEM_swap64(val64));
+}
+
+MEM_STATIC size_t MEM_readLEST(const void* memPtr)
+{
+ if (MEM_32bits())
+ return (size_t)MEM_readLE32(memPtr);
+ else
+ return (size_t)MEM_readLE64(memPtr);
+}
+
+MEM_STATIC void MEM_writeLEST(void* memPtr, size_t val)
+{
+ if (MEM_32bits())
+ MEM_writeLE32(memPtr, (U32)val);
+ else
+ MEM_writeLE64(memPtr, (U64)val);
+}
+
+/*=== Big endian r/w ===*/
+
+MEM_STATIC U32 MEM_readBE32(const void* memPtr)
+{
+ if (MEM_isLittleEndian())
+ return MEM_swap32(MEM_read32(memPtr));
+ else
+ return MEM_read32(memPtr);
+}
+
+MEM_STATIC void MEM_writeBE32(void* memPtr, U32 val32)
+{
+ if (MEM_isLittleEndian())
+ MEM_write32(memPtr, MEM_swap32(val32));
+ else
+ MEM_write32(memPtr, val32);
+}
+
+MEM_STATIC U64 MEM_readBE64(const void* memPtr)
+{
+ if (MEM_isLittleEndian())
+ return MEM_swap64(MEM_read64(memPtr));
+ else
+ return MEM_read64(memPtr);
+}
+
+MEM_STATIC void MEM_writeBE64(void* memPtr, U64 val64)
+{
+ if (MEM_isLittleEndian())
+ MEM_write64(memPtr, MEM_swap64(val64));
+ else
+ MEM_write64(memPtr, val64);
+}
+
+MEM_STATIC size_t MEM_readBEST(const void* memPtr)
+{
+ if (MEM_32bits())
+ return (size_t)MEM_readBE32(memPtr);
+ else
+ return (size_t)MEM_readBE64(memPtr);
+}
+
+MEM_STATIC void MEM_writeBEST(void* memPtr, size_t val)
+{
+ if (MEM_32bits())
+ MEM_writeBE32(memPtr, (U32)val);
+ else
+ MEM_writeBE64(memPtr, (U64)val);
+}
+
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* MEM_H_MODULE */
diff --git a/Utilities/cmzstd/lib/common/pool.c b/Utilities/cmzstd/lib/common/pool.c
new file mode 100644
index 000000000..7a8294543
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/pool.c
@@ -0,0 +1,340 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+
+/* ====== Dependencies ======= */
+#include <stddef.h> /* size_t */
+#include "debug.h" /* assert */
+#include "zstd_internal.h" /* ZSTD_malloc, ZSTD_free */
+#include "pool.h"
+
+/* ====== Compiler specifics ====== */
+#if defined(_MSC_VER)
+# pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
+#endif
+
+
+#ifdef ZSTD_MULTITHREAD
+
+#include "threading.h" /* pthread adaptation */
+
+/* A job is a function and an opaque argument */
+typedef struct POOL_job_s {
+ POOL_function function;
+ void *opaque;
+} POOL_job;
+
+struct POOL_ctx_s {
+ ZSTD_customMem customMem;
+ /* Keep track of the threads */
+ ZSTD_pthread_t* threads;
+ size_t threadCapacity;
+ size_t threadLimit;
+
+ /* The queue is a circular buffer */
+ POOL_job *queue;
+ size_t queueHead;
+ size_t queueTail;
+ size_t queueSize;
+
+ /* The number of threads working on jobs */
+ size_t numThreadsBusy;
+ /* Indicates if the queue is empty */
+ int queueEmpty;
+
+ /* The mutex protects the queue */
+ ZSTD_pthread_mutex_t queueMutex;
+ /* Condition variable for pushers to wait on when the queue is full */
+ ZSTD_pthread_cond_t queuePushCond;
+ /* Condition variables for poppers to wait on when the queue is empty */
+ ZSTD_pthread_cond_t queuePopCond;
+ /* Indicates if the queue is shutting down */
+ int shutdown;
+};
+
+/* POOL_thread() :
+ * Work thread for the thread pool.
+ * Waits for jobs and executes them.
+ * @returns : NULL on failure else non-null.
+ */
+static void* POOL_thread(void* opaque) {
+ POOL_ctx* const ctx = (POOL_ctx*)opaque;
+ if (!ctx) { return NULL; }
+ for (;;) {
+ /* Lock the mutex and wait for a non-empty queue or until shutdown */
+ ZSTD_pthread_mutex_lock(&ctx->queueMutex);
+
+ while ( ctx->queueEmpty
+ || (ctx->numThreadsBusy >= ctx->threadLimit) ) {
+ if (ctx->shutdown) {
+ /* even if !queueEmpty, (possible if numThreadsBusy >= threadLimit),
+ * a few threads will be shutdown while !queueEmpty,
+ * but enough threads will remain active to finish the queue */
+ ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
+ return opaque;
+ }
+ ZSTD_pthread_cond_wait(&ctx->queuePopCond, &ctx->queueMutex);
+ }
+ /* Pop a job off the queue */
+ { POOL_job const job = ctx->queue[ctx->queueHead];
+ ctx->queueHead = (ctx->queueHead + 1) % ctx->queueSize;
+ ctx->numThreadsBusy++;
+ ctx->queueEmpty = ctx->queueHead == ctx->queueTail;
+ /* Unlock the mutex, signal a pusher, and run the job */
+ ZSTD_pthread_cond_signal(&ctx->queuePushCond);
+ ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
+
+ job.function(job.opaque);
+
+ /* If the intended queue size was 0, signal after finishing job */
+ ZSTD_pthread_mutex_lock(&ctx->queueMutex);
+ ctx->numThreadsBusy--;
+ if (ctx->queueSize == 1) {
+ ZSTD_pthread_cond_signal(&ctx->queuePushCond);
+ }
+ ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
+ }
+ } /* for (;;) */
+ assert(0); /* Unreachable */
+}
+
+POOL_ctx* POOL_create(size_t numThreads, size_t queueSize) {
+ return POOL_create_advanced(numThreads, queueSize, ZSTD_defaultCMem);
+}
+
+POOL_ctx* POOL_create_advanced(size_t numThreads, size_t queueSize,
+ ZSTD_customMem customMem) {
+ POOL_ctx* ctx;
+ /* Check parameters */
+ if (!numThreads) { return NULL; }
+ /* Allocate the context and zero initialize */
+ ctx = (POOL_ctx*)ZSTD_calloc(sizeof(POOL_ctx), customMem);
+ if (!ctx) { return NULL; }
+ /* Initialize the job queue.
+ * It needs one extra space since one space is wasted to differentiate
+ * empty and full queues.
+ */
+ ctx->queueSize = queueSize + 1;
+ ctx->queue = (POOL_job*)ZSTD_malloc(ctx->queueSize * sizeof(POOL_job), customMem);
+ ctx->queueHead = 0;
+ ctx->queueTail = 0;
+ ctx->numThreadsBusy = 0;
+ ctx->queueEmpty = 1;
+ (void)ZSTD_pthread_mutex_init(&ctx->queueMutex, NULL);
+ (void)ZSTD_pthread_cond_init(&ctx->queuePushCond, NULL);
+ (void)ZSTD_pthread_cond_init(&ctx->queuePopCond, NULL);
+ ctx->shutdown = 0;
+ /* Allocate space for the thread handles */
+ ctx->threads = (ZSTD_pthread_t*)ZSTD_malloc(numThreads * sizeof(ZSTD_pthread_t), customMem);
+ ctx->threadCapacity = 0;
+ ctx->customMem = customMem;
+ /* Check for errors */
+ if (!ctx->threads || !ctx->queue) { POOL_free(ctx); return NULL; }
+ /* Initialize the threads */
+ { size_t i;
+ for (i = 0; i < numThreads; ++i) {
+ if (ZSTD_pthread_create(&ctx->threads[i], NULL, &POOL_thread, ctx)) {
+ ctx->threadCapacity = i;
+ POOL_free(ctx);
+ return NULL;
+ } }
+ ctx->threadCapacity = numThreads;
+ ctx->threadLimit = numThreads;
+ }
+ return ctx;
+}
+
+/*! POOL_join() :
+ Shutdown the queue, wake any sleeping threads, and join all of the threads.
+*/
+static void POOL_join(POOL_ctx* ctx) {
+ /* Shut down the queue */
+ ZSTD_pthread_mutex_lock(&ctx->queueMutex);
+ ctx->shutdown = 1;
+ ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
+ /* Wake up sleeping threads */
+ ZSTD_pthread_cond_broadcast(&ctx->queuePushCond);
+ ZSTD_pthread_cond_broadcast(&ctx->queuePopCond);
+ /* Join all of the threads */
+ { size_t i;
+ for (i = 0; i < ctx->threadCapacity; ++i) {
+ ZSTD_pthread_join(ctx->threads[i], NULL); /* note : could fail */
+ } }
+}
+
+void POOL_free(POOL_ctx *ctx) {
+ if (!ctx) { return; }
+ POOL_join(ctx);
+ ZSTD_pthread_mutex_destroy(&ctx->queueMutex);
+ ZSTD_pthread_cond_destroy(&ctx->queuePushCond);
+ ZSTD_pthread_cond_destroy(&ctx->queuePopCond);
+ ZSTD_free(ctx->queue, ctx->customMem);
+ ZSTD_free(ctx->threads, ctx->customMem);
+ ZSTD_free(ctx, ctx->customMem);
+}
+
+
+
+size_t POOL_sizeof(POOL_ctx *ctx) {
+ if (ctx==NULL) return 0; /* supports sizeof NULL */
+ return sizeof(*ctx)
+ + ctx->queueSize * sizeof(POOL_job)
+ + ctx->threadCapacity * sizeof(ZSTD_pthread_t);
+}
+
+
+/* @return : 0 on success, 1 on error */
+static int POOL_resize_internal(POOL_ctx* ctx, size_t numThreads)
+{
+ if (numThreads <= ctx->threadCapacity) {
+ if (!numThreads) return 1;
+ ctx->threadLimit = numThreads;
+ return 0;
+ }
+ /* numThreads > threadCapacity */
+ { ZSTD_pthread_t* const threadPool = (ZSTD_pthread_t*)ZSTD_malloc(numThreads * sizeof(ZSTD_pthread_t), ctx->customMem);
+ if (!threadPool) return 1;
+ /* replace existing thread pool */
+ memcpy(threadPool, ctx->threads, ctx->threadCapacity * sizeof(*threadPool));
+ ZSTD_free(ctx->threads, ctx->customMem);
+ ctx->threads = threadPool;
+ /* Initialize additional threads */
+ { size_t threadId;
+ for (threadId = ctx->threadCapacity; threadId < numThreads; ++threadId) {
+ if (ZSTD_pthread_create(&threadPool[threadId], NULL, &POOL_thread, ctx)) {
+ ctx->threadCapacity = threadId;
+ return 1;
+ } }
+ } }
+ /* successfully expanded */
+ ctx->threadCapacity = numThreads;
+ ctx->threadLimit = numThreads;
+ return 0;
+}
+
+/* @return : 0 on success, 1 on error */
+int POOL_resize(POOL_ctx* ctx, size_t numThreads)
+{
+ int result;
+ if (ctx==NULL) return 1;
+ ZSTD_pthread_mutex_lock(&ctx->queueMutex);
+ result = POOL_resize_internal(ctx, numThreads);
+ ZSTD_pthread_cond_broadcast(&ctx->queuePopCond);
+ ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
+ return result;
+}
+
+/**
+ * Returns 1 if the queue is full and 0 otherwise.
+ *
+ * When queueSize is 1 (pool was created with an intended queueSize of 0),
+ * then a queue is empty if there is a thread free _and_ no job is waiting.
+ */
+static int isQueueFull(POOL_ctx const* ctx) {
+ if (ctx->queueSize > 1) {
+ return ctx->queueHead == ((ctx->queueTail + 1) % ctx->queueSize);
+ } else {
+ return (ctx->numThreadsBusy == ctx->threadLimit) ||
+ !ctx->queueEmpty;
+ }
+}
+
+
+static void POOL_add_internal(POOL_ctx* ctx, POOL_function function, void *opaque)
+{
+ POOL_job const job = {function, opaque};
+ assert(ctx != NULL);
+ if (ctx->shutdown) return;
+
+ ctx->queueEmpty = 0;
+ ctx->queue[ctx->queueTail] = job;
+ ctx->queueTail = (ctx->queueTail + 1) % ctx->queueSize;
+ ZSTD_pthread_cond_signal(&ctx->queuePopCond);
+}
+
+void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque)
+{
+ assert(ctx != NULL);
+ ZSTD_pthread_mutex_lock(&ctx->queueMutex);
+ /* Wait until there is space in the queue for the new job */
+ while (isQueueFull(ctx) && (!ctx->shutdown)) {
+ ZSTD_pthread_cond_wait(&ctx->queuePushCond, &ctx->queueMutex);
+ }
+ POOL_add_internal(ctx, function, opaque);
+ ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
+}
+
+
+int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque)
+{
+ assert(ctx != NULL);
+ ZSTD_pthread_mutex_lock(&ctx->queueMutex);
+ if (isQueueFull(ctx)) {
+ ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
+ return 0;
+ }
+ POOL_add_internal(ctx, function, opaque);
+ ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
+ return 1;
+}
+
+
+#else /* ZSTD_MULTITHREAD not defined */
+
+/* ========================== */
+/* No multi-threading support */
+/* ========================== */
+
+
+/* We don't need any data, but if it is empty, malloc() might return NULL. */
+struct POOL_ctx_s {
+ int dummy;
+};
+static POOL_ctx g_ctx;
+
+POOL_ctx* POOL_create(size_t numThreads, size_t queueSize) {
+ return POOL_create_advanced(numThreads, queueSize, ZSTD_defaultCMem);
+}
+
+POOL_ctx* POOL_create_advanced(size_t numThreads, size_t queueSize, ZSTD_customMem customMem) {
+ (void)numThreads;
+ (void)queueSize;
+ (void)customMem;
+ return &g_ctx;
+}
+
+void POOL_free(POOL_ctx* ctx) {
+ assert(!ctx || ctx == &g_ctx);
+ (void)ctx;
+}
+
+int POOL_resize(POOL_ctx* ctx, size_t numThreads) {
+ (void)ctx; (void)numThreads;
+ return 0;
+}
+
+void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque) {
+ (void)ctx;
+ function(opaque);
+}
+
+int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque) {
+ (void)ctx;
+ function(opaque);
+ return 1;
+}
+
+size_t POOL_sizeof(POOL_ctx* ctx) {
+ if (ctx==NULL) return 0; /* supports sizeof NULL */
+ assert(ctx == &g_ctx);
+ return sizeof(*ctx);
+}
+
+#endif /* ZSTD_MULTITHREAD */
diff --git a/Utilities/cmzstd/lib/common/pool.h b/Utilities/cmzstd/lib/common/pool.h
new file mode 100644
index 000000000..458d37f13
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/pool.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef POOL_H
+#define POOL_H
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+
+#include <stddef.h> /* size_t */
+#define ZSTD_STATIC_LINKING_ONLY /* ZSTD_customMem */
+#include "zstd.h"
+
+typedef struct POOL_ctx_s POOL_ctx;
+
+/*! POOL_create() :
+ * Create a thread pool with at most `numThreads` threads.
+ * `numThreads` must be at least 1.
+ * The maximum number of queued jobs before blocking is `queueSize`.
+ * @return : POOL_ctx pointer on success, else NULL.
+*/
+POOL_ctx* POOL_create(size_t numThreads, size_t queueSize);
+
+POOL_ctx* POOL_create_advanced(size_t numThreads, size_t queueSize,
+ ZSTD_customMem customMem);
+
+/*! POOL_free() :
+ * Free a thread pool returned by POOL_create().
+ */
+void POOL_free(POOL_ctx* ctx);
+
+/*! POOL_resize() :
+ * Expands or shrinks pool's number of threads.
+ * This is more efficient than releasing + creating a new context,
+ * since it tries to preserve and re-use existing threads.
+ * `numThreads` must be at least 1.
+ * @return : 0 when resize was successful,
+ * !0 (typically 1) if there is an error.
+ * note : only numThreads can be resized, queueSize remains unchanged.
+ */
+int POOL_resize(POOL_ctx* ctx, size_t numThreads);
+
+/*! POOL_sizeof() :
+ * @return threadpool memory usage
+ * note : compatible with NULL (returns 0 in this case)
+ */
+size_t POOL_sizeof(POOL_ctx* ctx);
+
+/*! POOL_function :
+ * The function type that can be added to a thread pool.
+ */
+typedef void (*POOL_function)(void*);
+
+/*! POOL_add() :
+ * Add the job `function(opaque)` to the thread pool. `ctx` must be valid.
+ * Possibly blocks until there is room in the queue.
+ * Note : The function may be executed asynchronously,
+ * therefore, `opaque` must live until function has been completed.
+ */
+void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque);
+
+
+/*! POOL_tryAdd() :
+ * Add the job `function(opaque)` to thread pool _if_ a worker is available.
+ * Returns immediately even if not (does not block).
+ * @return : 1 if successful, 0 if not.
+ */
+int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque);
+
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif
diff --git a/Utilities/cmzstd/lib/common/threading.c b/Utilities/cmzstd/lib/common/threading.c
new file mode 100644
index 000000000..8be8c8da9
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/threading.c
@@ -0,0 +1,75 @@
+/**
+ * Copyright (c) 2016 Tino Reichardt
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ *
+ * You can contact the author at:
+ * - zstdmt source repository: https://github.com/mcmilk/zstdmt
+ */
+
+/**
+ * This file will hold wrapper for systems, which do not support pthreads
+ */
+
+/* create fake symbol to avoid empty trnaslation unit warning */
+int g_ZSTD_threading_useles_symbol;
+
+#if defined(ZSTD_MULTITHREAD) && defined(_WIN32)
+
+/**
+ * Windows minimalist Pthread Wrapper, based on :
+ * http://www.cse.wustl.edu/~schmidt/win32-cv-1.html
+ */
+
+
+/* === Dependencies === */
+#include <process.h>
+#include <errno.h>
+#include "threading.h"
+
+
+/* === Implementation === */
+
+static unsigned __stdcall worker(void *arg)
+{
+ ZSTD_pthread_t* const thread = (ZSTD_pthread_t*) arg;
+ thread->arg = thread->start_routine(thread->arg);
+ return 0;
+}
+
+int ZSTD_pthread_create(ZSTD_pthread_t* thread, const void* unused,
+ void* (*start_routine) (void*), void* arg)
+{
+ (void)unused;
+ thread->arg = arg;
+ thread->start_routine = start_routine;
+ thread->handle = (HANDLE) _beginthreadex(NULL, 0, worker, thread, 0, NULL);
+
+ if (!thread->handle)
+ return errno;
+ else
+ return 0;
+}
+
+int ZSTD_pthread_join(ZSTD_pthread_t thread, void **value_ptr)
+{
+ DWORD result;
+
+ if (!thread.handle) return 0;
+
+ result = WaitForSingleObject(thread.handle, INFINITE);
+ switch (result) {
+ case WAIT_OBJECT_0:
+ if (value_ptr) *value_ptr = thread.arg;
+ return 0;
+ case WAIT_ABANDONED:
+ return EINVAL;
+ default:
+ return GetLastError();
+ }
+}
+
+#endif /* ZSTD_MULTITHREAD */
diff --git a/Utilities/cmzstd/lib/common/threading.h b/Utilities/cmzstd/lib/common/threading.h
new file mode 100644
index 000000000..d806c89d0
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/threading.h
@@ -0,0 +1,123 @@
+/**
+ * Copyright (c) 2016 Tino Reichardt
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ *
+ * You can contact the author at:
+ * - zstdmt source repository: https://github.com/mcmilk/zstdmt
+ */
+
+#ifndef THREADING_H_938743
+#define THREADING_H_938743
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#if defined(ZSTD_MULTITHREAD) && defined(_WIN32)
+
+/**
+ * Windows minimalist Pthread Wrapper, based on :
+ * http://www.cse.wustl.edu/~schmidt/win32-cv-1.html
+ */
+#ifdef WINVER
+# undef WINVER
+#endif
+#define WINVER 0x0600
+
+#ifdef _WIN32_WINNT
+# undef _WIN32_WINNT
+#endif
+#define _WIN32_WINNT 0x0600
+
+#ifndef WIN32_LEAN_AND_MEAN
+# define WIN32_LEAN_AND_MEAN
+#endif
+
+#undef ERROR /* reported already defined on VS 2015 (Rich Geldreich) */
+#include <windows.h>
+#undef ERROR
+#define ERROR(name) ZSTD_ERROR(name)
+
+
+/* mutex */
+#define ZSTD_pthread_mutex_t CRITICAL_SECTION
+#define ZSTD_pthread_mutex_init(a, b) ((void)(b), InitializeCriticalSection((a)), 0)
+#define ZSTD_pthread_mutex_destroy(a) DeleteCriticalSection((a))
+#define ZSTD_pthread_mutex_lock(a) EnterCriticalSection((a))
+#define ZSTD_pthread_mutex_unlock(a) LeaveCriticalSection((a))
+
+/* condition variable */
+#define ZSTD_pthread_cond_t CONDITION_VARIABLE
+#define ZSTD_pthread_cond_init(a, b) ((void)(b), InitializeConditionVariable((a)), 0)
+#define ZSTD_pthread_cond_destroy(a) ((void)(a))
+#define ZSTD_pthread_cond_wait(a, b) SleepConditionVariableCS((a), (b), INFINITE)
+#define ZSTD_pthread_cond_signal(a) WakeConditionVariable((a))
+#define ZSTD_pthread_cond_broadcast(a) WakeAllConditionVariable((a))
+
+/* ZSTD_pthread_create() and ZSTD_pthread_join() */
+typedef struct {
+ HANDLE handle;
+ void* (*start_routine)(void*);
+ void* arg;
+} ZSTD_pthread_t;
+
+int ZSTD_pthread_create(ZSTD_pthread_t* thread, const void* unused,
+ void* (*start_routine) (void*), void* arg);
+
+int ZSTD_pthread_join(ZSTD_pthread_t thread, void** value_ptr);
+
+/**
+ * add here more wrappers as required
+ */
+
+
+#elif defined(ZSTD_MULTITHREAD) /* posix assumed ; need a better detection method */
+/* === POSIX Systems === */
+# include <pthread.h>
+
+#define ZSTD_pthread_mutex_t pthread_mutex_t
+#define ZSTD_pthread_mutex_init(a, b) pthread_mutex_init((a), (b))
+#define ZSTD_pthread_mutex_destroy(a) pthread_mutex_destroy((a))
+#define ZSTD_pthread_mutex_lock(a) pthread_mutex_lock((a))
+#define ZSTD_pthread_mutex_unlock(a) pthread_mutex_unlock((a))
+
+#define ZSTD_pthread_cond_t pthread_cond_t
+#define ZSTD_pthread_cond_init(a, b) pthread_cond_init((a), (b))
+#define ZSTD_pthread_cond_destroy(a) pthread_cond_destroy((a))
+#define ZSTD_pthread_cond_wait(a, b) pthread_cond_wait((a), (b))
+#define ZSTD_pthread_cond_signal(a) pthread_cond_signal((a))
+#define ZSTD_pthread_cond_broadcast(a) pthread_cond_broadcast((a))
+
+#define ZSTD_pthread_t pthread_t
+#define ZSTD_pthread_create(a, b, c, d) pthread_create((a), (b), (c), (d))
+#define ZSTD_pthread_join(a, b) pthread_join((a),(b))
+
+#else /* ZSTD_MULTITHREAD not defined */
+/* No multithreading support */
+
+typedef int ZSTD_pthread_mutex_t;
+#define ZSTD_pthread_mutex_init(a, b) ((void)(a), (void)(b), 0)
+#define ZSTD_pthread_mutex_destroy(a) ((void)(a))
+#define ZSTD_pthread_mutex_lock(a) ((void)(a))
+#define ZSTD_pthread_mutex_unlock(a) ((void)(a))
+
+typedef int ZSTD_pthread_cond_t;
+#define ZSTD_pthread_cond_init(a, b) ((void)(a), (void)(b), 0)
+#define ZSTD_pthread_cond_destroy(a) ((void)(a))
+#define ZSTD_pthread_cond_wait(a, b) ((void)(a), (void)(b))
+#define ZSTD_pthread_cond_signal(a) ((void)(a))
+#define ZSTD_pthread_cond_broadcast(a) ((void)(a))
+
+/* do not use ZSTD_pthread_t */
+
+#endif /* ZSTD_MULTITHREAD */
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* THREADING_H_938743 */
diff --git a/Utilities/cmzstd/lib/common/xxhash.c b/Utilities/cmzstd/lib/common/xxhash.c
new file mode 100644
index 000000000..532b81619
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/xxhash.c
@@ -0,0 +1,876 @@
+/*
+* xxHash - Fast Hash algorithm
+* Copyright (C) 2012-2016, Yann Collet
+*
+* BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are
+* met:
+*
+* * Redistributions of source code must retain the above copyright
+* notice, this list of conditions and the following disclaimer.
+* * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+* OWNER 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.
+*
+* You can contact the author at :
+* - xxHash homepage: http://www.xxhash.com
+* - xxHash source repository : https://github.com/Cyan4973/xxHash
+*/
+
+
+/* *************************************
+* Tuning parameters
+***************************************/
+/*!XXH_FORCE_MEMORY_ACCESS :
+ * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
+ * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
+ * The below switch allow to select different access method for improved performance.
+ * Method 0 (default) : use `memcpy()`. Safe and portable.
+ * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
+ * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
+ * Method 2 : direct access. This method doesn't depend on compiler but violate C standard.
+ * It can generate buggy code on targets which do not support unaligned memory accesses.
+ * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
+ * See http://stackoverflow.com/a/32095106/646947 for details.
+ * Prefer these methods in priority order (0 > 1 > 2)
+ */
+#ifndef XXH_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */
+# if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
+# define XXH_FORCE_MEMORY_ACCESS 2
+# elif (defined(__INTEL_COMPILER) && !defined(WIN32)) || \
+ (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) ))
+# define XXH_FORCE_MEMORY_ACCESS 1
+# endif
+#endif
+
+/*!XXH_ACCEPT_NULL_INPUT_POINTER :
+ * If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer.
+ * When this option is enabled, xxHash output for null input pointers will be the same as a null-length input.
+ * By default, this option is disabled. To enable it, uncomment below define :
+ */
+/* #define XXH_ACCEPT_NULL_INPUT_POINTER 1 */
+
+/*!XXH_FORCE_NATIVE_FORMAT :
+ * By default, xxHash library provides endian-independant Hash values, based on little-endian convention.
+ * Results are therefore identical for little-endian and big-endian CPU.
+ * This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format.
+ * Should endian-independance be of no importance for your application, you may set the #define below to 1,
+ * to improve speed for Big-endian CPU.
+ * This option has no impact on Little_Endian CPU.
+ */
+#ifndef XXH_FORCE_NATIVE_FORMAT /* can be defined externally */
+# define XXH_FORCE_NATIVE_FORMAT 0
+#endif
+
+/*!XXH_FORCE_ALIGN_CHECK :
+ * This is a minor performance trick, only useful with lots of very small keys.
+ * It means : check for aligned/unaligned input.
+ * The check costs one initial branch per hash; set to 0 when the input data
+ * is guaranteed to be aligned.
+ */
+#ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */
+# if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
+# define XXH_FORCE_ALIGN_CHECK 0
+# else
+# define XXH_FORCE_ALIGN_CHECK 1
+# endif
+#endif
+
+
+/* *************************************
+* Includes & Memory related functions
+***************************************/
+/* Modify the local functions below should you wish to use some other memory routines */
+/* for malloc(), free() */
+#include <stdlib.h>
+#include <stddef.h> /* size_t */
+static void* XXH_malloc(size_t s) { return malloc(s); }
+static void XXH_free (void* p) { free(p); }
+/* for memcpy() */
+#include <string.h>
+static void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest,src,size); }
+
+#ifndef XXH_STATIC_LINKING_ONLY
+# define XXH_STATIC_LINKING_ONLY
+#endif
+#include "xxhash.h"
+
+
+/* *************************************
+* Compiler Specific Options
+***************************************/
+#if defined (__GNUC__) || defined(__cplusplus) || defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
+# define INLINE_KEYWORD inline
+#else
+# define INLINE_KEYWORD
+#endif
+
+#if defined(__GNUC__)
+# define FORCE_INLINE_ATTR __attribute__((always_inline))
+#elif defined(_MSC_VER)
+# define FORCE_INLINE_ATTR __forceinline
+#else
+# define FORCE_INLINE_ATTR
+#endif
+
+#define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR
+
+
+#ifdef _MSC_VER
+# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
+#endif
+
+
+/* *************************************
+* Basic Types
+***************************************/
+#ifndef MEM_MODULE
+# define MEM_MODULE
+# if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
+# include <stdint.h>
+ typedef uint8_t BYTE;
+ typedef uint16_t U16;
+ typedef uint32_t U32;
+ typedef int32_t S32;
+ typedef uint64_t U64;
+# else
+ typedef unsigned char BYTE;
+ typedef unsigned short U16;
+ typedef unsigned int U32;
+ typedef signed int S32;
+ typedef unsigned long long U64; /* if your compiler doesn't support unsigned long long, replace by another 64-bit type here. Note that xxhash.h will also need to be updated. */
+# endif
+#endif
+
+
+#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2))
+
+/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */
+static U32 XXH_read32(const void* memPtr) { return *(const U32*) memPtr; }
+static U64 XXH_read64(const void* memPtr) { return *(const U64*) memPtr; }
+
+#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1))
+
+/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
+/* currently only defined for gcc and icc */
+typedef union { U32 u32; U64 u64; } __attribute__((packed)) unalign;
+
+static U32 XXH_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
+static U64 XXH_read64(const void* ptr) { return ((const unalign*)ptr)->u64; }
+
+#else
+
+/* portable and safe solution. Generally efficient.
+ * see : http://stackoverflow.com/a/32095106/646947
+ */
+
+static U32 XXH_read32(const void* memPtr)
+{
+ U32 val;
+ memcpy(&val, memPtr, sizeof(val));
+ return val;
+}
+
+static U64 XXH_read64(const void* memPtr)
+{
+ U64 val;
+ memcpy(&val, memPtr, sizeof(val));
+ return val;
+}
+
+#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */
+
+
+/* ****************************************
+* Compiler-specific Functions and Macros
+******************************************/
+#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+
+/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */
+#if defined(_MSC_VER)
+# define XXH_rotl32(x,r) _rotl(x,r)
+# define XXH_rotl64(x,r) _rotl64(x,r)
+#else
+# define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r)))
+# define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r)))
+#endif
+
+#if defined(_MSC_VER) /* Visual Studio */
+# define XXH_swap32 _byteswap_ulong
+# define XXH_swap64 _byteswap_uint64
+#elif GCC_VERSION >= 403
+# define XXH_swap32 __builtin_bswap32
+# define XXH_swap64 __builtin_bswap64
+#else
+static U32 XXH_swap32 (U32 x)
+{
+ return ((x << 24) & 0xff000000 ) |
+ ((x << 8) & 0x00ff0000 ) |
+ ((x >> 8) & 0x0000ff00 ) |
+ ((x >> 24) & 0x000000ff );
+}
+static U64 XXH_swap64 (U64 x)
+{
+ return ((x << 56) & 0xff00000000000000ULL) |
+ ((x << 40) & 0x00ff000000000000ULL) |
+ ((x << 24) & 0x0000ff0000000000ULL) |
+ ((x << 8) & 0x000000ff00000000ULL) |
+ ((x >> 8) & 0x00000000ff000000ULL) |
+ ((x >> 24) & 0x0000000000ff0000ULL) |
+ ((x >> 40) & 0x000000000000ff00ULL) |
+ ((x >> 56) & 0x00000000000000ffULL);
+}
+#endif
+
+
+/* *************************************
+* Architecture Macros
+***************************************/
+typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess;
+
+/* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler command line */
+#ifndef XXH_CPU_LITTLE_ENDIAN
+ static const int g_one = 1;
+# define XXH_CPU_LITTLE_ENDIAN (*(const char*)(&g_one))
+#endif
+
+
+/* ***************************
+* Memory reads
+*****************************/
+typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment;
+
+FORCE_INLINE_TEMPLATE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align)
+{
+ if (align==XXH_unaligned)
+ return endian==XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr));
+ else
+ return endian==XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr);
+}
+
+FORCE_INLINE_TEMPLATE U32 XXH_readLE32(const void* ptr, XXH_endianess endian)
+{
+ return XXH_readLE32_align(ptr, endian, XXH_unaligned);
+}
+
+static U32 XXH_readBE32(const void* ptr)
+{
+ return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr);
+}
+
+FORCE_INLINE_TEMPLATE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align)
+{
+ if (align==XXH_unaligned)
+ return endian==XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr));
+ else
+ return endian==XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr);
+}
+
+FORCE_INLINE_TEMPLATE U64 XXH_readLE64(const void* ptr, XXH_endianess endian)
+{
+ return XXH_readLE64_align(ptr, endian, XXH_unaligned);
+}
+
+static U64 XXH_readBE64(const void* ptr)
+{
+ return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr);
+}
+
+
+/* *************************************
+* Macros
+***************************************/
+#define XXH_STATIC_ASSERT(c) { enum { XXH_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
+
+
+/* *************************************
+* Constants
+***************************************/
+static const U32 PRIME32_1 = 2654435761U;
+static const U32 PRIME32_2 = 2246822519U;
+static const U32 PRIME32_3 = 3266489917U;
+static const U32 PRIME32_4 = 668265263U;
+static const U32 PRIME32_5 = 374761393U;
+
+static const U64 PRIME64_1 = 11400714785074694791ULL;
+static const U64 PRIME64_2 = 14029467366897019727ULL;
+static const U64 PRIME64_3 = 1609587929392839161ULL;
+static const U64 PRIME64_4 = 9650029242287828579ULL;
+static const U64 PRIME64_5 = 2870177450012600261ULL;
+
+XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; }
+
+
+/* **************************
+* Utils
+****************************/
+XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* restrict dstState, const XXH32_state_t* restrict srcState)
+{
+ memcpy(dstState, srcState, sizeof(*dstState));
+}
+
+XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* restrict dstState, const XXH64_state_t* restrict srcState)
+{
+ memcpy(dstState, srcState, sizeof(*dstState));
+}
+
+
+/* ***************************
+* Simple Hash Functions
+*****************************/
+
+static U32 XXH32_round(U32 seed, U32 input)
+{
+ seed += input * PRIME32_2;
+ seed = XXH_rotl32(seed, 13);
+ seed *= PRIME32_1;
+ return seed;
+}
+
+FORCE_INLINE_TEMPLATE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align)
+{
+ const BYTE* p = (const BYTE*)input;
+ const BYTE* bEnd = p + len;
+ U32 h32;
+#define XXH_get32bits(p) XXH_readLE32_align(p, endian, align)
+
+#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
+ if (p==NULL) {
+ len=0;
+ bEnd=p=(const BYTE*)(size_t)16;
+ }
+#endif
+
+ if (len>=16) {
+ const BYTE* const limit = bEnd - 16;
+ U32 v1 = seed + PRIME32_1 + PRIME32_2;
+ U32 v2 = seed + PRIME32_2;
+ U32 v3 = seed + 0;
+ U32 v4 = seed - PRIME32_1;
+
+ do {
+ v1 = XXH32_round(v1, XXH_get32bits(p)); p+=4;
+ v2 = XXH32_round(v2, XXH_get32bits(p)); p+=4;
+ v3 = XXH32_round(v3, XXH_get32bits(p)); p+=4;
+ v4 = XXH32_round(v4, XXH_get32bits(p)); p+=4;
+ } while (p<=limit);
+
+ h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18);
+ } else {
+ h32 = seed + PRIME32_5;
+ }
+
+ h32 += (U32) len;
+
+ while (p+4<=bEnd) {
+ h32 += XXH_get32bits(p) * PRIME32_3;
+ h32 = XXH_rotl32(h32, 17) * PRIME32_4 ;
+ p+=4;
+ }
+
+ while (p<bEnd) {
+ h32 += (*p) * PRIME32_5;
+ h32 = XXH_rotl32(h32, 11) * PRIME32_1 ;
+ p++;
+ }
+
+ h32 ^= h32 >> 15;
+ h32 *= PRIME32_2;
+ h32 ^= h32 >> 13;
+ h32 *= PRIME32_3;
+ h32 ^= h32 >> 16;
+
+ return h32;
+}
+
+
+XXH_PUBLIC_API unsigned int XXH32 (const void* input, size_t len, unsigned int seed)
+{
+#if 0
+ /* Simple version, good for code maintenance, but unfortunately slow for small inputs */
+ XXH32_CREATESTATE_STATIC(state);
+ XXH32_reset(state, seed);
+ XXH32_update(state, input, len);
+ return XXH32_digest(state);
+#else
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+ if (XXH_FORCE_ALIGN_CHECK) {
+ if ((((size_t)input) & 3) == 0) { /* Input is 4-bytes aligned, leverage the speed benefit */
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);
+ else
+ return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);
+ } }
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);
+ else
+ return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);
+#endif
+}
+
+
+static U64 XXH64_round(U64 acc, U64 input)
+{
+ acc += input * PRIME64_2;
+ acc = XXH_rotl64(acc, 31);
+ acc *= PRIME64_1;
+ return acc;
+}
+
+static U64 XXH64_mergeRound(U64 acc, U64 val)
+{
+ val = XXH64_round(0, val);
+ acc ^= val;
+ acc = acc * PRIME64_1 + PRIME64_4;
+ return acc;
+}
+
+FORCE_INLINE_TEMPLATE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align)
+{
+ const BYTE* p = (const BYTE*)input;
+ const BYTE* const bEnd = p + len;
+ U64 h64;
+#define XXH_get64bits(p) XXH_readLE64_align(p, endian, align)
+
+#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
+ if (p==NULL) {
+ len=0;
+ bEnd=p=(const BYTE*)(size_t)32;
+ }
+#endif
+
+ if (len>=32) {
+ const BYTE* const limit = bEnd - 32;
+ U64 v1 = seed + PRIME64_1 + PRIME64_2;
+ U64 v2 = seed + PRIME64_2;
+ U64 v3 = seed + 0;
+ U64 v4 = seed - PRIME64_1;
+
+ do {
+ v1 = XXH64_round(v1, XXH_get64bits(p)); p+=8;
+ v2 = XXH64_round(v2, XXH_get64bits(p)); p+=8;
+ v3 = XXH64_round(v3, XXH_get64bits(p)); p+=8;
+ v4 = XXH64_round(v4, XXH_get64bits(p)); p+=8;
+ } while (p<=limit);
+
+ h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);
+ h64 = XXH64_mergeRound(h64, v1);
+ h64 = XXH64_mergeRound(h64, v2);
+ h64 = XXH64_mergeRound(h64, v3);
+ h64 = XXH64_mergeRound(h64, v4);
+
+ } else {
+ h64 = seed + PRIME64_5;
+ }
+
+ h64 += (U64) len;
+
+ while (p+8<=bEnd) {
+ U64 const k1 = XXH64_round(0, XXH_get64bits(p));
+ h64 ^= k1;
+ h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4;
+ p+=8;
+ }
+
+ if (p+4<=bEnd) {
+ h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1;
+ h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;
+ p+=4;
+ }
+
+ while (p<bEnd) {
+ h64 ^= (*p) * PRIME64_5;
+ h64 = XXH_rotl64(h64, 11) * PRIME64_1;
+ p++;
+ }
+
+ h64 ^= h64 >> 33;
+ h64 *= PRIME64_2;
+ h64 ^= h64 >> 29;
+ h64 *= PRIME64_3;
+ h64 ^= h64 >> 32;
+
+ return h64;
+}
+
+
+XXH_PUBLIC_API unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed)
+{
+#if 0
+ /* Simple version, good for code maintenance, but unfortunately slow for small inputs */
+ XXH64_CREATESTATE_STATIC(state);
+ XXH64_reset(state, seed);
+ XXH64_update(state, input, len);
+ return XXH64_digest(state);
+#else
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+ if (XXH_FORCE_ALIGN_CHECK) {
+ if ((((size_t)input) & 7)==0) { /* Input is aligned, let's leverage the speed advantage */
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);
+ else
+ return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);
+ } }
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);
+ else
+ return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);
+#endif
+}
+
+
+/* **************************************************
+* Advanced Hash Functions
+****************************************************/
+
+XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void)
+{
+ return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t));
+}
+XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr)
+{
+ XXH_free(statePtr);
+ return XXH_OK;
+}
+
+XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void)
+{
+ return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t));
+}
+XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr)
+{
+ XXH_free(statePtr);
+ return XXH_OK;
+}
+
+
+/*** Hash feed ***/
+
+XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, unsigned int seed)
+{
+ XXH32_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */
+ memset(&state, 0, sizeof(state)-4); /* do not write into reserved, for future removal */
+ state.v1 = seed + PRIME32_1 + PRIME32_2;
+ state.v2 = seed + PRIME32_2;
+ state.v3 = seed + 0;
+ state.v4 = seed - PRIME32_1;
+ memcpy(statePtr, &state, sizeof(state));
+ return XXH_OK;
+}
+
+
+XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, unsigned long long seed)
+{
+ XXH64_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */
+ memset(&state, 0, sizeof(state)-8); /* do not write into reserved, for future removal */
+ state.v1 = seed + PRIME64_1 + PRIME64_2;
+ state.v2 = seed + PRIME64_2;
+ state.v3 = seed + 0;
+ state.v4 = seed - PRIME64_1;
+ memcpy(statePtr, &state, sizeof(state));
+ return XXH_OK;
+}
+
+
+FORCE_INLINE_TEMPLATE XXH_errorcode XXH32_update_endian (XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian)
+{
+ const BYTE* p = (const BYTE*)input;
+ const BYTE* const bEnd = p + len;
+
+#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
+ if (input==NULL) return XXH_ERROR;
+#endif
+
+ state->total_len_32 += (unsigned)len;
+ state->large_len |= (len>=16) | (state->total_len_32>=16);
+
+ if (state->memsize + len < 16) { /* fill in tmp buffer */
+ XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len);
+ state->memsize += (unsigned)len;
+ return XXH_OK;
+ }
+
+ if (state->memsize) { /* some data left from previous update */
+ XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize);
+ { const U32* p32 = state->mem32;
+ state->v1 = XXH32_round(state->v1, XXH_readLE32(p32, endian)); p32++;
+ state->v2 = XXH32_round(state->v2, XXH_readLE32(p32, endian)); p32++;
+ state->v3 = XXH32_round(state->v3, XXH_readLE32(p32, endian)); p32++;
+ state->v4 = XXH32_round(state->v4, XXH_readLE32(p32, endian)); p32++;
+ }
+ p += 16-state->memsize;
+ state->memsize = 0;
+ }
+
+ if (p <= bEnd-16) {
+ const BYTE* const limit = bEnd - 16;
+ U32 v1 = state->v1;
+ U32 v2 = state->v2;
+ U32 v3 = state->v3;
+ U32 v4 = state->v4;
+
+ do {
+ v1 = XXH32_round(v1, XXH_readLE32(p, endian)); p+=4;
+ v2 = XXH32_round(v2, XXH_readLE32(p, endian)); p+=4;
+ v3 = XXH32_round(v3, XXH_readLE32(p, endian)); p+=4;
+ v4 = XXH32_round(v4, XXH_readLE32(p, endian)); p+=4;
+ } while (p<=limit);
+
+ state->v1 = v1;
+ state->v2 = v2;
+ state->v3 = v3;
+ state->v4 = v4;
+ }
+
+ if (p < bEnd) {
+ XXH_memcpy(state->mem32, p, (size_t)(bEnd-p));
+ state->memsize = (unsigned)(bEnd-p);
+ }
+
+ return XXH_OK;
+}
+
+XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len)
+{
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH32_update_endian(state_in, input, len, XXH_littleEndian);
+ else
+ return XXH32_update_endian(state_in, input, len, XXH_bigEndian);
+}
+
+
+
+FORCE_INLINE_TEMPLATE U32 XXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian)
+{
+ const BYTE * p = (const BYTE*)state->mem32;
+ const BYTE* const bEnd = (const BYTE*)(state->mem32) + state->memsize;
+ U32 h32;
+
+ if (state->large_len) {
+ h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18);
+ } else {
+ h32 = state->v3 /* == seed */ + PRIME32_5;
+ }
+
+ h32 += state->total_len_32;
+
+ while (p+4<=bEnd) {
+ h32 += XXH_readLE32(p, endian) * PRIME32_3;
+ h32 = XXH_rotl32(h32, 17) * PRIME32_4;
+ p+=4;
+ }
+
+ while (p<bEnd) {
+ h32 += (*p) * PRIME32_5;
+ h32 = XXH_rotl32(h32, 11) * PRIME32_1;
+ p++;
+ }
+
+ h32 ^= h32 >> 15;
+ h32 *= PRIME32_2;
+ h32 ^= h32 >> 13;
+ h32 *= PRIME32_3;
+ h32 ^= h32 >> 16;
+
+ return h32;
+}
+
+
+XXH_PUBLIC_API unsigned int XXH32_digest (const XXH32_state_t* state_in)
+{
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH32_digest_endian(state_in, XXH_littleEndian);
+ else
+ return XXH32_digest_endian(state_in, XXH_bigEndian);
+}
+
+
+
+/* **** XXH64 **** */
+
+FORCE_INLINE_TEMPLATE XXH_errorcode XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian)
+{
+ const BYTE* p = (const BYTE*)input;
+ const BYTE* const bEnd = p + len;
+
+#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
+ if (input==NULL) return XXH_ERROR;
+#endif
+
+ state->total_len += len;
+
+ if (state->memsize + len < 32) { /* fill in tmp buffer */
+ XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len);
+ state->memsize += (U32)len;
+ return XXH_OK;
+ }
+
+ if (state->memsize) { /* tmp buffer is full */
+ XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize);
+ state->v1 = XXH64_round(state->v1, XXH_readLE64(state->mem64+0, endian));
+ state->v2 = XXH64_round(state->v2, XXH_readLE64(state->mem64+1, endian));
+ state->v3 = XXH64_round(state->v3, XXH_readLE64(state->mem64+2, endian));
+ state->v4 = XXH64_round(state->v4, XXH_readLE64(state->mem64+3, endian));
+ p += 32-state->memsize;
+ state->memsize = 0;
+ }
+
+ if (p+32 <= bEnd) {
+ const BYTE* const limit = bEnd - 32;
+ U64 v1 = state->v1;
+ U64 v2 = state->v2;
+ U64 v3 = state->v3;
+ U64 v4 = state->v4;
+
+ do {
+ v1 = XXH64_round(v1, XXH_readLE64(p, endian)); p+=8;
+ v2 = XXH64_round(v2, XXH_readLE64(p, endian)); p+=8;
+ v3 = XXH64_round(v3, XXH_readLE64(p, endian)); p+=8;
+ v4 = XXH64_round(v4, XXH_readLE64(p, endian)); p+=8;
+ } while (p<=limit);
+
+ state->v1 = v1;
+ state->v2 = v2;
+ state->v3 = v3;
+ state->v4 = v4;
+ }
+
+ if (p < bEnd) {
+ XXH_memcpy(state->mem64, p, (size_t)(bEnd-p));
+ state->memsize = (unsigned)(bEnd-p);
+ }
+
+ return XXH_OK;
+}
+
+XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len)
+{
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH64_update_endian(state_in, input, len, XXH_littleEndian);
+ else
+ return XXH64_update_endian(state_in, input, len, XXH_bigEndian);
+}
+
+
+
+FORCE_INLINE_TEMPLATE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess endian)
+{
+ const BYTE * p = (const BYTE*)state->mem64;
+ const BYTE* const bEnd = (const BYTE*)state->mem64 + state->memsize;
+ U64 h64;
+
+ if (state->total_len >= 32) {
+ U64 const v1 = state->v1;
+ U64 const v2 = state->v2;
+ U64 const v3 = state->v3;
+ U64 const v4 = state->v4;
+
+ h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);
+ h64 = XXH64_mergeRound(h64, v1);
+ h64 = XXH64_mergeRound(h64, v2);
+ h64 = XXH64_mergeRound(h64, v3);
+ h64 = XXH64_mergeRound(h64, v4);
+ } else {
+ h64 = state->v3 + PRIME64_5;
+ }
+
+ h64 += (U64) state->total_len;
+
+ while (p+8<=bEnd) {
+ U64 const k1 = XXH64_round(0, XXH_readLE64(p, endian));
+ h64 ^= k1;
+ h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4;
+ p+=8;
+ }
+
+ if (p+4<=bEnd) {
+ h64 ^= (U64)(XXH_readLE32(p, endian)) * PRIME64_1;
+ h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;
+ p+=4;
+ }
+
+ while (p<bEnd) {
+ h64 ^= (*p) * PRIME64_5;
+ h64 = XXH_rotl64(h64, 11) * PRIME64_1;
+ p++;
+ }
+
+ h64 ^= h64 >> 33;
+ h64 *= PRIME64_2;
+ h64 ^= h64 >> 29;
+ h64 *= PRIME64_3;
+ h64 ^= h64 >> 32;
+
+ return h64;
+}
+
+
+XXH_PUBLIC_API unsigned long long XXH64_digest (const XXH64_state_t* state_in)
+{
+ XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
+
+ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
+ return XXH64_digest_endian(state_in, XXH_littleEndian);
+ else
+ return XXH64_digest_endian(state_in, XXH_bigEndian);
+}
+
+
+/* **************************
+* Canonical representation
+****************************/
+
+/*! Default XXH result types are basic unsigned 32 and 64 bits.
+* The canonical representation follows human-readable write convention, aka big-endian (large digits first).
+* These functions allow transformation of hash result into and from its canonical format.
+* This way, hash values can be written into a file or buffer, and remain comparable across different systems and programs.
+*/
+
+XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash)
+{
+ XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t));
+ if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash);
+ memcpy(dst, &hash, sizeof(*dst));
+}
+
+XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash)
+{
+ XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t));
+ if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash);
+ memcpy(dst, &hash, sizeof(*dst));
+}
+
+XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src)
+{
+ return XXH_readBE32(src);
+}
+
+XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src)
+{
+ return XXH_readBE64(src);
+}
diff --git a/Utilities/cmzstd/lib/common/xxhash.h b/Utilities/cmzstd/lib/common/xxhash.h
new file mode 100644
index 000000000..9bad1f59f
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/xxhash.h
@@ -0,0 +1,305 @@
+/*
+ xxHash - Extremely Fast Hash algorithm
+ Header File
+ Copyright (C) 2012-2016, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - xxHash source repository : https://github.com/Cyan4973/xxHash
+*/
+
+/* Notice extracted from xxHash homepage :
+
+xxHash is an extremely fast Hash algorithm, running at RAM speed limits.
+It also successfully passes all tests from the SMHasher suite.
+
+Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz)
+
+Name Speed Q.Score Author
+xxHash 5.4 GB/s 10
+CrapWow 3.2 GB/s 2 Andrew
+MumurHash 3a 2.7 GB/s 10 Austin Appleby
+SpookyHash 2.0 GB/s 10 Bob Jenkins
+SBox 1.4 GB/s 9 Bret Mulvey
+Lookup3 1.2 GB/s 9 Bob Jenkins
+SuperFastHash 1.2 GB/s 1 Paul Hsieh
+CityHash64 1.05 GB/s 10 Pike & Alakuijala
+FNV 0.55 GB/s 5 Fowler, Noll, Vo
+CRC32 0.43 GB/s 9
+MD5-32 0.33 GB/s 10 Ronald L. Rivest
+SHA1-32 0.28 GB/s 10
+
+Q.Score is a measure of quality of the hash function.
+It depends on successfully passing SMHasher test set.
+10 is a perfect score.
+
+A 64-bits version, named XXH64, is available since r35.
+It offers much better speed, but for 64-bits applications only.
+Name Speed on 64 bits Speed on 32 bits
+XXH64 13.8 GB/s 1.9 GB/s
+XXH32 6.8 GB/s 6.0 GB/s
+*/
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#ifndef XXHASH_H_5627135585666179
+#define XXHASH_H_5627135585666179 1
+
+
+/* ****************************
+* Definitions
+******************************/
+#include <stddef.h> /* size_t */
+typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode;
+
+
+/* ****************************
+* API modifier
+******************************/
+/** XXH_PRIVATE_API
+* This is useful if you want to include xxhash functions in `static` mode
+* in order to inline them, and remove their symbol from the public list.
+* Methodology :
+* #define XXH_PRIVATE_API
+* #include "xxhash.h"
+* `xxhash.c` is automatically included.
+* It's not useful to compile and link it as a separate module anymore.
+*/
+#ifdef XXH_PRIVATE_API
+# ifndef XXH_STATIC_LINKING_ONLY
+# define XXH_STATIC_LINKING_ONLY
+# endif
+# if defined(__GNUC__)
+# define XXH_PUBLIC_API static __inline __attribute__((unused))
+# elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
+# define XXH_PUBLIC_API static inline
+# elif defined(_MSC_VER)
+# define XXH_PUBLIC_API static __inline
+# else
+# define XXH_PUBLIC_API static /* this version may generate warnings for unused static functions; disable the relevant warning */
+# endif
+#else
+# define XXH_PUBLIC_API /* do nothing */
+#endif /* XXH_PRIVATE_API */
+
+/*!XXH_NAMESPACE, aka Namespace Emulation :
+
+If you want to include _and expose_ xxHash functions from within your own library,
+but also want to avoid symbol collisions with another library which also includes xxHash,
+
+you can use XXH_NAMESPACE, to automatically prefix any public symbol from xxhash library
+with the value of XXH_NAMESPACE (so avoid to keep it NULL and avoid numeric values).
+
+Note that no change is required within the calling program as long as it includes `xxhash.h` :
+regular symbol name will be automatically translated by this header.
+*/
+#ifdef XXH_NAMESPACE
+# define XXH_CAT(A,B) A##B
+# define XXH_NAME2(A,B) XXH_CAT(A,B)
+# define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32)
+# define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64)
+# define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber)
+# define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState)
+# define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState)
+# define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState)
+# define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState)
+# define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset)
+# define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset)
+# define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update)
+# define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update)
+# define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest)
+# define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest)
+# define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState)
+# define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState)
+# define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash)
+# define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash)
+# define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical)
+# define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical)
+#endif
+
+
+/* *************************************
+* Version
+***************************************/
+#define XXH_VERSION_MAJOR 0
+#define XXH_VERSION_MINOR 6
+#define XXH_VERSION_RELEASE 2
+#define XXH_VERSION_NUMBER (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE)
+XXH_PUBLIC_API unsigned XXH_versionNumber (void);
+
+
+/* ****************************
+* Simple Hash Functions
+******************************/
+typedef unsigned int XXH32_hash_t;
+typedef unsigned long long XXH64_hash_t;
+
+XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t length, unsigned int seed);
+XXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t length, unsigned long long seed);
+
+/*!
+XXH32() :
+ Calculate the 32-bits hash of sequence "length" bytes stored at memory address "input".
+ The memory between input & input+length must be valid (allocated and read-accessible).
+ "seed" can be used to alter the result predictably.
+ Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s
+XXH64() :
+ Calculate the 64-bits hash of sequence of length "len" stored at memory address "input".
+ "seed" can be used to alter the result predictably.
+ This function runs 2x faster on 64-bits systems, but slower on 32-bits systems (see benchmark).
+*/
+
+
+/* ****************************
+* Streaming Hash Functions
+******************************/
+typedef struct XXH32_state_s XXH32_state_t; /* incomplete type */
+typedef struct XXH64_state_s XXH64_state_t; /* incomplete type */
+
+/*! State allocation, compatible with dynamic libraries */
+
+XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void);
+XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr);
+
+XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void);
+XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr);
+
+
+/* hash streaming */
+
+XXH_PUBLIC_API XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, unsigned int seed);
+XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length);
+XXH_PUBLIC_API XXH32_hash_t XXH32_digest (const XXH32_state_t* statePtr);
+
+XXH_PUBLIC_API XXH_errorcode XXH64_reset (XXH64_state_t* statePtr, unsigned long long seed);
+XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length);
+XXH_PUBLIC_API XXH64_hash_t XXH64_digest (const XXH64_state_t* statePtr);
+
+/*
+These functions generate the xxHash of an input provided in multiple segments.
+Note that, for small input, they are slower than single-call functions, due to state management.
+For small input, prefer `XXH32()` and `XXH64()` .
+
+XXH state must first be allocated, using XXH*_createState() .
+
+Start a new hash by initializing state with a seed, using XXH*_reset().
+
+Then, feed the hash state by calling XXH*_update() as many times as necessary.
+Obviously, input must be allocated and read accessible.
+The function returns an error code, with 0 meaning OK, and any other value meaning there is an error.
+
+Finally, a hash value can be produced anytime, by using XXH*_digest().
+This function returns the nn-bits hash as an int or long long.
+
+It's still possible to continue inserting input into the hash state after a digest,
+and generate some new hashes later on, by calling again XXH*_digest().
+
+When done, free XXH state space if it was allocated dynamically.
+*/
+
+
+/* **************************
+* Utils
+****************************/
+#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) /* ! C99 */
+# define restrict /* disable restrict */
+#endif
+
+XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* restrict dst_state, const XXH32_state_t* restrict src_state);
+XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* restrict dst_state, const XXH64_state_t* restrict src_state);
+
+
+/* **************************
+* Canonical representation
+****************************/
+/* Default result type for XXH functions are primitive unsigned 32 and 64 bits.
+* The canonical representation uses human-readable write convention, aka big-endian (large digits first).
+* These functions allow transformation of hash result into and from its canonical format.
+* This way, hash values can be written into a file / memory, and remain comparable on different systems and programs.
+*/
+typedef struct { unsigned char digest[4]; } XXH32_canonical_t;
+typedef struct { unsigned char digest[8]; } XXH64_canonical_t;
+
+XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash);
+XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash);
+
+XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src);
+XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src);
+
+#endif /* XXHASH_H_5627135585666179 */
+
+
+
+/* ================================================================================================
+ This section contains definitions which are not guaranteed to remain stable.
+ They may change in future versions, becoming incompatible with a different version of the library.
+ They shall only be used with static linking.
+ Never use these definitions in association with dynamic linking !
+=================================================================================================== */
+#if defined(XXH_STATIC_LINKING_ONLY) && !defined(XXH_STATIC_H_3543687687345)
+#define XXH_STATIC_H_3543687687345
+
+/* These definitions are only meant to allow allocation of XXH state
+ statically, on stack, or in a struct for example.
+ Do not use members directly. */
+
+ struct XXH32_state_s {
+ unsigned total_len_32;
+ unsigned large_len;
+ unsigned v1;
+ unsigned v2;
+ unsigned v3;
+ unsigned v4;
+ unsigned mem32[4]; /* buffer defined as U32 for alignment */
+ unsigned memsize;
+ unsigned reserved; /* never read nor write, will be removed in a future version */
+ }; /* typedef'd to XXH32_state_t */
+
+ struct XXH64_state_s {
+ unsigned long long total_len;
+ unsigned long long v1;
+ unsigned long long v2;
+ unsigned long long v3;
+ unsigned long long v4;
+ unsigned long long mem64[4]; /* buffer defined as U64 for alignment */
+ unsigned memsize;
+ unsigned reserved[2]; /* never read nor write, will be removed in a future version */
+ }; /* typedef'd to XXH64_state_t */
+
+
+# ifdef XXH_PRIVATE_API
+# include "xxhash.c" /* include xxhash functions as `static`, for inlining */
+# endif
+
+#endif /* XXH_STATIC_LINKING_ONLY && XXH_STATIC_H_3543687687345 */
+
+
+#if defined (__cplusplus)
+}
+#endif
diff --git a/Utilities/cmzstd/lib/common/zstd_common.c b/Utilities/cmzstd/lib/common/zstd_common.c
new file mode 100644
index 000000000..667f4a27f
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/zstd_common.c
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+
+
+/*-*************************************
+* Dependencies
+***************************************/
+#include <stdlib.h> /* malloc, calloc, free */
+#include <string.h> /* memset */
+#include "error_private.h"
+#include "zstd_internal.h"
+
+
+/*-****************************************
+* Version
+******************************************/
+unsigned ZSTD_versionNumber(void) { return ZSTD_VERSION_NUMBER; }
+
+const char* ZSTD_versionString(void) { return ZSTD_VERSION_STRING; }
+
+
+/*-****************************************
+* ZSTD Error Management
+******************************************/
+#undef ZSTD_isError /* defined within zstd_internal.h */
+/*! ZSTD_isError() :
+ * tells if a return value is an error code
+ * symbol is required for external callers */
+unsigned ZSTD_isError(size_t code) { return ERR_isError(code); }
+
+/*! ZSTD_getErrorName() :
+ * provides error code string from function result (useful for debugging) */
+const char* ZSTD_getErrorName(size_t code) { return ERR_getErrorName(code); }
+
+/*! ZSTD_getError() :
+ * convert a `size_t` function result into a proper ZSTD_errorCode enum */
+ZSTD_ErrorCode ZSTD_getErrorCode(size_t code) { return ERR_getErrorCode(code); }
+
+/*! ZSTD_getErrorString() :
+ * provides error code string from enum */
+const char* ZSTD_getErrorString(ZSTD_ErrorCode code) { return ERR_getErrorString(code); }
+
+
+
+/*=**************************************************************
+* Custom allocator
+****************************************************************/
+void* ZSTD_malloc(size_t size, ZSTD_customMem customMem)
+{
+ if (customMem.customAlloc)
+ return customMem.customAlloc(customMem.opaque, size);
+ return malloc(size);
+}
+
+void* ZSTD_calloc(size_t size, ZSTD_customMem customMem)
+{
+ if (customMem.customAlloc) {
+ /* calloc implemented as malloc+memset;
+ * not as efficient as calloc, but next best guess for custom malloc */
+ void* const ptr = customMem.customAlloc(customMem.opaque, size);
+ memset(ptr, 0, size);
+ return ptr;
+ }
+ return calloc(1, size);
+}
+
+void ZSTD_free(void* ptr, ZSTD_customMem customMem)
+{
+ if (ptr!=NULL) {
+ if (customMem.customFree)
+ customMem.customFree(customMem.opaque, ptr);
+ else
+ free(ptr);
+ }
+}
diff --git a/Utilities/cmzstd/lib/common/zstd_errors.h b/Utilities/cmzstd/lib/common/zstd_errors.h
new file mode 100644
index 000000000..92a343389
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/zstd_errors.h
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef ZSTD_ERRORS_H_398273423
+#define ZSTD_ERRORS_H_398273423
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+/*===== dependency =====*/
+#include <stddef.h> /* size_t */
+
+
+/* ===== ZSTDERRORLIB_API : control library symbols visibility ===== */
+#ifndef ZSTDERRORLIB_VISIBILITY
+# if defined(__GNUC__) && (__GNUC__ >= 4)
+# define ZSTDERRORLIB_VISIBILITY __attribute__ ((visibility ("default")))
+# else
+# define ZSTDERRORLIB_VISIBILITY
+# endif
+#endif
+#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
+# define ZSTDERRORLIB_API __declspec(dllexport) ZSTDERRORLIB_VISIBILITY
+#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
+# define ZSTDERRORLIB_API __declspec(dllimport) ZSTDERRORLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
+#else
+# define ZSTDERRORLIB_API ZSTDERRORLIB_VISIBILITY
+#endif
+
+/*-*********************************************
+ * Error codes list
+ *-*********************************************
+ * Error codes _values_ are pinned down since v1.3.1 only.
+ * Therefore, don't rely on values if you may link to any version < v1.3.1.
+ *
+ * Only values < 100 are considered stable.
+ *
+ * note 1 : this API shall be used with static linking only.
+ * dynamic linking is not yet officially supported.
+ * note 2 : Prefer relying on the enum than on its value whenever possible
+ * This is the only supported way to use the error list < v1.3.1
+ * note 3 : ZSTD_isError() is always correct, whatever the library version.
+ **********************************************/
+typedef enum {
+ ZSTD_error_no_error = 0,
+ ZSTD_error_GENERIC = 1,
+ ZSTD_error_prefix_unknown = 10,
+ ZSTD_error_version_unsupported = 12,
+ ZSTD_error_frameParameter_unsupported = 14,
+ ZSTD_error_frameParameter_windowTooLarge = 16,
+ ZSTD_error_corruption_detected = 20,
+ ZSTD_error_checksum_wrong = 22,
+ ZSTD_error_dictionary_corrupted = 30,
+ ZSTD_error_dictionary_wrong = 32,
+ ZSTD_error_dictionaryCreation_failed = 34,
+ ZSTD_error_parameter_unsupported = 40,
+ ZSTD_error_parameter_outOfBound = 42,
+ ZSTD_error_tableLog_tooLarge = 44,
+ ZSTD_error_maxSymbolValue_tooLarge = 46,
+ ZSTD_error_maxSymbolValue_tooSmall = 48,
+ ZSTD_error_stage_wrong = 60,
+ ZSTD_error_init_missing = 62,
+ ZSTD_error_memory_allocation = 64,
+ ZSTD_error_workSpace_tooSmall= 66,
+ ZSTD_error_dstSize_tooSmall = 70,
+ ZSTD_error_srcSize_wrong = 72,
+ ZSTD_error_dstBuffer_null = 74,
+ /* following error codes are __NOT STABLE__, they can be removed or changed in future versions */
+ ZSTD_error_frameIndex_tooLarge = 100,
+ ZSTD_error_seekableIO = 102,
+ ZSTD_error_maxCode = 120 /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */
+} ZSTD_ErrorCode;
+
+/*! ZSTD_getErrorCode() :
+ convert a `size_t` function result into a `ZSTD_ErrorCode` enum type,
+ which can be used to compare with enum list published above */
+ZSTDERRORLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult);
+ZSTDERRORLIB_API const char* ZSTD_getErrorString(ZSTD_ErrorCode code); /**< Same as ZSTD_getErrorName, but using a `ZSTD_ErrorCode` enum argument */
+
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* ZSTD_ERRORS_H_398273423 */
diff --git a/Utilities/cmzstd/lib/common/zstd_internal.h b/Utilities/cmzstd/lib/common/zstd_internal.h
new file mode 100644
index 000000000..edeb74b9c
--- /dev/null
+++ b/Utilities/cmzstd/lib/common/zstd_internal.h
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef ZSTD_CCOMMON_H_MODULE
+#define ZSTD_CCOMMON_H_MODULE
+
+/* this module contains definitions which must be identical
+ * across compression, decompression and dictBuilder.
+ * It also contains a few functions useful to at least 2 of them
+ * and which benefit from being inlined */
+
+/*-*************************************
+* Dependencies
+***************************************/
+#include "compiler.h"
+#include "mem.h"
+#include "debug.h" /* assert, DEBUGLOG, RAWLOG, g_debuglevel */
+#include "error_private.h"
+#define ZSTD_STATIC_LINKING_ONLY
+#include "zstd.h"
+#define FSE_STATIC_LINKING_ONLY
+#include "fse.h"
+#define HUF_STATIC_LINKING_ONLY
+#include "huf.h"
+#ifndef XXH_STATIC_LINKING_ONLY
+# define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */
+#endif
+#include "xxhash.h" /* XXH_reset, update, digest */
+
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+/* ---- static assert (debug) --- */
+#define ZSTD_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c)
+#define ZSTD_isError ERR_isError /* for inlining */
+#define FSE_isError ERR_isError
+#define HUF_isError ERR_isError
+
+
+/*-*************************************
+* shared macros
+***************************************/
+#undef MIN
+#undef MAX
+#define MIN(a,b) ((a)<(b) ? (a) : (b))
+#define MAX(a,b) ((a)>(b) ? (a) : (b))
+#define CHECK_F(f) { size_t const errcod = f; if (ERR_isError(errcod)) return errcod; } /* check and Forward error code */
+#define CHECK_E(f, e) { size_t const errcod = f; if (ERR_isError(errcod)) return ERROR(e); } /* check and send Error code */
+
+
+/*-*************************************
+* Common constants
+***************************************/
+#define ZSTD_OPT_NUM (1<<12)
+
+#define ZSTD_REP_NUM 3 /* number of repcodes */
+#define ZSTD_REP_MOVE (ZSTD_REP_NUM-1)
+static const U32 repStartValue[ZSTD_REP_NUM] = { 1, 4, 8 };
+
+#define KB *(1 <<10)
+#define MB *(1 <<20)
+#define GB *(1U<<30)
+
+#define BIT7 128
+#define BIT6 64
+#define BIT5 32
+#define BIT4 16
+#define BIT1 2
+#define BIT0 1
+
+#define ZSTD_WINDOWLOG_ABSOLUTEMIN 10
+static const size_t ZSTD_fcs_fieldSize[4] = { 0, 2, 4, 8 };
+static const size_t ZSTD_did_fieldSize[4] = { 0, 1, 2, 4 };
+
+#define ZSTD_FRAMEIDSIZE 4 /* magic number size */
+
+#define ZSTD_BLOCKHEADERSIZE 3 /* C standard doesn't allow `static const` variable to be init using another `static const` variable */
+static const size_t ZSTD_blockHeaderSize = ZSTD_BLOCKHEADERSIZE;
+typedef enum { bt_raw, bt_rle, bt_compressed, bt_reserved } blockType_e;
+
+#define MIN_SEQUENCES_SIZE 1 /* nbSeq==0 */
+#define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */ + MIN_SEQUENCES_SIZE /* nbSeq==0 */) /* for a non-null block */
+
+#define HufLog 12
+typedef enum { set_basic, set_rle, set_compressed, set_repeat } symbolEncodingType_e;
+
+#define LONGNBSEQ 0x7F00
+
+#define MINMATCH 3
+
+#define Litbits 8
+#define MaxLit ((1<<Litbits) - 1)
+#define MaxML 52
+#define MaxLL 35
+#define DefaultMaxOff 28
+#define MaxOff 31
+#define MaxSeq MAX(MaxLL, MaxML) /* Assumption : MaxOff < MaxLL,MaxML */
+#define MLFSELog 9
+#define LLFSELog 9
+#define OffFSELog 8
+#define MaxFSELog MAX(MAX(MLFSELog, LLFSELog), OffFSELog)
+
+static const U32 LL_bits[MaxLL+1] = { 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, 1, 1, 2, 2, 3, 3,
+ 4, 6, 7, 8, 9,10,11,12,
+ 13,14,15,16 };
+static const S16 LL_defaultNorm[MaxLL+1] = { 4, 3, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 1, 1, 1,
+ 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 3, 2, 1, 1, 1, 1, 1,
+ -1,-1,-1,-1 };
+#define LL_DEFAULTNORMLOG 6 /* for static allocation */
+static const U32 LL_defaultNormLog = LL_DEFAULTNORMLOG;
+
+static const U32 ML_bits[MaxML+1] = { 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, 1, 1, 2, 2, 3, 3,
+ 4, 4, 5, 7, 8, 9,10,11,
+ 12,13,14,15,16 };
+static const S16 ML_defaultNorm[MaxML+1] = { 1, 4, 3, 2, 2, 2, 2, 2,
+ 2, 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 };
+#define ML_DEFAULTNORMLOG 6 /* for static allocation */
+static const U32 ML_defaultNormLog = ML_DEFAULTNORMLOG;
+
+static const S16 OF_defaultNorm[DefaultMaxOff+1] = { 1, 1, 1, 1, 1, 1, 2, 2,
+ 2, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1,
+ -1,-1,-1,-1,-1 };
+#define OF_DEFAULTNORMLOG 5 /* for static allocation */
+static const U32 OF_defaultNormLog = OF_DEFAULTNORMLOG;
+
+
+/*-*******************************************
+* Shared functions to include for inlining
+*********************************************/
+static void ZSTD_copy8(void* dst, const void* src) { memcpy(dst, src, 8); }
+#define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
+
+/*! ZSTD_wildcopy() :
+ * custom version of memcpy(), can overwrite up to WILDCOPY_OVERLENGTH bytes (if length==0) */
+#define WILDCOPY_OVERLENGTH 8
+MEM_STATIC void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length)
+{
+ const BYTE* ip = (const BYTE*)src;
+ BYTE* op = (BYTE*)dst;
+ BYTE* const oend = op + length;
+ do
+ COPY8(op, ip)
+ while (op < oend);
+}
+
+MEM_STATIC void ZSTD_wildcopy_e(void* dst, const void* src, void* dstEnd) /* should be faster for decoding, but strangely, not verified on all platform */
+{
+ const BYTE* ip = (const BYTE*)src;
+ BYTE* op = (BYTE*)dst;
+ BYTE* const oend = (BYTE*)dstEnd;
+ do
+ COPY8(op, ip)
+ while (op < oend);
+}
+
+
+/*-*******************************************
+* Private declarations
+*********************************************/
+typedef struct seqDef_s {
+ U32 offset;
+ U16 litLength;
+ U16 matchLength;
+} seqDef;
+
+typedef struct {
+ seqDef* sequencesStart;
+ seqDef* sequences;
+ BYTE* litStart;
+ BYTE* lit;
+ BYTE* llCode;
+ BYTE* mlCode;
+ BYTE* ofCode;
+ size_t maxNbSeq;
+ size_t maxNbLit;
+ U32 longLengthID; /* 0 == no longLength; 1 == Lit.longLength; 2 == Match.longLength; */
+ U32 longLengthPos;
+} seqStore_t;
+
+const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx); /* compress & dictBuilder */
+void ZSTD_seqToCodes(const seqStore_t* seqStorePtr); /* compress, dictBuilder, decodeCorpus (shouldn't get its definition from here) */
+
+/* custom memory allocation functions */
+void* ZSTD_malloc(size_t size, ZSTD_customMem customMem);
+void* ZSTD_calloc(size_t size, ZSTD_customMem customMem);
+void ZSTD_free(void* ptr, ZSTD_customMem customMem);
+
+
+MEM_STATIC U32 ZSTD_highbit32(U32 val) /* compress, dictBuilder, decodeCorpus */
+{
+ assert(val != 0);
+ {
+# if defined(_MSC_VER) /* Visual */
+ unsigned long r=0;
+ _BitScanReverse(&r, val);
+ return (unsigned)r;
+# elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */
+ return 31 - __builtin_clz(val);
+# else /* Software version */
+ static const U32 DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 };
+ U32 v = val;
+ v |= v >> 1;
+ v |= v >> 2;
+ v |= v >> 4;
+ v |= v >> 8;
+ v |= v >> 16;
+ return DeBruijnClz[(v * 0x07C4ACDDU) >> 27];
+# endif
+ }
+}
+
+
+/* ZSTD_invalidateRepCodes() :
+ * ensures next compression will not use repcodes from previous block.
+ * Note : only works with regular variant;
+ * do not use with extDict variant ! */
+void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx); /* zstdmt, adaptive_compression (shouldn't get this definition from here) */
+
+
+typedef struct {
+ blockType_e blockType;
+ U32 lastBlock;
+ U32 origSize;
+} blockProperties_t; /* declared here for decompress and fullbench */
+
+/*! ZSTD_getcBlockSize() :
+ * Provides the size of compressed block from block header `src` */
+/* Used by: decompress, fullbench (does not get its definition from here) */
+size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
+ blockProperties_t* bpPtr);
+
+/*! ZSTD_decodeSeqHeaders() :
+ * decode sequence header from src */
+/* Used by: decompress, fullbench (does not get its definition from here) */
+size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
+ const void* src, size_t srcSize);
+
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* ZSTD_CCOMMON_H_MODULE */
diff --git a/Utilities/cmzstd/lib/compress/fse_compress.c b/Utilities/cmzstd/lib/compress/fse_compress.c
new file mode 100644
index 000000000..60f357bbd
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/fse_compress.c
@@ -0,0 +1,721 @@
+/* ******************************************************************
+ FSE : Finite State Entropy encoder
+ Copyright (C) 2013-present, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
+ - Public forum : https://groups.google.com/forum/#!forum/lz4c
+****************************************************************** */
+
+/* **************************************************************
+* Includes
+****************************************************************/
+#include <stdlib.h> /* malloc, free, qsort */
+#include <string.h> /* memcpy, memset */
+#include "compiler.h"
+#include "mem.h" /* U32, U16, etc. */
+#include "debug.h" /* assert, DEBUGLOG */
+#include "hist.h" /* HIST_count_wksp */
+#include "bitstream.h"
+#define FSE_STATIC_LINKING_ONLY
+#include "fse.h"
+#include "error_private.h"
+
+
+/* **************************************************************
+* Error Management
+****************************************************************/
+#define FSE_isError ERR_isError
+
+
+/* **************************************************************
+* Templates
+****************************************************************/
+/*
+ designed to be included
+ for type-specific functions (template emulation in C)
+ Objective is to write these functions only once, for improved maintenance
+*/
+
+/* safety checks */
+#ifndef FSE_FUNCTION_EXTENSION
+# error "FSE_FUNCTION_EXTENSION must be defined"
+#endif
+#ifndef FSE_FUNCTION_TYPE
+# error "FSE_FUNCTION_TYPE must be defined"
+#endif
+
+/* Function names */
+#define FSE_CAT(X,Y) X##Y
+#define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
+#define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
+
+
+/* Function templates */
+
+/* FSE_buildCTable_wksp() :
+ * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
+ * wkspSize should be sized to handle worst case situation, which is `1<<max_tableLog * sizeof(FSE_FUNCTION_TYPE)`
+ * workSpace must also be properly aligned with FSE_FUNCTION_TYPE requirements
+ */
+size_t FSE_buildCTable_wksp(FSE_CTable* ct,
+ const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
+ void* workSpace, size_t wkspSize)
+{
+ U32 const tableSize = 1 << tableLog;
+ U32 const tableMask = tableSize - 1;
+ void* const ptr = ct;
+ U16* const tableU16 = ( (U16*) ptr) + 2;
+ void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableLog ? tableSize>>1 : 1) ;
+ FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
+ U32 const step = FSE_TABLESTEP(tableSize);
+ U32 cumul[FSE_MAX_SYMBOL_VALUE+2];
+
+ FSE_FUNCTION_TYPE* const tableSymbol = (FSE_FUNCTION_TYPE*)workSpace;
+ U32 highThreshold = tableSize-1;
+
+ /* CTable header */
+ if (((size_t)1 << tableLog) * sizeof(FSE_FUNCTION_TYPE) > wkspSize) return ERROR(tableLog_tooLarge);
+ tableU16[-2] = (U16) tableLog;
+ tableU16[-1] = (U16) maxSymbolValue;
+ assert(tableLog < 16); /* required for threshold strategy to work */
+
+ /* For explanations on how to distribute symbol values over the table :
+ * http://fastcompression.blogspot.fr/2014/02/fse-distributing-symbol-values.html */
+
+ #ifdef __clang_analyzer__
+ memset(tableSymbol, 0, sizeof(*tableSymbol) * tableSize); /* useless initialization, just to keep scan-build happy */
+ #endif
+
+ /* symbol start positions */
+ { U32 u;
+ cumul[0] = 0;
+ for (u=1; u <= maxSymbolValue+1; u++) {
+ if (normalizedCounter[u-1]==-1) { /* Low proba symbol */
+ cumul[u] = cumul[u-1] + 1;
+ tableSymbol[highThreshold--] = (FSE_FUNCTION_TYPE)(u-1);
+ } else {
+ cumul[u] = cumul[u-1] + normalizedCounter[u-1];
+ } }
+ cumul[maxSymbolValue+1] = tableSize+1;
+ }
+
+ /* Spread symbols */
+ { U32 position = 0;
+ U32 symbol;
+ for (symbol=0; symbol<=maxSymbolValue; symbol++) {
+ int nbOccurences;
+ int const freq = normalizedCounter[symbol];
+ for (nbOccurences=0; nbOccurences<freq; nbOccurences++) {
+ tableSymbol[position] = (FSE_FUNCTION_TYPE)symbol;
+ position = (position + step) & tableMask;
+ while (position > highThreshold)
+ position = (position + step) & tableMask; /* Low proba area */
+ } }
+
+ assert(position==0); /* Must have initialized all positions */
+ }
+
+ /* Build table */
+ { U32 u; for (u=0; u<tableSize; u++) {
+ FSE_FUNCTION_TYPE s = tableSymbol[u]; /* note : static analyzer may not understand tableSymbol is properly initialized */
+ tableU16[cumul[s]++] = (U16) (tableSize+u); /* TableU16 : sorted by symbol order; gives next state value */
+ } }
+
+ /* Build Symbol Transformation Table */
+ { unsigned total = 0;
+ unsigned s;
+ for (s=0; s<=maxSymbolValue; s++) {
+ switch (normalizedCounter[s])
+ {
+ case 0:
+ /* filling nonetheless, for compatibility with FSE_getMaxNbBits() */
+ symbolTT[s].deltaNbBits = ((tableLog+1) << 16) - (1<<tableLog);
+ break;
+
+ case -1:
+ case 1:
+ symbolTT[s].deltaNbBits = (tableLog << 16) - (1<<tableLog);
+ symbolTT[s].deltaFindState = total - 1;
+ total ++;
+ break;
+ default :
+ {
+ U32 const maxBitsOut = tableLog - BIT_highbit32 (normalizedCounter[s]-1);
+ U32 const minStatePlus = normalizedCounter[s] << maxBitsOut;
+ symbolTT[s].deltaNbBits = (maxBitsOut << 16) - minStatePlus;
+ symbolTT[s].deltaFindState = total - normalizedCounter[s];
+ total += normalizedCounter[s];
+ } } } }
+
+#if 0 /* debug : symbol costs */
+ DEBUGLOG(5, "\n --- table statistics : ");
+ { U32 symbol;
+ for (symbol=0; symbol<=maxSymbolValue; symbol++) {
+ DEBUGLOG(5, "%3u: w=%3i, maxBits=%u, fracBits=%.2f",
+ symbol, normalizedCounter[symbol],
+ FSE_getMaxNbBits(symbolTT, symbol),
+ (double)FSE_bitCost(symbolTT, tableLog, symbol, 8) / 256);
+ }
+ }
+#endif
+
+ return 0;
+}
+
+
+size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
+{
+ FSE_FUNCTION_TYPE tableSymbol[FSE_MAX_TABLESIZE]; /* memset() is not necessary, even if static analyzer complain about it */
+ return FSE_buildCTable_wksp(ct, normalizedCounter, maxSymbolValue, tableLog, tableSymbol, sizeof(tableSymbol));
+}
+
+
+
+#ifndef FSE_COMMONDEFS_ONLY
+
+
+/*-**************************************************************
+* FSE NCount encoding
+****************************************************************/
+size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog)
+{
+ size_t const maxHeaderSize = (((maxSymbolValue+1) * tableLog) >> 3) + 3;
+ return maxSymbolValue ? maxHeaderSize : FSE_NCOUNTBOUND; /* maxSymbolValue==0 ? use default */
+}
+
+static size_t
+FSE_writeNCount_generic (void* header, size_t headerBufferSize,
+ const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog,
+ unsigned writeIsSafe)
+{
+ BYTE* const ostart = (BYTE*) header;
+ BYTE* out = ostart;
+ BYTE* const oend = ostart + headerBufferSize;
+ int nbBits;
+ const int tableSize = 1 << tableLog;
+ int remaining;
+ int threshold;
+ U32 bitStream = 0;
+ int bitCount = 0;
+ unsigned symbol = 0;
+ unsigned const alphabetSize = maxSymbolValue + 1;
+ int previousIs0 = 0;
+
+ /* Table Size */
+ bitStream += (tableLog-FSE_MIN_TABLELOG) << bitCount;
+ bitCount += 4;
+
+ /* Init */
+ remaining = tableSize+1; /* +1 for extra accuracy */
+ threshold = tableSize;
+ nbBits = tableLog+1;
+
+ while ((symbol < alphabetSize) && (remaining>1)) { /* stops at 1 */
+ if (previousIs0) {
+ unsigned start = symbol;
+ while ((symbol < alphabetSize) && !normalizedCounter[symbol]) symbol++;
+ if (symbol == alphabetSize) break; /* incorrect distribution */
+ while (symbol >= start+24) {
+ start+=24;
+ bitStream += 0xFFFFU << bitCount;
+ if ((!writeIsSafe) && (out > oend-2))
+ return ERROR(dstSize_tooSmall); /* Buffer overflow */
+ out[0] = (BYTE) bitStream;
+ out[1] = (BYTE)(bitStream>>8);
+ out+=2;
+ bitStream>>=16;
+ }
+ while (symbol >= start+3) {
+ start+=3;
+ bitStream += 3 << bitCount;
+ bitCount += 2;
+ }
+ bitStream += (symbol-start) << bitCount;
+ bitCount += 2;
+ if (bitCount>16) {
+ if ((!writeIsSafe) && (out > oend - 2))
+ return ERROR(dstSize_tooSmall); /* Buffer overflow */
+ out[0] = (BYTE)bitStream;
+ out[1] = (BYTE)(bitStream>>8);
+ out += 2;
+ bitStream >>= 16;
+ bitCount -= 16;
+ } }
+ { int count = normalizedCounter[symbol++];
+ int const max = (2*threshold-1) - remaining;
+ remaining -= count < 0 ? -count : count;
+ count++; /* +1 for extra accuracy */
+ if (count>=threshold)
+ count += max; /* [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[ */
+ bitStream += count << bitCount;
+ bitCount += nbBits;
+ bitCount -= (count<max);
+ previousIs0 = (count==1);
+ if (remaining<1) return ERROR(GENERIC);
+ while (remaining<threshold) { nbBits--; threshold>>=1; }
+ }
+ if (bitCount>16) {
+ if ((!writeIsSafe) && (out > oend - 2))
+ return ERROR(dstSize_tooSmall); /* Buffer overflow */
+ out[0] = (BYTE)bitStream;
+ out[1] = (BYTE)(bitStream>>8);
+ out += 2;
+ bitStream >>= 16;
+ bitCount -= 16;
+ } }
+
+ if (remaining != 1)
+ return ERROR(GENERIC); /* incorrect normalized distribution */
+ assert(symbol <= alphabetSize);
+
+ /* flush remaining bitStream */
+ if ((!writeIsSafe) && (out > oend - 2))
+ return ERROR(dstSize_tooSmall); /* Buffer overflow */
+ out[0] = (BYTE)bitStream;
+ out[1] = (BYTE)(bitStream>>8);
+ out+= (bitCount+7) /8;
+
+ return (out-ostart);
+}
+
+
+size_t FSE_writeNCount (void* buffer, size_t bufferSize,
+ const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
+{
+ if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported */
+ if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported */
+
+ if (bufferSize < FSE_NCountWriteBound(maxSymbolValue, tableLog))
+ return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 0);
+
+ return FSE_writeNCount_generic(buffer, bufferSize, normalizedCounter, maxSymbolValue, tableLog, 1 /* write in buffer is safe */);
+}
+
+
+/*-**************************************************************
+* FSE Compression Code
+****************************************************************/
+
+FSE_CTable* FSE_createCTable (unsigned maxSymbolValue, unsigned tableLog)
+{
+ size_t size;
+ if (tableLog > FSE_TABLELOG_ABSOLUTE_MAX) tableLog = FSE_TABLELOG_ABSOLUTE_MAX;
+ size = FSE_CTABLE_SIZE_U32 (tableLog, maxSymbolValue) * sizeof(U32);
+ return (FSE_CTable*)malloc(size);
+}
+
+void FSE_freeCTable (FSE_CTable* ct) { free(ct); }
+
+/* provides the minimum logSize to safely represent a distribution */
+static unsigned FSE_minTableLog(size_t srcSize, unsigned maxSymbolValue)
+{
+ U32 minBitsSrc = BIT_highbit32((U32)(srcSize)) + 1;
+ U32 minBitsSymbols = BIT_highbit32(maxSymbolValue) + 2;
+ U32 minBits = minBitsSrc < minBitsSymbols ? minBitsSrc : minBitsSymbols;
+ assert(srcSize > 1); /* Not supported, RLE should be used instead */
+ return minBits;
+}
+
+unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus)
+{
+ U32 maxBitsSrc = BIT_highbit32((U32)(srcSize - 1)) - minus;
+ U32 tableLog = maxTableLog;
+ U32 minBits = FSE_minTableLog(srcSize, maxSymbolValue);
+ assert(srcSize > 1); /* Not supported, RLE should be used instead */
+ if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
+ if (maxBitsSrc < tableLog) tableLog = maxBitsSrc; /* Accuracy can be reduced */
+ if (minBits > tableLog) tableLog = minBits; /* Need a minimum to safely represent all symbol values */
+ if (tableLog < FSE_MIN_TABLELOG) tableLog = FSE_MIN_TABLELOG;
+ if (tableLog > FSE_MAX_TABLELOG) tableLog = FSE_MAX_TABLELOG;
+ return tableLog;
+}
+
+unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
+{
+ return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 2);
+}
+
+
+/* Secondary normalization method.
+ To be used when primary method fails. */
+
+static size_t FSE_normalizeM2(short* norm, U32 tableLog, const unsigned* count, size_t total, U32 maxSymbolValue)
+{
+ short const NOT_YET_ASSIGNED = -2;
+ U32 s;
+ U32 distributed = 0;
+ U32 ToDistribute;
+
+ /* Init */
+ U32 const lowThreshold = (U32)(total >> tableLog);
+ U32 lowOne = (U32)((total * 3) >> (tableLog + 1));
+
+ for (s=0; s<=maxSymbolValue; s++) {
+ if (count[s] == 0) {
+ norm[s]=0;
+ continue;
+ }
+ if (count[s] <= lowThreshold) {
+ norm[s] = -1;
+ distributed++;
+ total -= count[s];
+ continue;
+ }
+ if (count[s] <= lowOne) {
+ norm[s] = 1;
+ distributed++;
+ total -= count[s];
+ continue;
+ }
+
+ norm[s]=NOT_YET_ASSIGNED;
+ }
+ ToDistribute = (1 << tableLog) - distributed;
+
+ if (ToDistribute == 0)
+ return 0;
+
+ if ((total / ToDistribute) > lowOne) {
+ /* risk of rounding to zero */
+ lowOne = (U32)((total * 3) / (ToDistribute * 2));
+ for (s=0; s<=maxSymbolValue; s++) {
+ if ((norm[s] == NOT_YET_ASSIGNED) && (count[s] <= lowOne)) {
+ norm[s] = 1;
+ distributed++;
+ total -= count[s];
+ continue;
+ } }
+ ToDistribute = (1 << tableLog) - distributed;
+ }
+
+ if (distributed == maxSymbolValue+1) {
+ /* all values are pretty poor;
+ probably incompressible data (should have already been detected);
+ find max, then give all remaining points to max */
+ U32 maxV = 0, maxC = 0;
+ for (s=0; s<=maxSymbolValue; s++)
+ if (count[s] > maxC) { maxV=s; maxC=count[s]; }
+ norm[maxV] += (short)ToDistribute;
+ return 0;
+ }
+
+ if (total == 0) {
+ /* all of the symbols were low enough for the lowOne or lowThreshold */
+ for (s=0; ToDistribute > 0; s = (s+1)%(maxSymbolValue+1))
+ if (norm[s] > 0) { ToDistribute--; norm[s]++; }
+ return 0;
+ }
+
+ { U64 const vStepLog = 62 - tableLog;
+ U64 const mid = (1ULL << (vStepLog-1)) - 1;
+ U64 const rStep = ((((U64)1<<vStepLog) * ToDistribute) + mid) / total; /* scale on remaining */
+ U64 tmpTotal = mid;
+ for (s=0; s<=maxSymbolValue; s++) {
+ if (norm[s]==NOT_YET_ASSIGNED) {
+ U64 const end = tmpTotal + (count[s] * rStep);
+ U32 const sStart = (U32)(tmpTotal >> vStepLog);
+ U32 const sEnd = (U32)(end >> vStepLog);
+ U32 const weight = sEnd - sStart;
+ if (weight < 1)
+ return ERROR(GENERIC);
+ norm[s] = (short)weight;
+ tmpTotal = end;
+ } } }
+
+ return 0;
+}
+
+
+size_t FSE_normalizeCount (short* normalizedCounter, unsigned tableLog,
+ const unsigned* count, size_t total,
+ unsigned maxSymbolValue)
+{
+ /* Sanity checks */
+ if (tableLog==0) tableLog = FSE_DEFAULT_TABLELOG;
+ if (tableLog < FSE_MIN_TABLELOG) return ERROR(GENERIC); /* Unsupported size */
+ if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); /* Unsupported size */
+ if (tableLog < FSE_minTableLog(total, maxSymbolValue)) return ERROR(GENERIC); /* Too small tableLog, compression potentially impossible */
+
+ { static U32 const rtbTable[] = { 0, 473195, 504333, 520860, 550000, 700000, 750000, 830000 };
+ U64 const scale = 62 - tableLog;
+ U64 const step = ((U64)1<<62) / total; /* <== here, one division ! */
+ U64 const vStep = 1ULL<<(scale-20);
+ int stillToDistribute = 1<<tableLog;
+ unsigned s;
+ unsigned largest=0;
+ short largestP=0;
+ U32 lowThreshold = (U32)(total >> tableLog);
+
+ for (s=0; s<=maxSymbolValue; s++) {
+ if (count[s] == total) return 0; /* rle special case */
+ if (count[s] == 0) { normalizedCounter[s]=0; continue; }
+ if (count[s] <= lowThreshold) {
+ normalizedCounter[s] = -1;
+ stillToDistribute--;
+ } else {
+ short proba = (short)((count[s]*step) >> scale);
+ if (proba<8) {
+ U64 restToBeat = vStep * rtbTable[proba];
+ proba += (count[s]*step) - ((U64)proba<<scale) > restToBeat;
+ }
+ if (proba > largestP) { largestP=proba; largest=s; }
+ normalizedCounter[s] = proba;
+ stillToDistribute -= proba;
+ } }
+ if (-stillToDistribute >= (normalizedCounter[largest] >> 1)) {
+ /* corner case, need another normalization method */
+ size_t const errorCode = FSE_normalizeM2(normalizedCounter, tableLog, count, total, maxSymbolValue);
+ if (FSE_isError(errorCode)) return errorCode;
+ }
+ else normalizedCounter[largest] += (short)stillToDistribute;
+ }
+
+#if 0
+ { /* Print Table (debug) */
+ U32 s;
+ U32 nTotal = 0;
+ for (s=0; s<=maxSymbolValue; s++)
+ RAWLOG(2, "%3i: %4i \n", s, normalizedCounter[s]);
+ for (s=0; s<=maxSymbolValue; s++)
+ nTotal += abs(normalizedCounter[s]);
+ if (nTotal != (1U<<tableLog))
+ RAWLOG(2, "Warning !!! Total == %u != %u !!!", nTotal, 1U<<tableLog);
+ getchar();
+ }
+#endif
+
+ return tableLog;
+}
+
+
+/* fake FSE_CTable, for raw (uncompressed) input */
+size_t FSE_buildCTable_raw (FSE_CTable* ct, unsigned nbBits)
+{
+ const unsigned tableSize = 1 << nbBits;
+ const unsigned tableMask = tableSize - 1;
+ const unsigned maxSymbolValue = tableMask;
+ void* const ptr = ct;
+ U16* const tableU16 = ( (U16*) ptr) + 2;
+ void* const FSCT = ((U32*)ptr) + 1 /* header */ + (tableSize>>1); /* assumption : tableLog >= 1 */
+ FSE_symbolCompressionTransform* const symbolTT = (FSE_symbolCompressionTransform*) (FSCT);
+ unsigned s;
+
+ /* Sanity checks */
+ if (nbBits < 1) return ERROR(GENERIC); /* min size */
+
+ /* header */
+ tableU16[-2] = (U16) nbBits;
+ tableU16[-1] = (U16) maxSymbolValue;
+
+ /* Build table */
+ for (s=0; s<tableSize; s++)
+ tableU16[s] = (U16)(tableSize + s);
+
+ /* Build Symbol Transformation Table */
+ { const U32 deltaNbBits = (nbBits << 16) - (1 << nbBits);
+ for (s=0; s<=maxSymbolValue; s++) {
+ symbolTT[s].deltaNbBits = deltaNbBits;
+ symbolTT[s].deltaFindState = s-1;
+ } }
+
+ return 0;
+}
+
+/* fake FSE_CTable, for rle input (always same symbol) */
+size_t FSE_buildCTable_rle (FSE_CTable* ct, BYTE symbolValue)
+{
+ void* ptr = ct;
+ U16* tableU16 = ( (U16*) ptr) + 2;
+ void* FSCTptr = (U32*)ptr + 2;
+ FSE_symbolCompressionTransform* symbolTT = (FSE_symbolCompressionTransform*) FSCTptr;
+
+ /* header */
+ tableU16[-2] = (U16) 0;
+ tableU16[-1] = (U16) symbolValue;
+
+ /* Build table */
+ tableU16[0] = 0;
+ tableU16[1] = 0; /* just in case */
+
+ /* Build Symbol Transformation Table */
+ symbolTT[symbolValue].deltaNbBits = 0;
+ symbolTT[symbolValue].deltaFindState = 0;
+
+ return 0;
+}
+
+
+static size_t FSE_compress_usingCTable_generic (void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ const FSE_CTable* ct, const unsigned fast)
+{
+ const BYTE* const istart = (const BYTE*) src;
+ const BYTE* const iend = istart + srcSize;
+ const BYTE* ip=iend;
+
+ BIT_CStream_t bitC;
+ FSE_CState_t CState1, CState2;
+
+ /* init */
+ if (srcSize <= 2) return 0;
+ { size_t const initError = BIT_initCStream(&bitC, dst, dstSize);
+ if (FSE_isError(initError)) return 0; /* not enough space available to write a bitstream */ }
+
+#define FSE_FLUSHBITS(s) (fast ? BIT_flushBitsFast(s) : BIT_flushBits(s))
+
+ if (srcSize & 1) {
+ FSE_initCState2(&CState1, ct, *--ip);
+ FSE_initCState2(&CState2, ct, *--ip);
+ FSE_encodeSymbol(&bitC, &CState1, *--ip);
+ FSE_FLUSHBITS(&bitC);
+ } else {
+ FSE_initCState2(&CState2, ct, *--ip);
+ FSE_initCState2(&CState1, ct, *--ip);
+ }
+
+ /* join to mod 4 */
+ srcSize -= 2;
+ if ((sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) && (srcSize & 2)) { /* test bit 2 */
+ FSE_encodeSymbol(&bitC, &CState2, *--ip);
+ FSE_encodeSymbol(&bitC, &CState1, *--ip);
+ FSE_FLUSHBITS(&bitC);
+ }
+
+ /* 2 or 4 encoding per loop */
+ while ( ip>istart ) {
+
+ FSE_encodeSymbol(&bitC, &CState2, *--ip);
+
+ if (sizeof(bitC.bitContainer)*8 < FSE_MAX_TABLELOG*2+7 ) /* this test must be static */
+ FSE_FLUSHBITS(&bitC);
+
+ FSE_encodeSymbol(&bitC, &CState1, *--ip);
+
+ if (sizeof(bitC.bitContainer)*8 > FSE_MAX_TABLELOG*4+7 ) { /* this test must be static */
+ FSE_encodeSymbol(&bitC, &CState2, *--ip);
+ FSE_encodeSymbol(&bitC, &CState1, *--ip);
+ }
+
+ FSE_FLUSHBITS(&bitC);
+ }
+
+ FSE_flushCState(&bitC, &CState2);
+ FSE_flushCState(&bitC, &CState1);
+ return BIT_closeCStream(&bitC);
+}
+
+size_t FSE_compress_usingCTable (void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ const FSE_CTable* ct)
+{
+ unsigned const fast = (dstSize >= FSE_BLOCKBOUND(srcSize));
+
+ if (fast)
+ return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 1);
+ else
+ return FSE_compress_usingCTable_generic(dst, dstSize, src, srcSize, ct, 0);
+}
+
+
+size_t FSE_compressBound(size_t size) { return FSE_COMPRESSBOUND(size); }
+
+#define CHECK_V_F(e, f) size_t const e = f; if (ERR_isError(e)) return e
+#define CHECK_F(f) { CHECK_V_F(_var_err__, f); }
+
+/* FSE_compress_wksp() :
+ * Same as FSE_compress2(), but using an externally allocated scratch buffer (`workSpace`).
+ * `wkspSize` size must be `(1<<tableLog)`.
+ */
+size_t FSE_compress_wksp (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize)
+{
+ BYTE* const ostart = (BYTE*) dst;
+ BYTE* op = ostart;
+ BYTE* const oend = ostart + dstSize;
+
+ unsigned count[FSE_MAX_SYMBOL_VALUE+1];
+ S16 norm[FSE_MAX_SYMBOL_VALUE+1];
+ FSE_CTable* CTable = (FSE_CTable*)workSpace;
+ size_t const CTableSize = FSE_CTABLE_SIZE_U32(tableLog, maxSymbolValue);
+ void* scratchBuffer = (void*)(CTable + CTableSize);
+ size_t const scratchBufferSize = wkspSize - (CTableSize * sizeof(FSE_CTable));
+
+ /* init conditions */
+ if (wkspSize < FSE_WKSP_SIZE_U32(tableLog, maxSymbolValue)) return ERROR(tableLog_tooLarge);
+ if (srcSize <= 1) return 0; /* Not compressible */
+ if (!maxSymbolValue) maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
+ if (!tableLog) tableLog = FSE_DEFAULT_TABLELOG;
+
+ /* Scan input and build symbol stats */
+ { CHECK_V_F(maxCount, HIST_count_wksp(count, &maxSymbolValue, src, srcSize, scratchBuffer, scratchBufferSize) );
+ if (maxCount == srcSize) return 1; /* only a single symbol in src : rle */
+ if (maxCount == 1) return 0; /* each symbol present maximum once => not compressible */
+ if (maxCount < (srcSize >> 7)) return 0; /* Heuristic : not compressible enough */
+ }
+
+ tableLog = FSE_optimalTableLog(tableLog, srcSize, maxSymbolValue);
+ CHECK_F( FSE_normalizeCount(norm, tableLog, count, srcSize, maxSymbolValue) );
+
+ /* Write table description header */
+ { CHECK_V_F(nc_err, FSE_writeNCount(op, oend-op, norm, maxSymbolValue, tableLog) );
+ op += nc_err;
+ }
+
+ /* Compress */
+ CHECK_F( FSE_buildCTable_wksp(CTable, norm, maxSymbolValue, tableLog, scratchBuffer, scratchBufferSize) );
+ { CHECK_V_F(cSize, FSE_compress_usingCTable(op, oend - op, src, srcSize, CTable) );
+ if (cSize == 0) return 0; /* not enough space for compressed data */
+ op += cSize;
+ }
+
+ /* check compressibility */
+ if ( (size_t)(op-ostart) >= srcSize-1 ) return 0;
+
+ return op-ostart;
+}
+
+typedef struct {
+ FSE_CTable CTable_max[FSE_CTABLE_SIZE_U32(FSE_MAX_TABLELOG, FSE_MAX_SYMBOL_VALUE)];
+ BYTE scratchBuffer[1 << FSE_MAX_TABLELOG];
+} fseWkspMax_t;
+
+size_t FSE_compress2 (void* dst, size_t dstCapacity, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog)
+{
+ fseWkspMax_t scratchBuffer;
+ DEBUG_STATIC_ASSERT(sizeof(scratchBuffer) >= FSE_WKSP_SIZE_U32(FSE_MAX_TABLELOG, FSE_MAX_SYMBOL_VALUE)); /* compilation failures here means scratchBuffer is not large enough */
+ if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
+ return FSE_compress_wksp(dst, dstCapacity, src, srcSize, maxSymbolValue, tableLog, &scratchBuffer, sizeof(scratchBuffer));
+}
+
+size_t FSE_compress (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
+{
+ return FSE_compress2(dst, dstCapacity, src, srcSize, FSE_MAX_SYMBOL_VALUE, FSE_DEFAULT_TABLELOG);
+}
+
+
+#endif /* FSE_COMMONDEFS_ONLY */
diff --git a/Utilities/cmzstd/lib/compress/hist.c b/Utilities/cmzstd/lib/compress/hist.c
new file mode 100644
index 000000000..45b7babc1
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/hist.c
@@ -0,0 +1,203 @@
+/* ******************************************************************
+ hist : Histogram functions
+ part of Finite State Entropy project
+ Copyright (C) 2013-present, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
+ - Public forum : https://groups.google.com/forum/#!forum/lz4c
+****************************************************************** */
+
+/* --- dependencies --- */
+#include "mem.h" /* U32, BYTE, etc. */
+#include "debug.h" /* assert, DEBUGLOG */
+#include "error_private.h" /* ERROR */
+#include "hist.h"
+
+
+/* --- Error management --- */
+unsigned HIST_isError(size_t code) { return ERR_isError(code); }
+
+/*-**************************************************************
+ * Histogram functions
+ ****************************************************************/
+unsigned HIST_count_simple(unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* src, size_t srcSize)
+{
+ const BYTE* ip = (const BYTE*)src;
+ const BYTE* const end = ip + srcSize;
+ unsigned maxSymbolValue = *maxSymbolValuePtr;
+ unsigned largestCount=0;
+
+ memset(count, 0, (maxSymbolValue+1) * sizeof(*count));
+ if (srcSize==0) { *maxSymbolValuePtr = 0; return 0; }
+
+ while (ip<end) {
+ assert(*ip <= maxSymbolValue);
+ count[*ip++]++;
+ }
+
+ while (!count[maxSymbolValue]) maxSymbolValue--;
+ *maxSymbolValuePtr = maxSymbolValue;
+
+ { U32 s;
+ for (s=0; s<=maxSymbolValue; s++)
+ if (count[s] > largestCount) largestCount = count[s];
+ }
+
+ return largestCount;
+}
+
+typedef enum { trustInput, checkMaxSymbolValue } HIST_checkInput_e;
+
+/* HIST_count_parallel_wksp() :
+ * store histogram into 4 intermediate tables, recombined at the end.
+ * this design makes better use of OoO cpus,
+ * and is noticeably faster when some values are heavily repeated.
+ * But it needs some additional workspace for intermediate tables.
+ * `workSpace` size must be a table of size >= HIST_WKSP_SIZE_U32.
+ * @return : largest histogram frequency,
+ * or an error code (notably when histogram would be larger than *maxSymbolValuePtr). */
+static size_t HIST_count_parallel_wksp(
+ unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* source, size_t sourceSize,
+ HIST_checkInput_e check,
+ U32* const workSpace)
+{
+ const BYTE* ip = (const BYTE*)source;
+ const BYTE* const iend = ip+sourceSize;
+ unsigned maxSymbolValue = *maxSymbolValuePtr;
+ unsigned max=0;
+ U32* const Counting1 = workSpace;
+ U32* const Counting2 = Counting1 + 256;
+ U32* const Counting3 = Counting2 + 256;
+ U32* const Counting4 = Counting3 + 256;
+
+ memset(workSpace, 0, 4*256*sizeof(unsigned));
+
+ /* safety checks */
+ if (!sourceSize) {
+ memset(count, 0, maxSymbolValue + 1);
+ *maxSymbolValuePtr = 0;
+ return 0;
+ }
+ if (!maxSymbolValue) maxSymbolValue = 255; /* 0 == default */
+
+ /* by stripes of 16 bytes */
+ { U32 cached = MEM_read32(ip); ip += 4;
+ while (ip < iend-15) {
+ U32 c = cached; cached = MEM_read32(ip); ip += 4;
+ Counting1[(BYTE) c ]++;
+ Counting2[(BYTE)(c>>8) ]++;
+ Counting3[(BYTE)(c>>16)]++;
+ Counting4[ c>>24 ]++;
+ c = cached; cached = MEM_read32(ip); ip += 4;
+ Counting1[(BYTE) c ]++;
+ Counting2[(BYTE)(c>>8) ]++;
+ Counting3[(BYTE)(c>>16)]++;
+ Counting4[ c>>24 ]++;
+ c = cached; cached = MEM_read32(ip); ip += 4;
+ Counting1[(BYTE) c ]++;
+ Counting2[(BYTE)(c>>8) ]++;
+ Counting3[(BYTE)(c>>16)]++;
+ Counting4[ c>>24 ]++;
+ c = cached; cached = MEM_read32(ip); ip += 4;
+ Counting1[(BYTE) c ]++;
+ Counting2[(BYTE)(c>>8) ]++;
+ Counting3[(BYTE)(c>>16)]++;
+ Counting4[ c>>24 ]++;
+ }
+ ip-=4;
+ }
+
+ /* finish last symbols */
+ while (ip<iend) Counting1[*ip++]++;
+
+ if (check) { /* verify stats will fit into destination table */
+ U32 s; for (s=255; s>maxSymbolValue; s--) {
+ Counting1[s] += Counting2[s] + Counting3[s] + Counting4[s];
+ if (Counting1[s]) return ERROR(maxSymbolValue_tooSmall);
+ } }
+
+ { U32 s;
+ if (maxSymbolValue > 255) maxSymbolValue = 255;
+ for (s=0; s<=maxSymbolValue; s++) {
+ count[s] = Counting1[s] + Counting2[s] + Counting3[s] + Counting4[s];
+ if (count[s] > max) max = count[s];
+ } }
+
+ while (!count[maxSymbolValue]) maxSymbolValue--;
+ *maxSymbolValuePtr = maxSymbolValue;
+ return (size_t)max;
+}
+
+/* HIST_countFast_wksp() :
+ * Same as HIST_countFast(), but using an externally provided scratch buffer.
+ * `workSpace` is a writable buffer which must be 4-bytes aligned,
+ * `workSpaceSize` must be >= HIST_WKSP_SIZE
+ */
+size_t HIST_countFast_wksp(unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* source, size_t sourceSize,
+ void* workSpace, size_t workSpaceSize)
+{
+ if (sourceSize < 1500) /* heuristic threshold */
+ return HIST_count_simple(count, maxSymbolValuePtr, source, sourceSize);
+ if ((size_t)workSpace & 3) return ERROR(GENERIC); /* must be aligned on 4-bytes boundaries */
+ if (workSpaceSize < HIST_WKSP_SIZE) return ERROR(workSpace_tooSmall);
+ return HIST_count_parallel_wksp(count, maxSymbolValuePtr, source, sourceSize, trustInput, (U32*)workSpace);
+}
+
+/* fast variant (unsafe : won't check if src contains values beyond count[] limit) */
+size_t HIST_countFast(unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* source, size_t sourceSize)
+{
+ unsigned tmpCounters[HIST_WKSP_SIZE_U32];
+ return HIST_countFast_wksp(count, maxSymbolValuePtr, source, sourceSize, tmpCounters, sizeof(tmpCounters));
+}
+
+/* HIST_count_wksp() :
+ * Same as HIST_count(), but using an externally provided scratch buffer.
+ * `workSpace` size must be table of >= HIST_WKSP_SIZE_U32 unsigned */
+size_t HIST_count_wksp(unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* source, size_t sourceSize,
+ void* workSpace, size_t workSpaceSize)
+{
+ if ((size_t)workSpace & 3) return ERROR(GENERIC); /* must be aligned on 4-bytes boundaries */
+ if (workSpaceSize < HIST_WKSP_SIZE) return ERROR(workSpace_tooSmall);
+ if (*maxSymbolValuePtr < 255)
+ return HIST_count_parallel_wksp(count, maxSymbolValuePtr, source, sourceSize, checkMaxSymbolValue, (U32*)workSpace);
+ *maxSymbolValuePtr = 255;
+ return HIST_countFast_wksp(count, maxSymbolValuePtr, source, sourceSize, workSpace, workSpaceSize);
+}
+
+size_t HIST_count(unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* src, size_t srcSize)
+{
+ unsigned tmpCounters[HIST_WKSP_SIZE_U32];
+ return HIST_count_wksp(count, maxSymbolValuePtr, src, srcSize, tmpCounters, sizeof(tmpCounters));
+}
diff --git a/Utilities/cmzstd/lib/compress/hist.h b/Utilities/cmzstd/lib/compress/hist.h
new file mode 100644
index 000000000..8b389358d
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/hist.h
@@ -0,0 +1,95 @@
+/* ******************************************************************
+ hist : Histogram functions
+ part of Finite State Entropy project
+ Copyright (C) 2013-present, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
+ - Public forum : https://groups.google.com/forum/#!forum/lz4c
+****************************************************************** */
+
+/* --- dependencies --- */
+#include <stddef.h> /* size_t */
+
+
+/* --- simple histogram functions --- */
+
+/*! HIST_count():
+ * Provides the precise count of each byte within a table 'count'.
+ * 'count' is a table of unsigned int, of minimum size (*maxSymbolValuePtr+1).
+ * Updates *maxSymbolValuePtr with actual largest symbol value detected.
+ * @return : count of the most frequent symbol (which isn't identified).
+ * or an error code, which can be tested using HIST_isError().
+ * note : if return == srcSize, there is only one symbol.
+ */
+size_t HIST_count(unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* src, size_t srcSize);
+
+unsigned HIST_isError(size_t code); /**< tells if a return value is an error code */
+
+
+/* --- advanced histogram functions --- */
+
+#define HIST_WKSP_SIZE_U32 1024
+#define HIST_WKSP_SIZE (HIST_WKSP_SIZE_U32 * sizeof(unsigned))
+/** HIST_count_wksp() :
+ * Same as HIST_count(), but using an externally provided scratch buffer.
+ * Benefit is this function will use very little stack space.
+ * `workSpace` is a writable buffer which must be 4-bytes aligned,
+ * `workSpaceSize` must be >= HIST_WKSP_SIZE
+ */
+size_t HIST_count_wksp(unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* src, size_t srcSize,
+ void* workSpace, size_t workSpaceSize);
+
+/** HIST_countFast() :
+ * same as HIST_count(), but blindly trusts that all byte values within src are <= *maxSymbolValuePtr.
+ * This function is unsafe, and will segfault if any value within `src` is `> *maxSymbolValuePtr`
+ */
+size_t HIST_countFast(unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* src, size_t srcSize);
+
+/** HIST_countFast_wksp() :
+ * Same as HIST_countFast(), but using an externally provided scratch buffer.
+ * `workSpace` is a writable buffer which must be 4-bytes aligned,
+ * `workSpaceSize` must be >= HIST_WKSP_SIZE
+ */
+size_t HIST_countFast_wksp(unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* src, size_t srcSize,
+ void* workSpace, size_t workSpaceSize);
+
+/*! HIST_count_simple() :
+ * Same as HIST_countFast(), this function is unsafe,
+ * and will segfault if any value within `src` is `> *maxSymbolValuePtr`.
+ * It is also a bit slower for large inputs.
+ * However, it does not need any additional memory (not even on stack).
+ * @return : count of the most frequent symbol.
+ * Note this function doesn't produce any error (i.e. it must succeed).
+ */
+unsigned HIST_count_simple(unsigned* count, unsigned* maxSymbolValuePtr,
+ const void* src, size_t srcSize);
diff --git a/Utilities/cmzstd/lib/compress/huf_compress.c b/Utilities/cmzstd/lib/compress/huf_compress.c
new file mode 100644
index 000000000..f074f1e0a
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/huf_compress.c
@@ -0,0 +1,798 @@
+/* ******************************************************************
+ Huffman encoder, part of New Generation Entropy library
+ Copyright (C) 2013-2016, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
+ - Public forum : https://groups.google.com/forum/#!forum/lz4c
+****************************************************************** */
+
+/* **************************************************************
+* Compiler specifics
+****************************************************************/
+#ifdef _MSC_VER /* Visual Studio */
+# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
+#endif
+
+
+/* **************************************************************
+* Includes
+****************************************************************/
+#include <string.h> /* memcpy, memset */
+#include <stdio.h> /* printf (debug) */
+#include "compiler.h"
+#include "bitstream.h"
+#include "hist.h"
+#define FSE_STATIC_LINKING_ONLY /* FSE_optimalTableLog_internal */
+#include "fse.h" /* header compression */
+#define HUF_STATIC_LINKING_ONLY
+#include "huf.h"
+#include "error_private.h"
+
+
+/* **************************************************************
+* Error Management
+****************************************************************/
+#define HUF_isError ERR_isError
+#define HUF_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c) /* use only *after* variable declarations */
+#define CHECK_V_F(e, f) size_t const e = f; if (ERR_isError(e)) return e
+#define CHECK_F(f) { CHECK_V_F(_var_err__, f); }
+
+
+/* **************************************************************
+* Utils
+****************************************************************/
+unsigned HUF_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
+{
+ return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 1);
+}
+
+
+/* *******************************************************
+* HUF : Huffman block compression
+*********************************************************/
+/* HUF_compressWeights() :
+ * Same as FSE_compress(), but dedicated to huff0's weights compression.
+ * The use case needs much less stack memory.
+ * Note : all elements within weightTable are supposed to be <= HUF_TABLELOG_MAX.
+ */
+#define MAX_FSE_TABLELOG_FOR_HUFF_HEADER 6
+static size_t HUF_compressWeights (void* dst, size_t dstSize, const void* weightTable, size_t wtSize)
+{
+ BYTE* const ostart = (BYTE*) dst;
+ BYTE* op = ostart;
+ BYTE* const oend = ostart + dstSize;
+
+ unsigned maxSymbolValue = HUF_TABLELOG_MAX;
+ U32 tableLog = MAX_FSE_TABLELOG_FOR_HUFF_HEADER;
+
+ FSE_CTable CTable[FSE_CTABLE_SIZE_U32(MAX_FSE_TABLELOG_FOR_HUFF_HEADER, HUF_TABLELOG_MAX)];
+ BYTE scratchBuffer[1<<MAX_FSE_TABLELOG_FOR_HUFF_HEADER];
+
+ unsigned count[HUF_TABLELOG_MAX+1];
+ S16 norm[HUF_TABLELOG_MAX+1];
+
+ /* init conditions */
+ if (wtSize <= 1) return 0; /* Not compressible */
+
+ /* Scan input and build symbol stats */
+ { unsigned const maxCount = HIST_count_simple(count, &maxSymbolValue, weightTable, wtSize); /* never fails */
+ if (maxCount == wtSize) return 1; /* only a single symbol in src : rle */
+ if (maxCount == 1) return 0; /* each symbol present maximum once => not compressible */
+ }
+
+ tableLog = FSE_optimalTableLog(tableLog, wtSize, maxSymbolValue);
+ CHECK_F( FSE_normalizeCount(norm, tableLog, count, wtSize, maxSymbolValue) );
+
+ /* Write table description header */
+ { CHECK_V_F(hSize, FSE_writeNCount(op, oend-op, norm, maxSymbolValue, tableLog) );
+ op += hSize;
+ }
+
+ /* Compress */
+ CHECK_F( FSE_buildCTable_wksp(CTable, norm, maxSymbolValue, tableLog, scratchBuffer, sizeof(scratchBuffer)) );
+ { CHECK_V_F(cSize, FSE_compress_usingCTable(op, oend - op, weightTable, wtSize, CTable) );
+ if (cSize == 0) return 0; /* not enough space for compressed data */
+ op += cSize;
+ }
+
+ return op-ostart;
+}
+
+
+struct HUF_CElt_s {
+ U16 val;
+ BYTE nbBits;
+}; /* typedef'd to HUF_CElt within "huf.h" */
+
+/*! HUF_writeCTable() :
+ `CTable` : Huffman tree to save, using huf representation.
+ @return : size of saved CTable */
+size_t HUF_writeCTable (void* dst, size_t maxDstSize,
+ const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog)
+{
+ BYTE bitsToWeight[HUF_TABLELOG_MAX + 1]; /* precomputed conversion table */
+ BYTE huffWeight[HUF_SYMBOLVALUE_MAX];
+ BYTE* op = (BYTE*)dst;
+ U32 n;
+
+ /* check conditions */
+ if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);
+
+ /* convert to weight */
+ bitsToWeight[0] = 0;
+ for (n=1; n<huffLog+1; n++)
+ bitsToWeight[n] = (BYTE)(huffLog + 1 - n);
+ for (n=0; n<maxSymbolValue; n++)
+ huffWeight[n] = bitsToWeight[CTable[n].nbBits];
+
+ /* attempt weights compression by FSE */
+ { CHECK_V_F(hSize, HUF_compressWeights(op+1, maxDstSize-1, huffWeight, maxSymbolValue) );
+ if ((hSize>1) & (hSize < maxSymbolValue/2)) { /* FSE compressed */
+ op[0] = (BYTE)hSize;
+ return hSize+1;
+ } }
+
+ /* write raw values as 4-bits (max : 15) */
+ if (maxSymbolValue > (256-128)) return ERROR(GENERIC); /* should not happen : likely means source cannot be compressed */
+ if (((maxSymbolValue+1)/2) + 1 > maxDstSize) return ERROR(dstSize_tooSmall); /* not enough space within dst buffer */
+ op[0] = (BYTE)(128 /*special case*/ + (maxSymbolValue-1));
+ huffWeight[maxSymbolValue] = 0; /* to be sure it doesn't cause msan issue in final combination */
+ for (n=0; n<maxSymbolValue; n+=2)
+ op[(n/2)+1] = (BYTE)((huffWeight[n] << 4) + huffWeight[n+1]);
+ return ((maxSymbolValue+1)/2) + 1;
+}
+
+
+size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize)
+{
+ BYTE huffWeight[HUF_SYMBOLVALUE_MAX + 1]; /* init not required, even though some static analyzer may complain */
+ U32 rankVal[HUF_TABLELOG_ABSOLUTEMAX + 1]; /* large enough for values from 0 to 16 */
+ U32 tableLog = 0;
+ U32 nbSymbols = 0;
+
+ /* get symbol weights */
+ CHECK_V_F(readSize, HUF_readStats(huffWeight, HUF_SYMBOLVALUE_MAX+1, rankVal, &nbSymbols, &tableLog, src, srcSize));
+
+ /* check result */
+ if (tableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
+ if (nbSymbols > *maxSymbolValuePtr+1) return ERROR(maxSymbolValue_tooSmall);
+
+ /* Prepare base value per rank */
+ { U32 n, nextRankStart = 0;
+ for (n=1; n<=tableLog; n++) {
+ U32 current = nextRankStart;
+ nextRankStart += (rankVal[n] << (n-1));
+ rankVal[n] = current;
+ } }
+
+ /* fill nbBits */
+ { U32 n; for (n=0; n<nbSymbols; n++) {
+ const U32 w = huffWeight[n];
+ CTable[n].nbBits = (BYTE)(tableLog + 1 - w);
+ } }
+
+ /* fill val */
+ { U16 nbPerRank[HUF_TABLELOG_MAX+2] = {0}; /* support w=0=>n=tableLog+1 */
+ U16 valPerRank[HUF_TABLELOG_MAX+2] = {0};
+ { U32 n; for (n=0; n<nbSymbols; n++) nbPerRank[CTable[n].nbBits]++; }
+ /* determine stating value per rank */
+ valPerRank[tableLog+1] = 0; /* for w==0 */
+ { U16 min = 0;
+ U32 n; for (n=tableLog; n>0; n--) { /* start at n=tablelog <-> w=1 */
+ valPerRank[n] = min; /* get starting value within each rank */
+ min += nbPerRank[n];
+ min >>= 1;
+ } }
+ /* assign value within rank, symbol order */
+ { U32 n; for (n=0; n<nbSymbols; n++) CTable[n].val = valPerRank[CTable[n].nbBits]++; }
+ }
+
+ *maxSymbolValuePtr = nbSymbols - 1;
+ return readSize;
+}
+
+U32 HUF_getNbBits(const void* symbolTable, U32 symbolValue)
+{
+ const HUF_CElt* table = (const HUF_CElt*)symbolTable;
+ assert(symbolValue <= HUF_SYMBOLVALUE_MAX);
+ return table[symbolValue].nbBits;
+}
+
+
+typedef struct nodeElt_s {
+ U32 count;
+ U16 parent;
+ BYTE byte;
+ BYTE nbBits;
+} nodeElt;
+
+static U32 HUF_setMaxHeight(nodeElt* huffNode, U32 lastNonNull, U32 maxNbBits)
+{
+ const U32 largestBits = huffNode[lastNonNull].nbBits;
+ if (largestBits <= maxNbBits) return largestBits; /* early exit : no elt > maxNbBits */
+
+ /* there are several too large elements (at least >= 2) */
+ { int totalCost = 0;
+ const U32 baseCost = 1 << (largestBits - maxNbBits);
+ U32 n = lastNonNull;
+
+ while (huffNode[n].nbBits > maxNbBits) {
+ totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits));
+ huffNode[n].nbBits = (BYTE)maxNbBits;
+ n --;
+ } /* n stops at huffNode[n].nbBits <= maxNbBits */
+ while (huffNode[n].nbBits == maxNbBits) n--; /* n end at index of smallest symbol using < maxNbBits */
+
+ /* renorm totalCost */
+ totalCost >>= (largestBits - maxNbBits); /* note : totalCost is necessarily a multiple of baseCost */
+
+ /* repay normalized cost */
+ { U32 const noSymbol = 0xF0F0F0F0;
+ U32 rankLast[HUF_TABLELOG_MAX+2];
+ int pos;
+
+ /* Get pos of last (smallest) symbol per rank */
+ memset(rankLast, 0xF0, sizeof(rankLast));
+ { U32 currentNbBits = maxNbBits;
+ for (pos=n ; pos >= 0; pos--) {
+ if (huffNode[pos].nbBits >= currentNbBits) continue;
+ currentNbBits = huffNode[pos].nbBits; /* < maxNbBits */
+ rankLast[maxNbBits-currentNbBits] = pos;
+ } }
+
+ while (totalCost > 0) {
+ U32 nBitsToDecrease = BIT_highbit32(totalCost) + 1;
+ for ( ; nBitsToDecrease > 1; nBitsToDecrease--) {
+ U32 highPos = rankLast[nBitsToDecrease];
+ U32 lowPos = rankLast[nBitsToDecrease-1];
+ if (highPos == noSymbol) continue;
+ if (lowPos == noSymbol) break;
+ { U32 const highTotal = huffNode[highPos].count;
+ U32 const lowTotal = 2 * huffNode[lowPos].count;
+ if (highTotal <= lowTotal) break;
+ } }
+ /* only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) */
+ /* HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary */
+ while ((nBitsToDecrease<=HUF_TABLELOG_MAX) && (rankLast[nBitsToDecrease] == noSymbol))
+ nBitsToDecrease ++;
+ totalCost -= 1 << (nBitsToDecrease-1);
+ if (rankLast[nBitsToDecrease-1] == noSymbol)
+ rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease]; /* this rank is no longer empty */
+ huffNode[rankLast[nBitsToDecrease]].nbBits ++;
+ if (rankLast[nBitsToDecrease] == 0) /* special case, reached largest symbol */
+ rankLast[nBitsToDecrease] = noSymbol;
+ else {
+ rankLast[nBitsToDecrease]--;
+ if (huffNode[rankLast[nBitsToDecrease]].nbBits != maxNbBits-nBitsToDecrease)
+ rankLast[nBitsToDecrease] = noSymbol; /* this rank is now empty */
+ } } /* while (totalCost > 0) */
+
+ while (totalCost < 0) { /* Sometimes, cost correction overshoot */
+ if (rankLast[1] == noSymbol) { /* special case : no rank 1 symbol (using maxNbBits-1); let's create one from largest rank 0 (using maxNbBits) */
+ while (huffNode[n].nbBits == maxNbBits) n--;
+ huffNode[n+1].nbBits--;
+ rankLast[1] = n+1;
+ totalCost++;
+ continue;
+ }
+ huffNode[ rankLast[1] + 1 ].nbBits--;
+ rankLast[1]++;
+ totalCost ++;
+ } } } /* there are several too large elements (at least >= 2) */
+
+ return maxNbBits;
+}
+
+
+typedef struct {
+ U32 base;
+ U32 current;
+} rankPos;
+
+static void HUF_sort(nodeElt* huffNode, const unsigned* count, U32 maxSymbolValue)
+{
+ rankPos rank[32];
+ U32 n;
+
+ memset(rank, 0, sizeof(rank));
+ for (n=0; n<=maxSymbolValue; n++) {
+ U32 r = BIT_highbit32(count[n] + 1);
+ rank[r].base ++;
+ }
+ for (n=30; n>0; n--) rank[n-1].base += rank[n].base;
+ for (n=0; n<32; n++) rank[n].current = rank[n].base;
+ for (n=0; n<=maxSymbolValue; n++) {
+ U32 const c = count[n];
+ U32 const r = BIT_highbit32(c+1) + 1;
+ U32 pos = rank[r].current++;
+ while ((pos > rank[r].base) && (c > huffNode[pos-1].count)) {
+ huffNode[pos] = huffNode[pos-1];
+ pos--;
+ }
+ huffNode[pos].count = c;
+ huffNode[pos].byte = (BYTE)n;
+ }
+}
+
+
+/** HUF_buildCTable_wksp() :
+ * Same as HUF_buildCTable(), but using externally allocated scratch buffer.
+ * `workSpace` must be aligned on 4-bytes boundaries, and be at least as large as a table of HUF_CTABLE_WORKSPACE_SIZE_U32 unsigned.
+ */
+#define STARTNODE (HUF_SYMBOLVALUE_MAX+1)
+typedef nodeElt huffNodeTable[HUF_CTABLE_WORKSPACE_SIZE_U32];
+size_t HUF_buildCTable_wksp (HUF_CElt* tree, const unsigned* count, U32 maxSymbolValue, U32 maxNbBits, void* workSpace, size_t wkspSize)
+{
+ nodeElt* const huffNode0 = (nodeElt*)workSpace;
+ nodeElt* const huffNode = huffNode0+1;
+ U32 n, nonNullRank;
+ int lowS, lowN;
+ U16 nodeNb = STARTNODE;
+ U32 nodeRoot;
+
+ /* safety checks */
+ if (((size_t)workSpace & 3) != 0) return ERROR(GENERIC); /* must be aligned on 4-bytes boundaries */
+ if (wkspSize < sizeof(huffNodeTable)) return ERROR(workSpace_tooSmall);
+ if (maxNbBits == 0) maxNbBits = HUF_TABLELOG_DEFAULT;
+ if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);
+ memset(huffNode0, 0, sizeof(huffNodeTable));
+
+ /* sort, decreasing order */
+ HUF_sort(huffNode, count, maxSymbolValue);
+
+ /* init for parents */
+ nonNullRank = maxSymbolValue;
+ while(huffNode[nonNullRank].count == 0) nonNullRank--;
+ lowS = nonNullRank; nodeRoot = nodeNb + lowS - 1; lowN = nodeNb;
+ huffNode[nodeNb].count = huffNode[lowS].count + huffNode[lowS-1].count;
+ huffNode[lowS].parent = huffNode[lowS-1].parent = nodeNb;
+ nodeNb++; lowS-=2;
+ for (n=nodeNb; n<=nodeRoot; n++) huffNode[n].count = (U32)(1U<<30);
+ huffNode0[0].count = (U32)(1U<<31); /* fake entry, strong barrier */
+
+ /* create parents */
+ while (nodeNb <= nodeRoot) {
+ U32 n1 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
+ U32 n2 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
+ huffNode[nodeNb].count = huffNode[n1].count + huffNode[n2].count;
+ huffNode[n1].parent = huffNode[n2].parent = nodeNb;
+ nodeNb++;
+ }
+
+ /* distribute weights (unlimited tree height) */
+ huffNode[nodeRoot].nbBits = 0;
+ for (n=nodeRoot-1; n>=STARTNODE; n--)
+ huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;
+ for (n=0; n<=nonNullRank; n++)
+ huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;
+
+ /* enforce maxTableLog */
+ maxNbBits = HUF_setMaxHeight(huffNode, nonNullRank, maxNbBits);
+
+ /* fill result into tree (val, nbBits) */
+ { U16 nbPerRank[HUF_TABLELOG_MAX+1] = {0};
+ U16 valPerRank[HUF_TABLELOG_MAX+1] = {0};
+ if (maxNbBits > HUF_TABLELOG_MAX) return ERROR(GENERIC); /* check fit into table */
+ for (n=0; n<=nonNullRank; n++)
+ nbPerRank[huffNode[n].nbBits]++;
+ /* determine stating value per rank */
+ { U16 min = 0;
+ for (n=maxNbBits; n>0; n--) {
+ valPerRank[n] = min; /* get starting value within each rank */
+ min += nbPerRank[n];
+ min >>= 1;
+ } }
+ for (n=0; n<=maxSymbolValue; n++)
+ tree[huffNode[n].byte].nbBits = huffNode[n].nbBits; /* push nbBits per symbol, symbol order */
+ for (n=0; n<=maxSymbolValue; n++)
+ tree[n].val = valPerRank[tree[n].nbBits]++; /* assign value within rank, symbol order */
+ }
+
+ return maxNbBits;
+}
+
+/** HUF_buildCTable() :
+ * @return : maxNbBits
+ * Note : count is used before tree is written, so they can safely overlap
+ */
+size_t HUF_buildCTable (HUF_CElt* tree, const unsigned* count, unsigned maxSymbolValue, unsigned maxNbBits)
+{
+ huffNodeTable nodeTable;
+ return HUF_buildCTable_wksp(tree, count, maxSymbolValue, maxNbBits, nodeTable, sizeof(nodeTable));
+}
+
+static size_t HUF_estimateCompressedSize(HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue)
+{
+ size_t nbBits = 0;
+ int s;
+ for (s = 0; s <= (int)maxSymbolValue; ++s) {
+ nbBits += CTable[s].nbBits * count[s];
+ }
+ return nbBits >> 3;
+}
+
+static int HUF_validateCTable(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue) {
+ int bad = 0;
+ int s;
+ for (s = 0; s <= (int)maxSymbolValue; ++s) {
+ bad |= (count[s] != 0) & (CTable[s].nbBits == 0);
+ }
+ return !bad;
+}
+
+size_t HUF_compressBound(size_t size) { return HUF_COMPRESSBOUND(size); }
+
+FORCE_INLINE_TEMPLATE void
+HUF_encodeSymbol(BIT_CStream_t* bitCPtr, U32 symbol, const HUF_CElt* CTable)
+{
+ BIT_addBitsFast(bitCPtr, CTable[symbol].val, CTable[symbol].nbBits);
+}
+
+#define HUF_FLUSHBITS(s) BIT_flushBits(s)
+
+#define HUF_FLUSHBITS_1(stream) \
+ if (sizeof((stream)->bitContainer)*8 < HUF_TABLELOG_MAX*2+7) HUF_FLUSHBITS(stream)
+
+#define HUF_FLUSHBITS_2(stream) \
+ if (sizeof((stream)->bitContainer)*8 < HUF_TABLELOG_MAX*4+7) HUF_FLUSHBITS(stream)
+
+FORCE_INLINE_TEMPLATE size_t
+HUF_compress1X_usingCTable_internal_body(void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ const HUF_CElt* CTable)
+{
+ const BYTE* ip = (const BYTE*) src;
+ BYTE* const ostart = (BYTE*)dst;
+ BYTE* const oend = ostart + dstSize;
+ BYTE* op = ostart;
+ size_t n;
+ BIT_CStream_t bitC;
+
+ /* init */
+ if (dstSize < 8) return 0; /* not enough space to compress */
+ { size_t const initErr = BIT_initCStream(&bitC, op, oend-op);
+ if (HUF_isError(initErr)) return 0; }
+
+ n = srcSize & ~3; /* join to mod 4 */
+ switch (srcSize & 3)
+ {
+ case 3 : HUF_encodeSymbol(&bitC, ip[n+ 2], CTable);
+ HUF_FLUSHBITS_2(&bitC);
+ /* fall-through */
+ case 2 : HUF_encodeSymbol(&bitC, ip[n+ 1], CTable);
+ HUF_FLUSHBITS_1(&bitC);
+ /* fall-through */
+ case 1 : HUF_encodeSymbol(&bitC, ip[n+ 0], CTable);
+ HUF_FLUSHBITS(&bitC);
+ /* fall-through */
+ case 0 : /* fall-through */
+ default: break;
+ }
+
+ for (; n>0; n-=4) { /* note : n&3==0 at this stage */
+ HUF_encodeSymbol(&bitC, ip[n- 1], CTable);
+ HUF_FLUSHBITS_1(&bitC);
+ HUF_encodeSymbol(&bitC, ip[n- 2], CTable);
+ HUF_FLUSHBITS_2(&bitC);
+ HUF_encodeSymbol(&bitC, ip[n- 3], CTable);
+ HUF_FLUSHBITS_1(&bitC);
+ HUF_encodeSymbol(&bitC, ip[n- 4], CTable);
+ HUF_FLUSHBITS(&bitC);
+ }
+
+ return BIT_closeCStream(&bitC);
+}
+
+#if DYNAMIC_BMI2
+
+static TARGET_ATTRIBUTE("bmi2") size_t
+HUF_compress1X_usingCTable_internal_bmi2(void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ const HUF_CElt* CTable)
+{
+ return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
+}
+
+static size_t
+HUF_compress1X_usingCTable_internal_default(void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ const HUF_CElt* CTable)
+{
+ return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
+}
+
+static size_t
+HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ const HUF_CElt* CTable, const int bmi2)
+{
+ if (bmi2) {
+ return HUF_compress1X_usingCTable_internal_bmi2(dst, dstSize, src, srcSize, CTable);
+ }
+ return HUF_compress1X_usingCTable_internal_default(dst, dstSize, src, srcSize, CTable);
+}
+
+#else
+
+static size_t
+HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ const HUF_CElt* CTable, const int bmi2)
+{
+ (void)bmi2;
+ return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
+}
+
+#endif
+
+size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable)
+{
+ return HUF_compress1X_usingCTable_internal(dst, dstSize, src, srcSize, CTable, /* bmi2 */ 0);
+}
+
+
+static size_t
+HUF_compress4X_usingCTable_internal(void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ const HUF_CElt* CTable, int bmi2)
+{
+ size_t const segmentSize = (srcSize+3)/4; /* first 3 segments */
+ const BYTE* ip = (const BYTE*) src;
+ const BYTE* const iend = ip + srcSize;
+ BYTE* const ostart = (BYTE*) dst;
+ BYTE* const oend = ostart + dstSize;
+ BYTE* op = ostart;
+
+ if (dstSize < 6 + 1 + 1 + 1 + 8) return 0; /* minimum space to compress successfully */
+ if (srcSize < 12) return 0; /* no saving possible : too small input */
+ op += 6; /* jumpTable */
+
+ { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, oend-op, ip, segmentSize, CTable, bmi2) );
+ if (cSize==0) return 0;
+ assert(cSize <= 65535);
+ MEM_writeLE16(ostart, (U16)cSize);
+ op += cSize;
+ }
+
+ ip += segmentSize;
+ { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, oend-op, ip, segmentSize, CTable, bmi2) );
+ if (cSize==0) return 0;
+ assert(cSize <= 65535);
+ MEM_writeLE16(ostart+2, (U16)cSize);
+ op += cSize;
+ }
+
+ ip += segmentSize;
+ { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, oend-op, ip, segmentSize, CTable, bmi2) );
+ if (cSize==0) return 0;
+ assert(cSize <= 65535);
+ MEM_writeLE16(ostart+4, (U16)cSize);
+ op += cSize;
+ }
+
+ ip += segmentSize;
+ { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, oend-op, ip, iend-ip, CTable, bmi2) );
+ if (cSize==0) return 0;
+ op += cSize;
+ }
+
+ return op-ostart;
+}
+
+size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable)
+{
+ return HUF_compress4X_usingCTable_internal(dst, dstSize, src, srcSize, CTable, /* bmi2 */ 0);
+}
+
+typedef enum { HUF_singleStream, HUF_fourStreams } HUF_nbStreams_e;
+
+static size_t HUF_compressCTable_internal(
+ BYTE* const ostart, BYTE* op, BYTE* const oend,
+ const void* src, size_t srcSize,
+ HUF_nbStreams_e nbStreams, const HUF_CElt* CTable, const int bmi2)
+{
+ size_t const cSize = (nbStreams==HUF_singleStream) ?
+ HUF_compress1X_usingCTable_internal(op, oend - op, src, srcSize, CTable, bmi2) :
+ HUF_compress4X_usingCTable_internal(op, oend - op, src, srcSize, CTable, bmi2);
+ if (HUF_isError(cSize)) { return cSize; }
+ if (cSize==0) { return 0; } /* uncompressible */
+ op += cSize;
+ /* check compressibility */
+ if ((size_t)(op-ostart) >= srcSize-1) { return 0; }
+ return op-ostart;
+}
+
+typedef struct {
+ unsigned count[HUF_SYMBOLVALUE_MAX + 1];
+ HUF_CElt CTable[HUF_SYMBOLVALUE_MAX + 1];
+ huffNodeTable nodeTable;
+} HUF_compress_tables_t;
+
+/* HUF_compress_internal() :
+ * `workSpace` must a table of at least HUF_WORKSPACE_SIZE_U32 unsigned */
+static size_t
+HUF_compress_internal (void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned huffLog,
+ HUF_nbStreams_e nbStreams,
+ void* workSpace, size_t wkspSize,
+ HUF_CElt* oldHufTable, HUF_repeat* repeat, int preferRepeat,
+ const int bmi2)
+{
+ HUF_compress_tables_t* const table = (HUF_compress_tables_t*)workSpace;
+ BYTE* const ostart = (BYTE*)dst;
+ BYTE* const oend = ostart + dstSize;
+ BYTE* op = ostart;
+
+ /* checks & inits */
+ if (((size_t)workSpace & 3) != 0) return ERROR(GENERIC); /* must be aligned on 4-bytes boundaries */
+ if (wkspSize < HUF_WORKSPACE_SIZE) return ERROR(workSpace_tooSmall);
+ if (!srcSize) return 0; /* Uncompressed */
+ if (!dstSize) return 0; /* cannot fit anything within dst budget */
+ if (srcSize > HUF_BLOCKSIZE_MAX) return ERROR(srcSize_wrong); /* current block size limit */
+ if (huffLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
+ if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);
+ if (!maxSymbolValue) maxSymbolValue = HUF_SYMBOLVALUE_MAX;
+ if (!huffLog) huffLog = HUF_TABLELOG_DEFAULT;
+
+ /* Heuristic : If old table is valid, use it for small inputs */
+ if (preferRepeat && repeat && *repeat == HUF_repeat_valid) {
+ return HUF_compressCTable_internal(ostart, op, oend,
+ src, srcSize,
+ nbStreams, oldHufTable, bmi2);
+ }
+
+ /* Scan input and build symbol stats */
+ { CHECK_V_F(largest, HIST_count_wksp (table->count, &maxSymbolValue, (const BYTE*)src, srcSize, workSpace, wkspSize) );
+ if (largest == srcSize) { *ostart = ((const BYTE*)src)[0]; return 1; } /* single symbol, rle */
+ if (largest <= (srcSize >> 7)+4) return 0; /* heuristic : probably not compressible enough */
+ }
+
+ /* Check validity of previous table */
+ if ( repeat
+ && *repeat == HUF_repeat_check
+ && !HUF_validateCTable(oldHufTable, table->count, maxSymbolValue)) {
+ *repeat = HUF_repeat_none;
+ }
+ /* Heuristic : use existing table for small inputs */
+ if (preferRepeat && repeat && *repeat != HUF_repeat_none) {
+ return HUF_compressCTable_internal(ostart, op, oend,
+ src, srcSize,
+ nbStreams, oldHufTable, bmi2);
+ }
+
+ /* Build Huffman Tree */
+ huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue);
+ { size_t const maxBits = HUF_buildCTable_wksp(table->CTable, table->count,
+ maxSymbolValue, huffLog,
+ table->nodeTable, sizeof(table->nodeTable));
+ CHECK_F(maxBits);
+ huffLog = (U32)maxBits;
+ /* Zero unused symbols in CTable, so we can check it for validity */
+ memset(table->CTable + (maxSymbolValue + 1), 0,
+ sizeof(table->CTable) - ((maxSymbolValue + 1) * sizeof(HUF_CElt)));
+ }
+
+ /* Write table description header */
+ { CHECK_V_F(hSize, HUF_writeCTable (op, dstSize, table->CTable, maxSymbolValue, huffLog) );
+ /* Check if using previous huffman table is beneficial */
+ if (repeat && *repeat != HUF_repeat_none) {
+ size_t const oldSize = HUF_estimateCompressedSize(oldHufTable, table->count, maxSymbolValue);
+ size_t const newSize = HUF_estimateCompressedSize(table->CTable, table->count, maxSymbolValue);
+ if (oldSize <= hSize + newSize || hSize + 12 >= srcSize) {
+ return HUF_compressCTable_internal(ostart, op, oend,
+ src, srcSize,
+ nbStreams, oldHufTable, bmi2);
+ } }
+
+ /* Use the new huffman table */
+ if (hSize + 12ul >= srcSize) { return 0; }
+ op += hSize;
+ if (repeat) { *repeat = HUF_repeat_none; }
+ if (oldHufTable)
+ memcpy(oldHufTable, table->CTable, sizeof(table->CTable)); /* Save new table */
+ }
+ return HUF_compressCTable_internal(ostart, op, oend,
+ src, srcSize,
+ nbStreams, table->CTable, bmi2);
+}
+
+
+size_t HUF_compress1X_wksp (void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned huffLog,
+ void* workSpace, size_t wkspSize)
+{
+ return HUF_compress_internal(dst, dstSize, src, srcSize,
+ maxSymbolValue, huffLog, HUF_singleStream,
+ workSpace, wkspSize,
+ NULL, NULL, 0, 0 /*bmi2*/);
+}
+
+size_t HUF_compress1X_repeat (void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned huffLog,
+ void* workSpace, size_t wkspSize,
+ HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2)
+{
+ return HUF_compress_internal(dst, dstSize, src, srcSize,
+ maxSymbolValue, huffLog, HUF_singleStream,
+ workSpace, wkspSize, hufTable,
+ repeat, preferRepeat, bmi2);
+}
+
+size_t HUF_compress1X (void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned huffLog)
+{
+ unsigned workSpace[HUF_WORKSPACE_SIZE_U32];
+ return HUF_compress1X_wksp(dst, dstSize, src, srcSize, maxSymbolValue, huffLog, workSpace, sizeof(workSpace));
+}
+
+/* HUF_compress4X_repeat():
+ * compress input using 4 streams.
+ * provide workspace to generate compression tables */
+size_t HUF_compress4X_wksp (void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned huffLog,
+ void* workSpace, size_t wkspSize)
+{
+ return HUF_compress_internal(dst, dstSize, src, srcSize,
+ maxSymbolValue, huffLog, HUF_fourStreams,
+ workSpace, wkspSize,
+ NULL, NULL, 0, 0 /*bmi2*/);
+}
+
+/* HUF_compress4X_repeat():
+ * compress input using 4 streams.
+ * re-use an existing huffman compression table */
+size_t HUF_compress4X_repeat (void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned huffLog,
+ void* workSpace, size_t wkspSize,
+ HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2)
+{
+ return HUF_compress_internal(dst, dstSize, src, srcSize,
+ maxSymbolValue, huffLog, HUF_fourStreams,
+ workSpace, wkspSize,
+ hufTable, repeat, preferRepeat, bmi2);
+}
+
+size_t HUF_compress2 (void* dst, size_t dstSize,
+ const void* src, size_t srcSize,
+ unsigned maxSymbolValue, unsigned huffLog)
+{
+ unsigned workSpace[HUF_WORKSPACE_SIZE_U32];
+ return HUF_compress4X_wksp(dst, dstSize, src, srcSize, maxSymbolValue, huffLog, workSpace, sizeof(workSpace));
+}
+
+size_t HUF_compress (void* dst, size_t maxDstSize, const void* src, size_t srcSize)
+{
+ return HUF_compress2(dst, maxDstSize, src, srcSize, 255, HUF_TABLELOG_DEFAULT);
+}
diff --git a/Utilities/cmzstd/lib/compress/zstd_compress.c b/Utilities/cmzstd/lib/compress/zstd_compress.c
new file mode 100644
index 000000000..c2c9d3bc5
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_compress.c
@@ -0,0 +1,4290 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+/*-*************************************
+* Dependencies
+***************************************/
+#include <limits.h> /* INT_MAX */
+#include <string.h> /* memset */
+#include "cpu.h"
+#include "mem.h"
+#include "hist.h" /* HIST_countFast_wksp */
+#define FSE_STATIC_LINKING_ONLY /* FSE_encodeSymbol */
+#include "fse.h"
+#define HUF_STATIC_LINKING_ONLY
+#include "huf.h"
+#include "zstd_compress_internal.h"
+#include "zstd_fast.h"
+#include "zstd_double_fast.h"
+#include "zstd_lazy.h"
+#include "zstd_opt.h"
+#include "zstd_ldm.h"
+
+
+/*-*************************************
+* Helper functions
+***************************************/
+size_t ZSTD_compressBound(size_t srcSize) {
+ return ZSTD_COMPRESSBOUND(srcSize);
+}
+
+
+/*-*************************************
+* Context memory management
+***************************************/
+struct ZSTD_CDict_s {
+ void* dictBuffer;
+ const void* dictContent;
+ size_t dictContentSize;
+ void* workspace;
+ size_t workspaceSize;
+ ZSTD_matchState_t matchState;
+ ZSTD_compressedBlockState_t cBlockState;
+ ZSTD_customMem customMem;
+ U32 dictID;
+}; /* typedef'd to ZSTD_CDict within "zstd.h" */
+
+ZSTD_CCtx* ZSTD_createCCtx(void)
+{
+ return ZSTD_createCCtx_advanced(ZSTD_defaultCMem);
+}
+
+static void ZSTD_initCCtx(ZSTD_CCtx* cctx, ZSTD_customMem memManager)
+{
+ assert(cctx != NULL);
+ memset(cctx, 0, sizeof(*cctx));
+ cctx->customMem = memManager;
+ cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
+ { size_t const err = ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);
+ assert(!ZSTD_isError(err));
+ (void)err;
+ }
+}
+
+ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem)
+{
+ ZSTD_STATIC_ASSERT(zcss_init==0);
+ ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN==(0ULL - 1));
+ if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
+ { ZSTD_CCtx* const cctx = (ZSTD_CCtx*)ZSTD_malloc(sizeof(ZSTD_CCtx), customMem);
+ if (!cctx) return NULL;
+ ZSTD_initCCtx(cctx, customMem);
+ return cctx;
+ }
+}
+
+ZSTD_CCtx* ZSTD_initStaticCCtx(void *workspace, size_t workspaceSize)
+{
+ ZSTD_CCtx* const cctx = (ZSTD_CCtx*) workspace;
+ if (workspaceSize <= sizeof(ZSTD_CCtx)) return NULL; /* minimum size */
+ if ((size_t)workspace & 7) return NULL; /* must be 8-aligned */
+ memset(workspace, 0, workspaceSize); /* may be a bit generous, could memset be smaller ? */
+ cctx->staticSize = workspaceSize;
+ cctx->workSpace = (void*)(cctx+1);
+ cctx->workSpaceSize = workspaceSize - sizeof(ZSTD_CCtx);
+
+ /* statically sized space. entropyWorkspace never moves (but prev/next block swap places) */
+ if (cctx->workSpaceSize < HUF_WORKSPACE_SIZE + 2 * sizeof(ZSTD_compressedBlockState_t)) return NULL;
+ assert(((size_t)cctx->workSpace & (sizeof(void*)-1)) == 0); /* ensure correct alignment */
+ cctx->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)cctx->workSpace;
+ cctx->blockState.nextCBlock = cctx->blockState.prevCBlock + 1;
+ {
+ void* const ptr = cctx->blockState.nextCBlock + 1;
+ cctx->entropyWorkspace = (U32*)ptr;
+ }
+ cctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
+ return cctx;
+}
+
+static void ZSTD_freeCCtxContent(ZSTD_CCtx* cctx)
+{
+ assert(cctx != NULL);
+ assert(cctx->staticSize == 0);
+ ZSTD_free(cctx->workSpace, cctx->customMem); cctx->workSpace = NULL;
+ ZSTD_freeCDict(cctx->cdictLocal); cctx->cdictLocal = NULL;
+#ifdef ZSTD_MULTITHREAD
+ ZSTDMT_freeCCtx(cctx->mtctx); cctx->mtctx = NULL;
+#endif
+}
+
+size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx)
+{
+ if (cctx==NULL) return 0; /* support free on NULL */
+ if (cctx->staticSize) return ERROR(memory_allocation); /* not compatible with static CCtx */
+ ZSTD_freeCCtxContent(cctx);
+ ZSTD_free(cctx, cctx->customMem);
+ return 0;
+}
+
+
+static size_t ZSTD_sizeof_mtctx(const ZSTD_CCtx* cctx)
+{
+#ifdef ZSTD_MULTITHREAD
+ return ZSTDMT_sizeof_CCtx(cctx->mtctx);
+#else
+ (void)cctx;
+ return 0;
+#endif
+}
+
+
+size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx)
+{
+ if (cctx==NULL) return 0; /* support sizeof on NULL */
+ return sizeof(*cctx) + cctx->workSpaceSize
+ + ZSTD_sizeof_CDict(cctx->cdictLocal)
+ + ZSTD_sizeof_mtctx(cctx);
+}
+
+size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs)
+{
+ return ZSTD_sizeof_CCtx(zcs); /* same object */
+}
+
+/* private API call, for dictBuilder only */
+const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx) { return &(ctx->seqStore); }
+
+static ZSTD_CCtx_params ZSTD_makeCCtxParamsFromCParams(
+ ZSTD_compressionParameters cParams)
+{
+ ZSTD_CCtx_params cctxParams;
+ memset(&cctxParams, 0, sizeof(cctxParams));
+ cctxParams.cParams = cParams;
+ cctxParams.compressionLevel = ZSTD_CLEVEL_DEFAULT; /* should not matter, as all cParams are presumed properly defined */
+ assert(!ZSTD_checkCParams(cParams));
+ cctxParams.fParams.contentSizeFlag = 1;
+ return cctxParams;
+}
+
+static ZSTD_CCtx_params* ZSTD_createCCtxParams_advanced(
+ ZSTD_customMem customMem)
+{
+ ZSTD_CCtx_params* params;
+ if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
+ params = (ZSTD_CCtx_params*)ZSTD_calloc(
+ sizeof(ZSTD_CCtx_params), customMem);
+ if (!params) { return NULL; }
+ params->customMem = customMem;
+ params->compressionLevel = ZSTD_CLEVEL_DEFAULT;
+ params->fParams.contentSizeFlag = 1;
+ return params;
+}
+
+ZSTD_CCtx_params* ZSTD_createCCtxParams(void)
+{
+ return ZSTD_createCCtxParams_advanced(ZSTD_defaultCMem);
+}
+
+size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params)
+{
+ if (params == NULL) { return 0; }
+ ZSTD_free(params, params->customMem);
+ return 0;
+}
+
+size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params)
+{
+ return ZSTD_CCtxParams_init(params, ZSTD_CLEVEL_DEFAULT);
+}
+
+size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel) {
+ if (!cctxParams) { return ERROR(GENERIC); }
+ memset(cctxParams, 0, sizeof(*cctxParams));
+ cctxParams->compressionLevel = compressionLevel;
+ cctxParams->fParams.contentSizeFlag = 1;
+ return 0;
+}
+
+size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params)
+{
+ if (!cctxParams) { return ERROR(GENERIC); }
+ CHECK_F( ZSTD_checkCParams(params.cParams) );
+ memset(cctxParams, 0, sizeof(*cctxParams));
+ cctxParams->cParams = params.cParams;
+ cctxParams->fParams = params.fParams;
+ cctxParams->compressionLevel = ZSTD_CLEVEL_DEFAULT; /* should not matter, as all cParams are presumed properly defined */
+ assert(!ZSTD_checkCParams(params.cParams));
+ return 0;
+}
+
+/* ZSTD_assignParamsToCCtxParams() :
+ * params is presumed valid at this stage */
+static ZSTD_CCtx_params ZSTD_assignParamsToCCtxParams(
+ ZSTD_CCtx_params cctxParams, ZSTD_parameters params)
+{
+ ZSTD_CCtx_params ret = cctxParams;
+ ret.cParams = params.cParams;
+ ret.fParams = params.fParams;
+ ret.compressionLevel = ZSTD_CLEVEL_DEFAULT; /* should not matter, as all cParams are presumed properly defined */
+ assert(!ZSTD_checkCParams(params.cParams));
+ return ret;
+}
+
+ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter param)
+{
+ ZSTD_bounds bounds = { 0, 0, 0 };
+
+ switch(param)
+ {
+ case ZSTD_c_compressionLevel:
+ bounds.lowerBound = ZSTD_minCLevel();
+ bounds.upperBound = ZSTD_maxCLevel();
+ return bounds;
+
+ case ZSTD_c_windowLog:
+ bounds.lowerBound = ZSTD_WINDOWLOG_MIN;
+ bounds.upperBound = ZSTD_WINDOWLOG_MAX;
+ return bounds;
+
+ case ZSTD_c_hashLog:
+ bounds.lowerBound = ZSTD_HASHLOG_MIN;
+ bounds.upperBound = ZSTD_HASHLOG_MAX;
+ return bounds;
+
+ case ZSTD_c_chainLog:
+ bounds.lowerBound = ZSTD_CHAINLOG_MIN;
+ bounds.upperBound = ZSTD_CHAINLOG_MAX;
+ return bounds;
+
+ case ZSTD_c_searchLog:
+ bounds.lowerBound = ZSTD_SEARCHLOG_MIN;
+ bounds.upperBound = ZSTD_SEARCHLOG_MAX;
+ return bounds;
+
+ case ZSTD_c_minMatch:
+ bounds.lowerBound = ZSTD_MINMATCH_MIN;
+ bounds.upperBound = ZSTD_MINMATCH_MAX;
+ return bounds;
+
+ case ZSTD_c_targetLength:
+ bounds.lowerBound = ZSTD_TARGETLENGTH_MIN;
+ bounds.upperBound = ZSTD_TARGETLENGTH_MAX;
+ return bounds;
+
+ case ZSTD_c_strategy:
+ bounds.lowerBound = ZSTD_STRATEGY_MIN;
+ bounds.upperBound = ZSTD_STRATEGY_MAX;
+ return bounds;
+
+ case ZSTD_c_contentSizeFlag:
+ bounds.lowerBound = 0;
+ bounds.upperBound = 1;
+ return bounds;
+
+ case ZSTD_c_checksumFlag:
+ bounds.lowerBound = 0;
+ bounds.upperBound = 1;
+ return bounds;
+
+ case ZSTD_c_dictIDFlag:
+ bounds.lowerBound = 0;
+ bounds.upperBound = 1;
+ return bounds;
+
+ case ZSTD_c_nbWorkers:
+ bounds.lowerBound = 0;
+#ifdef ZSTD_MULTITHREAD
+ bounds.upperBound = ZSTDMT_NBWORKERS_MAX;
+#else
+ bounds.upperBound = 0;
+#endif
+ return bounds;
+
+ case ZSTD_c_jobSize:
+ bounds.lowerBound = 0;
+#ifdef ZSTD_MULTITHREAD
+ bounds.upperBound = ZSTDMT_JOBSIZE_MAX;
+#else
+ bounds.upperBound = 0;
+#endif
+ return bounds;
+
+ case ZSTD_c_overlapLog:
+ bounds.lowerBound = ZSTD_OVERLAPLOG_MIN;
+ bounds.upperBound = ZSTD_OVERLAPLOG_MAX;
+ return bounds;
+
+ case ZSTD_c_enableLongDistanceMatching:
+ bounds.lowerBound = 0;
+ bounds.upperBound = 1;
+ return bounds;
+
+ case ZSTD_c_ldmHashLog:
+ bounds.lowerBound = ZSTD_LDM_HASHLOG_MIN;
+ bounds.upperBound = ZSTD_LDM_HASHLOG_MAX;
+ return bounds;
+
+ case ZSTD_c_ldmMinMatch:
+ bounds.lowerBound = ZSTD_LDM_MINMATCH_MIN;
+ bounds.upperBound = ZSTD_LDM_MINMATCH_MAX;
+ return bounds;
+
+ case ZSTD_c_ldmBucketSizeLog:
+ bounds.lowerBound = ZSTD_LDM_BUCKETSIZELOG_MIN;
+ bounds.upperBound = ZSTD_LDM_BUCKETSIZELOG_MAX;
+ return bounds;
+
+ case ZSTD_c_ldmHashRateLog:
+ bounds.lowerBound = ZSTD_LDM_HASHRATELOG_MIN;
+ bounds.upperBound = ZSTD_LDM_HASHRATELOG_MAX;
+ return bounds;
+
+ /* experimental parameters */
+ case ZSTD_c_rsyncable:
+ bounds.lowerBound = 0;
+ bounds.upperBound = 1;
+ return bounds;
+
+ case ZSTD_c_forceMaxWindow :
+ bounds.lowerBound = 0;
+ bounds.upperBound = 1;
+ return bounds;
+
+ case ZSTD_c_format:
+ ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
+ bounds.lowerBound = ZSTD_f_zstd1;
+ bounds.upperBound = ZSTD_f_zstd1_magicless; /* note : how to ensure at compile time that this is the highest value enum ? */
+ return bounds;
+
+ case ZSTD_c_forceAttachDict:
+ ZSTD_STATIC_ASSERT(ZSTD_dictDefaultAttach < ZSTD_dictForceCopy);
+ bounds.lowerBound = ZSTD_dictDefaultAttach;
+ bounds.upperBound = ZSTD_dictForceCopy; /* note : how to ensure at compile time that this is the highest value enum ? */
+ return bounds;
+
+ default:
+ { ZSTD_bounds const boundError = { ERROR(parameter_unsupported), 0, 0 };
+ return boundError;
+ }
+ }
+}
+
+/* ZSTD_cParam_withinBounds:
+ * @return 1 if value is within cParam bounds,
+ * 0 otherwise */
+static int ZSTD_cParam_withinBounds(ZSTD_cParameter cParam, int value)
+{
+ ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam);
+ if (ZSTD_isError(bounds.error)) return 0;
+ if (value < bounds.lowerBound) return 0;
+ if (value > bounds.upperBound) return 0;
+ return 1;
+}
+
+#define BOUNDCHECK(cParam, val) { \
+ if (!ZSTD_cParam_withinBounds(cParam,val)) { \
+ return ERROR(parameter_outOfBound); \
+} }
+
+
+static int ZSTD_isUpdateAuthorized(ZSTD_cParameter param)
+{
+ switch(param)
+ {
+ case ZSTD_c_compressionLevel:
+ case ZSTD_c_hashLog:
+ case ZSTD_c_chainLog:
+ case ZSTD_c_searchLog:
+ case ZSTD_c_minMatch:
+ case ZSTD_c_targetLength:
+ case ZSTD_c_strategy:
+ return 1;
+
+ case ZSTD_c_format:
+ case ZSTD_c_windowLog:
+ case ZSTD_c_contentSizeFlag:
+ case ZSTD_c_checksumFlag:
+ case ZSTD_c_dictIDFlag:
+ case ZSTD_c_forceMaxWindow :
+ case ZSTD_c_nbWorkers:
+ case ZSTD_c_jobSize:
+ case ZSTD_c_overlapLog:
+ case ZSTD_c_rsyncable:
+ case ZSTD_c_enableLongDistanceMatching:
+ case ZSTD_c_ldmHashLog:
+ case ZSTD_c_ldmMinMatch:
+ case ZSTD_c_ldmBucketSizeLog:
+ case ZSTD_c_ldmHashRateLog:
+ case ZSTD_c_forceAttachDict:
+ default:
+ return 0;
+ }
+}
+
+size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value)
+{
+ DEBUGLOG(4, "ZSTD_CCtx_setParameter (%i, %i)", (int)param, value);
+ if (cctx->streamStage != zcss_init) {
+ if (ZSTD_isUpdateAuthorized(param)) {
+ cctx->cParamsChanged = 1;
+ } else {
+ return ERROR(stage_wrong);
+ } }
+
+ switch(param)
+ {
+ case ZSTD_c_format :
+ return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
+
+ case ZSTD_c_compressionLevel:
+ if (cctx->cdict) return ERROR(stage_wrong);
+ return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
+
+ case ZSTD_c_windowLog:
+ case ZSTD_c_hashLog:
+ case ZSTD_c_chainLog:
+ case ZSTD_c_searchLog:
+ case ZSTD_c_minMatch:
+ case ZSTD_c_targetLength:
+ case ZSTD_c_strategy:
+ if (cctx->cdict) return ERROR(stage_wrong);
+ return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
+
+ case ZSTD_c_contentSizeFlag:
+ case ZSTD_c_checksumFlag:
+ case ZSTD_c_dictIDFlag:
+ return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
+
+ case ZSTD_c_forceMaxWindow : /* Force back-references to remain < windowSize,
+ * even when referencing into Dictionary content.
+ * default : 0 when using a CDict, 1 when using a Prefix */
+ return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
+
+ case ZSTD_c_forceAttachDict:
+ return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
+
+ case ZSTD_c_nbWorkers:
+ if ((value!=0) && cctx->staticSize) {
+ return ERROR(parameter_unsupported); /* MT not compatible with static alloc */
+ }
+ return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
+
+ case ZSTD_c_jobSize:
+ case ZSTD_c_overlapLog:
+ case ZSTD_c_rsyncable:
+ return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
+
+ case ZSTD_c_enableLongDistanceMatching:
+ case ZSTD_c_ldmHashLog:
+ case ZSTD_c_ldmMinMatch:
+ case ZSTD_c_ldmBucketSizeLog:
+ case ZSTD_c_ldmHashRateLog:
+ if (cctx->cdict) return ERROR(stage_wrong);
+ return ZSTD_CCtxParam_setParameter(&cctx->requestedParams, param, value);
+
+ default: return ERROR(parameter_unsupported);
+ }
+}
+
+size_t ZSTD_CCtxParam_setParameter(ZSTD_CCtx_params* CCtxParams,
+ ZSTD_cParameter param, int value)
+{
+ DEBUGLOG(4, "ZSTD_CCtxParam_setParameter (%i, %i)", (int)param, value);
+ switch(param)
+ {
+ case ZSTD_c_format :
+ BOUNDCHECK(ZSTD_c_format, value);
+ CCtxParams->format = (ZSTD_format_e)value;
+ return (size_t)CCtxParams->format;
+
+ case ZSTD_c_compressionLevel : {
+ int cLevel = value;
+ if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel();
+ if (cLevel < ZSTD_minCLevel()) cLevel = ZSTD_minCLevel();
+ if (cLevel) { /* 0 : does not change current level */
+ CCtxParams->compressionLevel = cLevel;
+ }
+ if (CCtxParams->compressionLevel >= 0) return CCtxParams->compressionLevel;
+ return 0; /* return type (size_t) cannot represent negative values */
+ }
+
+ case ZSTD_c_windowLog :
+ if (value!=0) /* 0 => use default */
+ BOUNDCHECK(ZSTD_c_windowLog, value);
+ CCtxParams->cParams.windowLog = value;
+ return CCtxParams->cParams.windowLog;
+
+ case ZSTD_c_hashLog :
+ if (value!=0) /* 0 => use default */
+ BOUNDCHECK(ZSTD_c_hashLog, value);
+ CCtxParams->cParams.hashLog = value;
+ return CCtxParams->cParams.hashLog;
+
+ case ZSTD_c_chainLog :
+ if (value!=0) /* 0 => use default */
+ BOUNDCHECK(ZSTD_c_chainLog, value);
+ CCtxParams->cParams.chainLog = value;
+ return CCtxParams->cParams.chainLog;
+
+ case ZSTD_c_searchLog :
+ if (value!=0) /* 0 => use default */
+ BOUNDCHECK(ZSTD_c_searchLog, value);
+ CCtxParams->cParams.searchLog = value;
+ return value;
+
+ case ZSTD_c_minMatch :
+ if (value!=0) /* 0 => use default */
+ BOUNDCHECK(ZSTD_c_minMatch, value);
+ CCtxParams->cParams.minMatch = value;
+ return CCtxParams->cParams.minMatch;
+
+ case ZSTD_c_targetLength :
+ BOUNDCHECK(ZSTD_c_targetLength, value);
+ CCtxParams->cParams.targetLength = value;
+ return CCtxParams->cParams.targetLength;
+
+ case ZSTD_c_strategy :
+ if (value!=0) /* 0 => use default */
+ BOUNDCHECK(ZSTD_c_strategy, value);
+ CCtxParams->cParams.strategy = (ZSTD_strategy)value;
+ return (size_t)CCtxParams->cParams.strategy;
+
+ case ZSTD_c_contentSizeFlag :
+ /* Content size written in frame header _when known_ (default:1) */
+ DEBUGLOG(4, "set content size flag = %u", (value!=0));
+ CCtxParams->fParams.contentSizeFlag = value != 0;
+ return CCtxParams->fParams.contentSizeFlag;
+
+ case ZSTD_c_checksumFlag :
+ /* A 32-bits content checksum will be calculated and written at end of frame (default:0) */
+ CCtxParams->fParams.checksumFlag = value != 0;
+ return CCtxParams->fParams.checksumFlag;
+
+ case ZSTD_c_dictIDFlag : /* When applicable, dictionary's dictID is provided in frame header (default:1) */
+ DEBUGLOG(4, "set dictIDFlag = %u", (value!=0));
+ CCtxParams->fParams.noDictIDFlag = !value;
+ return !CCtxParams->fParams.noDictIDFlag;
+
+ case ZSTD_c_forceMaxWindow :
+ CCtxParams->forceWindow = (value != 0);
+ return CCtxParams->forceWindow;
+
+ case ZSTD_c_forceAttachDict : {
+ const ZSTD_dictAttachPref_e pref = (ZSTD_dictAttachPref_e)value;
+ BOUNDCHECK(ZSTD_c_forceAttachDict, pref);
+ CCtxParams->attachDictPref = pref;
+ return CCtxParams->attachDictPref;
+ }
+
+ case ZSTD_c_nbWorkers :
+#ifndef ZSTD_MULTITHREAD
+ if (value!=0) return ERROR(parameter_unsupported);
+ return 0;
+#else
+ return ZSTDMT_CCtxParam_setNbWorkers(CCtxParams, value);
+#endif
+
+ case ZSTD_c_jobSize :
+#ifndef ZSTD_MULTITHREAD
+ return ERROR(parameter_unsupported);
+#else
+ return ZSTDMT_CCtxParam_setMTCtxParameter(CCtxParams, ZSTDMT_p_jobSize, value);
+#endif
+
+ case ZSTD_c_overlapLog :
+#ifndef ZSTD_MULTITHREAD
+ return ERROR(parameter_unsupported);
+#else
+ return ZSTDMT_CCtxParam_setMTCtxParameter(CCtxParams, ZSTDMT_p_overlapLog, value);
+#endif
+
+ case ZSTD_c_rsyncable :
+#ifndef ZSTD_MULTITHREAD
+ return ERROR(parameter_unsupported);
+#else
+ return ZSTDMT_CCtxParam_setMTCtxParameter(CCtxParams, ZSTDMT_p_rsyncable, value);
+#endif
+
+ case ZSTD_c_enableLongDistanceMatching :
+ CCtxParams->ldmParams.enableLdm = (value!=0);
+ return CCtxParams->ldmParams.enableLdm;
+
+ case ZSTD_c_ldmHashLog :
+ if (value!=0) /* 0 ==> auto */
+ BOUNDCHECK(ZSTD_c_ldmHashLog, value);
+ CCtxParams->ldmParams.hashLog = value;
+ return CCtxParams->ldmParams.hashLog;
+
+ case ZSTD_c_ldmMinMatch :
+ if (value!=0) /* 0 ==> default */
+ BOUNDCHECK(ZSTD_c_ldmMinMatch, value);
+ CCtxParams->ldmParams.minMatchLength = value;
+ return CCtxParams->ldmParams.minMatchLength;
+
+ case ZSTD_c_ldmBucketSizeLog :
+ if (value!=0) /* 0 ==> default */
+ BOUNDCHECK(ZSTD_c_ldmBucketSizeLog, value);
+ CCtxParams->ldmParams.bucketSizeLog = value;
+ return CCtxParams->ldmParams.bucketSizeLog;
+
+ case ZSTD_c_ldmHashRateLog :
+ if (value > ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN)
+ return ERROR(parameter_outOfBound);
+ CCtxParams->ldmParams.hashRateLog = value;
+ return CCtxParams->ldmParams.hashRateLog;
+
+ default: return ERROR(parameter_unsupported);
+ }
+}
+
+size_t ZSTD_CCtx_getParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value)
+{
+ return ZSTD_CCtxParam_getParameter(&cctx->requestedParams, param, value);
+}
+
+size_t ZSTD_CCtxParam_getParameter(
+ ZSTD_CCtx_params* CCtxParams, ZSTD_cParameter param, int* value)
+{
+ switch(param)
+ {
+ case ZSTD_c_format :
+ *value = CCtxParams->format;
+ break;
+ case ZSTD_c_compressionLevel :
+ *value = CCtxParams->compressionLevel;
+ break;
+ case ZSTD_c_windowLog :
+ *value = CCtxParams->cParams.windowLog;
+ break;
+ case ZSTD_c_hashLog :
+ *value = CCtxParams->cParams.hashLog;
+ break;
+ case ZSTD_c_chainLog :
+ *value = CCtxParams->cParams.chainLog;
+ break;
+ case ZSTD_c_searchLog :
+ *value = CCtxParams->cParams.searchLog;
+ break;
+ case ZSTD_c_minMatch :
+ *value = CCtxParams->cParams.minMatch;
+ break;
+ case ZSTD_c_targetLength :
+ *value = CCtxParams->cParams.targetLength;
+ break;
+ case ZSTD_c_strategy :
+ *value = (unsigned)CCtxParams->cParams.strategy;
+ break;
+ case ZSTD_c_contentSizeFlag :
+ *value = CCtxParams->fParams.contentSizeFlag;
+ break;
+ case ZSTD_c_checksumFlag :
+ *value = CCtxParams->fParams.checksumFlag;
+ break;
+ case ZSTD_c_dictIDFlag :
+ *value = !CCtxParams->fParams.noDictIDFlag;
+ break;
+ case ZSTD_c_forceMaxWindow :
+ *value = CCtxParams->forceWindow;
+ break;
+ case ZSTD_c_forceAttachDict :
+ *value = CCtxParams->attachDictPref;
+ break;
+ case ZSTD_c_nbWorkers :
+#ifndef ZSTD_MULTITHREAD
+ assert(CCtxParams->nbWorkers == 0);
+#endif
+ *value = CCtxParams->nbWorkers;
+ break;
+ case ZSTD_c_jobSize :
+#ifndef ZSTD_MULTITHREAD
+ return ERROR(parameter_unsupported);
+#else
+ assert(CCtxParams->jobSize <= INT_MAX);
+ *value = (int)CCtxParams->jobSize;
+ break;
+#endif
+ case ZSTD_c_overlapLog :
+#ifndef ZSTD_MULTITHREAD
+ return ERROR(parameter_unsupported);
+#else
+ *value = CCtxParams->overlapLog;
+ break;
+#endif
+ case ZSTD_c_rsyncable :
+#ifndef ZSTD_MULTITHREAD
+ return ERROR(parameter_unsupported);
+#else
+ *value = CCtxParams->rsyncable;
+ break;
+#endif
+ case ZSTD_c_enableLongDistanceMatching :
+ *value = CCtxParams->ldmParams.enableLdm;
+ break;
+ case ZSTD_c_ldmHashLog :
+ *value = CCtxParams->ldmParams.hashLog;
+ break;
+ case ZSTD_c_ldmMinMatch :
+ *value = CCtxParams->ldmParams.minMatchLength;
+ break;
+ case ZSTD_c_ldmBucketSizeLog :
+ *value = CCtxParams->ldmParams.bucketSizeLog;
+ break;
+ case ZSTD_c_ldmHashRateLog :
+ *value = CCtxParams->ldmParams.hashRateLog;
+ break;
+ default: return ERROR(parameter_unsupported);
+ }
+ return 0;
+}
+
+/** ZSTD_CCtx_setParametersUsingCCtxParams() :
+ * just applies `params` into `cctx`
+ * no action is performed, parameters are merely stored.
+ * If ZSTDMT is enabled, parameters are pushed to cctx->mtctx.
+ * This is possible even if a compression is ongoing.
+ * In which case, new parameters will be applied on the fly, starting with next compression job.
+ */
+size_t ZSTD_CCtx_setParametersUsingCCtxParams(
+ ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params)
+{
+ DEBUGLOG(4, "ZSTD_CCtx_setParametersUsingCCtxParams");
+ if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
+ if (cctx->cdict) return ERROR(stage_wrong);
+
+ cctx->requestedParams = *params;
+ return 0;
+}
+
+ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize)
+{
+ DEBUGLOG(4, "ZSTD_CCtx_setPledgedSrcSize to %u bytes", (U32)pledgedSrcSize);
+ if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
+ cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
+ return 0;
+}
+
+size_t ZSTD_CCtx_loadDictionary_advanced(
+ ZSTD_CCtx* cctx, const void* dict, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType)
+{
+ if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
+ if (cctx->staticSize) return ERROR(memory_allocation); /* no malloc for static CCtx */
+ DEBUGLOG(4, "ZSTD_CCtx_loadDictionary_advanced (size: %u)", (U32)dictSize);
+ ZSTD_freeCDict(cctx->cdictLocal); /* in case one already exists */
+ if (dict==NULL || dictSize==0) { /* no dictionary mode */
+ cctx->cdictLocal = NULL;
+ cctx->cdict = NULL;
+ } else {
+ ZSTD_compressionParameters const cParams =
+ ZSTD_getCParamsFromCCtxParams(&cctx->requestedParams, cctx->pledgedSrcSizePlusOne-1, dictSize);
+ cctx->cdictLocal = ZSTD_createCDict_advanced(
+ dict, dictSize,
+ dictLoadMethod, dictContentType,
+ cParams, cctx->customMem);
+ cctx->cdict = cctx->cdictLocal;
+ if (cctx->cdictLocal == NULL)
+ return ERROR(memory_allocation);
+ }
+ return 0;
+}
+
+ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(
+ ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
+{
+ return ZSTD_CCtx_loadDictionary_advanced(
+ cctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
+}
+
+ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize)
+{
+ return ZSTD_CCtx_loadDictionary_advanced(
+ cctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
+}
+
+
+size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
+{
+ if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
+ cctx->cdict = cdict;
+ memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* exclusive */
+ return 0;
+}
+
+size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize)
+{
+ return ZSTD_CCtx_refPrefix_advanced(cctx, prefix, prefixSize, ZSTD_dct_rawContent);
+}
+
+size_t ZSTD_CCtx_refPrefix_advanced(
+ ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
+{
+ if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
+ cctx->cdict = NULL; /* prefix discards any prior cdict */
+ cctx->prefixDict.dict = prefix;
+ cctx->prefixDict.dictSize = prefixSize;
+ cctx->prefixDict.dictContentType = dictContentType;
+ return 0;
+}
+
+/*! ZSTD_CCtx_reset() :
+ * Also dumps dictionary */
+size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset)
+{
+ if ( (reset == ZSTD_reset_session_only)
+ || (reset == ZSTD_reset_session_and_parameters) ) {
+ cctx->streamStage = zcss_init;
+ cctx->pledgedSrcSizePlusOne = 0;
+ }
+ if ( (reset == ZSTD_reset_parameters)
+ || (reset == ZSTD_reset_session_and_parameters) ) {
+ if (cctx->streamStage != zcss_init) return ERROR(stage_wrong);
+ cctx->cdict = NULL;
+ return ZSTD_CCtxParams_reset(&cctx->requestedParams);
+ }
+ return 0;
+}
+
+
+/** ZSTD_checkCParams() :
+ control CParam values remain within authorized range.
+ @return : 0, or an error code if one value is beyond authorized range */
+size_t ZSTD_checkCParams(ZSTD_compressionParameters cParams)
+{
+ BOUNDCHECK(ZSTD_c_windowLog, cParams.windowLog);
+ BOUNDCHECK(ZSTD_c_chainLog, cParams.chainLog);
+ BOUNDCHECK(ZSTD_c_hashLog, cParams.hashLog);
+ BOUNDCHECK(ZSTD_c_searchLog, cParams.searchLog);
+ BOUNDCHECK(ZSTD_c_minMatch, cParams.minMatch);
+ BOUNDCHECK(ZSTD_c_targetLength,cParams.targetLength);
+ BOUNDCHECK(ZSTD_c_strategy, cParams.strategy);
+ return 0;
+}
+
+/** ZSTD_clampCParams() :
+ * make CParam values within valid range.
+ * @return : valid CParams */
+static ZSTD_compressionParameters
+ZSTD_clampCParams(ZSTD_compressionParameters cParams)
+{
+# define CLAMP_TYPE(cParam, val, type) { \
+ ZSTD_bounds const bounds = ZSTD_cParam_getBounds(cParam); \
+ if ((int)val<bounds.lowerBound) val=(type)bounds.lowerBound; \
+ else if ((int)val>bounds.upperBound) val=(type)bounds.upperBound; \
+ }
+# define CLAMP(cParam, val) CLAMP_TYPE(cParam, val, int)
+ CLAMP(ZSTD_c_windowLog, cParams.windowLog);
+ CLAMP(ZSTD_c_chainLog, cParams.chainLog);
+ CLAMP(ZSTD_c_hashLog, cParams.hashLog);
+ CLAMP(ZSTD_c_searchLog, cParams.searchLog);
+ CLAMP(ZSTD_c_minMatch, cParams.minMatch);
+ CLAMP(ZSTD_c_targetLength,cParams.targetLength);
+ CLAMP_TYPE(ZSTD_c_strategy,cParams.strategy, ZSTD_strategy);
+ return cParams;
+}
+
+/** ZSTD_cycleLog() :
+ * condition for correct operation : hashLog > 1 */
+static U32 ZSTD_cycleLog(U32 hashLog, ZSTD_strategy strat)
+{
+ U32 const btScale = ((U32)strat >= (U32)ZSTD_btlazy2);
+ return hashLog - btScale;
+}
+
+/** ZSTD_adjustCParams_internal() :
+ optimize `cPar` for a given input (`srcSize` and `dictSize`).
+ mostly downsizing to reduce memory consumption and initialization latency.
+ Both `srcSize` and `dictSize` are optional (use 0 if unknown).
+ Note : cPar is assumed validated. Use ZSTD_checkCParams() to ensure this condition. */
+static ZSTD_compressionParameters
+ZSTD_adjustCParams_internal(ZSTD_compressionParameters cPar,
+ unsigned long long srcSize,
+ size_t dictSize)
+{
+ static const U64 minSrcSize = 513; /* (1<<9) + 1 */
+ static const U64 maxWindowResize = 1ULL << (ZSTD_WINDOWLOG_MAX-1);
+ assert(ZSTD_checkCParams(cPar)==0);
+
+ if (dictSize && (srcSize+1<2) /* srcSize unknown */ )
+ srcSize = minSrcSize; /* presumed small when there is a dictionary */
+ else if (srcSize == 0)
+ srcSize = ZSTD_CONTENTSIZE_UNKNOWN; /* 0 == unknown : presumed large */
+
+ /* resize windowLog if input is small enough, to use less memory */
+ if ( (srcSize < maxWindowResize)
+ && (dictSize < maxWindowResize) ) {
+ U32 const tSize = (U32)(srcSize + dictSize);
+ static U32 const hashSizeMin = 1 << ZSTD_HASHLOG_MIN;
+ U32 const srcLog = (tSize < hashSizeMin) ? ZSTD_HASHLOG_MIN :
+ ZSTD_highbit32(tSize-1) + 1;
+ if (cPar.windowLog > srcLog) cPar.windowLog = srcLog;
+ }
+ if (cPar.hashLog > cPar.windowLog+1) cPar.hashLog = cPar.windowLog+1;
+ { U32 const cycleLog = ZSTD_cycleLog(cPar.chainLog, cPar.strategy);
+ if (cycleLog > cPar.windowLog)
+ cPar.chainLog -= (cycleLog - cPar.windowLog);
+ }
+
+ if (cPar.windowLog < ZSTD_WINDOWLOG_ABSOLUTEMIN)
+ cPar.windowLog = ZSTD_WINDOWLOG_ABSOLUTEMIN; /* required for frame header */
+
+ return cPar;
+}
+
+ZSTD_compressionParameters
+ZSTD_adjustCParams(ZSTD_compressionParameters cPar,
+ unsigned long long srcSize,
+ size_t dictSize)
+{
+ cPar = ZSTD_clampCParams(cPar);
+ return ZSTD_adjustCParams_internal(cPar, srcSize, dictSize);
+}
+
+ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
+ const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize)
+{
+ ZSTD_compressionParameters cParams = ZSTD_getCParams(CCtxParams->compressionLevel, srcSizeHint, dictSize);
+ if (CCtxParams->ldmParams.enableLdm) cParams.windowLog = ZSTD_LDM_DEFAULT_WINDOW_LOG;
+ if (CCtxParams->cParams.windowLog) cParams.windowLog = CCtxParams->cParams.windowLog;
+ if (CCtxParams->cParams.hashLog) cParams.hashLog = CCtxParams->cParams.hashLog;
+ if (CCtxParams->cParams.chainLog) cParams.chainLog = CCtxParams->cParams.chainLog;
+ if (CCtxParams->cParams.searchLog) cParams.searchLog = CCtxParams->cParams.searchLog;
+ if (CCtxParams->cParams.minMatch) cParams.minMatch = CCtxParams->cParams.minMatch;
+ if (CCtxParams->cParams.targetLength) cParams.targetLength = CCtxParams->cParams.targetLength;
+ if (CCtxParams->cParams.strategy) cParams.strategy = CCtxParams->cParams.strategy;
+ assert(!ZSTD_checkCParams(cParams));
+ return ZSTD_adjustCParams_internal(cParams, srcSizeHint, dictSize);
+}
+
+static size_t
+ZSTD_sizeof_matchState(const ZSTD_compressionParameters* const cParams,
+ const U32 forCCtx)
+{
+ size_t const chainSize = (cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cParams->chainLog);
+ size_t const hSize = ((size_t)1) << cParams->hashLog;
+ U32 const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
+ size_t const h3Size = ((size_t)1) << hashLog3;
+ size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
+ size_t const optPotentialSpace = ((MaxML+1) + (MaxLL+1) + (MaxOff+1) + (1<<Litbits)) * sizeof(U32)
+ + (ZSTD_OPT_NUM+1) * (sizeof(ZSTD_match_t)+sizeof(ZSTD_optimal_t));
+ size_t const optSpace = (forCCtx && (cParams->strategy >= ZSTD_btopt))
+ ? optPotentialSpace
+ : 0;
+ DEBUGLOG(4, "chainSize: %u - hSize: %u - h3Size: %u",
+ (U32)chainSize, (U32)hSize, (U32)h3Size);
+ return tableSpace + optSpace;
+}
+
+size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params)
+{
+ /* Estimate CCtx size is supported for single-threaded compression only. */
+ if (params->nbWorkers > 0) { return ERROR(GENERIC); }
+ { ZSTD_compressionParameters const cParams =
+ ZSTD_getCParamsFromCCtxParams(params, 0, 0);
+ size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << cParams.windowLog);
+ U32 const divider = (cParams.minMatch==3) ? 3 : 4;
+ size_t const maxNbSeq = blockSize / divider;
+ size_t const tokenSpace = WILDCOPY_OVERLENGTH + blockSize + 11*maxNbSeq;
+ size_t const entropySpace = HUF_WORKSPACE_SIZE;
+ size_t const blockStateSpace = 2 * sizeof(ZSTD_compressedBlockState_t);
+ size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 1);
+
+ size_t const ldmSpace = ZSTD_ldm_getTableSize(params->ldmParams);
+ size_t const ldmSeqSpace = ZSTD_ldm_getMaxNbSeq(params->ldmParams, blockSize) * sizeof(rawSeq);
+
+ size_t const neededSpace = entropySpace + blockStateSpace + tokenSpace +
+ matchStateSize + ldmSpace + ldmSeqSpace;
+
+ DEBUGLOG(5, "sizeof(ZSTD_CCtx) : %u", (U32)sizeof(ZSTD_CCtx));
+ DEBUGLOG(5, "estimate workSpace : %u", (U32)neededSpace);
+ return sizeof(ZSTD_CCtx) + neededSpace;
+ }
+}
+
+size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams)
+{
+ ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams);
+ return ZSTD_estimateCCtxSize_usingCCtxParams(&params);
+}
+
+static size_t ZSTD_estimateCCtxSize_internal(int compressionLevel)
+{
+ ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, 0);
+ return ZSTD_estimateCCtxSize_usingCParams(cParams);
+}
+
+size_t ZSTD_estimateCCtxSize(int compressionLevel)
+{
+ int level;
+ size_t memBudget = 0;
+ for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
+ size_t const newMB = ZSTD_estimateCCtxSize_internal(level);
+ if (newMB > memBudget) memBudget = newMB;
+ }
+ return memBudget;
+}
+
+size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params)
+{
+ if (params->nbWorkers > 0) { return ERROR(GENERIC); }
+ { size_t const CCtxSize = ZSTD_estimateCCtxSize_usingCCtxParams(params);
+ size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, (size_t)1 << params->cParams.windowLog);
+ size_t const inBuffSize = ((size_t)1 << params->cParams.windowLog) + blockSize;
+ size_t const outBuffSize = ZSTD_compressBound(blockSize) + 1;
+ size_t const streamingSize = inBuffSize + outBuffSize;
+
+ return CCtxSize + streamingSize;
+ }
+}
+
+size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams)
+{
+ ZSTD_CCtx_params const params = ZSTD_makeCCtxParamsFromCParams(cParams);
+ return ZSTD_estimateCStreamSize_usingCCtxParams(&params);
+}
+
+static size_t ZSTD_estimateCStreamSize_internal(int compressionLevel)
+{
+ ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, 0);
+ return ZSTD_estimateCStreamSize_usingCParams(cParams);
+}
+
+size_t ZSTD_estimateCStreamSize(int compressionLevel)
+{
+ int level;
+ size_t memBudget = 0;
+ for (level=MIN(compressionLevel, 1); level<=compressionLevel; level++) {
+ size_t const newMB = ZSTD_estimateCStreamSize_internal(level);
+ if (newMB > memBudget) memBudget = newMB;
+ }
+ return memBudget;
+}
+
+/* ZSTD_getFrameProgression():
+ * tells how much data has been consumed (input) and produced (output) for current frame.
+ * able to count progression inside worker threads (non-blocking mode).
+ */
+ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx)
+{
+#ifdef ZSTD_MULTITHREAD
+ if (cctx->appliedParams.nbWorkers > 0) {
+ return ZSTDMT_getFrameProgression(cctx->mtctx);
+ }
+#endif
+ { ZSTD_frameProgression fp;
+ size_t const buffered = (cctx->inBuff == NULL) ? 0 :
+ cctx->inBuffPos - cctx->inToCompress;
+ if (buffered) assert(cctx->inBuffPos >= cctx->inToCompress);
+ assert(buffered <= ZSTD_BLOCKSIZE_MAX);
+ fp.ingested = cctx->consumedSrcSize + buffered;
+ fp.consumed = cctx->consumedSrcSize;
+ fp.produced = cctx->producedCSize;
+ fp.flushed = cctx->producedCSize; /* simplified; some data might still be left within streaming output buffer */
+ fp.currentJobID = 0;
+ fp.nbActiveWorkers = 0;
+ return fp;
+} }
+
+/*! ZSTD_toFlushNow()
+ * Only useful for multithreading scenarios currently (nbWorkers >= 1).
+ */
+size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx)
+{
+#ifdef ZSTD_MULTITHREAD
+ if (cctx->appliedParams.nbWorkers > 0) {
+ return ZSTDMT_toFlushNow(cctx->mtctx);
+ }
+#endif
+ (void)cctx;
+ return 0; /* over-simplification; could also check if context is currently running in streaming mode, and in which case, report how many bytes are left to be flushed within output buffer */
+}
+
+
+
+static U32 ZSTD_equivalentCParams(ZSTD_compressionParameters cParams1,
+ ZSTD_compressionParameters cParams2)
+{
+ return (cParams1.hashLog == cParams2.hashLog)
+ & (cParams1.chainLog == cParams2.chainLog)
+ & (cParams1.strategy == cParams2.strategy) /* opt parser space */
+ & ((cParams1.minMatch==3) == (cParams2.minMatch==3)); /* hashlog3 space */
+}
+
+static void ZSTD_assertEqualCParams(ZSTD_compressionParameters cParams1,
+ ZSTD_compressionParameters cParams2)
+{
+ (void)cParams1;
+ (void)cParams2;
+ assert(cParams1.windowLog == cParams2.windowLog);
+ assert(cParams1.chainLog == cParams2.chainLog);
+ assert(cParams1.hashLog == cParams2.hashLog);
+ assert(cParams1.searchLog == cParams2.searchLog);
+ assert(cParams1.minMatch == cParams2.minMatch);
+ assert(cParams1.targetLength == cParams2.targetLength);
+ assert(cParams1.strategy == cParams2.strategy);
+}
+
+/** The parameters are equivalent if ldm is not enabled in both sets or
+ * all the parameters are equivalent. */
+static U32 ZSTD_equivalentLdmParams(ldmParams_t ldmParams1,
+ ldmParams_t ldmParams2)
+{
+ return (!ldmParams1.enableLdm && !ldmParams2.enableLdm) ||
+ (ldmParams1.enableLdm == ldmParams2.enableLdm &&
+ ldmParams1.hashLog == ldmParams2.hashLog &&
+ ldmParams1.bucketSizeLog == ldmParams2.bucketSizeLog &&
+ ldmParams1.minMatchLength == ldmParams2.minMatchLength &&
+ ldmParams1.hashRateLog == ldmParams2.hashRateLog);
+}
+
+typedef enum { ZSTDb_not_buffered, ZSTDb_buffered } ZSTD_buffered_policy_e;
+
+/* ZSTD_sufficientBuff() :
+ * check internal buffers exist for streaming if buffPol == ZSTDb_buffered .
+ * Note : they are assumed to be correctly sized if ZSTD_equivalentCParams()==1 */
+static U32 ZSTD_sufficientBuff(size_t bufferSize1, size_t maxNbSeq1,
+ size_t maxNbLit1,
+ ZSTD_buffered_policy_e buffPol2,
+ ZSTD_compressionParameters cParams2,
+ U64 pledgedSrcSize)
+{
+ size_t const windowSize2 = MAX(1, (size_t)MIN(((U64)1 << cParams2.windowLog), pledgedSrcSize));
+ size_t const blockSize2 = MIN(ZSTD_BLOCKSIZE_MAX, windowSize2);
+ size_t const maxNbSeq2 = blockSize2 / ((cParams2.minMatch == 3) ? 3 : 4);
+ size_t const maxNbLit2 = blockSize2;
+ size_t const neededBufferSize2 = (buffPol2==ZSTDb_buffered) ? windowSize2 + blockSize2 : 0;
+ DEBUGLOG(4, "ZSTD_sufficientBuff: is neededBufferSize2=%u <= bufferSize1=%u",
+ (U32)neededBufferSize2, (U32)bufferSize1);
+ DEBUGLOG(4, "ZSTD_sufficientBuff: is maxNbSeq2=%u <= maxNbSeq1=%u",
+ (U32)maxNbSeq2, (U32)maxNbSeq1);
+ DEBUGLOG(4, "ZSTD_sufficientBuff: is maxNbLit2=%u <= maxNbLit1=%u",
+ (U32)maxNbLit2, (U32)maxNbLit1);
+ return (maxNbLit2 <= maxNbLit1)
+ & (maxNbSeq2 <= maxNbSeq1)
+ & (neededBufferSize2 <= bufferSize1);
+}
+
+/** Equivalence for resetCCtx purposes */
+static U32 ZSTD_equivalentParams(ZSTD_CCtx_params params1,
+ ZSTD_CCtx_params params2,
+ size_t buffSize1,
+ size_t maxNbSeq1, size_t maxNbLit1,
+ ZSTD_buffered_policy_e buffPol2,
+ U64 pledgedSrcSize)
+{
+ DEBUGLOG(4, "ZSTD_equivalentParams: pledgedSrcSize=%u", (U32)pledgedSrcSize);
+ if (!ZSTD_equivalentCParams(params1.cParams, params2.cParams)) {
+ DEBUGLOG(4, "ZSTD_equivalentCParams() == 0");
+ return 0;
+ }
+ if (!ZSTD_equivalentLdmParams(params1.ldmParams, params2.ldmParams)) {
+ DEBUGLOG(4, "ZSTD_equivalentLdmParams() == 0");
+ return 0;
+ }
+ if (!ZSTD_sufficientBuff(buffSize1, maxNbSeq1, maxNbLit1, buffPol2,
+ params2.cParams, pledgedSrcSize)) {
+ DEBUGLOG(4, "ZSTD_sufficientBuff() == 0");
+ return 0;
+ }
+ return 1;
+}
+
+static void ZSTD_reset_compressedBlockState(ZSTD_compressedBlockState_t* bs)
+{
+ int i;
+ for (i = 0; i < ZSTD_REP_NUM; ++i)
+ bs->rep[i] = repStartValue[i];
+ bs->entropy.huf.repeatMode = HUF_repeat_none;
+ bs->entropy.fse.offcode_repeatMode = FSE_repeat_none;
+ bs->entropy.fse.matchlength_repeatMode = FSE_repeat_none;
+ bs->entropy.fse.litlength_repeatMode = FSE_repeat_none;
+}
+
+/*! ZSTD_invalidateMatchState()
+ * Invalidate all the matches in the match finder tables.
+ * Requires nextSrc and base to be set (can be NULL).
+ */
+static void ZSTD_invalidateMatchState(ZSTD_matchState_t* ms)
+{
+ ZSTD_window_clear(&ms->window);
+
+ ms->nextToUpdate = ms->window.dictLimit;
+ ms->nextToUpdate3 = ms->window.dictLimit;
+ ms->loadedDictEnd = 0;
+ ms->opt.litLengthSum = 0; /* force reset of btopt stats */
+ ms->dictMatchState = NULL;
+}
+
+/*! ZSTD_continueCCtx() :
+ * reuse CCtx without reset (note : requires no dictionary) */
+static size_t ZSTD_continueCCtx(ZSTD_CCtx* cctx, ZSTD_CCtx_params params, U64 pledgedSrcSize)
+{
+ size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params.cParams.windowLog), pledgedSrcSize));
+ size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize);
+ DEBUGLOG(4, "ZSTD_continueCCtx: re-use context in place");
+
+ cctx->blockSize = blockSize; /* previous block size could be different even for same windowLog, due to pledgedSrcSize */
+ cctx->appliedParams = params;
+ cctx->blockState.matchState.cParams = params.cParams;
+ cctx->pledgedSrcSizePlusOne = pledgedSrcSize+1;
+ cctx->consumedSrcSize = 0;
+ cctx->producedCSize = 0;
+ if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
+ cctx->appliedParams.fParams.contentSizeFlag = 0;
+ DEBUGLOG(4, "pledged content size : %u ; flag : %u",
+ (U32)pledgedSrcSize, cctx->appliedParams.fParams.contentSizeFlag);
+ cctx->stage = ZSTDcs_init;
+ cctx->dictID = 0;
+ if (params.ldmParams.enableLdm)
+ ZSTD_window_clear(&cctx->ldmState.window);
+ ZSTD_referenceExternalSequences(cctx, NULL, 0);
+ ZSTD_invalidateMatchState(&cctx->blockState.matchState);
+ ZSTD_reset_compressedBlockState(cctx->blockState.prevCBlock);
+ XXH64_reset(&cctx->xxhState, 0);
+ return 0;
+}
+
+typedef enum { ZSTDcrp_continue, ZSTDcrp_noMemset } ZSTD_compResetPolicy_e;
+
+static void*
+ZSTD_reset_matchState(ZSTD_matchState_t* ms,
+ void* ptr,
+ const ZSTD_compressionParameters* cParams,
+ ZSTD_compResetPolicy_e const crp, U32 const forCCtx)
+{
+ size_t const chainSize = (cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cParams->chainLog);
+ size_t const hSize = ((size_t)1) << cParams->hashLog;
+ U32 const hashLog3 = (forCCtx && cParams->minMatch==3) ? MIN(ZSTD_HASHLOG3_MAX, cParams->windowLog) : 0;
+ size_t const h3Size = ((size_t)1) << hashLog3;
+ size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
+
+ assert(((size_t)ptr & 3) == 0);
+
+ ms->hashLog3 = hashLog3;
+ memset(&ms->window, 0, sizeof(ms->window));
+ ms->window.dictLimit = 1; /* start from 1, so that 1st position is valid */
+ ms->window.lowLimit = 1; /* it ensures first and later CCtx usages compress the same */
+ ms->window.nextSrc = ms->window.base + 1; /* see issue #1241 */
+ ZSTD_invalidateMatchState(ms);
+
+ /* opt parser space */
+ if (forCCtx && (cParams->strategy >= ZSTD_btopt)) {
+ DEBUGLOG(4, "reserving optimal parser space");
+ ms->opt.litFreq = (unsigned*)ptr;
+ ms->opt.litLengthFreq = ms->opt.litFreq + (1<<Litbits);
+ ms->opt.matchLengthFreq = ms->opt.litLengthFreq + (MaxLL+1);
+ ms->opt.offCodeFreq = ms->opt.matchLengthFreq + (MaxML+1);
+ ptr = ms->opt.offCodeFreq + (MaxOff+1);
+ ms->opt.matchTable = (ZSTD_match_t*)ptr;
+ ptr = ms->opt.matchTable + ZSTD_OPT_NUM+1;
+ ms->opt.priceTable = (ZSTD_optimal_t*)ptr;
+ ptr = ms->opt.priceTable + ZSTD_OPT_NUM+1;
+ }
+
+ /* table Space */
+ DEBUGLOG(4, "reset table : %u", crp!=ZSTDcrp_noMemset);
+ assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
+ if (crp!=ZSTDcrp_noMemset) memset(ptr, 0, tableSpace); /* reset tables only */
+ ms->hashTable = (U32*)(ptr);
+ ms->chainTable = ms->hashTable + hSize;
+ ms->hashTable3 = ms->chainTable + chainSize;
+ ptr = ms->hashTable3 + h3Size;
+
+ ms->cParams = *cParams;
+
+ assert(((size_t)ptr & 3) == 0);
+ return ptr;
+}
+
+#define ZSTD_WORKSPACETOOLARGE_FACTOR 3 /* define "workspace is too large" as this number of times larger than needed */
+#define ZSTD_WORKSPACETOOLARGE_MAXDURATION 128 /* when workspace is continuously too large
+ * during at least this number of times,
+ * context's memory usage is considered wasteful,
+ * because it's sized to handle a worst case scenario which rarely happens.
+ * In which case, resize it down to free some memory */
+
+/*! ZSTD_resetCCtx_internal() :
+ note : `params` are assumed fully validated at this stage */
+static size_t ZSTD_resetCCtx_internal(ZSTD_CCtx* zc,
+ ZSTD_CCtx_params params,
+ U64 pledgedSrcSize,
+ ZSTD_compResetPolicy_e const crp,
+ ZSTD_buffered_policy_e const zbuff)
+{
+ DEBUGLOG(4, "ZSTD_resetCCtx_internal: pledgedSrcSize=%u, wlog=%u",
+ (U32)pledgedSrcSize, params.cParams.windowLog);
+ assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
+
+ if (crp == ZSTDcrp_continue) {
+ if (ZSTD_equivalentParams(zc->appliedParams, params,
+ zc->inBuffSize,
+ zc->seqStore.maxNbSeq, zc->seqStore.maxNbLit,
+ zbuff, pledgedSrcSize)) {
+ DEBUGLOG(4, "ZSTD_equivalentParams()==1 -> continue mode (wLog1=%u, blockSize1=%zu)",
+ zc->appliedParams.cParams.windowLog, zc->blockSize);
+ zc->workSpaceOversizedDuration += (zc->workSpaceOversizedDuration > 0); /* if it was too large, it still is */
+ if (zc->workSpaceOversizedDuration <= ZSTD_WORKSPACETOOLARGE_MAXDURATION)
+ return ZSTD_continueCCtx(zc, params, pledgedSrcSize);
+ } }
+ DEBUGLOG(4, "ZSTD_equivalentParams()==0 -> reset CCtx");
+
+ if (params.ldmParams.enableLdm) {
+ /* Adjust long distance matching parameters */
+ ZSTD_ldm_adjustParameters(&params.ldmParams, &params.cParams);
+ assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);
+ assert(params.ldmParams.hashRateLog < 32);
+ zc->ldmState.hashPower = ZSTD_rollingHash_primePower(params.ldmParams.minMatchLength);
+ }
+
+ { size_t const windowSize = MAX(1, (size_t)MIN(((U64)1 << params.cParams.windowLog), pledgedSrcSize));
+ size_t const blockSize = MIN(ZSTD_BLOCKSIZE_MAX, windowSize);
+ U32 const divider = (params.cParams.minMatch==3) ? 3 : 4;
+ size_t const maxNbSeq = blockSize / divider;
+ size_t const tokenSpace = WILDCOPY_OVERLENGTH + blockSize + 11*maxNbSeq;
+ size_t const buffOutSize = (zbuff==ZSTDb_buffered) ? ZSTD_compressBound(blockSize)+1 : 0;
+ size_t const buffInSize = (zbuff==ZSTDb_buffered) ? windowSize + blockSize : 0;
+ size_t const matchStateSize = ZSTD_sizeof_matchState(&params.cParams, /* forCCtx */ 1);
+ size_t const maxNbLdmSeq = ZSTD_ldm_getMaxNbSeq(params.ldmParams, blockSize);
+ void* ptr; /* used to partition workSpace */
+
+ /* Check if workSpace is large enough, alloc a new one if needed */
+ { size_t const entropySpace = HUF_WORKSPACE_SIZE;
+ size_t const blockStateSpace = 2 * sizeof(ZSTD_compressedBlockState_t);
+ size_t const bufferSpace = buffInSize + buffOutSize;
+ size_t const ldmSpace = ZSTD_ldm_getTableSize(params.ldmParams);
+ size_t const ldmSeqSpace = maxNbLdmSeq * sizeof(rawSeq);
+
+ size_t const neededSpace = entropySpace + blockStateSpace + ldmSpace +
+ ldmSeqSpace + matchStateSize + tokenSpace +
+ bufferSpace;
+
+ int const workSpaceTooSmall = zc->workSpaceSize < neededSpace;
+ int const workSpaceTooLarge = zc->workSpaceSize > ZSTD_WORKSPACETOOLARGE_FACTOR * neededSpace;
+ int const workSpaceWasteful = workSpaceTooLarge && (zc->workSpaceOversizedDuration > ZSTD_WORKSPACETOOLARGE_MAXDURATION);
+ zc->workSpaceOversizedDuration = workSpaceTooLarge ? zc->workSpaceOversizedDuration+1 : 0;
+
+ DEBUGLOG(4, "Need %zuKB workspace, including %zuKB for match state, and %zuKB for buffers",
+ neededSpace>>10, matchStateSize>>10, bufferSpace>>10);
+ DEBUGLOG(4, "windowSize: %zu - blockSize: %zu", windowSize, blockSize);
+
+ if (workSpaceTooSmall || workSpaceWasteful) {
+ DEBUGLOG(4, "Need to resize workSpaceSize from %zuKB to %zuKB",
+ zc->workSpaceSize >> 10,
+ neededSpace >> 10);
+ /* static cctx : no resize, error out */
+ if (zc->staticSize) return ERROR(memory_allocation);
+
+ zc->workSpaceSize = 0;
+ ZSTD_free(zc->workSpace, zc->customMem);
+ zc->workSpace = ZSTD_malloc(neededSpace, zc->customMem);
+ if (zc->workSpace == NULL) return ERROR(memory_allocation);
+ zc->workSpaceSize = neededSpace;
+ zc->workSpaceOversizedDuration = 0;
+
+ /* Statically sized space.
+ * entropyWorkspace never moves,
+ * though prev/next block swap places */
+ assert(((size_t)zc->workSpace & 3) == 0); /* ensure correct alignment */
+ assert(zc->workSpaceSize >= 2 * sizeof(ZSTD_compressedBlockState_t));
+ zc->blockState.prevCBlock = (ZSTD_compressedBlockState_t*)zc->workSpace;
+ zc->blockState.nextCBlock = zc->blockState.prevCBlock + 1;
+ ptr = zc->blockState.nextCBlock + 1;
+ zc->entropyWorkspace = (U32*)ptr;
+ } }
+
+ /* init params */
+ zc->appliedParams = params;
+ zc->blockState.matchState.cParams = params.cParams;
+ zc->pledgedSrcSizePlusOne = pledgedSrcSize+1;
+ zc->consumedSrcSize = 0;
+ zc->producedCSize = 0;
+ if (pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN)
+ zc->appliedParams.fParams.contentSizeFlag = 0;
+ DEBUGLOG(4, "pledged content size : %u ; flag : %u",
+ (unsigned)pledgedSrcSize, zc->appliedParams.fParams.contentSizeFlag);
+ zc->blockSize = blockSize;
+
+ XXH64_reset(&zc->xxhState, 0);
+ zc->stage = ZSTDcs_init;
+ zc->dictID = 0;
+
+ ZSTD_reset_compressedBlockState(zc->blockState.prevCBlock);
+
+ ptr = zc->entropyWorkspace + HUF_WORKSPACE_SIZE_U32;
+
+ /* ldm hash table */
+ /* initialize bucketOffsets table later for pointer alignment */
+ if (params.ldmParams.enableLdm) {
+ size_t const ldmHSize = ((size_t)1) << params.ldmParams.hashLog;
+ memset(ptr, 0, ldmHSize * sizeof(ldmEntry_t));
+ assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
+ zc->ldmState.hashTable = (ldmEntry_t*)ptr;
+ ptr = zc->ldmState.hashTable + ldmHSize;
+ zc->ldmSequences = (rawSeq*)ptr;
+ ptr = zc->ldmSequences + maxNbLdmSeq;
+ zc->maxNbLdmSequences = maxNbLdmSeq;
+
+ memset(&zc->ldmState.window, 0, sizeof(zc->ldmState.window));
+ }
+ assert(((size_t)ptr & 3) == 0); /* ensure ptr is properly aligned */
+
+ ptr = ZSTD_reset_matchState(&zc->blockState.matchState, ptr, &params.cParams, crp, /* forCCtx */ 1);
+
+ /* sequences storage */
+ zc->seqStore.maxNbSeq = maxNbSeq;
+ zc->seqStore.sequencesStart = (seqDef*)ptr;
+ ptr = zc->seqStore.sequencesStart + maxNbSeq;
+ zc->seqStore.llCode = (BYTE*) ptr;
+ zc->seqStore.mlCode = zc->seqStore.llCode + maxNbSeq;
+ zc->seqStore.ofCode = zc->seqStore.mlCode + maxNbSeq;
+ zc->seqStore.litStart = zc->seqStore.ofCode + maxNbSeq;
+ /* ZSTD_wildcopy() is used to copy into the literals buffer,
+ * so we have to oversize the buffer by WILDCOPY_OVERLENGTH bytes.
+ */
+ zc->seqStore.maxNbLit = blockSize;
+ ptr = zc->seqStore.litStart + blockSize + WILDCOPY_OVERLENGTH;
+
+ /* ldm bucketOffsets table */
+ if (params.ldmParams.enableLdm) {
+ size_t const ldmBucketSize =
+ ((size_t)1) << (params.ldmParams.hashLog -
+ params.ldmParams.bucketSizeLog);
+ memset(ptr, 0, ldmBucketSize);
+ zc->ldmState.bucketOffsets = (BYTE*)ptr;
+ ptr = zc->ldmState.bucketOffsets + ldmBucketSize;
+ ZSTD_window_clear(&zc->ldmState.window);
+ }
+ ZSTD_referenceExternalSequences(zc, NULL, 0);
+
+ /* buffers */
+ zc->inBuffSize = buffInSize;
+ zc->inBuff = (char*)ptr;
+ zc->outBuffSize = buffOutSize;
+ zc->outBuff = zc->inBuff + buffInSize;
+
+ return 0;
+ }
+}
+
+/* ZSTD_invalidateRepCodes() :
+ * ensures next compression will not use repcodes from previous block.
+ * Note : only works with regular variant;
+ * do not use with extDict variant ! */
+void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx) {
+ int i;
+ for (i=0; i<ZSTD_REP_NUM; i++) cctx->blockState.prevCBlock->rep[i] = 0;
+ assert(!ZSTD_window_hasExtDict(cctx->blockState.matchState.window));
+}
+
+/* These are the approximate sizes for each strategy past which copying the
+ * dictionary tables into the working context is faster than using them
+ * in-place.
+ */
+static const size_t attachDictSizeCutoffs[ZSTD_STRATEGY_MAX+1] = {
+ 8 KB, /* unused */
+ 8 KB, /* ZSTD_fast */
+ 16 KB, /* ZSTD_dfast */
+ 32 KB, /* ZSTD_greedy */
+ 32 KB, /* ZSTD_lazy */
+ 32 KB, /* ZSTD_lazy2 */
+ 32 KB, /* ZSTD_btlazy2 */
+ 32 KB, /* ZSTD_btopt */
+ 8 KB, /* ZSTD_btultra */
+ 8 KB /* ZSTD_btultra2 */
+};
+
+static int ZSTD_shouldAttachDict(const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params,
+ U64 pledgedSrcSize)
+{
+ size_t cutoff = attachDictSizeCutoffs[cdict->matchState.cParams.strategy];
+ return ( pledgedSrcSize <= cutoff
+ || pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN
+ || params.attachDictPref == ZSTD_dictForceAttach )
+ && params.attachDictPref != ZSTD_dictForceCopy
+ && !params.forceWindow; /* dictMatchState isn't correctly
+ * handled in _enforceMaxDist */
+}
+
+static size_t ZSTD_resetCCtx_byAttachingCDict(
+ ZSTD_CCtx* cctx,
+ const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params,
+ U64 pledgedSrcSize,
+ ZSTD_buffered_policy_e zbuff)
+{
+ {
+ const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;
+ unsigned const windowLog = params.cParams.windowLog;
+ assert(windowLog != 0);
+ /* Resize working context table params for input only, since the dict
+ * has its own tables. */
+ params.cParams = ZSTD_adjustCParams_internal(*cdict_cParams, pledgedSrcSize, 0);
+ params.cParams.windowLog = windowLog;
+ ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
+ ZSTDcrp_continue, zbuff);
+ assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
+ }
+
+ {
+ const U32 cdictEnd = (U32)( cdict->matchState.window.nextSrc
+ - cdict->matchState.window.base);
+ const U32 cdictLen = cdictEnd - cdict->matchState.window.dictLimit;
+ if (cdictLen == 0) {
+ /* don't even attach dictionaries with no contents */
+ DEBUGLOG(4, "skipping attaching empty dictionary");
+ } else {
+ DEBUGLOG(4, "attaching dictionary into context");
+ cctx->blockState.matchState.dictMatchState = &cdict->matchState;
+
+ /* prep working match state so dict matches never have negative indices
+ * when they are translated to the working context's index space. */
+ if (cctx->blockState.matchState.window.dictLimit < cdictEnd) {
+ cctx->blockState.matchState.window.nextSrc =
+ cctx->blockState.matchState.window.base + cdictEnd;
+ ZSTD_window_clear(&cctx->blockState.matchState.window);
+ }
+ cctx->blockState.matchState.loadedDictEnd = cctx->blockState.matchState.window.dictLimit;
+ }
+ }
+
+ cctx->dictID = cdict->dictID;
+
+ /* copy block state */
+ memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
+
+ return 0;
+}
+
+static size_t ZSTD_resetCCtx_byCopyingCDict(ZSTD_CCtx* cctx,
+ const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params,
+ U64 pledgedSrcSize,
+ ZSTD_buffered_policy_e zbuff)
+{
+ const ZSTD_compressionParameters *cdict_cParams = &cdict->matchState.cParams;
+
+ DEBUGLOG(4, "copying dictionary into context");
+
+ { unsigned const windowLog = params.cParams.windowLog;
+ assert(windowLog != 0);
+ /* Copy only compression parameters related to tables. */
+ params.cParams = *cdict_cParams;
+ params.cParams.windowLog = windowLog;
+ ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
+ ZSTDcrp_noMemset, zbuff);
+ assert(cctx->appliedParams.cParams.strategy == cdict_cParams->strategy);
+ assert(cctx->appliedParams.cParams.hashLog == cdict_cParams->hashLog);
+ assert(cctx->appliedParams.cParams.chainLog == cdict_cParams->chainLog);
+ }
+
+ /* copy tables */
+ { size_t const chainSize = (cdict_cParams->strategy == ZSTD_fast) ? 0 : ((size_t)1 << cdict_cParams->chainLog);
+ size_t const hSize = (size_t)1 << cdict_cParams->hashLog;
+ size_t const tableSpace = (chainSize + hSize) * sizeof(U32);
+ assert((U32*)cctx->blockState.matchState.chainTable == (U32*)cctx->blockState.matchState.hashTable + hSize); /* chainTable must follow hashTable */
+ assert((U32*)cctx->blockState.matchState.hashTable3 == (U32*)cctx->blockState.matchState.chainTable + chainSize);
+ assert((U32*)cdict->matchState.chainTable == (U32*)cdict->matchState.hashTable + hSize); /* chainTable must follow hashTable */
+ assert((U32*)cdict->matchState.hashTable3 == (U32*)cdict->matchState.chainTable + chainSize);
+ memcpy(cctx->blockState.matchState.hashTable, cdict->matchState.hashTable, tableSpace); /* presumes all tables follow each other */
+ }
+
+ /* Zero the hashTable3, since the cdict never fills it */
+ { size_t const h3Size = (size_t)1 << cctx->blockState.matchState.hashLog3;
+ assert(cdict->matchState.hashLog3 == 0);
+ memset(cctx->blockState.matchState.hashTable3, 0, h3Size * sizeof(U32));
+ }
+
+ /* copy dictionary offsets */
+ { ZSTD_matchState_t const* srcMatchState = &cdict->matchState;
+ ZSTD_matchState_t* dstMatchState = &cctx->blockState.matchState;
+ dstMatchState->window = srcMatchState->window;
+ dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
+ dstMatchState->nextToUpdate3= srcMatchState->nextToUpdate3;
+ dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
+ }
+
+ cctx->dictID = cdict->dictID;
+
+ /* copy block state */
+ memcpy(cctx->blockState.prevCBlock, &cdict->cBlockState, sizeof(cdict->cBlockState));
+
+ return 0;
+}
+
+/* We have a choice between copying the dictionary context into the working
+ * context, or referencing the dictionary context from the working context
+ * in-place. We decide here which strategy to use. */
+static size_t ZSTD_resetCCtx_usingCDict(ZSTD_CCtx* cctx,
+ const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params,
+ U64 pledgedSrcSize,
+ ZSTD_buffered_policy_e zbuff)
+{
+
+ DEBUGLOG(4, "ZSTD_resetCCtx_usingCDict (pledgedSrcSize=%u)",
+ (unsigned)pledgedSrcSize);
+
+ if (ZSTD_shouldAttachDict(cdict, params, pledgedSrcSize)) {
+ return ZSTD_resetCCtx_byAttachingCDict(
+ cctx, cdict, params, pledgedSrcSize, zbuff);
+ } else {
+ return ZSTD_resetCCtx_byCopyingCDict(
+ cctx, cdict, params, pledgedSrcSize, zbuff);
+ }
+}
+
+/*! ZSTD_copyCCtx_internal() :
+ * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
+ * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
+ * The "context", in this case, refers to the hash and chain tables,
+ * entropy tables, and dictionary references.
+ * `windowLog` value is enforced if != 0, otherwise value is copied from srcCCtx.
+ * @return : 0, or an error code */
+static size_t ZSTD_copyCCtx_internal(ZSTD_CCtx* dstCCtx,
+ const ZSTD_CCtx* srcCCtx,
+ ZSTD_frameParameters fParams,
+ U64 pledgedSrcSize,
+ ZSTD_buffered_policy_e zbuff)
+{
+ DEBUGLOG(5, "ZSTD_copyCCtx_internal");
+ if (srcCCtx->stage!=ZSTDcs_init) return ERROR(stage_wrong);
+
+ memcpy(&dstCCtx->customMem, &srcCCtx->customMem, sizeof(ZSTD_customMem));
+ { ZSTD_CCtx_params params = dstCCtx->requestedParams;
+ /* Copy only compression parameters related to tables. */
+ params.cParams = srcCCtx->appliedParams.cParams;
+ params.fParams = fParams;
+ ZSTD_resetCCtx_internal(dstCCtx, params, pledgedSrcSize,
+ ZSTDcrp_noMemset, zbuff);
+ assert(dstCCtx->appliedParams.cParams.windowLog == srcCCtx->appliedParams.cParams.windowLog);
+ assert(dstCCtx->appliedParams.cParams.strategy == srcCCtx->appliedParams.cParams.strategy);
+ assert(dstCCtx->appliedParams.cParams.hashLog == srcCCtx->appliedParams.cParams.hashLog);
+ assert(dstCCtx->appliedParams.cParams.chainLog == srcCCtx->appliedParams.cParams.chainLog);
+ assert(dstCCtx->blockState.matchState.hashLog3 == srcCCtx->blockState.matchState.hashLog3);
+ }
+
+ /* copy tables */
+ { size_t const chainSize = (srcCCtx->appliedParams.cParams.strategy == ZSTD_fast) ? 0 : ((size_t)1 << srcCCtx->appliedParams.cParams.chainLog);
+ size_t const hSize = (size_t)1 << srcCCtx->appliedParams.cParams.hashLog;
+ size_t const h3Size = (size_t)1 << srcCCtx->blockState.matchState.hashLog3;
+ size_t const tableSpace = (chainSize + hSize + h3Size) * sizeof(U32);
+ assert((U32*)dstCCtx->blockState.matchState.chainTable == (U32*)dstCCtx->blockState.matchState.hashTable + hSize); /* chainTable must follow hashTable */
+ assert((U32*)dstCCtx->blockState.matchState.hashTable3 == (U32*)dstCCtx->blockState.matchState.chainTable + chainSize);
+ memcpy(dstCCtx->blockState.matchState.hashTable, srcCCtx->blockState.matchState.hashTable, tableSpace); /* presumes all tables follow each other */
+ }
+
+ /* copy dictionary offsets */
+ {
+ const ZSTD_matchState_t* srcMatchState = &srcCCtx->blockState.matchState;
+ ZSTD_matchState_t* dstMatchState = &dstCCtx->blockState.matchState;
+ dstMatchState->window = srcMatchState->window;
+ dstMatchState->nextToUpdate = srcMatchState->nextToUpdate;
+ dstMatchState->nextToUpdate3= srcMatchState->nextToUpdate3;
+ dstMatchState->loadedDictEnd= srcMatchState->loadedDictEnd;
+ }
+ dstCCtx->dictID = srcCCtx->dictID;
+
+ /* copy block state */
+ memcpy(dstCCtx->blockState.prevCBlock, srcCCtx->blockState.prevCBlock, sizeof(*srcCCtx->blockState.prevCBlock));
+
+ return 0;
+}
+
+/*! ZSTD_copyCCtx() :
+ * Duplicate an existing context `srcCCtx` into another one `dstCCtx`.
+ * Only works during stage ZSTDcs_init (i.e. after creation, but before first call to ZSTD_compressContinue()).
+ * pledgedSrcSize==0 means "unknown".
+* @return : 0, or an error code */
+size_t ZSTD_copyCCtx(ZSTD_CCtx* dstCCtx, const ZSTD_CCtx* srcCCtx, unsigned long long pledgedSrcSize)
+{
+ ZSTD_frameParameters fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
+ ZSTD_buffered_policy_e const zbuff = (ZSTD_buffered_policy_e)(srcCCtx->inBuffSize>0);
+ ZSTD_STATIC_ASSERT((U32)ZSTDb_buffered==1);
+ if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
+ fParams.contentSizeFlag = (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN);
+
+ return ZSTD_copyCCtx_internal(dstCCtx, srcCCtx,
+ fParams, pledgedSrcSize,
+ zbuff);
+}
+
+
+#define ZSTD_ROWSIZE 16
+/*! ZSTD_reduceTable() :
+ * reduce table indexes by `reducerValue`, or squash to zero.
+ * PreserveMark preserves "unsorted mark" for btlazy2 strategy.
+ * It must be set to a clear 0/1 value, to remove branch during inlining.
+ * Presume table size is a multiple of ZSTD_ROWSIZE
+ * to help auto-vectorization */
+FORCE_INLINE_TEMPLATE void
+ZSTD_reduceTable_internal (U32* const table, U32 const size, U32 const reducerValue, int const preserveMark)
+{
+ int const nbRows = (int)size / ZSTD_ROWSIZE;
+ int cellNb = 0;
+ int rowNb;
+ assert((size & (ZSTD_ROWSIZE-1)) == 0); /* multiple of ZSTD_ROWSIZE */
+ assert(size < (1U<<31)); /* can be casted to int */
+ for (rowNb=0 ; rowNb < nbRows ; rowNb++) {
+ int column;
+ for (column=0; column<ZSTD_ROWSIZE; column++) {
+ if (preserveMark) {
+ U32 const adder = (table[cellNb] == ZSTD_DUBT_UNSORTED_MARK) ? reducerValue : 0;
+ table[cellNb] += adder;
+ }
+ if (table[cellNb] < reducerValue) table[cellNb] = 0;
+ else table[cellNb] -= reducerValue;
+ cellNb++;
+ } }
+}
+
+static void ZSTD_reduceTable(U32* const table, U32 const size, U32 const reducerValue)
+{
+ ZSTD_reduceTable_internal(table, size, reducerValue, 0);
+}
+
+static void ZSTD_reduceTable_btlazy2(U32* const table, U32 const size, U32 const reducerValue)
+{
+ ZSTD_reduceTable_internal(table, size, reducerValue, 1);
+}
+
+/*! ZSTD_reduceIndex() :
+* rescale all indexes to avoid future overflow (indexes are U32) */
+static void ZSTD_reduceIndex (ZSTD_CCtx* zc, const U32 reducerValue)
+{
+ ZSTD_matchState_t* const ms = &zc->blockState.matchState;
+ { U32 const hSize = (U32)1 << zc->appliedParams.cParams.hashLog;
+ ZSTD_reduceTable(ms->hashTable, hSize, reducerValue);
+ }
+
+ if (zc->appliedParams.cParams.strategy != ZSTD_fast) {
+ U32 const chainSize = (U32)1 << zc->appliedParams.cParams.chainLog;
+ if (zc->appliedParams.cParams.strategy == ZSTD_btlazy2)
+ ZSTD_reduceTable_btlazy2(ms->chainTable, chainSize, reducerValue);
+ else
+ ZSTD_reduceTable(ms->chainTable, chainSize, reducerValue);
+ }
+
+ if (ms->hashLog3) {
+ U32 const h3Size = (U32)1 << ms->hashLog3;
+ ZSTD_reduceTable(ms->hashTable3, h3Size, reducerValue);
+ }
+}
+
+
+/*-*******************************************************
+* Block entropic compression
+*********************************************************/
+
+/* See doc/zstd_compression_format.md for detailed format description */
+
+static size_t ZSTD_noCompressBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize, U32 lastBlock)
+{
+ U32 const cBlockHeader24 = lastBlock + (((U32)bt_raw)<<1) + (U32)(srcSize << 3);
+ if (srcSize + ZSTD_blockHeaderSize > dstCapacity) return ERROR(dstSize_tooSmall);
+ MEM_writeLE24(dst, cBlockHeader24);
+ memcpy((BYTE*)dst + ZSTD_blockHeaderSize, src, srcSize);
+ return ZSTD_blockHeaderSize + srcSize;
+}
+
+static size_t ZSTD_noCompressLiterals (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
+{
+ BYTE* const ostart = (BYTE* const)dst;
+ U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
+
+ if (srcSize + flSize > dstCapacity) return ERROR(dstSize_tooSmall);
+
+ switch(flSize)
+ {
+ case 1: /* 2 - 1 - 5 */
+ ostart[0] = (BYTE)((U32)set_basic + (srcSize<<3));
+ break;
+ case 2: /* 2 - 2 - 12 */
+ MEM_writeLE16(ostart, (U16)((U32)set_basic + (1<<2) + (srcSize<<4)));
+ break;
+ case 3: /* 2 - 2 - 20 */
+ MEM_writeLE32(ostart, (U32)((U32)set_basic + (3<<2) + (srcSize<<4)));
+ break;
+ default: /* not necessary : flSize is {1,2,3} */
+ assert(0);
+ }
+
+ memcpy(ostart + flSize, src, srcSize);
+ return srcSize + flSize;
+}
+
+static size_t ZSTD_compressRleLiteralsBlock (void* dst, size_t dstCapacity, const void* src, size_t srcSize)
+{
+ BYTE* const ostart = (BYTE* const)dst;
+ U32 const flSize = 1 + (srcSize>31) + (srcSize>4095);
+
+ (void)dstCapacity; /* dstCapacity already guaranteed to be >=4, hence large enough */
+
+ switch(flSize)
+ {
+ case 1: /* 2 - 1 - 5 */
+ ostart[0] = (BYTE)((U32)set_rle + (srcSize<<3));
+ break;
+ case 2: /* 2 - 2 - 12 */
+ MEM_writeLE16(ostart, (U16)((U32)set_rle + (1<<2) + (srcSize<<4)));
+ break;
+ case 3: /* 2 - 2 - 20 */
+ MEM_writeLE32(ostart, (U32)((U32)set_rle + (3<<2) + (srcSize<<4)));
+ break;
+ default: /* not necessary : flSize is {1,2,3} */
+ assert(0);
+ }
+
+ ostart[flSize] = *(const BYTE*)src;
+ return flSize+1;
+}
+
+
+/* ZSTD_minGain() :
+ * minimum compression required
+ * to generate a compress block or a compressed literals section.
+ * note : use same formula for both situations */
+static size_t ZSTD_minGain(size_t srcSize, ZSTD_strategy strat)
+{
+ U32 const minlog = (strat>=ZSTD_btultra) ? (U32)(strat) - 1 : 6;
+ ZSTD_STATIC_ASSERT(ZSTD_btultra == 8);
+ assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat));
+ return (srcSize >> minlog) + 2;
+}
+
+static size_t ZSTD_compressLiterals (ZSTD_hufCTables_t const* prevHuf,
+ ZSTD_hufCTables_t* nextHuf,
+ ZSTD_strategy strategy, int disableLiteralCompression,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ void* workspace, size_t wkspSize,
+ const int bmi2)
+{
+ size_t const minGain = ZSTD_minGain(srcSize, strategy);
+ size_t const lhSize = 3 + (srcSize >= 1 KB) + (srcSize >= 16 KB);
+ BYTE* const ostart = (BYTE*)dst;
+ U32 singleStream = srcSize < 256;
+ symbolEncodingType_e hType = set_compressed;
+ size_t cLitSize;
+
+ DEBUGLOG(5,"ZSTD_compressLiterals (disableLiteralCompression=%i)",
+ disableLiteralCompression);
+
+ /* Prepare nextEntropy assuming reusing the existing table */
+ memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
+
+ if (disableLiteralCompression)
+ return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
+
+ /* small ? don't even attempt compression (speed opt) */
+# define COMPRESS_LITERALS_SIZE_MIN 63
+ { size_t const minLitSize = (prevHuf->repeatMode == HUF_repeat_valid) ? 6 : COMPRESS_LITERALS_SIZE_MIN;
+ if (srcSize <= minLitSize) return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
+ }
+
+ if (dstCapacity < lhSize+1) return ERROR(dstSize_tooSmall); /* not enough space for compression */
+ { HUF_repeat repeat = prevHuf->repeatMode;
+ int const preferRepeat = strategy < ZSTD_lazy ? srcSize <= 1024 : 0;
+ if (repeat == HUF_repeat_valid && lhSize == 3) singleStream = 1;
+ cLitSize = singleStream ? HUF_compress1X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11,
+ workspace, wkspSize, (HUF_CElt*)nextHuf->CTable, &repeat, preferRepeat, bmi2)
+ : HUF_compress4X_repeat(ostart+lhSize, dstCapacity-lhSize, src, srcSize, 255, 11,
+ workspace, wkspSize, (HUF_CElt*)nextHuf->CTable, &repeat, preferRepeat, bmi2);
+ if (repeat != HUF_repeat_none) {
+ /* reused the existing table */
+ hType = set_repeat;
+ }
+ }
+
+ if ((cLitSize==0) | (cLitSize >= srcSize - minGain) | ERR_isError(cLitSize)) {
+ memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
+ return ZSTD_noCompressLiterals(dst, dstCapacity, src, srcSize);
+ }
+ if (cLitSize==1) {
+ memcpy(nextHuf, prevHuf, sizeof(*prevHuf));
+ return ZSTD_compressRleLiteralsBlock(dst, dstCapacity, src, srcSize);
+ }
+
+ if (hType == set_compressed) {
+ /* using a newly constructed table */
+ nextHuf->repeatMode = HUF_repeat_check;
+ }
+
+ /* Build header */
+ switch(lhSize)
+ {
+ case 3: /* 2 - 2 - 10 - 10 */
+ { U32 const lhc = hType + ((!singleStream) << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<14);
+ MEM_writeLE24(ostart, lhc);
+ break;
+ }
+ case 4: /* 2 - 2 - 14 - 14 */
+ { U32 const lhc = hType + (2 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<18);
+ MEM_writeLE32(ostart, lhc);
+ break;
+ }
+ case 5: /* 2 - 2 - 18 - 18 */
+ { U32 const lhc = hType + (3 << 2) + ((U32)srcSize<<4) + ((U32)cLitSize<<22);
+ MEM_writeLE32(ostart, lhc);
+ ostart[4] = (BYTE)(cLitSize >> 10);
+ break;
+ }
+ default: /* not possible : lhSize is {3,4,5} */
+ assert(0);
+ }
+ return lhSize+cLitSize;
+}
+
+
+void ZSTD_seqToCodes(const seqStore_t* seqStorePtr)
+{
+ const seqDef* const sequences = seqStorePtr->sequencesStart;
+ BYTE* const llCodeTable = seqStorePtr->llCode;
+ BYTE* const ofCodeTable = seqStorePtr->ofCode;
+ BYTE* const mlCodeTable = seqStorePtr->mlCode;
+ U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
+ U32 u;
+ assert(nbSeq <= seqStorePtr->maxNbSeq);
+ for (u=0; u<nbSeq; u++) {
+ U32 const llv = sequences[u].litLength;
+ U32 const mlv = sequences[u].matchLength;
+ llCodeTable[u] = (BYTE)ZSTD_LLcode(llv);
+ ofCodeTable[u] = (BYTE)ZSTD_highbit32(sequences[u].offset);
+ mlCodeTable[u] = (BYTE)ZSTD_MLcode(mlv);
+ }
+ if (seqStorePtr->longLengthID==1)
+ llCodeTable[seqStorePtr->longLengthPos] = MaxLL;
+ if (seqStorePtr->longLengthID==2)
+ mlCodeTable[seqStorePtr->longLengthPos] = MaxML;
+}
+
+
+/**
+ * -log2(x / 256) lookup table for x in [0, 256).
+ * If x == 0: Return 0
+ * Else: Return floor(-log2(x / 256) * 256)
+ */
+static unsigned const kInverseProbabiltyLog256[256] = {
+ 0, 2048, 1792, 1642, 1536, 1453, 1386, 1329, 1280, 1236, 1197, 1162,
+ 1130, 1100, 1073, 1047, 1024, 1001, 980, 960, 941, 923, 906, 889,
+ 874, 859, 844, 830, 817, 804, 791, 779, 768, 756, 745, 734,
+ 724, 714, 704, 694, 685, 676, 667, 658, 650, 642, 633, 626,
+ 618, 610, 603, 595, 588, 581, 574, 567, 561, 554, 548, 542,
+ 535, 529, 523, 517, 512, 506, 500, 495, 489, 484, 478, 473,
+ 468, 463, 458, 453, 448, 443, 438, 434, 429, 424, 420, 415,
+ 411, 407, 402, 398, 394, 390, 386, 382, 377, 373, 370, 366,
+ 362, 358, 354, 350, 347, 343, 339, 336, 332, 329, 325, 322,
+ 318, 315, 311, 308, 305, 302, 298, 295, 292, 289, 286, 282,
+ 279, 276, 273, 270, 267, 264, 261, 258, 256, 253, 250, 247,
+ 244, 241, 239, 236, 233, 230, 228, 225, 222, 220, 217, 215,
+ 212, 209, 207, 204, 202, 199, 197, 194, 192, 190, 187, 185,
+ 182, 180, 178, 175, 173, 171, 168, 166, 164, 162, 159, 157,
+ 155, 153, 151, 149, 146, 144, 142, 140, 138, 136, 134, 132,
+ 130, 128, 126, 123, 121, 119, 117, 115, 114, 112, 110, 108,
+ 106, 104, 102, 100, 98, 96, 94, 93, 91, 89, 87, 85,
+ 83, 82, 80, 78, 76, 74, 73, 71, 69, 67, 66, 64,
+ 62, 61, 59, 57, 55, 54, 52, 50, 49, 47, 46, 44,
+ 42, 41, 39, 37, 36, 34, 33, 31, 30, 28, 26, 25,
+ 23, 22, 20, 19, 17, 16, 14, 13, 11, 10, 8, 7,
+ 5, 4, 2, 1,
+};
+
+
+/**
+ * Returns the cost in bits of encoding the distribution described by count
+ * using the entropy bound.
+ */
+static size_t ZSTD_entropyCost(unsigned const* count, unsigned const max, size_t const total)
+{
+ unsigned cost = 0;
+ unsigned s;
+ for (s = 0; s <= max; ++s) {
+ unsigned norm = (unsigned)((256 * count[s]) / total);
+ if (count[s] != 0 && norm == 0)
+ norm = 1;
+ assert(count[s] < total);
+ cost += count[s] * kInverseProbabiltyLog256[norm];
+ }
+ return cost >> 8;
+}
+
+
+/**
+ * Returns the cost in bits of encoding the distribution in count using the
+ * table described by norm. The max symbol support by norm is assumed >= max.
+ * norm must be valid for every symbol with non-zero probability in count.
+ */
+static size_t ZSTD_crossEntropyCost(short const* norm, unsigned accuracyLog,
+ unsigned const* count, unsigned const max)
+{
+ unsigned const shift = 8 - accuracyLog;
+ size_t cost = 0;
+ unsigned s;
+ assert(accuracyLog <= 8);
+ for (s = 0; s <= max; ++s) {
+ unsigned const normAcc = norm[s] != -1 ? norm[s] : 1;
+ unsigned const norm256 = normAcc << shift;
+ assert(norm256 > 0);
+ assert(norm256 < 256);
+ cost += count[s] * kInverseProbabiltyLog256[norm256];
+ }
+ return cost >> 8;
+}
+
+
+static unsigned ZSTD_getFSEMaxSymbolValue(FSE_CTable const* ctable) {
+ void const* ptr = ctable;
+ U16 const* u16ptr = (U16 const*)ptr;
+ U32 const maxSymbolValue = MEM_read16(u16ptr + 1);
+ return maxSymbolValue;
+}
+
+
+/**
+ * Returns the cost in bits of encoding the distribution in count using ctable.
+ * Returns an error if ctable cannot represent all the symbols in count.
+ */
+static size_t ZSTD_fseBitCost(
+ FSE_CTable const* ctable,
+ unsigned const* count,
+ unsigned const max)
+{
+ unsigned const kAccuracyLog = 8;
+ size_t cost = 0;
+ unsigned s;
+ FSE_CState_t cstate;
+ FSE_initCState(&cstate, ctable);
+ if (ZSTD_getFSEMaxSymbolValue(ctable) < max) {
+ DEBUGLOG(5, "Repeat FSE_CTable has maxSymbolValue %u < %u",
+ ZSTD_getFSEMaxSymbolValue(ctable), max);
+ return ERROR(GENERIC);
+ }
+ for (s = 0; s <= max; ++s) {
+ unsigned const tableLog = cstate.stateLog;
+ unsigned const badCost = (tableLog + 1) << kAccuracyLog;
+ unsigned const bitCost = FSE_bitCost(cstate.symbolTT, tableLog, s, kAccuracyLog);
+ if (count[s] == 0)
+ continue;
+ if (bitCost >= badCost) {
+ DEBUGLOG(5, "Repeat FSE_CTable has Prob[%u] == 0", s);
+ return ERROR(GENERIC);
+ }
+ cost += count[s] * bitCost;
+ }
+ return cost >> kAccuracyLog;
+}
+
+/**
+ * Returns the cost in bytes of encoding the normalized count header.
+ * Returns an error if any of the helper functions return an error.
+ */
+static size_t ZSTD_NCountCost(unsigned const* count, unsigned const max,
+ size_t const nbSeq, unsigned const FSELog)
+{
+ BYTE wksp[FSE_NCOUNTBOUND];
+ S16 norm[MaxSeq + 1];
+ const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
+ CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq, max));
+ return FSE_writeNCount(wksp, sizeof(wksp), norm, max, tableLog);
+}
+
+
+typedef enum {
+ ZSTD_defaultDisallowed = 0,
+ ZSTD_defaultAllowed = 1
+} ZSTD_defaultPolicy_e;
+
+MEM_STATIC symbolEncodingType_e
+ZSTD_selectEncodingType(
+ FSE_repeat* repeatMode, unsigned const* count, unsigned const max,
+ size_t const mostFrequent, size_t nbSeq, unsigned const FSELog,
+ FSE_CTable const* prevCTable,
+ short const* defaultNorm, U32 defaultNormLog,
+ ZSTD_defaultPolicy_e const isDefaultAllowed,
+ ZSTD_strategy const strategy)
+{
+ ZSTD_STATIC_ASSERT(ZSTD_defaultDisallowed == 0 && ZSTD_defaultAllowed != 0);
+ if (mostFrequent == nbSeq) {
+ *repeatMode = FSE_repeat_none;
+ if (isDefaultAllowed && nbSeq <= 2) {
+ /* Prefer set_basic over set_rle when there are 2 or less symbols,
+ * since RLE uses 1 byte, but set_basic uses 5-6 bits per symbol.
+ * If basic encoding isn't possible, always choose RLE.
+ */
+ DEBUGLOG(5, "Selected set_basic");
+ return set_basic;
+ }
+ DEBUGLOG(5, "Selected set_rle");
+ return set_rle;
+ }
+ if (strategy < ZSTD_lazy) {
+ if (isDefaultAllowed) {
+ size_t const staticFse_nbSeq_max = 1000;
+ size_t const mult = 10 - strategy;
+ size_t const baseLog = 3;
+ size_t const dynamicFse_nbSeq_min = (((size_t)1 << defaultNormLog) * mult) >> baseLog; /* 28-36 for offset, 56-72 for lengths */
+ assert(defaultNormLog >= 5 && defaultNormLog <= 6); /* xx_DEFAULTNORMLOG */
+ assert(mult <= 9 && mult >= 7);
+ if ( (*repeatMode == FSE_repeat_valid)
+ && (nbSeq < staticFse_nbSeq_max) ) {
+ DEBUGLOG(5, "Selected set_repeat");
+ return set_repeat;
+ }
+ if ( (nbSeq < dynamicFse_nbSeq_min)
+ || (mostFrequent < (nbSeq >> (defaultNormLog-1))) ) {
+ DEBUGLOG(5, "Selected set_basic");
+ /* The format allows default tables to be repeated, but it isn't useful.
+ * When using simple heuristics to select encoding type, we don't want
+ * to confuse these tables with dictionaries. When running more careful
+ * analysis, we don't need to waste time checking both repeating tables
+ * and default tables.
+ */
+ *repeatMode = FSE_repeat_none;
+ return set_basic;
+ }
+ }
+ } else {
+ size_t const basicCost = isDefaultAllowed ? ZSTD_crossEntropyCost(defaultNorm, defaultNormLog, count, max) : ERROR(GENERIC);
+ size_t const repeatCost = *repeatMode != FSE_repeat_none ? ZSTD_fseBitCost(prevCTable, count, max) : ERROR(GENERIC);
+ size_t const NCountCost = ZSTD_NCountCost(count, max, nbSeq, FSELog);
+ size_t const compressedCost = (NCountCost << 3) + ZSTD_entropyCost(count, max, nbSeq);
+
+ if (isDefaultAllowed) {
+ assert(!ZSTD_isError(basicCost));
+ assert(!(*repeatMode == FSE_repeat_valid && ZSTD_isError(repeatCost)));
+ }
+ assert(!ZSTD_isError(NCountCost));
+ assert(compressedCost < ERROR(maxCode));
+ DEBUGLOG(5, "Estimated bit costs: basic=%u\trepeat=%u\tcompressed=%u",
+ (unsigned)basicCost, (unsigned)repeatCost, (unsigned)compressedCost);
+ if (basicCost <= repeatCost && basicCost <= compressedCost) {
+ DEBUGLOG(5, "Selected set_basic");
+ assert(isDefaultAllowed);
+ *repeatMode = FSE_repeat_none;
+ return set_basic;
+ }
+ if (repeatCost <= compressedCost) {
+ DEBUGLOG(5, "Selected set_repeat");
+ assert(!ZSTD_isError(repeatCost));
+ return set_repeat;
+ }
+ assert(compressedCost < basicCost && compressedCost < repeatCost);
+ }
+ DEBUGLOG(5, "Selected set_compressed");
+ *repeatMode = FSE_repeat_check;
+ return set_compressed;
+}
+
+MEM_STATIC size_t
+ZSTD_buildCTable(void* dst, size_t dstCapacity,
+ FSE_CTable* nextCTable, U32 FSELog, symbolEncodingType_e type,
+ unsigned* count, U32 max,
+ const BYTE* codeTable, size_t nbSeq,
+ const S16* defaultNorm, U32 defaultNormLog, U32 defaultMax,
+ const FSE_CTable* prevCTable, size_t prevCTableSize,
+ void* workspace, size_t workspaceSize)
+{
+ BYTE* op = (BYTE*)dst;
+ const BYTE* const oend = op + dstCapacity;
+ DEBUGLOG(6, "ZSTD_buildCTable (dstCapacity=%u)", (unsigned)dstCapacity);
+
+ switch (type) {
+ case set_rle:
+ CHECK_F(FSE_buildCTable_rle(nextCTable, (BYTE)max));
+ if (dstCapacity==0) return ERROR(dstSize_tooSmall);
+ *op = codeTable[0];
+ return 1;
+ case set_repeat:
+ memcpy(nextCTable, prevCTable, prevCTableSize);
+ return 0;
+ case set_basic:
+ CHECK_F(FSE_buildCTable_wksp(nextCTable, defaultNorm, defaultMax, defaultNormLog, workspace, workspaceSize)); /* note : could be pre-calculated */
+ return 0;
+ case set_compressed: {
+ S16 norm[MaxSeq + 1];
+ size_t nbSeq_1 = nbSeq;
+ const U32 tableLog = FSE_optimalTableLog(FSELog, nbSeq, max);
+ if (count[codeTable[nbSeq-1]] > 1) {
+ count[codeTable[nbSeq-1]]--;
+ nbSeq_1--;
+ }
+ assert(nbSeq_1 > 1);
+ CHECK_F(FSE_normalizeCount(norm, tableLog, count, nbSeq_1, max));
+ { size_t const NCountSize = FSE_writeNCount(op, oend - op, norm, max, tableLog); /* overflow protected */
+ if (FSE_isError(NCountSize)) return NCountSize;
+ CHECK_F(FSE_buildCTable_wksp(nextCTable, norm, max, tableLog, workspace, workspaceSize));
+ return NCountSize;
+ }
+ }
+ default: return assert(0), ERROR(GENERIC);
+ }
+}
+
+FORCE_INLINE_TEMPLATE size_t
+ZSTD_encodeSequences_body(
+ void* dst, size_t dstCapacity,
+ FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
+ FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
+ FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
+ seqDef const* sequences, size_t nbSeq, int longOffsets)
+{
+ BIT_CStream_t blockStream;
+ FSE_CState_t stateMatchLength;
+ FSE_CState_t stateOffsetBits;
+ FSE_CState_t stateLitLength;
+
+ CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */
+ DEBUGLOG(6, "available space for bitstream : %i (dstCapacity=%u)",
+ (int)(blockStream.endPtr - blockStream.startPtr),
+ (unsigned)dstCapacity);
+
+ /* first symbols */
+ FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
+ FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
+ FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
+ BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
+ if (MEM_32bits()) BIT_flushBits(&blockStream);
+ BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);
+ if (MEM_32bits()) BIT_flushBits(&blockStream);
+ if (longOffsets) {
+ U32 const ofBits = ofCodeTable[nbSeq-1];
+ int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
+ if (extraBits) {
+ BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);
+ BIT_flushBits(&blockStream);
+ }
+ BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,
+ ofBits - extraBits);
+ } else {
+ BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);
+ }
+ BIT_flushBits(&blockStream);
+
+ { size_t n;
+ for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
+ BYTE const llCode = llCodeTable[n];
+ BYTE const ofCode = ofCodeTable[n];
+ BYTE const mlCode = mlCodeTable[n];
+ U32 const llBits = LL_bits[llCode];
+ U32 const ofBits = ofCode;
+ U32 const mlBits = ML_bits[mlCode];
+ DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u",
+ (unsigned)sequences[n].litLength,
+ (unsigned)sequences[n].matchLength + MINMATCH,
+ (unsigned)sequences[n].offset);
+ /* 32b*/ /* 64b*/
+ /* (7)*/ /* (7)*/
+ FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
+ FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
+ if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
+ FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
+ if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
+ BIT_flushBits(&blockStream); /* (7)*/
+ BIT_addBits(&blockStream, sequences[n].litLength, llBits);
+ if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
+ BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);
+ if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
+ if (longOffsets) {
+ int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
+ if (extraBits) {
+ BIT_addBits(&blockStream, sequences[n].offset, extraBits);
+ BIT_flushBits(&blockStream); /* (7)*/
+ }
+ BIT_addBits(&blockStream, sequences[n].offset >> extraBits,
+ ofBits - extraBits); /* 31 */
+ } else {
+ BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */
+ }
+ BIT_flushBits(&blockStream); /* (7)*/
+ DEBUGLOG(7, "remaining space : %i", (int)(blockStream.endPtr - blockStream.ptr));
+ } }
+
+ DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog);
+ FSE_flushCState(&blockStream, &stateMatchLength);
+ DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog);
+ FSE_flushCState(&blockStream, &stateOffsetBits);
+ DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog);
+ FSE_flushCState(&blockStream, &stateLitLength);
+
+ { size_t const streamSize = BIT_closeCStream(&blockStream);
+ if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */
+ return streamSize;
+ }
+}
+
+static size_t
+ZSTD_encodeSequences_default(
+ void* dst, size_t dstCapacity,
+ FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
+ FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
+ FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
+ seqDef const* sequences, size_t nbSeq, int longOffsets)
+{
+ return ZSTD_encodeSequences_body(dst, dstCapacity,
+ CTable_MatchLength, mlCodeTable,
+ CTable_OffsetBits, ofCodeTable,
+ CTable_LitLength, llCodeTable,
+ sequences, nbSeq, longOffsets);
+}
+
+
+#if DYNAMIC_BMI2
+
+static TARGET_ATTRIBUTE("bmi2") size_t
+ZSTD_encodeSequences_bmi2(
+ void* dst, size_t dstCapacity,
+ FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
+ FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
+ FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
+ seqDef const* sequences, size_t nbSeq, int longOffsets)
+{
+ return ZSTD_encodeSequences_body(dst, dstCapacity,
+ CTable_MatchLength, mlCodeTable,
+ CTable_OffsetBits, ofCodeTable,
+ CTable_LitLength, llCodeTable,
+ sequences, nbSeq, longOffsets);
+}
+
+#endif
+
+static size_t ZSTD_encodeSequences(
+ void* dst, size_t dstCapacity,
+ FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
+ FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
+ FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
+ seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2)
+{
+ DEBUGLOG(5, "ZSTD_encodeSequences: dstCapacity = %u", (unsigned)dstCapacity);
+#if DYNAMIC_BMI2
+ if (bmi2) {
+ return ZSTD_encodeSequences_bmi2(dst, dstCapacity,
+ CTable_MatchLength, mlCodeTable,
+ CTable_OffsetBits, ofCodeTable,
+ CTable_LitLength, llCodeTable,
+ sequences, nbSeq, longOffsets);
+ }
+#endif
+ (void)bmi2;
+ return ZSTD_encodeSequences_default(dst, dstCapacity,
+ CTable_MatchLength, mlCodeTable,
+ CTable_OffsetBits, ofCodeTable,
+ CTable_LitLength, llCodeTable,
+ sequences, nbSeq, longOffsets);
+}
+
+/* ZSTD_compressSequences_internal():
+ * actually compresses both literals and sequences */
+MEM_STATIC size_t
+ZSTD_compressSequences_internal(seqStore_t* seqStorePtr,
+ const ZSTD_entropyCTables_t* prevEntropy,
+ ZSTD_entropyCTables_t* nextEntropy,
+ const ZSTD_CCtx_params* cctxParams,
+ void* dst, size_t dstCapacity,
+ void* workspace, size_t wkspSize,
+ const int bmi2)
+{
+ const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN;
+ ZSTD_strategy const strategy = cctxParams->cParams.strategy;
+ unsigned count[MaxSeq+1];
+ FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable;
+ FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable;
+ FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable;
+ U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */
+ const seqDef* const sequences = seqStorePtr->sequencesStart;
+ const BYTE* const ofCodeTable = seqStorePtr->ofCode;
+ const BYTE* const llCodeTable = seqStorePtr->llCode;
+ const BYTE* const mlCodeTable = seqStorePtr->mlCode;
+ BYTE* const ostart = (BYTE*)dst;
+ BYTE* const oend = ostart + dstCapacity;
+ BYTE* op = ostart;
+ size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart;
+ BYTE* seqHead;
+ BYTE* lastNCount = NULL;
+
+ ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
+ DEBUGLOG(5, "ZSTD_compressSequences_internal");
+
+ /* Compress literals */
+ { const BYTE* const literals = seqStorePtr->litStart;
+ size_t const litSize = seqStorePtr->lit - literals;
+ int const disableLiteralCompression = (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0);
+ size_t const cSize = ZSTD_compressLiterals(
+ &prevEntropy->huf, &nextEntropy->huf,
+ cctxParams->cParams.strategy, disableLiteralCompression,
+ op, dstCapacity,
+ literals, litSize,
+ workspace, wkspSize,
+ bmi2);
+ if (ZSTD_isError(cSize))
+ return cSize;
+ assert(cSize <= dstCapacity);
+ op += cSize;
+ }
+
+ /* Sequences Header */
+ if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/) return ERROR(dstSize_tooSmall);
+ if (nbSeq < 0x7F)
+ *op++ = (BYTE)nbSeq;
+ else if (nbSeq < LONGNBSEQ)
+ op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2;
+ else
+ op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3;
+ if (nbSeq==0) {
+ /* Copy the old tables over as if we repeated them */
+ memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse));
+ return op - ostart;
+ }
+
+ /* seqHead : flags for FSE encoding type */
+ seqHead = op++;
+
+ /* convert length/distances into codes */
+ ZSTD_seqToCodes(seqStorePtr);
+ /* build CTable for Literal Lengths */
+ { unsigned max = MaxLL;
+ size_t const mostFrequent = HIST_countFast_wksp(count, &max, llCodeTable, nbSeq, workspace, wkspSize); /* can't fail */
+ DEBUGLOG(5, "Building LL table");
+ nextEntropy->fse.litlength_repeatMode = prevEntropy->fse.litlength_repeatMode;
+ LLtype = ZSTD_selectEncodingType(&nextEntropy->fse.litlength_repeatMode,
+ count, max, mostFrequent, nbSeq,
+ LLFSELog, prevEntropy->fse.litlengthCTable,
+ LL_defaultNorm, LL_defaultNormLog,
+ ZSTD_defaultAllowed, strategy);
+ assert(set_basic < set_compressed && set_rle < set_compressed);
+ assert(!(LLtype < set_compressed && nextEntropy->fse.litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
+ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_LitLength, LLFSELog, (symbolEncodingType_e)LLtype,
+ count, max, llCodeTable, nbSeq, LL_defaultNorm, LL_defaultNormLog, MaxLL,
+ prevEntropy->fse.litlengthCTable, sizeof(prevEntropy->fse.litlengthCTable),
+ workspace, wkspSize);
+ if (ZSTD_isError(countSize)) return countSize;
+ if (LLtype == set_compressed)
+ lastNCount = op;
+ op += countSize;
+ } }
+ /* build CTable for Offsets */
+ { unsigned max = MaxOff;
+ size_t const mostFrequent = HIST_countFast_wksp(count, &max, ofCodeTable, nbSeq, workspace, wkspSize); /* can't fail */
+ /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */
+ ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed;
+ DEBUGLOG(5, "Building OF table");
+ nextEntropy->fse.offcode_repeatMode = prevEntropy->fse.offcode_repeatMode;
+ Offtype = ZSTD_selectEncodingType(&nextEntropy->fse.offcode_repeatMode,
+ count, max, mostFrequent, nbSeq,
+ OffFSELog, prevEntropy->fse.offcodeCTable,
+ OF_defaultNorm, OF_defaultNormLog,
+ defaultPolicy, strategy);
+ assert(!(Offtype < set_compressed && nextEntropy->fse.offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */
+ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)Offtype,
+ count, max, ofCodeTable, nbSeq, OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff,
+ prevEntropy->fse.offcodeCTable, sizeof(prevEntropy->fse.offcodeCTable),
+ workspace, wkspSize);
+ if (ZSTD_isError(countSize)) return countSize;
+ if (Offtype == set_compressed)
+ lastNCount = op;
+ op += countSize;
+ } }
+ /* build CTable for MatchLengths */
+ { unsigned max = MaxML;
+ size_t const mostFrequent = HIST_countFast_wksp(count, &max, mlCodeTable, nbSeq, workspace, wkspSize); /* can't fail */
+ DEBUGLOG(5, "Building ML table (remaining space : %i)", (int)(oend-op));
+ nextEntropy->fse.matchlength_repeatMode = prevEntropy->fse.matchlength_repeatMode;
+ MLtype = ZSTD_selectEncodingType(&nextEntropy->fse.matchlength_repeatMode,
+ count, max, mostFrequent, nbSeq,
+ MLFSELog, prevEntropy->fse.matchlengthCTable,
+ ML_defaultNorm, ML_defaultNormLog,
+ ZSTD_defaultAllowed, strategy);
+ assert(!(MLtype < set_compressed && nextEntropy->fse.matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */
+ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_MatchLength, MLFSELog, (symbolEncodingType_e)MLtype,
+ count, max, mlCodeTable, nbSeq, ML_defaultNorm, ML_defaultNormLog, MaxML,
+ prevEntropy->fse.matchlengthCTable, sizeof(prevEntropy->fse.matchlengthCTable),
+ workspace, wkspSize);
+ if (ZSTD_isError(countSize)) return countSize;
+ if (MLtype == set_compressed)
+ lastNCount = op;
+ op += countSize;
+ } }
+
+ *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2));
+
+ { size_t const bitstreamSize = ZSTD_encodeSequences(
+ op, oend - op,
+ CTable_MatchLength, mlCodeTable,
+ CTable_OffsetBits, ofCodeTable,
+ CTable_LitLength, llCodeTable,
+ sequences, nbSeq,
+ longOffsets, bmi2);
+ if (ZSTD_isError(bitstreamSize)) return bitstreamSize;
+ op += bitstreamSize;
+ /* zstd versions <= 1.3.4 mistakenly report corruption when
+ * FSE_readNCount() recieves a buffer < 4 bytes.
+ * Fixed by https://github.com/facebook/zstd/pull/1146.
+ * This can happen when the last set_compressed table present is 2
+ * bytes and the bitstream is only one byte.
+ * In this exceedingly rare case, we will simply emit an uncompressed
+ * block, since it isn't worth optimizing.
+ */
+ if (lastNCount && (op - lastNCount) < 4) {
+ /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */
+ assert(op - lastNCount == 3);
+ DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by "
+ "emitting an uncompressed block.");
+ return 0;
+ }
+ }
+
+ DEBUGLOG(5, "compressed block size : %u", (unsigned)(op - ostart));
+ return op - ostart;
+}
+
+MEM_STATIC size_t
+ZSTD_compressSequences(seqStore_t* seqStorePtr,
+ const ZSTD_entropyCTables_t* prevEntropy,
+ ZSTD_entropyCTables_t* nextEntropy,
+ const ZSTD_CCtx_params* cctxParams,
+ void* dst, size_t dstCapacity,
+ size_t srcSize,
+ void* workspace, size_t wkspSize,
+ int bmi2)
+{
+ size_t const cSize = ZSTD_compressSequences_internal(
+ seqStorePtr, prevEntropy, nextEntropy, cctxParams,
+ dst, dstCapacity,
+ workspace, wkspSize, bmi2);
+ if (cSize == 0) return 0;
+ /* When srcSize <= dstCapacity, there is enough space to write a raw uncompressed block.
+ * Since we ran out of space, block must be not compressible, so fall back to raw uncompressed block.
+ */
+ if ((cSize == ERROR(dstSize_tooSmall)) & (srcSize <= dstCapacity))
+ return 0; /* block not compressed */
+ if (ZSTD_isError(cSize)) return cSize;
+
+ /* Check compressibility */
+ { size_t const maxCSize = srcSize - ZSTD_minGain(srcSize, cctxParams->cParams.strategy);
+ if (cSize >= maxCSize) return 0; /* block not compressed */
+ }
+
+ return cSize;
+}
+
+/* ZSTD_selectBlockCompressor() :
+ * Not static, but internal use only (used by long distance matcher)
+ * assumption : strat is a valid strategy */
+ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_dictMode_e dictMode)
+{
+ static const ZSTD_blockCompressor blockCompressor[3][ZSTD_STRATEGY_MAX+1] = {
+ { ZSTD_compressBlock_fast /* default for 0 */,
+ ZSTD_compressBlock_fast,
+ ZSTD_compressBlock_doubleFast,
+ ZSTD_compressBlock_greedy,
+ ZSTD_compressBlock_lazy,
+ ZSTD_compressBlock_lazy2,
+ ZSTD_compressBlock_btlazy2,
+ ZSTD_compressBlock_btopt,
+ ZSTD_compressBlock_btultra,
+ ZSTD_compressBlock_btultra2 },
+ { ZSTD_compressBlock_fast_extDict /* default for 0 */,
+ ZSTD_compressBlock_fast_extDict,
+ ZSTD_compressBlock_doubleFast_extDict,
+ ZSTD_compressBlock_greedy_extDict,
+ ZSTD_compressBlock_lazy_extDict,
+ ZSTD_compressBlock_lazy2_extDict,
+ ZSTD_compressBlock_btlazy2_extDict,
+ ZSTD_compressBlock_btopt_extDict,
+ ZSTD_compressBlock_btultra_extDict,
+ ZSTD_compressBlock_btultra_extDict },
+ { ZSTD_compressBlock_fast_dictMatchState /* default for 0 */,
+ ZSTD_compressBlock_fast_dictMatchState,
+ ZSTD_compressBlock_doubleFast_dictMatchState,
+ ZSTD_compressBlock_greedy_dictMatchState,
+ ZSTD_compressBlock_lazy_dictMatchState,
+ ZSTD_compressBlock_lazy2_dictMatchState,
+ ZSTD_compressBlock_btlazy2_dictMatchState,
+ ZSTD_compressBlock_btopt_dictMatchState,
+ ZSTD_compressBlock_btultra_dictMatchState,
+ ZSTD_compressBlock_btultra_dictMatchState }
+ };
+ ZSTD_blockCompressor selectedCompressor;
+ ZSTD_STATIC_ASSERT((unsigned)ZSTD_fast == 1);
+
+ assert(ZSTD_cParam_withinBounds(ZSTD_c_strategy, strat));
+ selectedCompressor = blockCompressor[(int)dictMode][(int)strat];
+ assert(selectedCompressor != NULL);
+ return selectedCompressor;
+}
+
+static void ZSTD_storeLastLiterals(seqStore_t* seqStorePtr,
+ const BYTE* anchor, size_t lastLLSize)
+{
+ memcpy(seqStorePtr->lit, anchor, lastLLSize);
+ seqStorePtr->lit += lastLLSize;
+}
+
+void ZSTD_resetSeqStore(seqStore_t* ssPtr)
+{
+ ssPtr->lit = ssPtr->litStart;
+ ssPtr->sequences = ssPtr->sequencesStart;
+ ssPtr->longLengthID = 0;
+}
+
+static size_t ZSTD_compressBlock_internal(ZSTD_CCtx* zc,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize)
+{
+ ZSTD_matchState_t* const ms = &zc->blockState.matchState;
+ size_t cSize;
+ DEBUGLOG(5, "ZSTD_compressBlock_internal (dstCapacity=%u, dictLimit=%u, nextToUpdate=%u)",
+ (unsigned)dstCapacity, (unsigned)ms->window.dictLimit, (unsigned)ms->nextToUpdate);
+ assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
+
+ /* Assert that we have correctly flushed the ctx params into the ms's copy */
+ ZSTD_assertEqualCParams(zc->appliedParams.cParams, ms->cParams);
+
+ if (srcSize < MIN_CBLOCK_SIZE+ZSTD_blockHeaderSize+1) {
+ ZSTD_ldm_skipSequences(&zc->externSeqStore, srcSize, zc->appliedParams.cParams.minMatch);
+ cSize = 0;
+ goto out; /* don't even attempt compression below a certain srcSize */
+ }
+ ZSTD_resetSeqStore(&(zc->seqStore));
+ ms->opt.symbolCosts = &zc->blockState.prevCBlock->entropy; /* required for optimal parser to read stats from dictionary */
+
+ /* a gap between an attached dict and the current window is not safe,
+ * they must remain adjacent,
+ * and when that stops being the case, the dict must be unset */
+ assert(ms->dictMatchState == NULL || ms->loadedDictEnd == ms->window.dictLimit);
+
+ /* limited update after a very long match */
+ { const BYTE* const base = ms->window.base;
+ const BYTE* const istart = (const BYTE*)src;
+ const U32 current = (U32)(istart-base);
+ if (sizeof(ptrdiff_t)==8) assert(istart - base < (ptrdiff_t)(U32)(-1)); /* ensure no overflow */
+ if (current > ms->nextToUpdate + 384)
+ ms->nextToUpdate = current - MIN(192, (U32)(current - ms->nextToUpdate - 384));
+ }
+
+ /* select and store sequences */
+ { ZSTD_dictMode_e const dictMode = ZSTD_matchState_dictMode(ms);
+ size_t lastLLSize;
+ { int i;
+ for (i = 0; i < ZSTD_REP_NUM; ++i)
+ zc->blockState.nextCBlock->rep[i] = zc->blockState.prevCBlock->rep[i];
+ }
+ if (zc->externSeqStore.pos < zc->externSeqStore.size) {
+ assert(!zc->appliedParams.ldmParams.enableLdm);
+ /* Updates ldmSeqStore.pos */
+ lastLLSize =
+ ZSTD_ldm_blockCompress(&zc->externSeqStore,
+ ms, &zc->seqStore,
+ zc->blockState.nextCBlock->rep,
+ src, srcSize);
+ assert(zc->externSeqStore.pos <= zc->externSeqStore.size);
+ } else if (zc->appliedParams.ldmParams.enableLdm) {
+ rawSeqStore_t ldmSeqStore = {NULL, 0, 0, 0};
+
+ ldmSeqStore.seq = zc->ldmSequences;
+ ldmSeqStore.capacity = zc->maxNbLdmSequences;
+ /* Updates ldmSeqStore.size */
+ CHECK_F(ZSTD_ldm_generateSequences(&zc->ldmState, &ldmSeqStore,
+ &zc->appliedParams.ldmParams,
+ src, srcSize));
+ /* Updates ldmSeqStore.pos */
+ lastLLSize =
+ ZSTD_ldm_blockCompress(&ldmSeqStore,
+ ms, &zc->seqStore,
+ zc->blockState.nextCBlock->rep,
+ src, srcSize);
+ assert(ldmSeqStore.pos == ldmSeqStore.size);
+ } else { /* not long range mode */
+ ZSTD_blockCompressor const blockCompressor = ZSTD_selectBlockCompressor(zc->appliedParams.cParams.strategy, dictMode);
+ lastLLSize = blockCompressor(ms, &zc->seqStore, zc->blockState.nextCBlock->rep, src, srcSize);
+ }
+ { const BYTE* const lastLiterals = (const BYTE*)src + srcSize - lastLLSize;
+ ZSTD_storeLastLiterals(&zc->seqStore, lastLiterals, lastLLSize);
+ } }
+
+ /* encode sequences and literals */
+ cSize = ZSTD_compressSequences(&zc->seqStore,
+ &zc->blockState.prevCBlock->entropy, &zc->blockState.nextCBlock->entropy,
+ &zc->appliedParams,
+ dst, dstCapacity,
+ srcSize,
+ zc->entropyWorkspace, HUF_WORKSPACE_SIZE /* statically allocated in resetCCtx */,
+ zc->bmi2);
+
+out:
+ if (!ZSTD_isError(cSize) && cSize != 0) {
+ /* confirm repcodes and entropy tables when emitting a compressed block */
+ ZSTD_compressedBlockState_t* const tmp = zc->blockState.prevCBlock;
+ zc->blockState.prevCBlock = zc->blockState.nextCBlock;
+ zc->blockState.nextCBlock = tmp;
+ }
+ /* We check that dictionaries have offset codes available for the first
+ * block. After the first block, the offcode table might not have large
+ * enough codes to represent the offsets in the data.
+ */
+ if (zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode == FSE_repeat_valid)
+ zc->blockState.prevCBlock->entropy.fse.offcode_repeatMode = FSE_repeat_check;
+
+ return cSize;
+}
+
+
+/*! ZSTD_compress_frameChunk() :
+* Compress a chunk of data into one or multiple blocks.
+* All blocks will be terminated, all input will be consumed.
+* Function will issue an error if there is not enough `dstCapacity` to hold the compressed content.
+* Frame is supposed already started (header already produced)
+* @return : compressed size, or an error code
+*/
+static size_t ZSTD_compress_frameChunk (ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ U32 lastFrameChunk)
+{
+ size_t blockSize = cctx->blockSize;
+ size_t remaining = srcSize;
+ const BYTE* ip = (const BYTE*)src;
+ BYTE* const ostart = (BYTE*)dst;
+ BYTE* op = ostart;
+ U32 const maxDist = (U32)1 << cctx->appliedParams.cParams.windowLog;
+ assert(cctx->appliedParams.cParams.windowLog <= 31);
+
+ DEBUGLOG(5, "ZSTD_compress_frameChunk (blockSize=%u)", (unsigned)blockSize);
+ if (cctx->appliedParams.fParams.checksumFlag && srcSize)
+ XXH64_update(&cctx->xxhState, src, srcSize);
+
+ while (remaining) {
+ ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
+ U32 const lastBlock = lastFrameChunk & (blockSize >= remaining);
+
+ if (dstCapacity < ZSTD_blockHeaderSize + MIN_CBLOCK_SIZE)
+ return ERROR(dstSize_tooSmall); /* not enough space to store compressed block */
+ if (remaining < blockSize) blockSize = remaining;
+
+ if (ZSTD_window_needOverflowCorrection(ms->window, ip + blockSize)) {
+ U32 const cycleLog = ZSTD_cycleLog(cctx->appliedParams.cParams.chainLog, cctx->appliedParams.cParams.strategy);
+ U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, maxDist, ip);
+ ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
+ ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
+ ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
+ ZSTD_reduceIndex(cctx, correction);
+ if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;
+ else ms->nextToUpdate -= correction;
+ ms->loadedDictEnd = 0;
+ ms->dictMatchState = NULL;
+ }
+ ZSTD_window_enforceMaxDist(&ms->window, ip + blockSize, maxDist, &ms->loadedDictEnd, &ms->dictMatchState);
+ if (ms->nextToUpdate < ms->window.lowLimit) ms->nextToUpdate = ms->window.lowLimit;
+
+ { size_t cSize = ZSTD_compressBlock_internal(cctx,
+ op+ZSTD_blockHeaderSize, dstCapacity-ZSTD_blockHeaderSize,
+ ip, blockSize);
+ if (ZSTD_isError(cSize)) return cSize;
+
+ if (cSize == 0) { /* block is not compressible */
+ cSize = ZSTD_noCompressBlock(op, dstCapacity, ip, blockSize, lastBlock);
+ if (ZSTD_isError(cSize)) return cSize;
+ } else {
+ U32 const cBlockHeader24 = lastBlock + (((U32)bt_compressed)<<1) + (U32)(cSize << 3);
+ MEM_writeLE24(op, cBlockHeader24);
+ cSize += ZSTD_blockHeaderSize;
+ }
+
+ ip += blockSize;
+ assert(remaining >= blockSize);
+ remaining -= blockSize;
+ op += cSize;
+ assert(dstCapacity >= cSize);
+ dstCapacity -= cSize;
+ DEBUGLOG(5, "ZSTD_compress_frameChunk: adding a block of size %u",
+ (unsigned)cSize);
+ } }
+
+ if (lastFrameChunk && (op>ostart)) cctx->stage = ZSTDcs_ending;
+ return op-ostart;
+}
+
+
+static size_t ZSTD_writeFrameHeader(void* dst, size_t dstCapacity,
+ ZSTD_CCtx_params params, U64 pledgedSrcSize, U32 dictID)
+{ BYTE* const op = (BYTE*)dst;
+ U32 const dictIDSizeCodeLength = (dictID>0) + (dictID>=256) + (dictID>=65536); /* 0-3 */
+ U32 const dictIDSizeCode = params.fParams.noDictIDFlag ? 0 : dictIDSizeCodeLength; /* 0-3 */
+ U32 const checksumFlag = params.fParams.checksumFlag>0;
+ U32 const windowSize = (U32)1 << params.cParams.windowLog;
+ U32 const singleSegment = params.fParams.contentSizeFlag && (windowSize >= pledgedSrcSize);
+ BYTE const windowLogByte = (BYTE)((params.cParams.windowLog - ZSTD_WINDOWLOG_ABSOLUTEMIN) << 3);
+ U32 const fcsCode = params.fParams.contentSizeFlag ?
+ (pledgedSrcSize>=256) + (pledgedSrcSize>=65536+256) + (pledgedSrcSize>=0xFFFFFFFFU) : 0; /* 0-3 */
+ BYTE const frameHeaderDecriptionByte = (BYTE)(dictIDSizeCode + (checksumFlag<<2) + (singleSegment<<5) + (fcsCode<<6) );
+ size_t pos=0;
+
+ assert(!(params.fParams.contentSizeFlag && pledgedSrcSize == ZSTD_CONTENTSIZE_UNKNOWN));
+ if (dstCapacity < ZSTD_FRAMEHEADERSIZE_MAX) return ERROR(dstSize_tooSmall);
+ DEBUGLOG(4, "ZSTD_writeFrameHeader : dictIDFlag : %u ; dictID : %u ; dictIDSizeCode : %u",
+ !params.fParams.noDictIDFlag, (unsigned)dictID, (unsigned)dictIDSizeCode);
+
+ if (params.format == ZSTD_f_zstd1) {
+ MEM_writeLE32(dst, ZSTD_MAGICNUMBER);
+ pos = 4;
+ }
+ op[pos++] = frameHeaderDecriptionByte;
+ if (!singleSegment) op[pos++] = windowLogByte;
+ switch(dictIDSizeCode)
+ {
+ default: assert(0); /* impossible */
+ case 0 : break;
+ case 1 : op[pos] = (BYTE)(dictID); pos++; break;
+ case 2 : MEM_writeLE16(op+pos, (U16)dictID); pos+=2; break;
+ case 3 : MEM_writeLE32(op+pos, dictID); pos+=4; break;
+ }
+ switch(fcsCode)
+ {
+ default: assert(0); /* impossible */
+ case 0 : if (singleSegment) op[pos++] = (BYTE)(pledgedSrcSize); break;
+ case 1 : MEM_writeLE16(op+pos, (U16)(pledgedSrcSize-256)); pos+=2; break;
+ case 2 : MEM_writeLE32(op+pos, (U32)(pledgedSrcSize)); pos+=4; break;
+ case 3 : MEM_writeLE64(op+pos, (U64)(pledgedSrcSize)); pos+=8; break;
+ }
+ return pos;
+}
+
+/* ZSTD_writeLastEmptyBlock() :
+ * output an empty Block with end-of-frame mark to complete a frame
+ * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
+ * or an error code if `dstCapcity` is too small (<ZSTD_blockHeaderSize)
+ */
+size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity)
+{
+ if (dstCapacity < ZSTD_blockHeaderSize) return ERROR(dstSize_tooSmall);
+ { U32 const cBlockHeader24 = 1 /*lastBlock*/ + (((U32)bt_raw)<<1); /* 0 size */
+ MEM_writeLE24(dst, cBlockHeader24);
+ return ZSTD_blockHeaderSize;
+ }
+}
+
+size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq)
+{
+ if (cctx->stage != ZSTDcs_init)
+ return ERROR(stage_wrong);
+ if (cctx->appliedParams.ldmParams.enableLdm)
+ return ERROR(parameter_unsupported);
+ cctx->externSeqStore.seq = seq;
+ cctx->externSeqStore.size = nbSeq;
+ cctx->externSeqStore.capacity = nbSeq;
+ cctx->externSeqStore.pos = 0;
+ return 0;
+}
+
+
+static size_t ZSTD_compressContinue_internal (ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ U32 frame, U32 lastFrameChunk)
+{
+ ZSTD_matchState_t* const ms = &cctx->blockState.matchState;
+ size_t fhSize = 0;
+
+ DEBUGLOG(5, "ZSTD_compressContinue_internal, stage: %u, srcSize: %u",
+ cctx->stage, (unsigned)srcSize);
+ if (cctx->stage==ZSTDcs_created) return ERROR(stage_wrong); /* missing init (ZSTD_compressBegin) */
+
+ if (frame && (cctx->stage==ZSTDcs_init)) {
+ fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, cctx->appliedParams,
+ cctx->pledgedSrcSizePlusOne-1, cctx->dictID);
+ if (ZSTD_isError(fhSize)) return fhSize;
+ dstCapacity -= fhSize;
+ dst = (char*)dst + fhSize;
+ cctx->stage = ZSTDcs_ongoing;
+ }
+
+ if (!srcSize) return fhSize; /* do not generate an empty block if no input */
+
+ if (!ZSTD_window_update(&ms->window, src, srcSize)) {
+ ms->nextToUpdate = ms->window.dictLimit;
+ }
+ if (cctx->appliedParams.ldmParams.enableLdm) {
+ ZSTD_window_update(&cctx->ldmState.window, src, srcSize);
+ }
+
+ if (!frame) {
+ /* overflow check and correction for block mode */
+ if (ZSTD_window_needOverflowCorrection(ms->window, (const char*)src + srcSize)) {
+ U32 const cycleLog = ZSTD_cycleLog(cctx->appliedParams.cParams.chainLog, cctx->appliedParams.cParams.strategy);
+ U32 const correction = ZSTD_window_correctOverflow(&ms->window, cycleLog, 1 << cctx->appliedParams.cParams.windowLog, src);
+ ZSTD_STATIC_ASSERT(ZSTD_CHAINLOG_MAX <= 30);
+ ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX_32 <= 30);
+ ZSTD_STATIC_ASSERT(ZSTD_WINDOWLOG_MAX <= 31);
+ ZSTD_reduceIndex(cctx, correction);
+ if (ms->nextToUpdate < correction) ms->nextToUpdate = 0;
+ else ms->nextToUpdate -= correction;
+ ms->loadedDictEnd = 0;
+ ms->dictMatchState = NULL;
+ }
+ }
+
+ DEBUGLOG(5, "ZSTD_compressContinue_internal (blockSize=%u)", (unsigned)cctx->blockSize);
+ { size_t const cSize = frame ?
+ ZSTD_compress_frameChunk (cctx, dst, dstCapacity, src, srcSize, lastFrameChunk) :
+ ZSTD_compressBlock_internal (cctx, dst, dstCapacity, src, srcSize);
+ if (ZSTD_isError(cSize)) return cSize;
+ cctx->consumedSrcSize += srcSize;
+ cctx->producedCSize += (cSize + fhSize);
+ assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
+ if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */
+ ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
+ if (cctx->consumedSrcSize+1 > cctx->pledgedSrcSizePlusOne) {
+ DEBUGLOG(4, "error : pledgedSrcSize = %u, while realSrcSize >= %u",
+ (unsigned)cctx->pledgedSrcSizePlusOne-1, (unsigned)cctx->consumedSrcSize);
+ return ERROR(srcSize_wrong);
+ }
+ }
+ return cSize + fhSize;
+ }
+}
+
+size_t ZSTD_compressContinue (ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize)
+{
+ DEBUGLOG(5, "ZSTD_compressContinue (srcSize=%u)", (unsigned)srcSize);
+ return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 1 /* frame mode */, 0 /* last chunk */);
+}
+
+
+size_t ZSTD_getBlockSize(const ZSTD_CCtx* cctx)
+{
+ ZSTD_compressionParameters const cParams = cctx->appliedParams.cParams;
+ assert(!ZSTD_checkCParams(cParams));
+ return MIN (ZSTD_BLOCKSIZE_MAX, (U32)1 << cParams.windowLog);
+}
+
+size_t ZSTD_compressBlock(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
+{
+ size_t const blockSizeMax = ZSTD_getBlockSize(cctx);
+ if (srcSize > blockSizeMax) return ERROR(srcSize_wrong);
+
+ return ZSTD_compressContinue_internal(cctx, dst, dstCapacity, src, srcSize, 0 /* frame mode */, 0 /* last chunk */);
+}
+
+/*! ZSTD_loadDictionaryContent() :
+ * @return : 0, or an error code
+ */
+static size_t ZSTD_loadDictionaryContent(ZSTD_matchState_t* ms,
+ ZSTD_CCtx_params const* params,
+ const void* src, size_t srcSize,
+ ZSTD_dictTableLoadMethod_e dtlm)
+{
+ const BYTE* const ip = (const BYTE*) src;
+ const BYTE* const iend = ip + srcSize;
+
+ ZSTD_window_update(&ms->window, src, srcSize);
+ ms->loadedDictEnd = params->forceWindow ? 0 : (U32)(iend - ms->window.base);
+
+ /* Assert that we the ms params match the params we're being given */
+ ZSTD_assertEqualCParams(params->cParams, ms->cParams);
+
+ if (srcSize <= HASH_READ_SIZE) return 0;
+
+ switch(params->cParams.strategy)
+ {
+ case ZSTD_fast:
+ ZSTD_fillHashTable(ms, iend, dtlm);
+ break;
+ case ZSTD_dfast:
+ ZSTD_fillDoubleHashTable(ms, iend, dtlm);
+ break;
+
+ case ZSTD_greedy:
+ case ZSTD_lazy:
+ case ZSTD_lazy2:
+ if (srcSize >= HASH_READ_SIZE)
+ ZSTD_insertAndFindFirstIndex(ms, iend-HASH_READ_SIZE);
+ break;
+
+ case ZSTD_btlazy2: /* we want the dictionary table fully sorted */
+ case ZSTD_btopt:
+ case ZSTD_btultra:
+ case ZSTD_btultra2:
+ if (srcSize >= HASH_READ_SIZE)
+ ZSTD_updateTree(ms, iend-HASH_READ_SIZE, iend);
+ break;
+
+ default:
+ assert(0); /* not possible : not a valid strategy id */
+ }
+
+ ms->nextToUpdate = (U32)(iend - ms->window.base);
+ return 0;
+}
+
+
+/* Dictionaries that assign zero probability to symbols that show up causes problems
+ when FSE encoding. Refuse dictionaries that assign zero probability to symbols
+ that we may encounter during compression.
+ NOTE: This behavior is not standard and could be improved in the future. */
+static size_t ZSTD_checkDictNCount(short* normalizedCounter, unsigned dictMaxSymbolValue, unsigned maxSymbolValue) {
+ U32 s;
+ if (dictMaxSymbolValue < maxSymbolValue) return ERROR(dictionary_corrupted);
+ for (s = 0; s <= maxSymbolValue; ++s) {
+ if (normalizedCounter[s] == 0) return ERROR(dictionary_corrupted);
+ }
+ return 0;
+}
+
+
+/* Dictionary format :
+ * See :
+ * https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#dictionary-format
+ */
+/*! ZSTD_loadZstdDictionary() :
+ * @return : dictID, or an error code
+ * assumptions : magic number supposed already checked
+ * dictSize supposed > 8
+ */
+static size_t ZSTD_loadZstdDictionary(ZSTD_compressedBlockState_t* bs,
+ ZSTD_matchState_t* ms,
+ ZSTD_CCtx_params const* params,
+ const void* dict, size_t dictSize,
+ ZSTD_dictTableLoadMethod_e dtlm,
+ void* workspace)
+{
+ const BYTE* dictPtr = (const BYTE*)dict;
+ const BYTE* const dictEnd = dictPtr + dictSize;
+ short offcodeNCount[MaxOff+1];
+ unsigned offcodeMaxValue = MaxOff;
+ size_t dictID;
+
+ ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog)));
+ assert(dictSize > 8);
+ assert(MEM_readLE32(dictPtr) == ZSTD_MAGIC_DICTIONARY);
+
+ dictPtr += 4; /* skip magic number */
+ dictID = params->fParams.noDictIDFlag ? 0 : MEM_readLE32(dictPtr);
+ dictPtr += 4;
+
+ { unsigned maxSymbolValue = 255;
+ size_t const hufHeaderSize = HUF_readCTable((HUF_CElt*)bs->entropy.huf.CTable, &maxSymbolValue, dictPtr, dictEnd-dictPtr);
+ if (HUF_isError(hufHeaderSize)) return ERROR(dictionary_corrupted);
+ if (maxSymbolValue < 255) return ERROR(dictionary_corrupted);
+ dictPtr += hufHeaderSize;
+ }
+
+ { unsigned offcodeLog;
+ size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
+ if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
+ if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted);
+ /* Defer checking offcodeMaxValue because we need to know the size of the dictionary content */
+ /* fill all offset symbols to avoid garbage at end of table */
+ CHECK_E( FSE_buildCTable_wksp(bs->entropy.fse.offcodeCTable,
+ offcodeNCount, MaxOff, offcodeLog,
+ workspace, HUF_WORKSPACE_SIZE),
+ dictionary_corrupted);
+ dictPtr += offcodeHeaderSize;
+ }
+
+ { short matchlengthNCount[MaxML+1];
+ unsigned matchlengthMaxValue = MaxML, matchlengthLog;
+ size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
+ if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
+ if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted);
+ /* Every match length code must have non-zero probability */
+ CHECK_F( ZSTD_checkDictNCount(matchlengthNCount, matchlengthMaxValue, MaxML));
+ CHECK_E( FSE_buildCTable_wksp(bs->entropy.fse.matchlengthCTable,
+ matchlengthNCount, matchlengthMaxValue, matchlengthLog,
+ workspace, HUF_WORKSPACE_SIZE),
+ dictionary_corrupted);
+ dictPtr += matchlengthHeaderSize;
+ }
+
+ { short litlengthNCount[MaxLL+1];
+ unsigned litlengthMaxValue = MaxLL, litlengthLog;
+ size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
+ if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
+ if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted);
+ /* Every literal length code must have non-zero probability */
+ CHECK_F( ZSTD_checkDictNCount(litlengthNCount, litlengthMaxValue, MaxLL));
+ CHECK_E( FSE_buildCTable_wksp(bs->entropy.fse.litlengthCTable,
+ litlengthNCount, litlengthMaxValue, litlengthLog,
+ workspace, HUF_WORKSPACE_SIZE),
+ dictionary_corrupted);
+ dictPtr += litlengthHeaderSize;
+ }
+
+ if (dictPtr+12 > dictEnd) return ERROR(dictionary_corrupted);
+ bs->rep[0] = MEM_readLE32(dictPtr+0);
+ bs->rep[1] = MEM_readLE32(dictPtr+4);
+ bs->rep[2] = MEM_readLE32(dictPtr+8);
+ dictPtr += 12;
+
+ { size_t const dictContentSize = (size_t)(dictEnd - dictPtr);
+ U32 offcodeMax = MaxOff;
+ if (dictContentSize <= ((U32)-1) - 128 KB) {
+ U32 const maxOffset = (U32)dictContentSize + 128 KB; /* The maximum offset that must be supported */
+ offcodeMax = ZSTD_highbit32(maxOffset); /* Calculate minimum offset code required to represent maxOffset */
+ }
+ /* All offset values <= dictContentSize + 128 KB must be representable */
+ CHECK_F (ZSTD_checkDictNCount(offcodeNCount, offcodeMaxValue, MIN(offcodeMax, MaxOff)));
+ /* All repCodes must be <= dictContentSize and != 0*/
+ { U32 u;
+ for (u=0; u<3; u++) {
+ if (bs->rep[u] == 0) return ERROR(dictionary_corrupted);
+ if (bs->rep[u] > dictContentSize) return ERROR(dictionary_corrupted);
+ } }
+
+ bs->entropy.huf.repeatMode = HUF_repeat_valid;
+ bs->entropy.fse.offcode_repeatMode = FSE_repeat_valid;
+ bs->entropy.fse.matchlength_repeatMode = FSE_repeat_valid;
+ bs->entropy.fse.litlength_repeatMode = FSE_repeat_valid;
+ CHECK_F(ZSTD_loadDictionaryContent(ms, params, dictPtr, dictContentSize, dtlm));
+ return dictID;
+ }
+}
+
+/** ZSTD_compress_insertDictionary() :
+* @return : dictID, or an error code */
+static size_t
+ZSTD_compress_insertDictionary(ZSTD_compressedBlockState_t* bs,
+ ZSTD_matchState_t* ms,
+ const ZSTD_CCtx_params* params,
+ const void* dict, size_t dictSize,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_dictTableLoadMethod_e dtlm,
+ void* workspace)
+{
+ DEBUGLOG(4, "ZSTD_compress_insertDictionary (dictSize=%u)", (U32)dictSize);
+ if ((dict==NULL) || (dictSize<=8)) return 0;
+
+ ZSTD_reset_compressedBlockState(bs);
+
+ /* dict restricted modes */
+ if (dictContentType == ZSTD_dct_rawContent)
+ return ZSTD_loadDictionaryContent(ms, params, dict, dictSize, dtlm);
+
+ if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) {
+ if (dictContentType == ZSTD_dct_auto) {
+ DEBUGLOG(4, "raw content dictionary detected");
+ return ZSTD_loadDictionaryContent(ms, params, dict, dictSize, dtlm);
+ }
+ if (dictContentType == ZSTD_dct_fullDict)
+ return ERROR(dictionary_wrong);
+ assert(0); /* impossible */
+ }
+
+ /* dict as full zstd dictionary */
+ return ZSTD_loadZstdDictionary(bs, ms, params, dict, dictSize, dtlm, workspace);
+}
+
+/*! ZSTD_compressBegin_internal() :
+ * @return : 0, or an error code */
+static size_t ZSTD_compressBegin_internal(ZSTD_CCtx* cctx,
+ const void* dict, size_t dictSize,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_dictTableLoadMethod_e dtlm,
+ const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params, U64 pledgedSrcSize,
+ ZSTD_buffered_policy_e zbuff)
+{
+ DEBUGLOG(4, "ZSTD_compressBegin_internal: wlog=%u", params.cParams.windowLog);
+ /* params are supposed to be fully validated at this point */
+ assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
+ assert(!((dict) && (cdict))); /* either dict or cdict, not both */
+
+ if (cdict && cdict->dictContentSize>0) {
+ return ZSTD_resetCCtx_usingCDict(cctx, cdict, params, pledgedSrcSize, zbuff);
+ }
+
+ CHECK_F( ZSTD_resetCCtx_internal(cctx, params, pledgedSrcSize,
+ ZSTDcrp_continue, zbuff) );
+ {
+ size_t const dictID = ZSTD_compress_insertDictionary(
+ cctx->blockState.prevCBlock, &cctx->blockState.matchState,
+ &params, dict, dictSize, dictContentType, dtlm, cctx->entropyWorkspace);
+ if (ZSTD_isError(dictID)) return dictID;
+ assert(dictID <= (size_t)(U32)-1);
+ cctx->dictID = (U32)dictID;
+ }
+ return 0;
+}
+
+size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
+ const void* dict, size_t dictSize,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_dictTableLoadMethod_e dtlm,
+ const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params,
+ unsigned long long pledgedSrcSize)
+{
+ DEBUGLOG(4, "ZSTD_compressBegin_advanced_internal: wlog=%u", params.cParams.windowLog);
+ /* compression parameters verification and optimization */
+ CHECK_F( ZSTD_checkCParams(params.cParams) );
+ return ZSTD_compressBegin_internal(cctx,
+ dict, dictSize, dictContentType, dtlm,
+ cdict,
+ params, pledgedSrcSize,
+ ZSTDb_not_buffered);
+}
+
+/*! ZSTD_compressBegin_advanced() :
+* @return : 0, or an error code */
+size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx,
+ const void* dict, size_t dictSize,
+ ZSTD_parameters params, unsigned long long pledgedSrcSize)
+{
+ ZSTD_CCtx_params const cctxParams =
+ ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
+ return ZSTD_compressBegin_advanced_internal(cctx,
+ dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast,
+ NULL /*cdict*/,
+ cctxParams, pledgedSrcSize);
+}
+
+size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel)
+{
+ ZSTD_parameters const params = ZSTD_getParams(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
+ ZSTD_CCtx_params const cctxParams =
+ ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
+ DEBUGLOG(4, "ZSTD_compressBegin_usingDict (dictSize=%u)", (unsigned)dictSize);
+ return ZSTD_compressBegin_internal(cctx, dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
+ cctxParams, ZSTD_CONTENTSIZE_UNKNOWN, ZSTDb_not_buffered);
+}
+
+size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel)
+{
+ return ZSTD_compressBegin_usingDict(cctx, NULL, 0, compressionLevel);
+}
+
+
+/*! ZSTD_writeEpilogue() :
+* Ends a frame.
+* @return : nb of bytes written into dst (or an error code) */
+static size_t ZSTD_writeEpilogue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity)
+{
+ BYTE* const ostart = (BYTE*)dst;
+ BYTE* op = ostart;
+ size_t fhSize = 0;
+
+ DEBUGLOG(4, "ZSTD_writeEpilogue");
+ if (cctx->stage == ZSTDcs_created) return ERROR(stage_wrong); /* init missing */
+
+ /* special case : empty frame */
+ if (cctx->stage == ZSTDcs_init) {
+ fhSize = ZSTD_writeFrameHeader(dst, dstCapacity, cctx->appliedParams, 0, 0);
+ if (ZSTD_isError(fhSize)) return fhSize;
+ dstCapacity -= fhSize;
+ op += fhSize;
+ cctx->stage = ZSTDcs_ongoing;
+ }
+
+ if (cctx->stage != ZSTDcs_ending) {
+ /* write one last empty block, make it the "last" block */
+ U32 const cBlockHeader24 = 1 /* last block */ + (((U32)bt_raw)<<1) + 0;
+ if (dstCapacity<4) return ERROR(dstSize_tooSmall);
+ MEM_writeLE32(op, cBlockHeader24);
+ op += ZSTD_blockHeaderSize;
+ dstCapacity -= ZSTD_blockHeaderSize;
+ }
+
+ if (cctx->appliedParams.fParams.checksumFlag) {
+ U32 const checksum = (U32) XXH64_digest(&cctx->xxhState);
+ if (dstCapacity<4) return ERROR(dstSize_tooSmall);
+ DEBUGLOG(4, "ZSTD_writeEpilogue: write checksum : %08X", (unsigned)checksum);
+ MEM_writeLE32(op, checksum);
+ op += 4;
+ }
+
+ cctx->stage = ZSTDcs_created; /* return to "created but no init" status */
+ return op-ostart;
+}
+
+size_t ZSTD_compressEnd (ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize)
+{
+ size_t endResult;
+ size_t const cSize = ZSTD_compressContinue_internal(cctx,
+ dst, dstCapacity, src, srcSize,
+ 1 /* frame mode */, 1 /* last chunk */);
+ if (ZSTD_isError(cSize)) return cSize;
+ endResult = ZSTD_writeEpilogue(cctx, (char*)dst + cSize, dstCapacity-cSize);
+ if (ZSTD_isError(endResult)) return endResult;
+ assert(!(cctx->appliedParams.fParams.contentSizeFlag && cctx->pledgedSrcSizePlusOne == 0));
+ if (cctx->pledgedSrcSizePlusOne != 0) { /* control src size */
+ ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_UNKNOWN == (unsigned long long)-1);
+ DEBUGLOG(4, "end of frame : controlling src size");
+ if (cctx->pledgedSrcSizePlusOne != cctx->consumedSrcSize+1) {
+ DEBUGLOG(4, "error : pledgedSrcSize = %u, while realSrcSize = %u",
+ (unsigned)cctx->pledgedSrcSizePlusOne-1, (unsigned)cctx->consumedSrcSize);
+ return ERROR(srcSize_wrong);
+ } }
+ return cSize + endResult;
+}
+
+
+static size_t ZSTD_compress_internal (ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const void* dict,size_t dictSize,
+ ZSTD_parameters params)
+{
+ ZSTD_CCtx_params const cctxParams =
+ ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
+ DEBUGLOG(4, "ZSTD_compress_internal");
+ return ZSTD_compress_advanced_internal(cctx,
+ dst, dstCapacity,
+ src, srcSize,
+ dict, dictSize,
+ cctxParams);
+}
+
+size_t ZSTD_compress_advanced (ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const void* dict,size_t dictSize,
+ ZSTD_parameters params)
+{
+ DEBUGLOG(4, "ZSTD_compress_advanced");
+ CHECK_F(ZSTD_checkCParams(params.cParams));
+ return ZSTD_compress_internal(cctx,
+ dst, dstCapacity,
+ src, srcSize,
+ dict, dictSize,
+ params);
+}
+
+/* Internal */
+size_t ZSTD_compress_advanced_internal(
+ ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const void* dict,size_t dictSize,
+ ZSTD_CCtx_params params)
+{
+ DEBUGLOG(4, "ZSTD_compress_advanced_internal (srcSize:%u)", (unsigned)srcSize);
+ CHECK_F( ZSTD_compressBegin_internal(cctx,
+ dict, dictSize, ZSTD_dct_auto, ZSTD_dtlm_fast, NULL,
+ params, srcSize, ZSTDb_not_buffered) );
+ return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
+}
+
+size_t ZSTD_compress_usingDict(ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const void* dict, size_t dictSize,
+ int compressionLevel)
+{
+ ZSTD_parameters const params = ZSTD_getParams(compressionLevel, srcSize + (!srcSize), dict ? dictSize : 0);
+ ZSTD_CCtx_params cctxParams = ZSTD_assignParamsToCCtxParams(cctx->requestedParams, params);
+ assert(params.fParams.contentSizeFlag == 1);
+ return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, dict, dictSize, cctxParams);
+}
+
+size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ int compressionLevel)
+{
+ DEBUGLOG(4, "ZSTD_compressCCtx (srcSize=%u)", (unsigned)srcSize);
+ assert(cctx != NULL);
+ return ZSTD_compress_usingDict(cctx, dst, dstCapacity, src, srcSize, NULL, 0, compressionLevel);
+}
+
+size_t ZSTD_compress(void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ int compressionLevel)
+{
+ size_t result;
+ ZSTD_CCtx ctxBody;
+ ZSTD_initCCtx(&ctxBody, ZSTD_defaultCMem);
+ result = ZSTD_compressCCtx(&ctxBody, dst, dstCapacity, src, srcSize, compressionLevel);
+ ZSTD_freeCCtxContent(&ctxBody); /* can't free ctxBody itself, as it's on stack; free only heap content */
+ return result;
+}
+
+
+/* ===== Dictionary API ===== */
+
+/*! ZSTD_estimateCDictSize_advanced() :
+ * Estimate amount of memory that will be needed to create a dictionary with following arguments */
+size_t ZSTD_estimateCDictSize_advanced(
+ size_t dictSize, ZSTD_compressionParameters cParams,
+ ZSTD_dictLoadMethod_e dictLoadMethod)
+{
+ DEBUGLOG(5, "sizeof(ZSTD_CDict) : %u", (unsigned)sizeof(ZSTD_CDict));
+ return sizeof(ZSTD_CDict) + HUF_WORKSPACE_SIZE + ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 0)
+ + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize);
+}
+
+size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel)
+{
+ ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
+ return ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
+}
+
+size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict)
+{
+ if (cdict==NULL) return 0; /* support sizeof on NULL */
+ DEBUGLOG(5, "sizeof(*cdict) : %u", (unsigned)sizeof(*cdict));
+ return cdict->workspaceSize + (cdict->dictBuffer ? cdict->dictContentSize : 0) + sizeof(*cdict);
+}
+
+static size_t ZSTD_initCDict_internal(
+ ZSTD_CDict* cdict,
+ const void* dictBuffer, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_compressionParameters cParams)
+{
+ DEBUGLOG(3, "ZSTD_initCDict_internal (dictContentType:%u)", (unsigned)dictContentType);
+ assert(!ZSTD_checkCParams(cParams));
+ cdict->matchState.cParams = cParams;
+ if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dictBuffer) || (!dictSize)) {
+ cdict->dictBuffer = NULL;
+ cdict->dictContent = dictBuffer;
+ } else {
+ void* const internalBuffer = ZSTD_malloc(dictSize, cdict->customMem);
+ cdict->dictBuffer = internalBuffer;
+ cdict->dictContent = internalBuffer;
+ if (!internalBuffer) return ERROR(memory_allocation);
+ memcpy(internalBuffer, dictBuffer, dictSize);
+ }
+ cdict->dictContentSize = dictSize;
+
+ /* Reset the state to no dictionary */
+ ZSTD_reset_compressedBlockState(&cdict->cBlockState);
+ { void* const end = ZSTD_reset_matchState(
+ &cdict->matchState,
+ (U32*)cdict->workspace + HUF_WORKSPACE_SIZE_U32,
+ &cParams, ZSTDcrp_continue, /* forCCtx */ 0);
+ assert(end == (char*)cdict->workspace + cdict->workspaceSize);
+ (void)end;
+ }
+ /* (Maybe) load the dictionary
+ * Skips loading the dictionary if it is <= 8 bytes.
+ */
+ { ZSTD_CCtx_params params;
+ memset(&params, 0, sizeof(params));
+ params.compressionLevel = ZSTD_CLEVEL_DEFAULT;
+ params.fParams.contentSizeFlag = 1;
+ params.cParams = cParams;
+ { size_t const dictID = ZSTD_compress_insertDictionary(
+ &cdict->cBlockState, &cdict->matchState, &params,
+ cdict->dictContent, cdict->dictContentSize,
+ dictContentType, ZSTD_dtlm_full, cdict->workspace);
+ if (ZSTD_isError(dictID)) return dictID;
+ assert(dictID <= (size_t)(U32)-1);
+ cdict->dictID = (U32)dictID;
+ }
+ }
+
+ return 0;
+}
+
+ZSTD_CDict* ZSTD_createCDict_advanced(const void* dictBuffer, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_compressionParameters cParams, ZSTD_customMem customMem)
+{
+ DEBUGLOG(3, "ZSTD_createCDict_advanced, mode %u", (unsigned)dictContentType);
+ if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
+
+ { ZSTD_CDict* const cdict = (ZSTD_CDict*)ZSTD_malloc(sizeof(ZSTD_CDict), customMem);
+ size_t const workspaceSize = HUF_WORKSPACE_SIZE + ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 0);
+ void* const workspace = ZSTD_malloc(workspaceSize, customMem);
+
+ if (!cdict || !workspace) {
+ ZSTD_free(cdict, customMem);
+ ZSTD_free(workspace, customMem);
+ return NULL;
+ }
+ cdict->customMem = customMem;
+ cdict->workspace = workspace;
+ cdict->workspaceSize = workspaceSize;
+ if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
+ dictBuffer, dictSize,
+ dictLoadMethod, dictContentType,
+ cParams) )) {
+ ZSTD_freeCDict(cdict);
+ return NULL;
+ }
+
+ return cdict;
+ }
+}
+
+ZSTD_CDict* ZSTD_createCDict(const void* dict, size_t dictSize, int compressionLevel)
+{
+ ZSTD_compressionParameters cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
+ return ZSTD_createCDict_advanced(dict, dictSize,
+ ZSTD_dlm_byCopy, ZSTD_dct_auto,
+ cParams, ZSTD_defaultCMem);
+}
+
+ZSTD_CDict* ZSTD_createCDict_byReference(const void* dict, size_t dictSize, int compressionLevel)
+{
+ ZSTD_compressionParameters cParams = ZSTD_getCParams(compressionLevel, 0, dictSize);
+ return ZSTD_createCDict_advanced(dict, dictSize,
+ ZSTD_dlm_byRef, ZSTD_dct_auto,
+ cParams, ZSTD_defaultCMem);
+}
+
+size_t ZSTD_freeCDict(ZSTD_CDict* cdict)
+{
+ if (cdict==NULL) return 0; /* support free on NULL */
+ { ZSTD_customMem const cMem = cdict->customMem;
+ ZSTD_free(cdict->workspace, cMem);
+ ZSTD_free(cdict->dictBuffer, cMem);
+ ZSTD_free(cdict, cMem);
+ return 0;
+ }
+}
+
+/*! ZSTD_initStaticCDict_advanced() :
+ * Generate a digested dictionary in provided memory area.
+ * workspace: The memory area to emplace the dictionary into.
+ * Provided pointer must 8-bytes aligned.
+ * It must outlive dictionary usage.
+ * workspaceSize: Use ZSTD_estimateCDictSize()
+ * to determine how large workspace must be.
+ * cParams : use ZSTD_getCParams() to transform a compression level
+ * into its relevants cParams.
+ * @return : pointer to ZSTD_CDict*, or NULL if error (size too small)
+ * Note : there is no corresponding "free" function.
+ * Since workspace was allocated externally, it must be freed externally.
+ */
+const ZSTD_CDict* ZSTD_initStaticCDict(
+ void* workspace, size_t workspaceSize,
+ const void* dict, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_compressionParameters cParams)
+{
+ size_t const matchStateSize = ZSTD_sizeof_matchState(&cParams, /* forCCtx */ 0);
+ size_t const neededSize = sizeof(ZSTD_CDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize)
+ + HUF_WORKSPACE_SIZE + matchStateSize;
+ ZSTD_CDict* const cdict = (ZSTD_CDict*) workspace;
+ void* ptr;
+ if ((size_t)workspace & 7) return NULL; /* 8-aligned */
+ DEBUGLOG(4, "(workspaceSize < neededSize) : (%u < %u) => %u",
+ (unsigned)workspaceSize, (unsigned)neededSize, (unsigned)(workspaceSize < neededSize));
+ if (workspaceSize < neededSize) return NULL;
+
+ if (dictLoadMethod == ZSTD_dlm_byCopy) {
+ memcpy(cdict+1, dict, dictSize);
+ dict = cdict+1;
+ ptr = (char*)workspace + sizeof(ZSTD_CDict) + dictSize;
+ } else {
+ ptr = cdict+1;
+ }
+ cdict->workspace = ptr;
+ cdict->workspaceSize = HUF_WORKSPACE_SIZE + matchStateSize;
+
+ if (ZSTD_isError( ZSTD_initCDict_internal(cdict,
+ dict, dictSize,
+ ZSTD_dlm_byRef, dictContentType,
+ cParams) ))
+ return NULL;
+
+ return cdict;
+}
+
+ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict)
+{
+ assert(cdict != NULL);
+ return cdict->matchState.cParams;
+}
+
+/* ZSTD_compressBegin_usingCDict_advanced() :
+ * cdict must be != NULL */
+size_t ZSTD_compressBegin_usingCDict_advanced(
+ ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict,
+ ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize)
+{
+ DEBUGLOG(4, "ZSTD_compressBegin_usingCDict_advanced");
+ if (cdict==NULL) return ERROR(dictionary_wrong);
+ { ZSTD_CCtx_params params = cctx->requestedParams;
+ params.cParams = ZSTD_getCParamsFromCDict(cdict);
+ /* Increase window log to fit the entire dictionary and source if the
+ * source size is known. Limit the increase to 19, which is the
+ * window log for compression level 1 with the largest source size.
+ */
+ if (pledgedSrcSize != ZSTD_CONTENTSIZE_UNKNOWN) {
+ U32 const limitedSrcSize = (U32)MIN(pledgedSrcSize, 1U << 19);
+ U32 const limitedSrcLog = limitedSrcSize > 1 ? ZSTD_highbit32(limitedSrcSize - 1) + 1 : 1;
+ params.cParams.windowLog = MAX(params.cParams.windowLog, limitedSrcLog);
+ }
+ params.fParams = fParams;
+ return ZSTD_compressBegin_internal(cctx,
+ NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast,
+ cdict,
+ params, pledgedSrcSize,
+ ZSTDb_not_buffered);
+ }
+}
+
+/* ZSTD_compressBegin_usingCDict() :
+ * pledgedSrcSize=0 means "unknown"
+ * if pledgedSrcSize>0, it will enable contentSizeFlag */
+size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict)
+{
+ ZSTD_frameParameters const fParams = { 0 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
+ DEBUGLOG(4, "ZSTD_compressBegin_usingCDict : dictIDFlag == %u", !fParams.noDictIDFlag);
+ return ZSTD_compressBegin_usingCDict_advanced(cctx, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN);
+}
+
+size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const ZSTD_CDict* cdict, ZSTD_frameParameters fParams)
+{
+ CHECK_F (ZSTD_compressBegin_usingCDict_advanced(cctx, cdict, fParams, srcSize)); /* will check if cdict != NULL */
+ return ZSTD_compressEnd(cctx, dst, dstCapacity, src, srcSize);
+}
+
+/*! ZSTD_compress_usingCDict() :
+ * Compression using a digested Dictionary.
+ * Faster startup than ZSTD_compress_usingDict(), recommended when same dictionary is used multiple times.
+ * Note that compression parameters are decided at CDict creation time
+ * while frame parameters are hardcoded */
+size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const ZSTD_CDict* cdict)
+{
+ ZSTD_frameParameters const fParams = { 1 /*content*/, 0 /*checksum*/, 0 /*noDictID*/ };
+ return ZSTD_compress_usingCDict_advanced(cctx, dst, dstCapacity, src, srcSize, cdict, fParams);
+}
+
+
+
+/* ******************************************************************
+* Streaming
+********************************************************************/
+
+ZSTD_CStream* ZSTD_createCStream(void)
+{
+ DEBUGLOG(3, "ZSTD_createCStream");
+ return ZSTD_createCStream_advanced(ZSTD_defaultCMem);
+}
+
+ZSTD_CStream* ZSTD_initStaticCStream(void *workspace, size_t workspaceSize)
+{
+ return ZSTD_initStaticCCtx(workspace, workspaceSize);
+}
+
+ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem)
+{ /* CStream and CCtx are now same object */
+ return ZSTD_createCCtx_advanced(customMem);
+}
+
+size_t ZSTD_freeCStream(ZSTD_CStream* zcs)
+{
+ return ZSTD_freeCCtx(zcs); /* same object */
+}
+
+
+
+/*====== Initialization ======*/
+
+size_t ZSTD_CStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX; }
+
+size_t ZSTD_CStreamOutSize(void)
+{
+ return ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + 4 /* 32-bits hash */ ;
+}
+
+static size_t ZSTD_resetCStream_internal(ZSTD_CStream* cctx,
+ const void* const dict, size_t const dictSize, ZSTD_dictContentType_e const dictContentType,
+ const ZSTD_CDict* const cdict,
+ ZSTD_CCtx_params params, unsigned long long const pledgedSrcSize)
+{
+ DEBUGLOG(4, "ZSTD_resetCStream_internal");
+ /* Finalize the compression parameters */
+ params.cParams = ZSTD_getCParamsFromCCtxParams(&params, pledgedSrcSize, dictSize);
+ /* params are supposed to be fully validated at this point */
+ assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
+ assert(!((dict) && (cdict))); /* either dict or cdict, not both */
+
+ CHECK_F( ZSTD_compressBegin_internal(cctx,
+ dict, dictSize, dictContentType, ZSTD_dtlm_fast,
+ cdict,
+ params, pledgedSrcSize,
+ ZSTDb_buffered) );
+
+ cctx->inToCompress = 0;
+ cctx->inBuffPos = 0;
+ cctx->inBuffTarget = cctx->blockSize
+ + (cctx->blockSize == pledgedSrcSize); /* for small input: avoid automatic flush on reaching end of block, since it would require to add a 3-bytes null block to end frame */
+ cctx->outBuffContentSize = cctx->outBuffFlushedSize = 0;
+ cctx->streamStage = zcss_load;
+ cctx->frameEnded = 0;
+ return 0; /* ready to go */
+}
+
+/* ZSTD_resetCStream():
+ * pledgedSrcSize == 0 means "unknown" */
+size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize)
+{
+ ZSTD_CCtx_params params = zcs->requestedParams;
+ DEBUGLOG(4, "ZSTD_resetCStream: pledgedSrcSize = %u", (unsigned)pledgedSrcSize);
+ if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
+ params.fParams.contentSizeFlag = 1;
+ return ZSTD_resetCStream_internal(zcs, NULL, 0, ZSTD_dct_auto, zcs->cdict, params, pledgedSrcSize);
+}
+
+/*! ZSTD_initCStream_internal() :
+ * Note : for lib/compress only. Used by zstdmt_compress.c.
+ * Assumption 1 : params are valid
+ * Assumption 2 : either dict, or cdict, is defined, not both */
+size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
+ const void* dict, size_t dictSize, const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params, unsigned long long pledgedSrcSize)
+{
+ DEBUGLOG(4, "ZSTD_initCStream_internal");
+ params.cParams = ZSTD_getCParamsFromCCtxParams(&params, pledgedSrcSize, dictSize);
+ assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
+ assert(!((dict) && (cdict))); /* either dict or cdict, not both */
+
+ if (dict && dictSize >= 8) {
+ DEBUGLOG(4, "loading dictionary of size %u", (unsigned)dictSize);
+ if (zcs->staticSize) { /* static CCtx : never uses malloc */
+ /* incompatible with internal cdict creation */
+ return ERROR(memory_allocation);
+ }
+ ZSTD_freeCDict(zcs->cdictLocal);
+ zcs->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
+ ZSTD_dlm_byCopy, ZSTD_dct_auto,
+ params.cParams, zcs->customMem);
+ zcs->cdict = zcs->cdictLocal;
+ if (zcs->cdictLocal == NULL) return ERROR(memory_allocation);
+ } else {
+ if (cdict) {
+ params.cParams = ZSTD_getCParamsFromCDict(cdict); /* cParams are enforced from cdict; it includes windowLog */
+ }
+ ZSTD_freeCDict(zcs->cdictLocal);
+ zcs->cdictLocal = NULL;
+ zcs->cdict = cdict;
+ }
+
+ return ZSTD_resetCStream_internal(zcs, NULL, 0, ZSTD_dct_auto, zcs->cdict, params, pledgedSrcSize);
+}
+
+/* ZSTD_initCStream_usingCDict_advanced() :
+ * same as ZSTD_initCStream_usingCDict(), with control over frame parameters */
+size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
+ const ZSTD_CDict* cdict,
+ ZSTD_frameParameters fParams,
+ unsigned long long pledgedSrcSize)
+{
+ DEBUGLOG(4, "ZSTD_initCStream_usingCDict_advanced");
+ if (!cdict) return ERROR(dictionary_wrong); /* cannot handle NULL cdict (does not know what to do) */
+ { ZSTD_CCtx_params params = zcs->requestedParams;
+ params.cParams = ZSTD_getCParamsFromCDict(cdict);
+ params.fParams = fParams;
+ return ZSTD_initCStream_internal(zcs,
+ NULL, 0, cdict,
+ params, pledgedSrcSize);
+ }
+}
+
+/* note : cdict must outlive compression session */
+size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict)
+{
+ ZSTD_frameParameters const fParams = { 0 /* contentSizeFlag */, 0 /* checksum */, 0 /* hideDictID */ };
+ DEBUGLOG(4, "ZSTD_initCStream_usingCDict");
+ return ZSTD_initCStream_usingCDict_advanced(zcs, cdict, fParams, ZSTD_CONTENTSIZE_UNKNOWN); /* note : will check that cdict != NULL */
+}
+
+
+/* ZSTD_initCStream_advanced() :
+ * pledgedSrcSize must be exact.
+ * if srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
+ * dict is loaded with default parameters ZSTD_dm_auto and ZSTD_dlm_byCopy. */
+size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
+ const void* dict, size_t dictSize,
+ ZSTD_parameters params, unsigned long long pledgedSrcSize)
+{
+ DEBUGLOG(4, "ZSTD_initCStream_advanced: pledgedSrcSize=%u, flag=%u",
+ (unsigned)pledgedSrcSize, params.fParams.contentSizeFlag);
+ CHECK_F( ZSTD_checkCParams(params.cParams) );
+ if ((pledgedSrcSize==0) && (params.fParams.contentSizeFlag==0)) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN; /* for compatibility with older programs relying on this behavior. Users should now specify ZSTD_CONTENTSIZE_UNKNOWN. This line will be removed in the future. */
+ zcs->requestedParams = ZSTD_assignParamsToCCtxParams(zcs->requestedParams, params);
+ return ZSTD_initCStream_internal(zcs, dict, dictSize, NULL /*cdict*/, zcs->requestedParams, pledgedSrcSize);
+}
+
+size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel)
+{
+ ZSTD_CCtxParams_init(&zcs->requestedParams, compressionLevel);
+ return ZSTD_initCStream_internal(zcs, dict, dictSize, NULL, zcs->requestedParams, ZSTD_CONTENTSIZE_UNKNOWN);
+}
+
+size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pss)
+{
+ U64 const pledgedSrcSize = (pss==0) ? ZSTD_CONTENTSIZE_UNKNOWN : pss; /* temporary : 0 interpreted as "unknown" during transition period. Users willing to specify "unknown" **must** use ZSTD_CONTENTSIZE_UNKNOWN. `0` will be interpreted as "empty" in the future */
+ ZSTD_CCtxParams_init(&zcs->requestedParams, compressionLevel);
+ return ZSTD_initCStream_internal(zcs, NULL, 0, NULL, zcs->requestedParams, pledgedSrcSize);
+}
+
+size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel)
+{
+ DEBUGLOG(4, "ZSTD_initCStream");
+ return ZSTD_initCStream_srcSize(zcs, compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN);
+}
+
+/*====== Compression ======*/
+
+static size_t ZSTD_nextInputSizeHint(const ZSTD_CCtx* cctx)
+{
+ size_t hintInSize = cctx->inBuffTarget - cctx->inBuffPos;
+ if (hintInSize==0) hintInSize = cctx->blockSize;
+ return hintInSize;
+}
+
+static size_t ZSTD_limitCopy(void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize)
+{
+ size_t const length = MIN(dstCapacity, srcSize);
+ if (length) memcpy(dst, src, length);
+ return length;
+}
+
+/** ZSTD_compressStream_generic():
+ * internal function for all *compressStream*() variants
+ * non-static, because can be called from zstdmt_compress.c
+ * @return : hint size for next input */
+size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
+ ZSTD_outBuffer* output,
+ ZSTD_inBuffer* input,
+ ZSTD_EndDirective const flushMode)
+{
+ const char* const istart = (const char*)input->src;
+ const char* const iend = istart + input->size;
+ const char* ip = istart + input->pos;
+ char* const ostart = (char*)output->dst;
+ char* const oend = ostart + output->size;
+ char* op = ostart + output->pos;
+ U32 someMoreWork = 1;
+
+ /* check expectations */
+ DEBUGLOG(5, "ZSTD_compressStream_generic, flush=%u", (unsigned)flushMode);
+ assert(zcs->inBuff != NULL);
+ assert(zcs->inBuffSize > 0);
+ assert(zcs->outBuff != NULL);
+ assert(zcs->outBuffSize > 0);
+ assert(output->pos <= output->size);
+ assert(input->pos <= input->size);
+
+ while (someMoreWork) {
+ switch(zcs->streamStage)
+ {
+ case zcss_init:
+ /* call ZSTD_initCStream() first ! */
+ return ERROR(init_missing);
+
+ case zcss_load:
+ if ( (flushMode == ZSTD_e_end)
+ && ((size_t)(oend-op) >= ZSTD_compressBound(iend-ip)) /* enough dstCapacity */
+ && (zcs->inBuffPos == 0) ) {
+ /* shortcut to compression pass directly into output buffer */
+ size_t const cSize = ZSTD_compressEnd(zcs,
+ op, oend-op, ip, iend-ip);
+ DEBUGLOG(4, "ZSTD_compressEnd : cSize=%u", (unsigned)cSize);
+ if (ZSTD_isError(cSize)) return cSize;
+ ip = iend;
+ op += cSize;
+ zcs->frameEnded = 1;
+ ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
+ someMoreWork = 0; break;
+ }
+ /* complete loading into inBuffer */
+ { size_t const toLoad = zcs->inBuffTarget - zcs->inBuffPos;
+ size_t const loaded = ZSTD_limitCopy(
+ zcs->inBuff + zcs->inBuffPos, toLoad,
+ ip, iend-ip);
+ zcs->inBuffPos += loaded;
+ ip += loaded;
+ if ( (flushMode == ZSTD_e_continue)
+ && (zcs->inBuffPos < zcs->inBuffTarget) ) {
+ /* not enough input to fill full block : stop here */
+ someMoreWork = 0; break;
+ }
+ if ( (flushMode == ZSTD_e_flush)
+ && (zcs->inBuffPos == zcs->inToCompress) ) {
+ /* empty */
+ someMoreWork = 0; break;
+ }
+ }
+ /* compress current block (note : this stage cannot be stopped in the middle) */
+ DEBUGLOG(5, "stream compression stage (flushMode==%u)", flushMode);
+ { void* cDst;
+ size_t cSize;
+ size_t const iSize = zcs->inBuffPos - zcs->inToCompress;
+ size_t oSize = oend-op;
+ unsigned const lastBlock = (flushMode == ZSTD_e_end) && (ip==iend);
+ if (oSize >= ZSTD_compressBound(iSize))
+ cDst = op; /* compress into output buffer, to skip flush stage */
+ else
+ cDst = zcs->outBuff, oSize = zcs->outBuffSize;
+ cSize = lastBlock ?
+ ZSTD_compressEnd(zcs, cDst, oSize,
+ zcs->inBuff + zcs->inToCompress, iSize) :
+ ZSTD_compressContinue(zcs, cDst, oSize,
+ zcs->inBuff + zcs->inToCompress, iSize);
+ if (ZSTD_isError(cSize)) return cSize;
+ zcs->frameEnded = lastBlock;
+ /* prepare next block */
+ zcs->inBuffTarget = zcs->inBuffPos + zcs->blockSize;
+ if (zcs->inBuffTarget > zcs->inBuffSize)
+ zcs->inBuffPos = 0, zcs->inBuffTarget = zcs->blockSize;
+ DEBUGLOG(5, "inBuffTarget:%u / inBuffSize:%u",
+ (unsigned)zcs->inBuffTarget, (unsigned)zcs->inBuffSize);
+ if (!lastBlock)
+ assert(zcs->inBuffTarget <= zcs->inBuffSize);
+ zcs->inToCompress = zcs->inBuffPos;
+ if (cDst == op) { /* no need to flush */
+ op += cSize;
+ if (zcs->frameEnded) {
+ DEBUGLOG(5, "Frame completed directly in outBuffer");
+ someMoreWork = 0;
+ ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
+ }
+ break;
+ }
+ zcs->outBuffContentSize = cSize;
+ zcs->outBuffFlushedSize = 0;
+ zcs->streamStage = zcss_flush; /* pass-through to flush stage */
+ }
+ /* fall-through */
+ case zcss_flush:
+ DEBUGLOG(5, "flush stage");
+ { size_t const toFlush = zcs->outBuffContentSize - zcs->outBuffFlushedSize;
+ size_t const flushed = ZSTD_limitCopy(op, oend-op,
+ zcs->outBuff + zcs->outBuffFlushedSize, toFlush);
+ DEBUGLOG(5, "toFlush: %u into %u ==> flushed: %u",
+ (unsigned)toFlush, (unsigned)(oend-op), (unsigned)flushed);
+ op += flushed;
+ zcs->outBuffFlushedSize += flushed;
+ if (toFlush!=flushed) {
+ /* flush not fully completed, presumably because dst is too small */
+ assert(op==oend);
+ someMoreWork = 0;
+ break;
+ }
+ zcs->outBuffContentSize = zcs->outBuffFlushedSize = 0;
+ if (zcs->frameEnded) {
+ DEBUGLOG(5, "Frame completed on flush");
+ someMoreWork = 0;
+ ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
+ break;
+ }
+ zcs->streamStage = zcss_load;
+ break;
+ }
+
+ default: /* impossible */
+ assert(0);
+ }
+ }
+
+ input->pos = ip - istart;
+ output->pos = op - ostart;
+ if (zcs->frameEnded) return 0;
+ return ZSTD_nextInputSizeHint(zcs);
+}
+
+static size_t ZSTD_nextInputSizeHint_MTorST(const ZSTD_CCtx* cctx)
+{
+#ifdef ZSTD_MULTITHREAD
+ if (cctx->appliedParams.nbWorkers >= 1) {
+ assert(cctx->mtctx != NULL);
+ return ZSTDMT_nextInputSizeHint(cctx->mtctx);
+ }
+#endif
+ return ZSTD_nextInputSizeHint(cctx);
+
+}
+
+size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
+{
+ CHECK_F( ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue) );
+ return ZSTD_nextInputSizeHint_MTorST(zcs);
+}
+
+
+size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
+ ZSTD_outBuffer* output,
+ ZSTD_inBuffer* input,
+ ZSTD_EndDirective endOp)
+{
+ DEBUGLOG(5, "ZSTD_compressStream2, endOp=%u ", (unsigned)endOp);
+ /* check conditions */
+ if (output->pos > output->size) return ERROR(GENERIC);
+ if (input->pos > input->size) return ERROR(GENERIC);
+ assert(cctx!=NULL);
+
+ /* transparent initialization stage */
+ if (cctx->streamStage == zcss_init) {
+ ZSTD_CCtx_params params = cctx->requestedParams;
+ ZSTD_prefixDict const prefixDict = cctx->prefixDict;
+ memset(&cctx->prefixDict, 0, sizeof(cctx->prefixDict)); /* single usage */
+ assert(prefixDict.dict==NULL || cctx->cdict==NULL); /* only one can be set */
+ DEBUGLOG(4, "ZSTD_compressStream2 : transparent init stage");
+ if (endOp == ZSTD_e_end) cctx->pledgedSrcSizePlusOne = input->size + 1; /* auto-fix pledgedSrcSize */
+ params.cParams = ZSTD_getCParamsFromCCtxParams(
+ &cctx->requestedParams, cctx->pledgedSrcSizePlusOne-1, 0 /*dictSize*/);
+
+
+#ifdef ZSTD_MULTITHREAD
+ if ((cctx->pledgedSrcSizePlusOne-1) <= ZSTDMT_JOBSIZE_MIN) {
+ params.nbWorkers = 0; /* do not invoke multi-threading when src size is too small */
+ }
+ if (params.nbWorkers > 0) {
+ /* mt context creation */
+ if (cctx->mtctx == NULL) {
+ DEBUGLOG(4, "ZSTD_compressStream2: creating new mtctx for nbWorkers=%u",
+ params.nbWorkers);
+ cctx->mtctx = ZSTDMT_createCCtx_advanced(params.nbWorkers, cctx->customMem);
+ if (cctx->mtctx == NULL) return ERROR(memory_allocation);
+ }
+ /* mt compression */
+ DEBUGLOG(4, "call ZSTDMT_initCStream_internal as nbWorkers=%u", params.nbWorkers);
+ CHECK_F( ZSTDMT_initCStream_internal(
+ cctx->mtctx,
+ prefixDict.dict, prefixDict.dictSize, ZSTD_dct_rawContent,
+ cctx->cdict, params, cctx->pledgedSrcSizePlusOne-1) );
+ cctx->streamStage = zcss_load;
+ cctx->appliedParams.nbWorkers = params.nbWorkers;
+ } else
+#endif
+ { CHECK_F( ZSTD_resetCStream_internal(cctx,
+ prefixDict.dict, prefixDict.dictSize, prefixDict.dictContentType,
+ cctx->cdict,
+ params, cctx->pledgedSrcSizePlusOne-1) );
+ assert(cctx->streamStage == zcss_load);
+ assert(cctx->appliedParams.nbWorkers == 0);
+ } }
+ /* end of transparent initialization stage */
+
+ /* compression stage */
+#ifdef ZSTD_MULTITHREAD
+ if (cctx->appliedParams.nbWorkers > 0) {
+ if (cctx->cParamsChanged) {
+ ZSTDMT_updateCParams_whileCompressing(cctx->mtctx, &cctx->requestedParams);
+ cctx->cParamsChanged = 0;
+ }
+ { size_t const flushMin = ZSTDMT_compressStream_generic(cctx->mtctx, output, input, endOp);
+ if ( ZSTD_isError(flushMin)
+ || (endOp == ZSTD_e_end && flushMin == 0) ) { /* compression completed */
+ ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
+ }
+ DEBUGLOG(5, "completed ZSTD_compressStream2 delegating to ZSTDMT_compressStream_generic");
+ return flushMin;
+ } }
+#endif
+ CHECK_F( ZSTD_compressStream_generic(cctx, output, input, endOp) );
+ DEBUGLOG(5, "completed ZSTD_compressStream2");
+ return cctx->outBuffContentSize - cctx->outBuffFlushedSize; /* remaining to flush */
+}
+
+size_t ZSTD_compressStream2_simpleArgs (
+ ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity, size_t* dstPos,
+ const void* src, size_t srcSize, size_t* srcPos,
+ ZSTD_EndDirective endOp)
+{
+ ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
+ ZSTD_inBuffer input = { src, srcSize, *srcPos };
+ /* ZSTD_compressStream2() will check validity of dstPos and srcPos */
+ size_t const cErr = ZSTD_compressStream2(cctx, &output, &input, endOp);
+ *dstPos = output.pos;
+ *srcPos = input.pos;
+ return cErr;
+}
+
+size_t ZSTD_compress2(ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize)
+{
+ ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
+ { size_t oPos = 0;
+ size_t iPos = 0;
+ size_t const result = ZSTD_compressStream2_simpleArgs(cctx,
+ dst, dstCapacity, &oPos,
+ src, srcSize, &iPos,
+ ZSTD_e_end);
+ if (ZSTD_isError(result)) return result;
+ if (result != 0) { /* compression not completed, due to lack of output space */
+ assert(oPos == dstCapacity);
+ return ERROR(dstSize_tooSmall);
+ }
+ assert(iPos == srcSize); /* all input is expected consumed */
+ return oPos;
+ }
+}
+
+/*====== Finalize ======*/
+
+/*! ZSTD_flushStream() :
+ * @return : amount of data remaining to flush */
+size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
+{
+ ZSTD_inBuffer input = { NULL, 0, 0 };
+ return ZSTD_compressStream2(zcs, output, &input, ZSTD_e_flush);
+}
+
+
+size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output)
+{
+ ZSTD_inBuffer input = { NULL, 0, 0 };
+ size_t const remainingToFlush = ZSTD_compressStream2(zcs, output, &input, ZSTD_e_end);
+ CHECK_F( remainingToFlush );
+ if (zcs->appliedParams.nbWorkers > 0) return remainingToFlush; /* minimal estimation */
+ /* single thread mode : attempt to calculate remaining to flush more precisely */
+ { size_t const lastBlockSize = zcs->frameEnded ? 0 : ZSTD_BLOCKHEADERSIZE;
+ size_t const checksumSize = zcs->frameEnded ? 0 : zcs->appliedParams.fParams.checksumFlag * 4;
+ size_t const toFlush = remainingToFlush + lastBlockSize + checksumSize;
+ DEBUGLOG(4, "ZSTD_endStream : remaining to flush : %u", (unsigned)toFlush);
+ return toFlush;
+ }
+}
+
+
+/*-===== Pre-defined compression levels =====-*/
+
+#define ZSTD_MAX_CLEVEL 22
+int ZSTD_maxCLevel(void) { return ZSTD_MAX_CLEVEL; }
+int ZSTD_minCLevel(void) { return (int)-ZSTD_TARGETLENGTH_MAX; }
+
+static const ZSTD_compressionParameters ZSTD_defaultCParameters[4][ZSTD_MAX_CLEVEL+1] = {
+{ /* "default" - guarantees a monotonically increasing memory budget */
+ /* W, C, H, S, L, TL, strat */
+ { 19, 12, 13, 1, 6, 1, ZSTD_fast }, /* base for negative levels */
+ { 19, 13, 14, 1, 7, 0, ZSTD_fast }, /* level 1 */
+ { 20, 15, 16, 1, 6, 0, ZSTD_fast }, /* level 2 */
+ { 21, 16, 17, 1, 5, 1, ZSTD_dfast }, /* level 3 */
+ { 21, 18, 18, 1, 5, 1, ZSTD_dfast }, /* level 4 */
+ { 21, 18, 19, 2, 5, 2, ZSTD_greedy }, /* level 5 */
+ { 21, 19, 19, 3, 5, 4, ZSTD_greedy }, /* level 6 */
+ { 21, 19, 19, 3, 5, 8, ZSTD_lazy }, /* level 7 */
+ { 21, 19, 19, 3, 5, 16, ZSTD_lazy2 }, /* level 8 */
+ { 21, 19, 20, 4, 5, 16, ZSTD_lazy2 }, /* level 9 */
+ { 22, 20, 21, 4, 5, 16, ZSTD_lazy2 }, /* level 10 */
+ { 22, 21, 22, 4, 5, 16, ZSTD_lazy2 }, /* level 11 */
+ { 22, 21, 22, 5, 5, 16, ZSTD_lazy2 }, /* level 12 */
+ { 22, 21, 22, 5, 5, 32, ZSTD_btlazy2 }, /* level 13 */
+ { 22, 22, 23, 5, 5, 32, ZSTD_btlazy2 }, /* level 14 */
+ { 22, 23, 23, 6, 5, 32, ZSTD_btlazy2 }, /* level 15 */
+ { 22, 22, 22, 5, 5, 48, ZSTD_btopt }, /* level 16 */
+ { 23, 23, 22, 5, 4, 64, ZSTD_btopt }, /* level 17 */
+ { 23, 23, 22, 6, 3, 64, ZSTD_btultra }, /* level 18 */
+ { 23, 24, 22, 7, 3,256, ZSTD_btultra2}, /* level 19 */
+ { 25, 25, 23, 7, 3,256, ZSTD_btultra2}, /* level 20 */
+ { 26, 26, 24, 7, 3,512, ZSTD_btultra2}, /* level 21 */
+ { 27, 27, 25, 9, 3,999, ZSTD_btultra2}, /* level 22 */
+},
+{ /* for srcSize <= 256 KB */
+ /* W, C, H, S, L, T, strat */
+ { 18, 12, 13, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
+ { 18, 13, 14, 1, 6, 0, ZSTD_fast }, /* level 1 */
+ { 18, 14, 14, 1, 5, 1, ZSTD_dfast }, /* level 2 */
+ { 18, 16, 16, 1, 4, 1, ZSTD_dfast }, /* level 3 */
+ { 18, 16, 17, 2, 5, 2, ZSTD_greedy }, /* level 4.*/
+ { 18, 18, 18, 3, 5, 2, ZSTD_greedy }, /* level 5.*/
+ { 18, 18, 19, 3, 5, 4, ZSTD_lazy }, /* level 6.*/
+ { 18, 18, 19, 4, 4, 4, ZSTD_lazy }, /* level 7 */
+ { 18, 18, 19, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
+ { 18, 18, 19, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
+ { 18, 18, 19, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
+ { 18, 18, 19, 5, 4, 12, ZSTD_btlazy2 }, /* level 11.*/
+ { 18, 19, 19, 7, 4, 12, ZSTD_btlazy2 }, /* level 12.*/
+ { 18, 18, 19, 4, 4, 16, ZSTD_btopt }, /* level 13 */
+ { 18, 18, 19, 4, 3, 32, ZSTD_btopt }, /* level 14.*/
+ { 18, 18, 19, 6, 3,128, ZSTD_btopt }, /* level 15.*/
+ { 18, 19, 19, 6, 3,128, ZSTD_btultra }, /* level 16.*/
+ { 18, 19, 19, 8, 3,256, ZSTD_btultra }, /* level 17.*/
+ { 18, 19, 19, 6, 3,128, ZSTD_btultra2}, /* level 18.*/
+ { 18, 19, 19, 8, 3,256, ZSTD_btultra2}, /* level 19.*/
+ { 18, 19, 19, 10, 3,512, ZSTD_btultra2}, /* level 20.*/
+ { 18, 19, 19, 12, 3,512, ZSTD_btultra2}, /* level 21.*/
+ { 18, 19, 19, 13, 3,999, ZSTD_btultra2}, /* level 22.*/
+},
+{ /* for srcSize <= 128 KB */
+ /* W, C, H, S, L, T, strat */
+ { 17, 12, 12, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
+ { 17, 12, 13, 1, 6, 0, ZSTD_fast }, /* level 1 */
+ { 17, 13, 15, 1, 5, 0, ZSTD_fast }, /* level 2 */
+ { 17, 15, 16, 2, 5, 1, ZSTD_dfast }, /* level 3 */
+ { 17, 17, 17, 2, 4, 1, ZSTD_dfast }, /* level 4 */
+ { 17, 16, 17, 3, 4, 2, ZSTD_greedy }, /* level 5 */
+ { 17, 17, 17, 3, 4, 4, ZSTD_lazy }, /* level 6 */
+ { 17, 17, 17, 3, 4, 8, ZSTD_lazy2 }, /* level 7 */
+ { 17, 17, 17, 4, 4, 8, ZSTD_lazy2 }, /* level 8 */
+ { 17, 17, 17, 5, 4, 8, ZSTD_lazy2 }, /* level 9 */
+ { 17, 17, 17, 6, 4, 8, ZSTD_lazy2 }, /* level 10 */
+ { 17, 17, 17, 5, 4, 8, ZSTD_btlazy2 }, /* level 11 */
+ { 17, 18, 17, 7, 4, 12, ZSTD_btlazy2 }, /* level 12 */
+ { 17, 18, 17, 3, 4, 12, ZSTD_btopt }, /* level 13.*/
+ { 17, 18, 17, 4, 3, 32, ZSTD_btopt }, /* level 14.*/
+ { 17, 18, 17, 6, 3,256, ZSTD_btopt }, /* level 15.*/
+ { 17, 18, 17, 6, 3,128, ZSTD_btultra }, /* level 16.*/
+ { 17, 18, 17, 8, 3,256, ZSTD_btultra }, /* level 17.*/
+ { 17, 18, 17, 10, 3,512, ZSTD_btultra }, /* level 18.*/
+ { 17, 18, 17, 5, 3,256, ZSTD_btultra2}, /* level 19.*/
+ { 17, 18, 17, 7, 3,512, ZSTD_btultra2}, /* level 20.*/
+ { 17, 18, 17, 9, 3,512, ZSTD_btultra2}, /* level 21.*/
+ { 17, 18, 17, 11, 3,999, ZSTD_btultra2}, /* level 22.*/
+},
+{ /* for srcSize <= 16 KB */
+ /* W, C, H, S, L, T, strat */
+ { 14, 12, 13, 1, 5, 1, ZSTD_fast }, /* base for negative levels */
+ { 14, 14, 15, 1, 5, 0, ZSTD_fast }, /* level 1 */
+ { 14, 14, 15, 1, 4, 0, ZSTD_fast }, /* level 2 */
+ { 14, 14, 15, 2, 4, 1, ZSTD_dfast }, /* level 3 */
+ { 14, 14, 14, 4, 4, 2, ZSTD_greedy }, /* level 4 */
+ { 14, 14, 14, 3, 4, 4, ZSTD_lazy }, /* level 5.*/
+ { 14, 14, 14, 4, 4, 8, ZSTD_lazy2 }, /* level 6 */
+ { 14, 14, 14, 6, 4, 8, ZSTD_lazy2 }, /* level 7 */
+ { 14, 14, 14, 8, 4, 8, ZSTD_lazy2 }, /* level 8.*/
+ { 14, 15, 14, 5, 4, 8, ZSTD_btlazy2 }, /* level 9.*/
+ { 14, 15, 14, 9, 4, 8, ZSTD_btlazy2 }, /* level 10.*/
+ { 14, 15, 14, 3, 4, 12, ZSTD_btopt }, /* level 11.*/
+ { 14, 15, 14, 4, 3, 24, ZSTD_btopt }, /* level 12.*/
+ { 14, 15, 14, 5, 3, 32, ZSTD_btultra }, /* level 13.*/
+ { 14, 15, 15, 6, 3, 64, ZSTD_btultra }, /* level 14.*/
+ { 14, 15, 15, 7, 3,256, ZSTD_btultra }, /* level 15.*/
+ { 14, 15, 15, 5, 3, 48, ZSTD_btultra2}, /* level 16.*/
+ { 14, 15, 15, 6, 3,128, ZSTD_btultra2}, /* level 17.*/
+ { 14, 15, 15, 7, 3,256, ZSTD_btultra2}, /* level 18.*/
+ { 14, 15, 15, 8, 3,256, ZSTD_btultra2}, /* level 19.*/
+ { 14, 15, 15, 8, 3,512, ZSTD_btultra2}, /* level 20.*/
+ { 14, 15, 15, 9, 3,512, ZSTD_btultra2}, /* level 21.*/
+ { 14, 15, 15, 10, 3,999, ZSTD_btultra2}, /* level 22.*/
+},
+};
+
+/*! ZSTD_getCParams() :
+* @return ZSTD_compressionParameters structure for a selected compression level, srcSize and dictSize.
+* Size values are optional, provide 0 if not known or unused */
+ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize)
+{
+ size_t const addedSize = srcSizeHint ? 0 : 500;
+ U64 const rSize = srcSizeHint+dictSize ? srcSizeHint+dictSize+addedSize : (U64)-1;
+ U32 const tableID = (rSize <= 256 KB) + (rSize <= 128 KB) + (rSize <= 16 KB); /* intentional underflow for srcSizeHint == 0 */
+ int row = compressionLevel;
+ DEBUGLOG(5, "ZSTD_getCParams (cLevel=%i)", compressionLevel);
+ if (compressionLevel == 0) row = ZSTD_CLEVEL_DEFAULT; /* 0 == default */
+ if (compressionLevel < 0) row = 0; /* entry 0 is baseline for fast mode */
+ if (compressionLevel > ZSTD_MAX_CLEVEL) row = ZSTD_MAX_CLEVEL;
+ { ZSTD_compressionParameters cp = ZSTD_defaultCParameters[tableID][row];
+ if (compressionLevel < 0) cp.targetLength = (unsigned)(-compressionLevel); /* acceleration factor */
+ return ZSTD_adjustCParams_internal(cp, srcSizeHint, dictSize);
+ }
+}
+
+/*! ZSTD_getParams() :
+* same as ZSTD_getCParams(), but @return a `ZSTD_parameters` object (instead of `ZSTD_compressionParameters`).
+* All fields of `ZSTD_frameParameters` are set to default (0) */
+ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long srcSizeHint, size_t dictSize) {
+ ZSTD_parameters params;
+ ZSTD_compressionParameters const cParams = ZSTD_getCParams(compressionLevel, srcSizeHint, dictSize);
+ DEBUGLOG(5, "ZSTD_getParams (cLevel=%i)", compressionLevel);
+ memset(&params, 0, sizeof(params));
+ params.cParams = cParams;
+ params.fParams.contentSizeFlag = 1;
+ return params;
+}
diff --git a/Utilities/cmzstd/lib/compress/zstd_compress_internal.h b/Utilities/cmzstd/lib/compress/zstd_compress_internal.h
new file mode 100644
index 000000000..29bca5985
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_compress_internal.h
@@ -0,0 +1,860 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+/* This header contains definitions
+ * that shall **only** be used by modules within lib/compress.
+ */
+
+#ifndef ZSTD_COMPRESS_H
+#define ZSTD_COMPRESS_H
+
+/*-*************************************
+* Dependencies
+***************************************/
+#include "zstd_internal.h"
+#ifdef ZSTD_MULTITHREAD
+# include "zstdmt_compress.h"
+#endif
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+
+/*-*************************************
+* Constants
+***************************************/
+#define kSearchStrength 8
+#define HASH_READ_SIZE 8
+#define ZSTD_DUBT_UNSORTED_MARK 1 /* For btlazy2 strategy, index 1 now means "unsorted".
+ It could be confused for a real successor at index "1", if sorted as larger than its predecessor.
+ It's not a big deal though : candidate will just be sorted again.
+ Additionnally, candidate position 1 will be lost.
+ But candidate 1 cannot hide a large tree of candidates, so it's a minimal loss.
+ The benefit is that ZSTD_DUBT_UNSORTED_MARK cannot be misdhandled after table re-use with a different strategy
+ Constant required by ZSTD_compressBlock_btlazy2() and ZSTD_reduceTable_internal() */
+
+
+/*-*************************************
+* Context memory management
+***************************************/
+typedef enum { ZSTDcs_created=0, ZSTDcs_init, ZSTDcs_ongoing, ZSTDcs_ending } ZSTD_compressionStage_e;
+typedef enum { zcss_init=0, zcss_load, zcss_flush } ZSTD_cStreamStage;
+
+typedef struct ZSTD_prefixDict_s {
+ const void* dict;
+ size_t dictSize;
+ ZSTD_dictContentType_e dictContentType;
+} ZSTD_prefixDict;
+
+typedef struct {
+ U32 CTable[HUF_CTABLE_SIZE_U32(255)];
+ HUF_repeat repeatMode;
+} ZSTD_hufCTables_t;
+
+typedef struct {
+ FSE_CTable offcodeCTable[FSE_CTABLE_SIZE_U32(OffFSELog, MaxOff)];
+ FSE_CTable matchlengthCTable[FSE_CTABLE_SIZE_U32(MLFSELog, MaxML)];
+ FSE_CTable litlengthCTable[FSE_CTABLE_SIZE_U32(LLFSELog, MaxLL)];
+ FSE_repeat offcode_repeatMode;
+ FSE_repeat matchlength_repeatMode;
+ FSE_repeat litlength_repeatMode;
+} ZSTD_fseCTables_t;
+
+typedef struct {
+ ZSTD_hufCTables_t huf;
+ ZSTD_fseCTables_t fse;
+} ZSTD_entropyCTables_t;
+
+typedef struct {
+ U32 off;
+ U32 len;
+} ZSTD_match_t;
+
+typedef struct {
+ int price;
+ U32 off;
+ U32 mlen;
+ U32 litlen;
+ U32 rep[ZSTD_REP_NUM];
+} ZSTD_optimal_t;
+
+typedef enum { zop_dynamic=0, zop_predef } ZSTD_OptPrice_e;
+
+typedef struct {
+ /* All tables are allocated inside cctx->workspace by ZSTD_resetCCtx_internal() */
+ unsigned* litFreq; /* table of literals statistics, of size 256 */
+ unsigned* litLengthFreq; /* table of litLength statistics, of size (MaxLL+1) */
+ unsigned* matchLengthFreq; /* table of matchLength statistics, of size (MaxML+1) */
+ unsigned* offCodeFreq; /* table of offCode statistics, of size (MaxOff+1) */
+ ZSTD_match_t* matchTable; /* list of found matches, of size ZSTD_OPT_NUM+1 */
+ ZSTD_optimal_t* priceTable; /* All positions tracked by optimal parser, of size ZSTD_OPT_NUM+1 */
+
+ U32 litSum; /* nb of literals */
+ U32 litLengthSum; /* nb of litLength codes */
+ U32 matchLengthSum; /* nb of matchLength codes */
+ U32 offCodeSum; /* nb of offset codes */
+ U32 litSumBasePrice; /* to compare to log2(litfreq) */
+ U32 litLengthSumBasePrice; /* to compare to log2(llfreq) */
+ U32 matchLengthSumBasePrice;/* to compare to log2(mlfreq) */
+ U32 offCodeSumBasePrice; /* to compare to log2(offreq) */
+ ZSTD_OptPrice_e priceType; /* prices can be determined dynamically, or follow a pre-defined cost structure */
+ const ZSTD_entropyCTables_t* symbolCosts; /* pre-calculated dictionary statistics */
+} optState_t;
+
+typedef struct {
+ ZSTD_entropyCTables_t entropy;
+ U32 rep[ZSTD_REP_NUM];
+} ZSTD_compressedBlockState_t;
+
+typedef struct {
+ BYTE const* nextSrc; /* next block here to continue on current prefix */
+ BYTE const* base; /* All regular indexes relative to this position */
+ BYTE const* dictBase; /* extDict indexes relative to this position */
+ U32 dictLimit; /* below that point, need extDict */
+ U32 lowLimit; /* below that point, no more data */
+} ZSTD_window_t;
+
+typedef struct ZSTD_matchState_t ZSTD_matchState_t;
+struct ZSTD_matchState_t {
+ ZSTD_window_t window; /* State for window round buffer management */
+ U32 loadedDictEnd; /* index of end of dictionary */
+ U32 nextToUpdate; /* index from which to continue table update */
+ U32 nextToUpdate3; /* index from which to continue table update */
+ U32 hashLog3; /* dispatch table : larger == faster, more memory */
+ U32* hashTable;
+ U32* hashTable3;
+ U32* chainTable;
+ optState_t opt; /* optimal parser state */
+ const ZSTD_matchState_t * dictMatchState;
+ ZSTD_compressionParameters cParams;
+};
+
+typedef struct {
+ ZSTD_compressedBlockState_t* prevCBlock;
+ ZSTD_compressedBlockState_t* nextCBlock;
+ ZSTD_matchState_t matchState;
+} ZSTD_blockState_t;
+
+typedef struct {
+ U32 offset;
+ U32 checksum;
+} ldmEntry_t;
+
+typedef struct {
+ ZSTD_window_t window; /* State for the window round buffer management */
+ ldmEntry_t* hashTable;
+ BYTE* bucketOffsets; /* Next position in bucket to insert entry */
+ U64 hashPower; /* Used to compute the rolling hash.
+ * Depends on ldmParams.minMatchLength */
+} ldmState_t;
+
+typedef struct {
+ U32 enableLdm; /* 1 if enable long distance matching */
+ U32 hashLog; /* Log size of hashTable */
+ U32 bucketSizeLog; /* Log bucket size for collision resolution, at most 8 */
+ U32 minMatchLength; /* Minimum match length */
+ U32 hashRateLog; /* Log number of entries to skip */
+ U32 windowLog; /* Window log for the LDM */
+} ldmParams_t;
+
+typedef struct {
+ U32 offset;
+ U32 litLength;
+ U32 matchLength;
+} rawSeq;
+
+typedef struct {
+ rawSeq* seq; /* The start of the sequences */
+ size_t pos; /* The position where reading stopped. <= size. */
+ size_t size; /* The number of sequences. <= capacity. */
+ size_t capacity; /* The capacity starting from `seq` pointer */
+} rawSeqStore_t;
+
+struct ZSTD_CCtx_params_s {
+ ZSTD_format_e format;
+ ZSTD_compressionParameters cParams;
+ ZSTD_frameParameters fParams;
+
+ int compressionLevel;
+ int forceWindow; /* force back-references to respect limit of
+ * 1<<wLog, even for dictionary */
+
+ ZSTD_dictAttachPref_e attachDictPref;
+
+ /* Multithreading: used to pass parameters to mtctx */
+ int nbWorkers;
+ size_t jobSize;
+ int overlapLog;
+ int rsyncable;
+
+ /* Long distance matching parameters */
+ ldmParams_t ldmParams;
+
+ /* Internal use, for createCCtxParams() and freeCCtxParams() only */
+ ZSTD_customMem customMem;
+}; /* typedef'd to ZSTD_CCtx_params within "zstd.h" */
+
+struct ZSTD_CCtx_s {
+ ZSTD_compressionStage_e stage;
+ int cParamsChanged; /* == 1 if cParams(except wlog) or compression level are changed in requestedParams. Triggers transmission of new params to ZSTDMT (if available) then reset to 0. */
+ int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */
+ ZSTD_CCtx_params requestedParams;
+ ZSTD_CCtx_params appliedParams;
+ U32 dictID;
+
+ int workSpaceOversizedDuration;
+ void* workSpace;
+ size_t workSpaceSize;
+ size_t blockSize;
+ unsigned long long pledgedSrcSizePlusOne; /* this way, 0 (default) == unknown */
+ unsigned long long consumedSrcSize;
+ unsigned long long producedCSize;
+ XXH64_state_t xxhState;
+ ZSTD_customMem customMem;
+ size_t staticSize;
+
+ seqStore_t seqStore; /* sequences storage ptrs */
+ ldmState_t ldmState; /* long distance matching state */
+ rawSeq* ldmSequences; /* Storage for the ldm output sequences */
+ size_t maxNbLdmSequences;
+ rawSeqStore_t externSeqStore; /* Mutable reference to external sequences */
+ ZSTD_blockState_t blockState;
+ U32* entropyWorkspace; /* entropy workspace of HUF_WORKSPACE_SIZE bytes */
+
+ /* streaming */
+ char* inBuff;
+ size_t inBuffSize;
+ size_t inToCompress;
+ size_t inBuffPos;
+ size_t inBuffTarget;
+ char* outBuff;
+ size_t outBuffSize;
+ size_t outBuffContentSize;
+ size_t outBuffFlushedSize;
+ ZSTD_cStreamStage streamStage;
+ U32 frameEnded;
+
+ /* Dictionary */
+ ZSTD_CDict* cdictLocal;
+ const ZSTD_CDict* cdict;
+ ZSTD_prefixDict prefixDict; /* single-usage dictionary */
+
+ /* Multi-threading */
+#ifdef ZSTD_MULTITHREAD
+ ZSTDMT_CCtx* mtctx;
+#endif
+};
+
+typedef enum { ZSTD_dtlm_fast, ZSTD_dtlm_full } ZSTD_dictTableLoadMethod_e;
+
+typedef enum { ZSTD_noDict = 0, ZSTD_extDict = 1, ZSTD_dictMatchState = 2 } ZSTD_dictMode_e;
+
+
+typedef size_t (*ZSTD_blockCompressor) (
+ ZSTD_matchState_t* bs, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+ZSTD_blockCompressor ZSTD_selectBlockCompressor(ZSTD_strategy strat, ZSTD_dictMode_e dictMode);
+
+
+MEM_STATIC U32 ZSTD_LLcode(U32 litLength)
+{
+ static const BYTE LL_Code[64] = { 0, 1, 2, 3, 4, 5, 6, 7,
+ 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 16, 17, 17, 18, 18, 19, 19,
+ 20, 20, 20, 20, 21, 21, 21, 21,
+ 22, 22, 22, 22, 22, 22, 22, 22,
+ 23, 23, 23, 23, 23, 23, 23, 23,
+ 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24 };
+ static const U32 LL_deltaCode = 19;
+ return (litLength > 63) ? ZSTD_highbit32(litLength) + LL_deltaCode : LL_Code[litLength];
+}
+
+/* ZSTD_MLcode() :
+ * note : mlBase = matchLength - MINMATCH;
+ * because it's the format it's stored in seqStore->sequences */
+MEM_STATIC U32 ZSTD_MLcode(U32 mlBase)
+{
+ static const BYTE ML_Code[128] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+ 32, 32, 33, 33, 34, 34, 35, 35, 36, 36, 36, 36, 37, 37, 37, 37,
+ 38, 38, 38, 38, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 39, 39,
+ 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40,
+ 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
+ 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
+ 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
+ static const U32 ML_deltaCode = 36;
+ return (mlBase > 127) ? ZSTD_highbit32(mlBase) + ML_deltaCode : ML_Code[mlBase];
+}
+
+/*! ZSTD_storeSeq() :
+ * Store a sequence (literal length, literals, offset code and match length code) into seqStore_t.
+ * `offsetCode` : distance to match + 3 (values 1-3 are repCodes).
+ * `mlBase` : matchLength - MINMATCH
+*/
+MEM_STATIC void ZSTD_storeSeq(seqStore_t* seqStorePtr, size_t litLength, const void* literals, U32 offsetCode, size_t mlBase)
+{
+#if defined(DEBUGLEVEL) && (DEBUGLEVEL >= 6)
+ static const BYTE* g_start = NULL;
+ if (g_start==NULL) g_start = (const BYTE*)literals; /* note : index only works for compression within a single segment */
+ { U32 const pos = (U32)((const BYTE*)literals - g_start);
+ DEBUGLOG(6, "Cpos%7u :%3u literals, match%4u bytes at offCode%7u",
+ pos, (U32)litLength, (U32)mlBase+MINMATCH, (U32)offsetCode);
+ }
+#endif
+ assert((size_t)(seqStorePtr->sequences - seqStorePtr->sequencesStart) < seqStorePtr->maxNbSeq);
+ /* copy Literals */
+ assert(seqStorePtr->maxNbLit <= 128 KB);
+ assert(seqStorePtr->lit + litLength <= seqStorePtr->litStart + seqStorePtr->maxNbLit);
+ ZSTD_wildcopy(seqStorePtr->lit, literals, litLength);
+ seqStorePtr->lit += litLength;
+
+ /* literal Length */
+ if (litLength>0xFFFF) {
+ assert(seqStorePtr->longLengthID == 0); /* there can only be a single long length */
+ seqStorePtr->longLengthID = 1;
+ seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
+ }
+ seqStorePtr->sequences[0].litLength = (U16)litLength;
+
+ /* match offset */
+ seqStorePtr->sequences[0].offset = offsetCode + 1;
+
+ /* match Length */
+ if (mlBase>0xFFFF) {
+ assert(seqStorePtr->longLengthID == 0); /* there can only be a single long length */
+ seqStorePtr->longLengthID = 2;
+ seqStorePtr->longLengthPos = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
+ }
+ seqStorePtr->sequences[0].matchLength = (U16)mlBase;
+
+ seqStorePtr->sequences++;
+}
+
+
+/*-*************************************
+* Match length counter
+***************************************/
+static unsigned ZSTD_NbCommonBytes (size_t val)
+{
+ if (MEM_isLittleEndian()) {
+ if (MEM_64bits()) {
+# if defined(_MSC_VER) && defined(_WIN64)
+ unsigned long r = 0;
+ _BitScanForward64( &r, (U64)val );
+ return (unsigned)(r>>3);
+# elif defined(__GNUC__) && (__GNUC__ >= 4)
+ return (__builtin_ctzll((U64)val) >> 3);
+# else
+ static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2,
+ 0, 3, 1, 3, 1, 4, 2, 7,
+ 0, 2, 3, 6, 1, 5, 3, 5,
+ 1, 3, 4, 4, 2, 5, 6, 7,
+ 7, 0, 1, 2, 3, 3, 4, 6,
+ 2, 6, 5, 5, 3, 4, 5, 6,
+ 7, 1, 2, 4, 6, 4, 4, 5,
+ 7, 2, 6, 5, 7, 6, 7, 7 };
+ return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
+# endif
+ } else { /* 32 bits */
+# if defined(_MSC_VER)
+ unsigned long r=0;
+ _BitScanForward( &r, (U32)val );
+ return (unsigned)(r>>3);
+# elif defined(__GNUC__) && (__GNUC__ >= 3)
+ return (__builtin_ctz((U32)val) >> 3);
+# else
+ static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0,
+ 3, 2, 2, 1, 3, 2, 0, 1,
+ 3, 3, 1, 2, 2, 2, 2, 0,
+ 3, 1, 2, 0, 1, 0, 1, 1 };
+ return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
+# endif
+ }
+ } else { /* Big Endian CPU */
+ if (MEM_64bits()) {
+# if defined(_MSC_VER) && defined(_WIN64)
+ unsigned long r = 0;
+ _BitScanReverse64( &r, val );
+ return (unsigned)(r>>3);
+# elif defined(__GNUC__) && (__GNUC__ >= 4)
+ return (__builtin_clzll(val) >> 3);
+# else
+ unsigned r;
+ const unsigned n32 = sizeof(size_t)*4; /* calculate this way due to compiler complaining in 32-bits mode */
+ if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }
+ if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
+ r += (!val);
+ return r;
+# endif
+ } else { /* 32 bits */
+# if defined(_MSC_VER)
+ unsigned long r = 0;
+ _BitScanReverse( &r, (unsigned long)val );
+ return (unsigned)(r>>3);
+# elif defined(__GNUC__) && (__GNUC__ >= 3)
+ return (__builtin_clz((U32)val) >> 3);
+# else
+ unsigned r;
+ if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
+ r += (!val);
+ return r;
+# endif
+ } }
+}
+
+
+MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* const pInLimit)
+{
+ const BYTE* const pStart = pIn;
+ const BYTE* const pInLoopLimit = pInLimit - (sizeof(size_t)-1);
+
+ if (pIn < pInLoopLimit) {
+ { size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
+ if (diff) return ZSTD_NbCommonBytes(diff); }
+ pIn+=sizeof(size_t); pMatch+=sizeof(size_t);
+ while (pIn < pInLoopLimit) {
+ size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
+ if (!diff) { pIn+=sizeof(size_t); pMatch+=sizeof(size_t); continue; }
+ pIn += ZSTD_NbCommonBytes(diff);
+ return (size_t)(pIn - pStart);
+ } }
+ if (MEM_64bits() && (pIn<(pInLimit-3)) && (MEM_read32(pMatch) == MEM_read32(pIn))) { pIn+=4; pMatch+=4; }
+ if ((pIn<(pInLimit-1)) && (MEM_read16(pMatch) == MEM_read16(pIn))) { pIn+=2; pMatch+=2; }
+ if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;
+ return (size_t)(pIn - pStart);
+}
+
+/** ZSTD_count_2segments() :
+ * can count match length with `ip` & `match` in 2 different segments.
+ * convention : on reaching mEnd, match count continue starting from iStart
+ */
+MEM_STATIC size_t
+ZSTD_count_2segments(const BYTE* ip, const BYTE* match,
+ const BYTE* iEnd, const BYTE* mEnd, const BYTE* iStart)
+{
+ const BYTE* const vEnd = MIN( ip + (mEnd - match), iEnd);
+ size_t const matchLength = ZSTD_count(ip, match, vEnd);
+ if (match + matchLength != mEnd) return matchLength;
+ DEBUGLOG(7, "ZSTD_count_2segments: found a 2-parts match (current length==%zu)", matchLength);
+ DEBUGLOG(7, "distance from match beginning to end dictionary = %zi", mEnd - match);
+ DEBUGLOG(7, "distance from current pos to end buffer = %zi", iEnd - ip);
+ DEBUGLOG(7, "next byte : ip==%02X, istart==%02X", ip[matchLength], *iStart);
+ DEBUGLOG(7, "final match length = %zu", matchLength + ZSTD_count(ip+matchLength, iStart, iEnd));
+ return matchLength + ZSTD_count(ip+matchLength, iStart, iEnd);
+}
+
+
+/*-*************************************
+ * Hashes
+ ***************************************/
+static const U32 prime3bytes = 506832829U;
+static U32 ZSTD_hash3(U32 u, U32 h) { return ((u << (32-24)) * prime3bytes) >> (32-h) ; }
+MEM_STATIC size_t ZSTD_hash3Ptr(const void* ptr, U32 h) { return ZSTD_hash3(MEM_readLE32(ptr), h); } /* only in zstd_opt.h */
+
+static const U32 prime4bytes = 2654435761U;
+static U32 ZSTD_hash4(U32 u, U32 h) { return (u * prime4bytes) >> (32-h) ; }
+static size_t ZSTD_hash4Ptr(const void* ptr, U32 h) { return ZSTD_hash4(MEM_read32(ptr), h); }
+
+static const U64 prime5bytes = 889523592379ULL;
+static size_t ZSTD_hash5(U64 u, U32 h) { return (size_t)(((u << (64-40)) * prime5bytes) >> (64-h)) ; }
+static size_t ZSTD_hash5Ptr(const void* p, U32 h) { return ZSTD_hash5(MEM_readLE64(p), h); }
+
+static const U64 prime6bytes = 227718039650203ULL;
+static size_t ZSTD_hash6(U64 u, U32 h) { return (size_t)(((u << (64-48)) * prime6bytes) >> (64-h)) ; }
+static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h); }
+
+static const U64 prime7bytes = 58295818150454627ULL;
+static size_t ZSTD_hash7(U64 u, U32 h) { return (size_t)(((u << (64-56)) * prime7bytes) >> (64-h)) ; }
+static size_t ZSTD_hash7Ptr(const void* p, U32 h) { return ZSTD_hash7(MEM_readLE64(p), h); }
+
+static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL;
+static size_t ZSTD_hash8(U64 u, U32 h) { return (size_t)(((u) * prime8bytes) >> (64-h)) ; }
+static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h); }
+
+MEM_STATIC size_t ZSTD_hashPtr(const void* p, U32 hBits, U32 mls)
+{
+ switch(mls)
+ {
+ default:
+ case 4: return ZSTD_hash4Ptr(p, hBits);
+ case 5: return ZSTD_hash5Ptr(p, hBits);
+ case 6: return ZSTD_hash6Ptr(p, hBits);
+ case 7: return ZSTD_hash7Ptr(p, hBits);
+ case 8: return ZSTD_hash8Ptr(p, hBits);
+ }
+}
+
+/** ZSTD_ipow() :
+ * Return base^exponent.
+ */
+static U64 ZSTD_ipow(U64 base, U64 exponent)
+{
+ U64 power = 1;
+ while (exponent) {
+ if (exponent & 1) power *= base;
+ exponent >>= 1;
+ base *= base;
+ }
+ return power;
+}
+
+#define ZSTD_ROLL_HASH_CHAR_OFFSET 10
+
+/** ZSTD_rollingHash_append() :
+ * Add the buffer to the hash value.
+ */
+static U64 ZSTD_rollingHash_append(U64 hash, void const* buf, size_t size)
+{
+ BYTE const* istart = (BYTE const*)buf;
+ size_t pos;
+ for (pos = 0; pos < size; ++pos) {
+ hash *= prime8bytes;
+ hash += istart[pos] + ZSTD_ROLL_HASH_CHAR_OFFSET;
+ }
+ return hash;
+}
+
+/** ZSTD_rollingHash_compute() :
+ * Compute the rolling hash value of the buffer.
+ */
+MEM_STATIC U64 ZSTD_rollingHash_compute(void const* buf, size_t size)
+{
+ return ZSTD_rollingHash_append(0, buf, size);
+}
+
+/** ZSTD_rollingHash_primePower() :
+ * Compute the primePower to be passed to ZSTD_rollingHash_rotate() for a hash
+ * over a window of length bytes.
+ */
+MEM_STATIC U64 ZSTD_rollingHash_primePower(U32 length)
+{
+ return ZSTD_ipow(prime8bytes, length - 1);
+}
+
+/** ZSTD_rollingHash_rotate() :
+ * Rotate the rolling hash by one byte.
+ */
+MEM_STATIC U64 ZSTD_rollingHash_rotate(U64 hash, BYTE toRemove, BYTE toAdd, U64 primePower)
+{
+ hash -= (toRemove + ZSTD_ROLL_HASH_CHAR_OFFSET) * primePower;
+ hash *= prime8bytes;
+ hash += toAdd + ZSTD_ROLL_HASH_CHAR_OFFSET;
+ return hash;
+}
+
+/*-*************************************
+* Round buffer management
+***************************************/
+/* Max current allowed */
+#define ZSTD_CURRENT_MAX ((3U << 29) + (1U << ZSTD_WINDOWLOG_MAX))
+/* Maximum chunk size before overflow correction needs to be called again */
+#define ZSTD_CHUNKSIZE_MAX \
+ ( ((U32)-1) /* Maximum ending current index */ \
+ - ZSTD_CURRENT_MAX) /* Maximum beginning lowLimit */
+
+/**
+ * ZSTD_window_clear():
+ * Clears the window containing the history by simply setting it to empty.
+ */
+MEM_STATIC void ZSTD_window_clear(ZSTD_window_t* window)
+{
+ size_t const endT = (size_t)(window->nextSrc - window->base);
+ U32 const end = (U32)endT;
+
+ window->lowLimit = end;
+ window->dictLimit = end;
+}
+
+/**
+ * ZSTD_window_hasExtDict():
+ * Returns non-zero if the window has a non-empty extDict.
+ */
+MEM_STATIC U32 ZSTD_window_hasExtDict(ZSTD_window_t const window)
+{
+ return window.lowLimit < window.dictLimit;
+}
+
+/**
+ * ZSTD_matchState_dictMode():
+ * Inspects the provided matchState and figures out what dictMode should be
+ * passed to the compressor.
+ */
+MEM_STATIC ZSTD_dictMode_e ZSTD_matchState_dictMode(const ZSTD_matchState_t *ms)
+{
+ return ZSTD_window_hasExtDict(ms->window) ?
+ ZSTD_extDict :
+ ms->dictMatchState != NULL ?
+ ZSTD_dictMatchState :
+ ZSTD_noDict;
+}
+
+/**
+ * ZSTD_window_needOverflowCorrection():
+ * Returns non-zero if the indices are getting too large and need overflow
+ * protection.
+ */
+MEM_STATIC U32 ZSTD_window_needOverflowCorrection(ZSTD_window_t const window,
+ void const* srcEnd)
+{
+ U32 const current = (U32)((BYTE const*)srcEnd - window.base);
+ return current > ZSTD_CURRENT_MAX;
+}
+
+/**
+ * ZSTD_window_correctOverflow():
+ * Reduces the indices to protect from index overflow.
+ * Returns the correction made to the indices, which must be applied to every
+ * stored index.
+ *
+ * The least significant cycleLog bits of the indices must remain the same,
+ * which may be 0. Every index up to maxDist in the past must be valid.
+ * NOTE: (maxDist & cycleMask) must be zero.
+ */
+MEM_STATIC U32 ZSTD_window_correctOverflow(ZSTD_window_t* window, U32 cycleLog,
+ U32 maxDist, void const* src)
+{
+ /* preemptive overflow correction:
+ * 1. correction is large enough:
+ * lowLimit > (3<<29) ==> current > 3<<29 + 1<<windowLog
+ * 1<<windowLog <= newCurrent < 1<<chainLog + 1<<windowLog
+ *
+ * current - newCurrent
+ * > (3<<29 + 1<<windowLog) - (1<<windowLog + 1<<chainLog)
+ * > (3<<29) - (1<<chainLog)
+ * > (3<<29) - (1<<30) (NOTE: chainLog <= 30)
+ * > 1<<29
+ *
+ * 2. (ip+ZSTD_CHUNKSIZE_MAX - cctx->base) doesn't overflow:
+ * After correction, current is less than (1<<chainLog + 1<<windowLog).
+ * In 64-bit mode we are safe, because we have 64-bit ptrdiff_t.
+ * In 32-bit mode we are safe, because (chainLog <= 29), so
+ * ip+ZSTD_CHUNKSIZE_MAX - cctx->base < 1<<32.
+ * 3. (cctx->lowLimit + 1<<windowLog) < 1<<32:
+ * windowLog <= 31 ==> 3<<29 + 1<<windowLog < 7<<29 < 1<<32.
+ */
+ U32 const cycleMask = (1U << cycleLog) - 1;
+ U32 const current = (U32)((BYTE const*)src - window->base);
+ U32 const newCurrent = (current & cycleMask) + maxDist;
+ U32 const correction = current - newCurrent;
+ assert((maxDist & cycleMask) == 0);
+ assert(current > newCurrent);
+ /* Loose bound, should be around 1<<29 (see above) */
+ assert(correction > 1<<28);
+
+ window->base += correction;
+ window->dictBase += correction;
+ window->lowLimit -= correction;
+ window->dictLimit -= correction;
+
+ DEBUGLOG(4, "Correction of 0x%x bytes to lowLimit=0x%x", correction,
+ window->lowLimit);
+ return correction;
+}
+
+/**
+ * ZSTD_window_enforceMaxDist():
+ * Updates lowLimit so that:
+ * (srcEnd - base) - lowLimit == maxDist + loadedDictEnd
+ *
+ * This allows a simple check that index >= lowLimit to see if index is valid.
+ * This must be called before a block compression call, with srcEnd as the block
+ * source end.
+ *
+ * If loadedDictEndPtr is not NULL, we set it to zero once we update lowLimit.
+ * This is because dictionaries are allowed to be referenced as long as the last
+ * byte of the dictionary is in the window, but once they are out of range,
+ * they cannot be referenced. If loadedDictEndPtr is NULL, we use
+ * loadedDictEnd == 0.
+ *
+ * In normal dict mode, the dict is between lowLimit and dictLimit. In
+ * dictMatchState mode, lowLimit and dictLimit are the same, and the dictionary
+ * is below them. forceWindow and dictMatchState are therefore incompatible.
+ */
+MEM_STATIC void
+ZSTD_window_enforceMaxDist(ZSTD_window_t* window,
+ void const* srcEnd,
+ U32 maxDist,
+ U32* loadedDictEndPtr,
+ const ZSTD_matchState_t** dictMatchStatePtr)
+{
+ U32 const blockEndIdx = (U32)((BYTE const*)srcEnd - window->base);
+ U32 loadedDictEnd = (loadedDictEndPtr != NULL) ? *loadedDictEndPtr : 0;
+ DEBUGLOG(5, "ZSTD_window_enforceMaxDist: blockEndIdx=%u, maxDist=%u",
+ (unsigned)blockEndIdx, (unsigned)maxDist);
+ if (blockEndIdx > maxDist + loadedDictEnd) {
+ U32 const newLowLimit = blockEndIdx - maxDist;
+ if (window->lowLimit < newLowLimit) window->lowLimit = newLowLimit;
+ if (window->dictLimit < window->lowLimit) {
+ DEBUGLOG(5, "Update dictLimit to match lowLimit, from %u to %u",
+ (unsigned)window->dictLimit, (unsigned)window->lowLimit);
+ window->dictLimit = window->lowLimit;
+ }
+ if (loadedDictEndPtr)
+ *loadedDictEndPtr = 0;
+ if (dictMatchStatePtr)
+ *dictMatchStatePtr = NULL;
+ }
+}
+
+/**
+ * ZSTD_window_update():
+ * Updates the window by appending [src, src + srcSize) to the window.
+ * If it is not contiguous, the current prefix becomes the extDict, and we
+ * forget about the extDict. Handles overlap of the prefix and extDict.
+ * Returns non-zero if the segment is contiguous.
+ */
+MEM_STATIC U32 ZSTD_window_update(ZSTD_window_t* window,
+ void const* src, size_t srcSize)
+{
+ BYTE const* const ip = (BYTE const*)src;
+ U32 contiguous = 1;
+ DEBUGLOG(5, "ZSTD_window_update");
+ /* Check if blocks follow each other */
+ if (src != window->nextSrc) {
+ /* not contiguous */
+ size_t const distanceFromBase = (size_t)(window->nextSrc - window->base);
+ DEBUGLOG(5, "Non contiguous blocks, new segment starts at %u", window->dictLimit);
+ window->lowLimit = window->dictLimit;
+ assert(distanceFromBase == (size_t)(U32)distanceFromBase); /* should never overflow */
+ window->dictLimit = (U32)distanceFromBase;
+ window->dictBase = window->base;
+ window->base = ip - distanceFromBase;
+ // ms->nextToUpdate = window->dictLimit;
+ if (window->dictLimit - window->lowLimit < HASH_READ_SIZE) window->lowLimit = window->dictLimit; /* too small extDict */
+ contiguous = 0;
+ }
+ window->nextSrc = ip + srcSize;
+ /* if input and dictionary overlap : reduce dictionary (area presumed modified by input) */
+ if ( (ip+srcSize > window->dictBase + window->lowLimit)
+ & (ip < window->dictBase + window->dictLimit)) {
+ ptrdiff_t const highInputIdx = (ip + srcSize) - window->dictBase;
+ U32 const lowLimitMax = (highInputIdx > (ptrdiff_t)window->dictLimit) ? window->dictLimit : (U32)highInputIdx;
+ window->lowLimit = lowLimitMax;
+ DEBUGLOG(5, "Overlapping extDict and input : new lowLimit = %u", window->lowLimit);
+ }
+ return contiguous;
+}
+
+
+/* debug functions */
+#if (DEBUGLEVEL>=2)
+
+MEM_STATIC double ZSTD_fWeight(U32 rawStat)
+{
+ U32 const fp_accuracy = 8;
+ U32 const fp_multiplier = (1 << fp_accuracy);
+ U32 const newStat = rawStat + 1;
+ U32 const hb = ZSTD_highbit32(newStat);
+ U32 const BWeight = hb * fp_multiplier;
+ U32 const FWeight = (newStat << fp_accuracy) >> hb;
+ U32 const weight = BWeight + FWeight;
+ assert(hb + fp_accuracy < 31);
+ return (double)weight / fp_multiplier;
+}
+
+/* display a table content,
+ * listing each element, its frequency, and its predicted bit cost */
+MEM_STATIC void ZSTD_debugTable(const U32* table, U32 max)
+{
+ unsigned u, sum;
+ for (u=0, sum=0; u<=max; u++) sum += table[u];
+ DEBUGLOG(2, "total nb elts: %u", sum);
+ for (u=0; u<=max; u++) {
+ DEBUGLOG(2, "%2u: %5u (%.2f)",
+ u, table[u], ZSTD_fWeight(sum) - ZSTD_fWeight(table[u]) );
+ }
+}
+
+#endif
+
+
+#if defined (__cplusplus)
+}
+#endif
+
+
+/* ==============================================================
+ * Private declarations
+ * These prototypes shall only be called from within lib/compress
+ * ============================================================== */
+
+/* ZSTD_getCParamsFromCCtxParams() :
+ * cParams are built depending on compressionLevel, src size hints,
+ * LDM and manually set compression parameters.
+ */
+ZSTD_compressionParameters ZSTD_getCParamsFromCCtxParams(
+ const ZSTD_CCtx_params* CCtxParams, U64 srcSizeHint, size_t dictSize);
+
+/*! ZSTD_initCStream_internal() :
+ * Private use only. Init streaming operation.
+ * expects params to be valid.
+ * must receive dict, or cdict, or none, but not both.
+ * @return : 0, or an error code */
+size_t ZSTD_initCStream_internal(ZSTD_CStream* zcs,
+ const void* dict, size_t dictSize,
+ const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params, unsigned long long pledgedSrcSize);
+
+void ZSTD_resetSeqStore(seqStore_t* ssPtr);
+
+/*! ZSTD_compressStream_generic() :
+ * Private use only. To be called from zstdmt_compress.c in single-thread mode. */
+size_t ZSTD_compressStream_generic(ZSTD_CStream* zcs,
+ ZSTD_outBuffer* output,
+ ZSTD_inBuffer* input,
+ ZSTD_EndDirective const flushMode);
+
+/*! ZSTD_getCParamsFromCDict() :
+ * as the name implies */
+ZSTD_compressionParameters ZSTD_getCParamsFromCDict(const ZSTD_CDict* cdict);
+
+/* ZSTD_compressBegin_advanced_internal() :
+ * Private use only. To be called from zstdmt_compress.c. */
+size_t ZSTD_compressBegin_advanced_internal(ZSTD_CCtx* cctx,
+ const void* dict, size_t dictSize,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_dictTableLoadMethod_e dtlm,
+ const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params,
+ unsigned long long pledgedSrcSize);
+
+/* ZSTD_compress_advanced_internal() :
+ * Private use only. To be called from zstdmt_compress.c. */
+size_t ZSTD_compress_advanced_internal(ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const void* dict,size_t dictSize,
+ ZSTD_CCtx_params params);
+
+
+/* ZSTD_writeLastEmptyBlock() :
+ * output an empty Block with end-of-frame mark to complete a frame
+ * @return : size of data written into `dst` (== ZSTD_blockHeaderSize (defined in zstd_internal.h))
+ * or an error code if `dstCapcity` is too small (<ZSTD_blockHeaderSize)
+ */
+size_t ZSTD_writeLastEmptyBlock(void* dst, size_t dstCapacity);
+
+
+/* ZSTD_referenceExternalSequences() :
+ * Must be called before starting a compression operation.
+ * seqs must parse a prefix of the source.
+ * This cannot be used when long range matching is enabled.
+ * Zstd will use these sequences, and pass the literals to a secondary block
+ * compressor.
+ * @return : An error code on failure.
+ * NOTE: seqs are not verified! Invalid sequences can cause out-of-bounds memory
+ * access and data corruption.
+ */
+size_t ZSTD_referenceExternalSequences(ZSTD_CCtx* cctx, rawSeq* seq, size_t nbSeq);
+
+
+#endif /* ZSTD_COMPRESS_H */
diff --git a/Utilities/cmzstd/lib/compress/zstd_double_fast.c b/Utilities/cmzstd/lib/compress/zstd_double_fast.c
new file mode 100644
index 000000000..47faf6d64
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_double_fast.c
@@ -0,0 +1,499 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#include "zstd_compress_internal.h"
+#include "zstd_double_fast.h"
+
+
+void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms,
+ void const* end, ZSTD_dictTableLoadMethod_e dtlm)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32* const hashLarge = ms->hashTable;
+ U32 const hBitsL = cParams->hashLog;
+ U32 const mls = cParams->minMatch;
+ U32* const hashSmall = ms->chainTable;
+ U32 const hBitsS = cParams->chainLog;
+ const BYTE* const base = ms->window.base;
+ const BYTE* ip = base + ms->nextToUpdate;
+ const BYTE* const iend = ((const BYTE*)end) - HASH_READ_SIZE;
+ const U32 fastHashFillStep = 3;
+
+ /* Always insert every fastHashFillStep position into the hash tables.
+ * Insert the other positions into the large hash table if their entry
+ * is empty.
+ */
+ for (; ip + fastHashFillStep - 1 <= iend; ip += fastHashFillStep) {
+ U32 const current = (U32)(ip - base);
+ U32 i;
+ for (i = 0; i < fastHashFillStep; ++i) {
+ size_t const smHash = ZSTD_hashPtr(ip + i, hBitsS, mls);
+ size_t const lgHash = ZSTD_hashPtr(ip + i, hBitsL, 8);
+ if (i == 0)
+ hashSmall[smHash] = current + i;
+ if (i == 0 || hashLarge[lgHash] == 0)
+ hashLarge[lgHash] = current + i;
+ /* Only load extra positions for ZSTD_dtlm_full */
+ if (dtlm == ZSTD_dtlm_fast)
+ break;
+ }
+ }
+}
+
+
+FORCE_INLINE_TEMPLATE
+size_t ZSTD_compressBlock_doubleFast_generic(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize,
+ U32 const mls /* template */, ZSTD_dictMode_e const dictMode)
+{
+ ZSTD_compressionParameters const* cParams = &ms->cParams;
+ U32* const hashLong = ms->hashTable;
+ const U32 hBitsL = cParams->hashLog;
+ U32* const hashSmall = ms->chainTable;
+ const U32 hBitsS = cParams->chainLog;
+ const BYTE* const base = ms->window.base;
+ const BYTE* const istart = (const BYTE*)src;
+ const BYTE* ip = istart;
+ const BYTE* anchor = istart;
+ const U32 prefixLowestIndex = ms->window.dictLimit;
+ const BYTE* const prefixLowest = base + prefixLowestIndex;
+ const BYTE* const iend = istart + srcSize;
+ const BYTE* const ilimit = iend - HASH_READ_SIZE;
+ U32 offset_1=rep[0], offset_2=rep[1];
+ U32 offsetSaved = 0;
+
+ const ZSTD_matchState_t* const dms = ms->dictMatchState;
+ const ZSTD_compressionParameters* const dictCParams =
+ dictMode == ZSTD_dictMatchState ?
+ &dms->cParams : NULL;
+ const U32* const dictHashLong = dictMode == ZSTD_dictMatchState ?
+ dms->hashTable : NULL;
+ const U32* const dictHashSmall = dictMode == ZSTD_dictMatchState ?
+ dms->chainTable : NULL;
+ const U32 dictStartIndex = dictMode == ZSTD_dictMatchState ?
+ dms->window.dictLimit : 0;
+ const BYTE* const dictBase = dictMode == ZSTD_dictMatchState ?
+ dms->window.base : NULL;
+ const BYTE* const dictStart = dictMode == ZSTD_dictMatchState ?
+ dictBase + dictStartIndex : NULL;
+ const BYTE* const dictEnd = dictMode == ZSTD_dictMatchState ?
+ dms->window.nextSrc : NULL;
+ const U32 dictIndexDelta = dictMode == ZSTD_dictMatchState ?
+ prefixLowestIndex - (U32)(dictEnd - dictBase) :
+ 0;
+ const U32 dictHBitsL = dictMode == ZSTD_dictMatchState ?
+ dictCParams->hashLog : hBitsL;
+ const U32 dictHBitsS = dictMode == ZSTD_dictMatchState ?
+ dictCParams->chainLog : hBitsS;
+ const U32 dictAndPrefixLength = (U32)(ip - prefixLowest + dictEnd - dictStart);
+
+ assert(dictMode == ZSTD_noDict || dictMode == ZSTD_dictMatchState);
+
+ /* init */
+ ip += (dictAndPrefixLength == 0);
+ if (dictMode == ZSTD_noDict) {
+ U32 const maxRep = (U32)(ip - prefixLowest);
+ if (offset_2 > maxRep) offsetSaved = offset_2, offset_2 = 0;
+ if (offset_1 > maxRep) offsetSaved = offset_1, offset_1 = 0;
+ }
+ if (dictMode == ZSTD_dictMatchState) {
+ /* dictMatchState repCode checks don't currently handle repCode == 0
+ * disabling. */
+ assert(offset_1 <= dictAndPrefixLength);
+ assert(offset_2 <= dictAndPrefixLength);
+ }
+
+ /* Main Search Loop */
+ while (ip < ilimit) { /* < instead of <=, because repcode check at (ip+1) */
+ size_t mLength;
+ U32 offset;
+ size_t const h2 = ZSTD_hashPtr(ip, hBitsL, 8);
+ size_t const h = ZSTD_hashPtr(ip, hBitsS, mls);
+ size_t const dictHL = ZSTD_hashPtr(ip, dictHBitsL, 8);
+ size_t const dictHS = ZSTD_hashPtr(ip, dictHBitsS, mls);
+ U32 const current = (U32)(ip-base);
+ U32 const matchIndexL = hashLong[h2];
+ U32 matchIndexS = hashSmall[h];
+ const BYTE* matchLong = base + matchIndexL;
+ const BYTE* match = base + matchIndexS;
+ const U32 repIndex = current + 1 - offset_1;
+ const BYTE* repMatch = (dictMode == ZSTD_dictMatchState
+ && repIndex < prefixLowestIndex) ?
+ dictBase + (repIndex - dictIndexDelta) :
+ base + repIndex;
+ hashLong[h2] = hashSmall[h] = current; /* update hash tables */
+
+ /* check dictMatchState repcode */
+ if (dictMode == ZSTD_dictMatchState
+ && ((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
+ && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
+ const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
+ mLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
+ ip++;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, 0, mLength-MINMATCH);
+ goto _match_stored;
+ }
+
+ /* check noDict repcode */
+ if ( dictMode == ZSTD_noDict
+ && ((offset_1 > 0) & (MEM_read32(ip+1-offset_1) == MEM_read32(ip+1)))) {
+ mLength = ZSTD_count(ip+1+4, ip+1+4-offset_1, iend) + 4;
+ ip++;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, 0, mLength-MINMATCH);
+ goto _match_stored;
+ }
+
+ if (matchIndexL > prefixLowestIndex) {
+ /* check prefix long match */
+ if (MEM_read64(matchLong) == MEM_read64(ip)) {
+ mLength = ZSTD_count(ip+8, matchLong+8, iend) + 8;
+ offset = (U32)(ip-matchLong);
+ while (((ip>anchor) & (matchLong>prefixLowest)) && (ip[-1] == matchLong[-1])) { ip--; matchLong--; mLength++; } /* catch up */
+ goto _match_found;
+ }
+ } else if (dictMode == ZSTD_dictMatchState) {
+ /* check dictMatchState long match */
+ U32 const dictMatchIndexL = dictHashLong[dictHL];
+ const BYTE* dictMatchL = dictBase + dictMatchIndexL;
+ assert(dictMatchL < dictEnd);
+
+ if (dictMatchL > dictStart && MEM_read64(dictMatchL) == MEM_read64(ip)) {
+ mLength = ZSTD_count_2segments(ip+8, dictMatchL+8, iend, dictEnd, prefixLowest) + 8;
+ offset = (U32)(current - dictMatchIndexL - dictIndexDelta);
+ while (((ip>anchor) & (dictMatchL>dictStart)) && (ip[-1] == dictMatchL[-1])) { ip--; dictMatchL--; mLength++; } /* catch up */
+ goto _match_found;
+ }
+ }
+
+ if (matchIndexS > prefixLowestIndex) {
+ /* check prefix short match */
+ if (MEM_read32(match) == MEM_read32(ip)) {
+ goto _search_next_long;
+ }
+ } else if (dictMode == ZSTD_dictMatchState) {
+ /* check dictMatchState short match */
+ U32 const dictMatchIndexS = dictHashSmall[dictHS];
+ match = dictBase + dictMatchIndexS;
+ matchIndexS = dictMatchIndexS + dictIndexDelta;
+
+ if (match > dictStart && MEM_read32(match) == MEM_read32(ip)) {
+ goto _search_next_long;
+ }
+ }
+
+ ip += ((ip-anchor) >> kSearchStrength) + 1;
+ continue;
+
+_search_next_long:
+
+ {
+ size_t const hl3 = ZSTD_hashPtr(ip+1, hBitsL, 8);
+ size_t const dictHLNext = ZSTD_hashPtr(ip+1, dictHBitsL, 8);
+ U32 const matchIndexL3 = hashLong[hl3];
+ const BYTE* matchL3 = base + matchIndexL3;
+ hashLong[hl3] = current + 1;
+
+ /* check prefix long +1 match */
+ if (matchIndexL3 > prefixLowestIndex) {
+ if (MEM_read64(matchL3) == MEM_read64(ip+1)) {
+ mLength = ZSTD_count(ip+9, matchL3+8, iend) + 8;
+ ip++;
+ offset = (U32)(ip-matchL3);
+ while (((ip>anchor) & (matchL3>prefixLowest)) && (ip[-1] == matchL3[-1])) { ip--; matchL3--; mLength++; } /* catch up */
+ goto _match_found;
+ }
+ } else if (dictMode == ZSTD_dictMatchState) {
+ /* check dict long +1 match */
+ U32 const dictMatchIndexL3 = dictHashLong[dictHLNext];
+ const BYTE* dictMatchL3 = dictBase + dictMatchIndexL3;
+ assert(dictMatchL3 < dictEnd);
+ if (dictMatchL3 > dictStart && MEM_read64(dictMatchL3) == MEM_read64(ip+1)) {
+ mLength = ZSTD_count_2segments(ip+1+8, dictMatchL3+8, iend, dictEnd, prefixLowest) + 8;
+ ip++;
+ offset = (U32)(current + 1 - dictMatchIndexL3 - dictIndexDelta);
+ while (((ip>anchor) & (dictMatchL3>dictStart)) && (ip[-1] == dictMatchL3[-1])) { ip--; dictMatchL3--; mLength++; } /* catch up */
+ goto _match_found;
+ }
+ }
+ }
+
+ /* if no long +1 match, explore the short match we found */
+ if (dictMode == ZSTD_dictMatchState && matchIndexS < prefixLowestIndex) {
+ mLength = ZSTD_count_2segments(ip+4, match+4, iend, dictEnd, prefixLowest) + 4;
+ offset = (U32)(current - matchIndexS);
+ while (((ip>anchor) & (match>dictStart)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */
+ } else {
+ mLength = ZSTD_count(ip+4, match+4, iend) + 4;
+ offset = (U32)(ip - match);
+ while (((ip>anchor) & (match>prefixLowest)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */
+ }
+
+ /* fall-through */
+
+_match_found:
+ offset_2 = offset_1;
+ offset_1 = offset;
+
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, offset + ZSTD_REP_MOVE, mLength-MINMATCH);
+
+_match_stored:
+ /* match found */
+ ip += mLength;
+ anchor = ip;
+
+ if (ip <= ilimit) {
+ /* Fill Table */
+ hashLong[ZSTD_hashPtr(base+current+2, hBitsL, 8)] =
+ hashSmall[ZSTD_hashPtr(base+current+2, hBitsS, mls)] = current+2; /* here because current+2 could be > iend-8 */
+ hashLong[ZSTD_hashPtr(ip-2, hBitsL, 8)] =
+ hashSmall[ZSTD_hashPtr(ip-2, hBitsS, mls)] = (U32)(ip-2-base);
+
+ /* check immediate repcode */
+ if (dictMode == ZSTD_dictMatchState) {
+ while (ip <= ilimit) {
+ U32 const current2 = (U32)(ip-base);
+ U32 const repIndex2 = current2 - offset_2;
+ const BYTE* repMatch2 = dictMode == ZSTD_dictMatchState
+ && repIndex2 < prefixLowestIndex ?
+ dictBase - dictIndexDelta + repIndex2 :
+ base + repIndex2;
+ if ( ((U32)((prefixLowestIndex-1) - (U32)repIndex2) >= 3 /* intentional overflow */)
+ && (MEM_read32(repMatch2) == MEM_read32(ip)) ) {
+ const BYTE* const repEnd2 = repIndex2 < prefixLowestIndex ? dictEnd : iend;
+ size_t const repLength2 = ZSTD_count_2segments(ip+4, repMatch2+4, iend, repEnd2, prefixLowest) + 4;
+ U32 tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; /* swap offset_2 <=> offset_1 */
+ ZSTD_storeSeq(seqStore, 0, anchor, 0, repLength2-MINMATCH);
+ hashSmall[ZSTD_hashPtr(ip, hBitsS, mls)] = current2;
+ hashLong[ZSTD_hashPtr(ip, hBitsL, 8)] = current2;
+ ip += repLength2;
+ anchor = ip;
+ continue;
+ }
+ break;
+ }
+ }
+
+ if (dictMode == ZSTD_noDict) {
+ while ( (ip <= ilimit)
+ && ( (offset_2>0)
+ & (MEM_read32(ip) == MEM_read32(ip - offset_2)) )) {
+ /* store sequence */
+ size_t const rLength = ZSTD_count(ip+4, ip+4-offset_2, iend) + 4;
+ U32 const tmpOff = offset_2; offset_2 = offset_1; offset_1 = tmpOff; /* swap offset_2 <=> offset_1 */
+ hashSmall[ZSTD_hashPtr(ip, hBitsS, mls)] = (U32)(ip-base);
+ hashLong[ZSTD_hashPtr(ip, hBitsL, 8)] = (U32)(ip-base);
+ ZSTD_storeSeq(seqStore, 0, anchor, 0, rLength-MINMATCH);
+ ip += rLength;
+ anchor = ip;
+ continue; /* faster when present ... (?) */
+ } } } }
+
+ /* save reps for next block */
+ rep[0] = offset_1 ? offset_1 : offsetSaved;
+ rep[1] = offset_2 ? offset_2 : offsetSaved;
+
+ /* Return the last literals size */
+ return iend - anchor;
+}
+
+
+size_t ZSTD_compressBlock_doubleFast(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ const U32 mls = ms->cParams.minMatch;
+ switch(mls)
+ {
+ default: /* includes case 3 */
+ case 4 :
+ return ZSTD_compressBlock_doubleFast_generic(ms, seqStore, rep, src, srcSize, 4, ZSTD_noDict);
+ case 5 :
+ return ZSTD_compressBlock_doubleFast_generic(ms, seqStore, rep, src, srcSize, 5, ZSTD_noDict);
+ case 6 :
+ return ZSTD_compressBlock_doubleFast_generic(ms, seqStore, rep, src, srcSize, 6, ZSTD_noDict);
+ case 7 :
+ return ZSTD_compressBlock_doubleFast_generic(ms, seqStore, rep, src, srcSize, 7, ZSTD_noDict);
+ }
+}
+
+
+size_t ZSTD_compressBlock_doubleFast_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ const U32 mls = ms->cParams.minMatch;
+ switch(mls)
+ {
+ default: /* includes case 3 */
+ case 4 :
+ return ZSTD_compressBlock_doubleFast_generic(ms, seqStore, rep, src, srcSize, 4, ZSTD_dictMatchState);
+ case 5 :
+ return ZSTD_compressBlock_doubleFast_generic(ms, seqStore, rep, src, srcSize, 5, ZSTD_dictMatchState);
+ case 6 :
+ return ZSTD_compressBlock_doubleFast_generic(ms, seqStore, rep, src, srcSize, 6, ZSTD_dictMatchState);
+ case 7 :
+ return ZSTD_compressBlock_doubleFast_generic(ms, seqStore, rep, src, srcSize, 7, ZSTD_dictMatchState);
+ }
+}
+
+
+static size_t ZSTD_compressBlock_doubleFast_extDict_generic(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize,
+ U32 const mls /* template */)
+{
+ ZSTD_compressionParameters const* cParams = &ms->cParams;
+ U32* const hashLong = ms->hashTable;
+ U32 const hBitsL = cParams->hashLog;
+ U32* const hashSmall = ms->chainTable;
+ U32 const hBitsS = cParams->chainLog;
+ const BYTE* const istart = (const BYTE*)src;
+ const BYTE* ip = istart;
+ const BYTE* anchor = istart;
+ const BYTE* const iend = istart + srcSize;
+ const BYTE* const ilimit = iend - 8;
+ const U32 prefixStartIndex = ms->window.dictLimit;
+ const BYTE* const base = ms->window.base;
+ const BYTE* const prefixStart = base + prefixStartIndex;
+ const U32 dictStartIndex = ms->window.lowLimit;
+ const BYTE* const dictBase = ms->window.dictBase;
+ const BYTE* const dictStart = dictBase + dictStartIndex;
+ const BYTE* const dictEnd = dictBase + prefixStartIndex;
+ U32 offset_1=rep[0], offset_2=rep[1];
+
+ DEBUGLOG(5, "ZSTD_compressBlock_doubleFast_extDict_generic (srcSize=%zu)", srcSize);
+
+ /* Search Loop */
+ while (ip < ilimit) { /* < instead of <=, because (ip+1) */
+ const size_t hSmall = ZSTD_hashPtr(ip, hBitsS, mls);
+ const U32 matchIndex = hashSmall[hSmall];
+ const BYTE* const matchBase = matchIndex < prefixStartIndex ? dictBase : base;
+ const BYTE* match = matchBase + matchIndex;
+
+ const size_t hLong = ZSTD_hashPtr(ip, hBitsL, 8);
+ const U32 matchLongIndex = hashLong[hLong];
+ const BYTE* const matchLongBase = matchLongIndex < prefixStartIndex ? dictBase : base;
+ const BYTE* matchLong = matchLongBase + matchLongIndex;
+
+ const U32 current = (U32)(ip-base);
+ const U32 repIndex = current + 1 - offset_1; /* offset_1 expected <= current +1 */
+ const BYTE* const repBase = repIndex < prefixStartIndex ? dictBase : base;
+ const BYTE* const repMatch = repBase + repIndex;
+ size_t mLength;
+ hashSmall[hSmall] = hashLong[hLong] = current; /* update hash table */
+
+ if ((((U32)((prefixStartIndex-1) - repIndex) >= 3) /* intentional underflow : ensure repIndex doesn't overlap dict + prefix */
+ & (repIndex > dictStartIndex))
+ && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
+ const BYTE* repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend;
+ mLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixStart) + 4;
+ ip++;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, 0, mLength-MINMATCH);
+ } else {
+ if ((matchLongIndex > dictStartIndex) && (MEM_read64(matchLong) == MEM_read64(ip))) {
+ const BYTE* const matchEnd = matchLongIndex < prefixStartIndex ? dictEnd : iend;
+ const BYTE* const lowMatchPtr = matchLongIndex < prefixStartIndex ? dictStart : prefixStart;
+ U32 offset;
+ mLength = ZSTD_count_2segments(ip+8, matchLong+8, iend, matchEnd, prefixStart) + 8;
+ offset = current - matchLongIndex;
+ while (((ip>anchor) & (matchLong>lowMatchPtr)) && (ip[-1] == matchLong[-1])) { ip--; matchLong--; mLength++; } /* catch up */
+ offset_2 = offset_1;
+ offset_1 = offset;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, offset + ZSTD_REP_MOVE, mLength-MINMATCH);
+
+ } else if ((matchIndex > dictStartIndex) && (MEM_read32(match) == MEM_read32(ip))) {
+ size_t const h3 = ZSTD_hashPtr(ip+1, hBitsL, 8);
+ U32 const matchIndex3 = hashLong[h3];
+ const BYTE* const match3Base = matchIndex3 < prefixStartIndex ? dictBase : base;
+ const BYTE* match3 = match3Base + matchIndex3;
+ U32 offset;
+ hashLong[h3] = current + 1;
+ if ( (matchIndex3 > dictStartIndex) && (MEM_read64(match3) == MEM_read64(ip+1)) ) {
+ const BYTE* const matchEnd = matchIndex3 < prefixStartIndex ? dictEnd : iend;
+ const BYTE* const lowMatchPtr = matchIndex3 < prefixStartIndex ? dictStart : prefixStart;
+ mLength = ZSTD_count_2segments(ip+9, match3+8, iend, matchEnd, prefixStart) + 8;
+ ip++;
+ offset = current+1 - matchIndex3;
+ while (((ip>anchor) & (match3>lowMatchPtr)) && (ip[-1] == match3[-1])) { ip--; match3--; mLength++; } /* catch up */
+ } else {
+ const BYTE* const matchEnd = matchIndex < prefixStartIndex ? dictEnd : iend;
+ const BYTE* const lowMatchPtr = matchIndex < prefixStartIndex ? dictStart : prefixStart;
+ mLength = ZSTD_count_2segments(ip+4, match+4, iend, matchEnd, prefixStart) + 4;
+ offset = current - matchIndex;
+ while (((ip>anchor) & (match>lowMatchPtr)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */
+ }
+ offset_2 = offset_1;
+ offset_1 = offset;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, offset + ZSTD_REP_MOVE, mLength-MINMATCH);
+
+ } else {
+ ip += ((ip-anchor) >> kSearchStrength) + 1;
+ continue;
+ } }
+
+ /* found a match : store it */
+ ip += mLength;
+ anchor = ip;
+
+ if (ip <= ilimit) {
+ /* Fill Table */
+ hashSmall[ZSTD_hashPtr(base+current+2, hBitsS, mls)] = current+2;
+ hashLong[ZSTD_hashPtr(base+current+2, hBitsL, 8)] = current+2;
+ hashSmall[ZSTD_hashPtr(ip-2, hBitsS, mls)] = (U32)(ip-2-base);
+ hashLong[ZSTD_hashPtr(ip-2, hBitsL, 8)] = (U32)(ip-2-base);
+ /* check immediate repcode */
+ while (ip <= ilimit) {
+ U32 const current2 = (U32)(ip-base);
+ U32 const repIndex2 = current2 - offset_2;
+ const BYTE* repMatch2 = repIndex2 < prefixStartIndex ? dictBase + repIndex2 : base + repIndex2;
+ if ( (((U32)((prefixStartIndex-1) - repIndex2) >= 3) /* intentional overflow : ensure repIndex2 doesn't overlap dict + prefix */
+ & (repIndex2 > dictStartIndex))
+ && (MEM_read32(repMatch2) == MEM_read32(ip)) ) {
+ const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend;
+ size_t const repLength2 = ZSTD_count_2segments(ip+4, repMatch2+4, iend, repEnd2, prefixStart) + 4;
+ U32 const tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; /* swap offset_2 <=> offset_1 */
+ ZSTD_storeSeq(seqStore, 0, anchor, 0, repLength2-MINMATCH);
+ hashSmall[ZSTD_hashPtr(ip, hBitsS, mls)] = current2;
+ hashLong[ZSTD_hashPtr(ip, hBitsL, 8)] = current2;
+ ip += repLength2;
+ anchor = ip;
+ continue;
+ }
+ break;
+ } } }
+
+ /* save reps for next block */
+ rep[0] = offset_1;
+ rep[1] = offset_2;
+
+ /* Return the last literals size */
+ return iend - anchor;
+}
+
+
+size_t ZSTD_compressBlock_doubleFast_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ U32 const mls = ms->cParams.minMatch;
+ switch(mls)
+ {
+ default: /* includes case 3 */
+ case 4 :
+ return ZSTD_compressBlock_doubleFast_extDict_generic(ms, seqStore, rep, src, srcSize, 4);
+ case 5 :
+ return ZSTD_compressBlock_doubleFast_extDict_generic(ms, seqStore, rep, src, srcSize, 5);
+ case 6 :
+ return ZSTD_compressBlock_doubleFast_extDict_generic(ms, seqStore, rep, src, srcSize, 6);
+ case 7 :
+ return ZSTD_compressBlock_doubleFast_extDict_generic(ms, seqStore, rep, src, srcSize, 7);
+ }
+}
diff --git a/Utilities/cmzstd/lib/compress/zstd_double_fast.h b/Utilities/cmzstd/lib/compress/zstd_double_fast.h
new file mode 100644
index 000000000..4fa31acfc
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_double_fast.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef ZSTD_DOUBLE_FAST_H
+#define ZSTD_DOUBLE_FAST_H
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#include "mem.h" /* U32 */
+#include "zstd_compress_internal.h" /* ZSTD_CCtx, size_t */
+
+void ZSTD_fillDoubleHashTable(ZSTD_matchState_t* ms,
+ void const* end, ZSTD_dictTableLoadMethod_e dtlm);
+size_t ZSTD_compressBlock_doubleFast(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_doubleFast_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_doubleFast_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* ZSTD_DOUBLE_FAST_H */
diff --git a/Utilities/cmzstd/lib/compress/zstd_fast.c b/Utilities/cmzstd/lib/compress/zstd_fast.c
new file mode 100644
index 000000000..40ba0f73e
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_fast.c
@@ -0,0 +1,391 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#include "zstd_compress_internal.h"
+#include "zstd_fast.h"
+
+
+void ZSTD_fillHashTable(ZSTD_matchState_t* ms,
+ void const* end, ZSTD_dictTableLoadMethod_e dtlm)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32* const hashTable = ms->hashTable;
+ U32 const hBits = cParams->hashLog;
+ U32 const mls = cParams->minMatch;
+ const BYTE* const base = ms->window.base;
+ const BYTE* ip = base + ms->nextToUpdate;
+ const BYTE* const iend = ((const BYTE*)end) - HASH_READ_SIZE;
+ const U32 fastHashFillStep = 3;
+
+ /* Always insert every fastHashFillStep position into the hash table.
+ * Insert the other positions if their hash entry is empty.
+ */
+ for ( ; ip + fastHashFillStep < iend + 2; ip += fastHashFillStep) {
+ U32 const current = (U32)(ip - base);
+ size_t const hash0 = ZSTD_hashPtr(ip, hBits, mls);
+ hashTable[hash0] = current;
+ if (dtlm == ZSTD_dtlm_fast) continue;
+ /* Only load extra positions for ZSTD_dtlm_full */
+ { U32 p;
+ for (p = 1; p < fastHashFillStep; ++p) {
+ size_t const hash = ZSTD_hashPtr(ip + p, hBits, mls);
+ if (hashTable[hash] == 0) { /* not yet filled */
+ hashTable[hash] = current + p;
+ } } } }
+}
+
+FORCE_INLINE_TEMPLATE
+size_t ZSTD_compressBlock_fast_generic(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize,
+ U32 const mls, ZSTD_dictMode_e const dictMode)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32* const hashTable = ms->hashTable;
+ U32 const hlog = cParams->hashLog;
+ /* support stepSize of 0 */
+ U32 const stepSize = cParams->targetLength + !(cParams->targetLength);
+ const BYTE* const base = ms->window.base;
+ const BYTE* const istart = (const BYTE*)src;
+ const BYTE* ip = istart;
+ const BYTE* anchor = istart;
+ const U32 prefixStartIndex = ms->window.dictLimit;
+ const BYTE* const prefixStart = base + prefixStartIndex;
+ const BYTE* const iend = istart + srcSize;
+ const BYTE* const ilimit = iend - HASH_READ_SIZE;
+ U32 offset_1=rep[0], offset_2=rep[1];
+ U32 offsetSaved = 0;
+
+ const ZSTD_matchState_t* const dms = ms->dictMatchState;
+ const ZSTD_compressionParameters* const dictCParams =
+ dictMode == ZSTD_dictMatchState ?
+ &dms->cParams : NULL;
+ const U32* const dictHashTable = dictMode == ZSTD_dictMatchState ?
+ dms->hashTable : NULL;
+ const U32 dictStartIndex = dictMode == ZSTD_dictMatchState ?
+ dms->window.dictLimit : 0;
+ const BYTE* const dictBase = dictMode == ZSTD_dictMatchState ?
+ dms->window.base : NULL;
+ const BYTE* const dictStart = dictMode == ZSTD_dictMatchState ?
+ dictBase + dictStartIndex : NULL;
+ const BYTE* const dictEnd = dictMode == ZSTD_dictMatchState ?
+ dms->window.nextSrc : NULL;
+ const U32 dictIndexDelta = dictMode == ZSTD_dictMatchState ?
+ prefixStartIndex - (U32)(dictEnd - dictBase) :
+ 0;
+ const U32 dictAndPrefixLength = (U32)(ip - prefixStart + dictEnd - dictStart);
+ const U32 dictHLog = dictMode == ZSTD_dictMatchState ?
+ dictCParams->hashLog : hlog;
+
+ assert(dictMode == ZSTD_noDict || dictMode == ZSTD_dictMatchState);
+
+ /* otherwise, we would get index underflow when translating a dict index
+ * into a local index */
+ assert(dictMode != ZSTD_dictMatchState
+ || prefixStartIndex >= (U32)(dictEnd - dictBase));
+
+ /* init */
+ ip += (dictAndPrefixLength == 0);
+ if (dictMode == ZSTD_noDict) {
+ U32 const maxRep = (U32)(ip - prefixStart);
+ if (offset_2 > maxRep) offsetSaved = offset_2, offset_2 = 0;
+ if (offset_1 > maxRep) offsetSaved = offset_1, offset_1 = 0;
+ }
+ if (dictMode == ZSTD_dictMatchState) {
+ /* dictMatchState repCode checks don't currently handle repCode == 0
+ * disabling. */
+ assert(offset_1 <= dictAndPrefixLength);
+ assert(offset_2 <= dictAndPrefixLength);
+ }
+
+ /* Main Search Loop */
+ while (ip < ilimit) { /* < instead of <=, because repcode check at (ip+1) */
+ size_t mLength;
+ size_t const h = ZSTD_hashPtr(ip, hlog, mls);
+ U32 const current = (U32)(ip-base);
+ U32 const matchIndex = hashTable[h];
+ const BYTE* match = base + matchIndex;
+ const U32 repIndex = current + 1 - offset_1;
+ const BYTE* repMatch = (dictMode == ZSTD_dictMatchState
+ && repIndex < prefixStartIndex) ?
+ dictBase + (repIndex - dictIndexDelta) :
+ base + repIndex;
+ hashTable[h] = current; /* update hash table */
+
+ if ( (dictMode == ZSTD_dictMatchState)
+ && ((U32)((prefixStartIndex-1) - repIndex) >= 3) /* intentional underflow : ensure repIndex isn't overlapping dict + prefix */
+ && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
+ const BYTE* const repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend;
+ mLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixStart) + 4;
+ ip++;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, 0, mLength-MINMATCH);
+ } else if ( dictMode == ZSTD_noDict
+ && ((offset_1 > 0) & (MEM_read32(ip+1-offset_1) == MEM_read32(ip+1)))) {
+ mLength = ZSTD_count(ip+1+4, ip+1+4-offset_1, iend) + 4;
+ ip++;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, 0, mLength-MINMATCH);
+ } else if ( (matchIndex <= prefixStartIndex) ) {
+ if (dictMode == ZSTD_dictMatchState) {
+ size_t const dictHash = ZSTD_hashPtr(ip, dictHLog, mls);
+ U32 const dictMatchIndex = dictHashTable[dictHash];
+ const BYTE* dictMatch = dictBase + dictMatchIndex;
+ if (dictMatchIndex <= dictStartIndex ||
+ MEM_read32(dictMatch) != MEM_read32(ip)) {
+ assert(stepSize >= 1);
+ ip += ((ip-anchor) >> kSearchStrength) + stepSize;
+ continue;
+ } else {
+ /* found a dict match */
+ U32 const offset = (U32)(current-dictMatchIndex-dictIndexDelta);
+ mLength = ZSTD_count_2segments(ip+4, dictMatch+4, iend, dictEnd, prefixStart) + 4;
+ while (((ip>anchor) & (dictMatch>dictStart))
+ && (ip[-1] == dictMatch[-1])) {
+ ip--; dictMatch--; mLength++;
+ } /* catch up */
+ offset_2 = offset_1;
+ offset_1 = offset;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, offset + ZSTD_REP_MOVE, mLength-MINMATCH);
+ }
+ } else {
+ assert(stepSize >= 1);
+ ip += ((ip-anchor) >> kSearchStrength) + stepSize;
+ continue;
+ }
+ } else if (MEM_read32(match) != MEM_read32(ip)) {
+ /* it's not a match, and we're not going to check the dictionary */
+ assert(stepSize >= 1);
+ ip += ((ip-anchor) >> kSearchStrength) + stepSize;
+ continue;
+ } else {
+ /* found a regular match */
+ U32 const offset = (U32)(ip-match);
+ mLength = ZSTD_count(ip+4, match+4, iend) + 4;
+ while (((ip>anchor) & (match>prefixStart))
+ && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */
+ offset_2 = offset_1;
+ offset_1 = offset;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, offset + ZSTD_REP_MOVE, mLength-MINMATCH);
+ }
+
+ /* match found */
+ ip += mLength;
+ anchor = ip;
+
+ if (ip <= ilimit) {
+ /* Fill Table */
+ assert(base+current+2 > istart); /* check base overflow */
+ hashTable[ZSTD_hashPtr(base+current+2, hlog, mls)] = current+2; /* here because current+2 could be > iend-8 */
+ hashTable[ZSTD_hashPtr(ip-2, hlog, mls)] = (U32)(ip-2-base);
+
+ /* check immediate repcode */
+ if (dictMode == ZSTD_dictMatchState) {
+ while (ip <= ilimit) {
+ U32 const current2 = (U32)(ip-base);
+ U32 const repIndex2 = current2 - offset_2;
+ const BYTE* repMatch2 = repIndex2 < prefixStartIndex ?
+ dictBase - dictIndexDelta + repIndex2 :
+ base + repIndex2;
+ if ( ((U32)((prefixStartIndex-1) - (U32)repIndex2) >= 3 /* intentional overflow */)
+ && (MEM_read32(repMatch2) == MEM_read32(ip)) ) {
+ const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend;
+ size_t const repLength2 = ZSTD_count_2segments(ip+4, repMatch2+4, iend, repEnd2, prefixStart) + 4;
+ U32 tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; /* swap offset_2 <=> offset_1 */
+ ZSTD_storeSeq(seqStore, 0, anchor, 0, repLength2-MINMATCH);
+ hashTable[ZSTD_hashPtr(ip, hlog, mls)] = current2;
+ ip += repLength2;
+ anchor = ip;
+ continue;
+ }
+ break;
+ }
+ }
+
+ if (dictMode == ZSTD_noDict) {
+ while ( (ip <= ilimit)
+ && ( (offset_2>0)
+ & (MEM_read32(ip) == MEM_read32(ip - offset_2)) )) {
+ /* store sequence */
+ size_t const rLength = ZSTD_count(ip+4, ip+4-offset_2, iend) + 4;
+ U32 const tmpOff = offset_2; offset_2 = offset_1; offset_1 = tmpOff; /* swap offset_2 <=> offset_1 */
+ hashTable[ZSTD_hashPtr(ip, hlog, mls)] = (U32)(ip-base);
+ ZSTD_storeSeq(seqStore, 0, anchor, 0, rLength-MINMATCH);
+ ip += rLength;
+ anchor = ip;
+ continue; /* faster when present ... (?) */
+ } } } }
+
+ /* save reps for next block */
+ rep[0] = offset_1 ? offset_1 : offsetSaved;
+ rep[1] = offset_2 ? offset_2 : offsetSaved;
+
+ /* Return the last literals size */
+ return iend - anchor;
+}
+
+
+size_t ZSTD_compressBlock_fast(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ ZSTD_compressionParameters const* cParams = &ms->cParams;
+ U32 const mls = cParams->minMatch;
+ assert(ms->dictMatchState == NULL);
+ switch(mls)
+ {
+ default: /* includes case 3 */
+ case 4 :
+ return ZSTD_compressBlock_fast_generic(ms, seqStore, rep, src, srcSize, 4, ZSTD_noDict);
+ case 5 :
+ return ZSTD_compressBlock_fast_generic(ms, seqStore, rep, src, srcSize, 5, ZSTD_noDict);
+ case 6 :
+ return ZSTD_compressBlock_fast_generic(ms, seqStore, rep, src, srcSize, 6, ZSTD_noDict);
+ case 7 :
+ return ZSTD_compressBlock_fast_generic(ms, seqStore, rep, src, srcSize, 7, ZSTD_noDict);
+ }
+}
+
+size_t ZSTD_compressBlock_fast_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ ZSTD_compressionParameters const* cParams = &ms->cParams;
+ U32 const mls = cParams->minMatch;
+ assert(ms->dictMatchState != NULL);
+ switch(mls)
+ {
+ default: /* includes case 3 */
+ case 4 :
+ return ZSTD_compressBlock_fast_generic(ms, seqStore, rep, src, srcSize, 4, ZSTD_dictMatchState);
+ case 5 :
+ return ZSTD_compressBlock_fast_generic(ms, seqStore, rep, src, srcSize, 5, ZSTD_dictMatchState);
+ case 6 :
+ return ZSTD_compressBlock_fast_generic(ms, seqStore, rep, src, srcSize, 6, ZSTD_dictMatchState);
+ case 7 :
+ return ZSTD_compressBlock_fast_generic(ms, seqStore, rep, src, srcSize, 7, ZSTD_dictMatchState);
+ }
+}
+
+
+static size_t ZSTD_compressBlock_fast_extDict_generic(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize, U32 const mls)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32* const hashTable = ms->hashTable;
+ U32 const hlog = cParams->hashLog;
+ /* support stepSize of 0 */
+ U32 const stepSize = cParams->targetLength + !(cParams->targetLength);
+ const BYTE* const base = ms->window.base;
+ const BYTE* const dictBase = ms->window.dictBase;
+ const BYTE* const istart = (const BYTE*)src;
+ const BYTE* ip = istart;
+ const BYTE* anchor = istart;
+ const U32 dictStartIndex = ms->window.lowLimit;
+ const BYTE* const dictStart = dictBase + dictStartIndex;
+ const U32 prefixStartIndex = ms->window.dictLimit;
+ const BYTE* const prefixStart = base + prefixStartIndex;
+ const BYTE* const dictEnd = dictBase + prefixStartIndex;
+ const BYTE* const iend = istart + srcSize;
+ const BYTE* const ilimit = iend - 8;
+ U32 offset_1=rep[0], offset_2=rep[1];
+
+ /* Search Loop */
+ while (ip < ilimit) { /* < instead of <=, because (ip+1) */
+ const size_t h = ZSTD_hashPtr(ip, hlog, mls);
+ const U32 matchIndex = hashTable[h];
+ const BYTE* const matchBase = matchIndex < prefixStartIndex ? dictBase : base;
+ const BYTE* match = matchBase + matchIndex;
+ const U32 current = (U32)(ip-base);
+ const U32 repIndex = current + 1 - offset_1;
+ const BYTE* const repBase = repIndex < prefixStartIndex ? dictBase : base;
+ const BYTE* const repMatch = repBase + repIndex;
+ size_t mLength;
+ hashTable[h] = current; /* update hash table */
+ assert(offset_1 <= current +1); /* check repIndex */
+
+ if ( (((U32)((prefixStartIndex-1) - repIndex) >= 3) /* intentional underflow */ & (repIndex > dictStartIndex))
+ && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
+ const BYTE* repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend;
+ mLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixStart) + 4;
+ ip++;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, 0, mLength-MINMATCH);
+ } else {
+ if ( (matchIndex < dictStartIndex) ||
+ (MEM_read32(match) != MEM_read32(ip)) ) {
+ assert(stepSize >= 1);
+ ip += ((ip-anchor) >> kSearchStrength) + stepSize;
+ continue;
+ }
+ { const BYTE* matchEnd = matchIndex < prefixStartIndex ? dictEnd : iend;
+ const BYTE* lowMatchPtr = matchIndex < prefixStartIndex ? dictStart : prefixStart;
+ U32 offset;
+ mLength = ZSTD_count_2segments(ip+4, match+4, iend, matchEnd, prefixStart) + 4;
+ while (((ip>anchor) & (match>lowMatchPtr)) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } /* catch up */
+ offset = current - matchIndex;
+ offset_2 = offset_1;
+ offset_1 = offset;
+ ZSTD_storeSeq(seqStore, ip-anchor, anchor, offset + ZSTD_REP_MOVE, mLength-MINMATCH);
+ } }
+
+ /* found a match : store it */
+ ip += mLength;
+ anchor = ip;
+
+ if (ip <= ilimit) {
+ /* Fill Table */
+ hashTable[ZSTD_hashPtr(base+current+2, hlog, mls)] = current+2;
+ hashTable[ZSTD_hashPtr(ip-2, hlog, mls)] = (U32)(ip-2-base);
+ /* check immediate repcode */
+ while (ip <= ilimit) {
+ U32 const current2 = (U32)(ip-base);
+ U32 const repIndex2 = current2 - offset_2;
+ const BYTE* repMatch2 = repIndex2 < prefixStartIndex ? dictBase + repIndex2 : base + repIndex2;
+ if ( (((U32)((prefixStartIndex-1) - repIndex2) >= 3) & (repIndex2 > dictStartIndex)) /* intentional overflow */
+ && (MEM_read32(repMatch2) == MEM_read32(ip)) ) {
+ const BYTE* const repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend;
+ size_t const repLength2 = ZSTD_count_2segments(ip+4, repMatch2+4, iend, repEnd2, prefixStart) + 4;
+ U32 tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; /* swap offset_2 <=> offset_1 */
+ ZSTD_storeSeq(seqStore, 0, anchor, 0, repLength2-MINMATCH);
+ hashTable[ZSTD_hashPtr(ip, hlog, mls)] = current2;
+ ip += repLength2;
+ anchor = ip;
+ continue;
+ }
+ break;
+ } } }
+
+ /* save reps for next block */
+ rep[0] = offset_1;
+ rep[1] = offset_2;
+
+ /* Return the last literals size */
+ return iend - anchor;
+}
+
+
+size_t ZSTD_compressBlock_fast_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ ZSTD_compressionParameters const* cParams = &ms->cParams;
+ U32 const mls = cParams->minMatch;
+ switch(mls)
+ {
+ default: /* includes case 3 */
+ case 4 :
+ return ZSTD_compressBlock_fast_extDict_generic(ms, seqStore, rep, src, srcSize, 4);
+ case 5 :
+ return ZSTD_compressBlock_fast_extDict_generic(ms, seqStore, rep, src, srcSize, 5);
+ case 6 :
+ return ZSTD_compressBlock_fast_extDict_generic(ms, seqStore, rep, src, srcSize, 6);
+ case 7 :
+ return ZSTD_compressBlock_fast_extDict_generic(ms, seqStore, rep, src, srcSize, 7);
+ }
+}
diff --git a/Utilities/cmzstd/lib/compress/zstd_fast.h b/Utilities/cmzstd/lib/compress/zstd_fast.h
new file mode 100644
index 000000000..b74a88c57
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_fast.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef ZSTD_FAST_H
+#define ZSTD_FAST_H
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#include "mem.h" /* U32 */
+#include "zstd_compress_internal.h"
+
+void ZSTD_fillHashTable(ZSTD_matchState_t* ms,
+ void const* end, ZSTD_dictTableLoadMethod_e dtlm);
+size_t ZSTD_compressBlock_fast(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_fast_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_fast_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* ZSTD_FAST_H */
diff --git a/Utilities/cmzstd/lib/compress/zstd_lazy.c b/Utilities/cmzstd/lib/compress/zstd_lazy.c
new file mode 100644
index 000000000..53f998a43
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_lazy.c
@@ -0,0 +1,1106 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#include "zstd_compress_internal.h"
+#include "zstd_lazy.h"
+
+
+/*-*************************************
+* Binary Tree search
+***************************************/
+
+static void
+ZSTD_updateDUBT(ZSTD_matchState_t* ms,
+ const BYTE* ip, const BYTE* iend,
+ U32 mls)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32* const hashTable = ms->hashTable;
+ U32 const hashLog = cParams->hashLog;
+
+ U32* const bt = ms->chainTable;
+ U32 const btLog = cParams->chainLog - 1;
+ U32 const btMask = (1 << btLog) - 1;
+
+ const BYTE* const base = ms->window.base;
+ U32 const target = (U32)(ip - base);
+ U32 idx = ms->nextToUpdate;
+
+ if (idx != target)
+ DEBUGLOG(7, "ZSTD_updateDUBT, from %u to %u (dictLimit:%u)",
+ idx, target, ms->window.dictLimit);
+ assert(ip + 8 <= iend); /* condition for ZSTD_hashPtr */
+ (void)iend;
+
+ assert(idx >= ms->window.dictLimit); /* condition for valid base+idx */
+ for ( ; idx < target ; idx++) {
+ size_t const h = ZSTD_hashPtr(base + idx, hashLog, mls); /* assumption : ip + 8 <= iend */
+ U32 const matchIndex = hashTable[h];
+
+ U32* const nextCandidatePtr = bt + 2*(idx&btMask);
+ U32* const sortMarkPtr = nextCandidatePtr + 1;
+
+ DEBUGLOG(8, "ZSTD_updateDUBT: insert %u", idx);
+ hashTable[h] = idx; /* Update Hash Table */
+ *nextCandidatePtr = matchIndex; /* update BT like a chain */
+ *sortMarkPtr = ZSTD_DUBT_UNSORTED_MARK;
+ }
+ ms->nextToUpdate = target;
+}
+
+
+/** ZSTD_insertDUBT1() :
+ * sort one already inserted but unsorted position
+ * assumption : current >= btlow == (current - btmask)
+ * doesn't fail */
+static void
+ZSTD_insertDUBT1(ZSTD_matchState_t* ms,
+ U32 current, const BYTE* inputEnd,
+ U32 nbCompares, U32 btLow,
+ const ZSTD_dictMode_e dictMode)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32* const bt = ms->chainTable;
+ U32 const btLog = cParams->chainLog - 1;
+ U32 const btMask = (1 << btLog) - 1;
+ size_t commonLengthSmaller=0, commonLengthLarger=0;
+ const BYTE* const base = ms->window.base;
+ const BYTE* const dictBase = ms->window.dictBase;
+ const U32 dictLimit = ms->window.dictLimit;
+ const BYTE* const ip = (current>=dictLimit) ? base + current : dictBase + current;
+ const BYTE* const iend = (current>=dictLimit) ? inputEnd : dictBase + dictLimit;
+ const BYTE* const dictEnd = dictBase + dictLimit;
+ const BYTE* const prefixStart = base + dictLimit;
+ const BYTE* match;
+ U32* smallerPtr = bt + 2*(current&btMask);
+ U32* largerPtr = smallerPtr + 1;
+ U32 matchIndex = *smallerPtr; /* this candidate is unsorted : next sorted candidate is reached through *smallerPtr, while *largerPtr contains previous unsorted candidate (which is already saved and can be overwritten) */
+ U32 dummy32; /* to be nullified at the end */
+ U32 const windowLow = ms->window.lowLimit;
+
+ DEBUGLOG(8, "ZSTD_insertDUBT1(%u) (dictLimit=%u, lowLimit=%u)",
+ current, dictLimit, windowLow);
+ assert(current >= btLow);
+ assert(ip < iend); /* condition for ZSTD_count */
+
+ while (nbCompares-- && (matchIndex > windowLow)) {
+ U32* const nextPtr = bt + 2*(matchIndex & btMask);
+ size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
+ assert(matchIndex < current);
+ /* note : all candidates are now supposed sorted,
+ * but it's still possible to have nextPtr[1] == ZSTD_DUBT_UNSORTED_MARK
+ * when a real index has the same value as ZSTD_DUBT_UNSORTED_MARK */
+
+ if ( (dictMode != ZSTD_extDict)
+ || (matchIndex+matchLength >= dictLimit) /* both in current segment*/
+ || (current < dictLimit) /* both in extDict */) {
+ const BYTE* const mBase = ( (dictMode != ZSTD_extDict)
+ || (matchIndex+matchLength >= dictLimit)) ?
+ base : dictBase;
+ assert( (matchIndex+matchLength >= dictLimit) /* might be wrong if extDict is incorrectly set to 0 */
+ || (current < dictLimit) );
+ match = mBase + matchIndex;
+ matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
+ } else {
+ match = dictBase + matchIndex;
+ matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
+ if (matchIndex+matchLength >= dictLimit)
+ match = base + matchIndex; /* preparation for next read of match[matchLength] */
+ }
+
+ DEBUGLOG(8, "ZSTD_insertDUBT1: comparing %u with %u : found %u common bytes ",
+ current, matchIndex, (U32)matchLength);
+
+ if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */
+ break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */
+ }
+
+ if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */
+ /* match is smaller than current */
+ *smallerPtr = matchIndex; /* update smaller idx */
+ commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
+ if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */
+ DEBUGLOG(8, "ZSTD_insertDUBT1: %u (>btLow=%u) is smaller : next => %u",
+ matchIndex, btLow, nextPtr[1]);
+ smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */
+ matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */
+ } else {
+ /* match is larger than current */
+ *largerPtr = matchIndex;
+ commonLengthLarger = matchLength;
+ if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */
+ DEBUGLOG(8, "ZSTD_insertDUBT1: %u (>btLow=%u) is larger => %u",
+ matchIndex, btLow, nextPtr[0]);
+ largerPtr = nextPtr;
+ matchIndex = nextPtr[0];
+ } }
+
+ *smallerPtr = *largerPtr = 0;
+}
+
+
+static size_t
+ZSTD_DUBT_findBetterDictMatch (
+ ZSTD_matchState_t* ms,
+ const BYTE* const ip, const BYTE* const iend,
+ size_t* offsetPtr,
+ size_t bestLength,
+ U32 nbCompares,
+ U32 const mls,
+ const ZSTD_dictMode_e dictMode)
+{
+ const ZSTD_matchState_t * const dms = ms->dictMatchState;
+ const ZSTD_compressionParameters* const dmsCParams = &dms->cParams;
+ const U32 * const dictHashTable = dms->hashTable;
+ U32 const hashLog = dmsCParams->hashLog;
+ size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
+ U32 dictMatchIndex = dictHashTable[h];
+
+ const BYTE* const base = ms->window.base;
+ const BYTE* const prefixStart = base + ms->window.dictLimit;
+ U32 const current = (U32)(ip-base);
+ const BYTE* const dictBase = dms->window.base;
+ const BYTE* const dictEnd = dms->window.nextSrc;
+ U32 const dictHighLimit = (U32)(dms->window.nextSrc - dms->window.base);
+ U32 const dictLowLimit = dms->window.lowLimit;
+ U32 const dictIndexDelta = ms->window.lowLimit - dictHighLimit;
+
+ U32* const dictBt = dms->chainTable;
+ U32 const btLog = dmsCParams->chainLog - 1;
+ U32 const btMask = (1 << btLog) - 1;
+ U32 const btLow = (btMask >= dictHighLimit - dictLowLimit) ? dictLowLimit : dictHighLimit - btMask;
+
+ size_t commonLengthSmaller=0, commonLengthLarger=0;
+
+ (void)dictMode;
+ assert(dictMode == ZSTD_dictMatchState);
+
+ while (nbCompares-- && (dictMatchIndex > dictLowLimit)) {
+ U32* const nextPtr = dictBt + 2*(dictMatchIndex & btMask);
+ size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
+ const BYTE* match = dictBase + dictMatchIndex;
+ matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
+ if (dictMatchIndex+matchLength >= dictHighLimit)
+ match = base + dictMatchIndex + dictIndexDelta; /* to prepare for next usage of match[matchLength] */
+
+ if (matchLength > bestLength) {
+ U32 matchIndex = dictMatchIndex + dictIndexDelta;
+ if ( (4*(int)(matchLength-bestLength)) > (int)(ZSTD_highbit32(current-matchIndex+1) - ZSTD_highbit32((U32)offsetPtr[0]+1)) ) {
+ DEBUGLOG(9, "ZSTD_DUBT_findBetterDictMatch(%u) : found better match length %u -> %u and offsetCode %u -> %u (dictMatchIndex %u, matchIndex %u)",
+ current, (U32)bestLength, (U32)matchLength, (U32)*offsetPtr, ZSTD_REP_MOVE + current - matchIndex, dictMatchIndex, matchIndex);
+ bestLength = matchLength, *offsetPtr = ZSTD_REP_MOVE + current - matchIndex;
+ }
+ if (ip+matchLength == iend) { /* reached end of input : ip[matchLength] is not valid, no way to know if it's larger or smaller than match */
+ break; /* drop, to guarantee consistency (miss a little bit of compression) */
+ }
+ }
+
+ if (match[matchLength] < ip[matchLength]) {
+ if (dictMatchIndex <= btLow) { break; } /* beyond tree size, stop the search */
+ commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
+ dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
+ } else {
+ /* match is larger than current */
+ if (dictMatchIndex <= btLow) { break; } /* beyond tree size, stop the search */
+ commonLengthLarger = matchLength;
+ dictMatchIndex = nextPtr[0];
+ }
+ }
+
+ if (bestLength >= MINMATCH) {
+ U32 const mIndex = current - ((U32)*offsetPtr - ZSTD_REP_MOVE); (void)mIndex;
+ DEBUGLOG(8, "ZSTD_DUBT_findBetterDictMatch(%u) : found match of length %u and offsetCode %u (pos %u)",
+ current, (U32)bestLength, (U32)*offsetPtr, mIndex);
+ }
+ return bestLength;
+
+}
+
+
+static size_t
+ZSTD_DUBT_findBestMatch(ZSTD_matchState_t* ms,
+ const BYTE* const ip, const BYTE* const iend,
+ size_t* offsetPtr,
+ U32 const mls,
+ const ZSTD_dictMode_e dictMode)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32* const hashTable = ms->hashTable;
+ U32 const hashLog = cParams->hashLog;
+ size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
+ U32 matchIndex = hashTable[h];
+
+ const BYTE* const base = ms->window.base;
+ U32 const current = (U32)(ip-base);
+ U32 const windowLow = ms->window.lowLimit;
+
+ U32* const bt = ms->chainTable;
+ U32 const btLog = cParams->chainLog - 1;
+ U32 const btMask = (1 << btLog) - 1;
+ U32 const btLow = (btMask >= current) ? 0 : current - btMask;
+ U32 const unsortLimit = MAX(btLow, windowLow);
+
+ U32* nextCandidate = bt + 2*(matchIndex&btMask);
+ U32* unsortedMark = bt + 2*(matchIndex&btMask) + 1;
+ U32 nbCompares = 1U << cParams->searchLog;
+ U32 nbCandidates = nbCompares;
+ U32 previousCandidate = 0;
+
+ DEBUGLOG(7, "ZSTD_DUBT_findBestMatch (%u) ", current);
+ assert(ip <= iend-8); /* required for h calculation */
+
+ /* reach end of unsorted candidates list */
+ while ( (matchIndex > unsortLimit)
+ && (*unsortedMark == ZSTD_DUBT_UNSORTED_MARK)
+ && (nbCandidates > 1) ) {
+ DEBUGLOG(8, "ZSTD_DUBT_findBestMatch: candidate %u is unsorted",
+ matchIndex);
+ *unsortedMark = previousCandidate; /* the unsortedMark becomes a reversed chain, to move up back to original position */
+ previousCandidate = matchIndex;
+ matchIndex = *nextCandidate;
+ nextCandidate = bt + 2*(matchIndex&btMask);
+ unsortedMark = bt + 2*(matchIndex&btMask) + 1;
+ nbCandidates --;
+ }
+
+ /* nullify last candidate if it's still unsorted
+ * simplification, detrimental to compression ratio, beneficial for speed */
+ if ( (matchIndex > unsortLimit)
+ && (*unsortedMark==ZSTD_DUBT_UNSORTED_MARK) ) {
+ DEBUGLOG(7, "ZSTD_DUBT_findBestMatch: nullify last unsorted candidate %u",
+ matchIndex);
+ *nextCandidate = *unsortedMark = 0;
+ }
+
+ /* batch sort stacked candidates */
+ matchIndex = previousCandidate;
+ while (matchIndex) { /* will end on matchIndex == 0 */
+ U32* const nextCandidateIdxPtr = bt + 2*(matchIndex&btMask) + 1;
+ U32 const nextCandidateIdx = *nextCandidateIdxPtr;
+ ZSTD_insertDUBT1(ms, matchIndex, iend,
+ nbCandidates, unsortLimit, dictMode);
+ matchIndex = nextCandidateIdx;
+ nbCandidates++;
+ }
+
+ /* find longest match */
+ { size_t commonLengthSmaller = 0, commonLengthLarger = 0;
+ const BYTE* const dictBase = ms->window.dictBase;
+ const U32 dictLimit = ms->window.dictLimit;
+ const BYTE* const dictEnd = dictBase + dictLimit;
+ const BYTE* const prefixStart = base + dictLimit;
+ U32* smallerPtr = bt + 2*(current&btMask);
+ U32* largerPtr = bt + 2*(current&btMask) + 1;
+ U32 matchEndIdx = current + 8 + 1;
+ U32 dummy32; /* to be nullified at the end */
+ size_t bestLength = 0;
+
+ matchIndex = hashTable[h];
+ hashTable[h] = current; /* Update Hash Table */
+
+ while (nbCompares-- && (matchIndex > windowLow)) {
+ U32* const nextPtr = bt + 2*(matchIndex & btMask);
+ size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
+ const BYTE* match;
+
+ if ((dictMode != ZSTD_extDict) || (matchIndex+matchLength >= dictLimit)) {
+ match = base + matchIndex;
+ matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
+ } else {
+ match = dictBase + matchIndex;
+ matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
+ if (matchIndex+matchLength >= dictLimit)
+ match = base + matchIndex; /* to prepare for next usage of match[matchLength] */
+ }
+
+ if (matchLength > bestLength) {
+ if (matchLength > matchEndIdx - matchIndex)
+ matchEndIdx = matchIndex + (U32)matchLength;
+ if ( (4*(int)(matchLength-bestLength)) > (int)(ZSTD_highbit32(current-matchIndex+1) - ZSTD_highbit32((U32)offsetPtr[0]+1)) )
+ bestLength = matchLength, *offsetPtr = ZSTD_REP_MOVE + current - matchIndex;
+ if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */
+ if (dictMode == ZSTD_dictMatchState) {
+ nbCompares = 0; /* in addition to avoiding checking any
+ * further in this loop, make sure we
+ * skip checking in the dictionary. */
+ }
+ break; /* drop, to guarantee consistency (miss a little bit of compression) */
+ }
+ }
+
+ if (match[matchLength] < ip[matchLength]) {
+ /* match is smaller than current */
+ *smallerPtr = matchIndex; /* update smaller idx */
+ commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
+ if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
+ smallerPtr = nextPtr+1; /* new "smaller" => larger of match */
+ matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
+ } else {
+ /* match is larger than current */
+ *largerPtr = matchIndex;
+ commonLengthLarger = matchLength;
+ if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
+ largerPtr = nextPtr;
+ matchIndex = nextPtr[0];
+ } }
+
+ *smallerPtr = *largerPtr = 0;
+
+ if (dictMode == ZSTD_dictMatchState && nbCompares) {
+ bestLength = ZSTD_DUBT_findBetterDictMatch(
+ ms, ip, iend,
+ offsetPtr, bestLength, nbCompares,
+ mls, dictMode);
+ }
+
+ assert(matchEndIdx > current+8); /* ensure nextToUpdate is increased */
+ ms->nextToUpdate = matchEndIdx - 8; /* skip repetitive patterns */
+ if (bestLength >= MINMATCH) {
+ U32 const mIndex = current - ((U32)*offsetPtr - ZSTD_REP_MOVE); (void)mIndex;
+ DEBUGLOG(8, "ZSTD_DUBT_findBestMatch(%u) : found match of length %u and offsetCode %u (pos %u)",
+ current, (U32)bestLength, (U32)*offsetPtr, mIndex);
+ }
+ return bestLength;
+ }
+}
+
+
+/** ZSTD_BtFindBestMatch() : Tree updater, providing best match */
+FORCE_INLINE_TEMPLATE size_t
+ZSTD_BtFindBestMatch( ZSTD_matchState_t* ms,
+ const BYTE* const ip, const BYTE* const iLimit,
+ size_t* offsetPtr,
+ const U32 mls /* template */,
+ const ZSTD_dictMode_e dictMode)
+{
+ DEBUGLOG(7, "ZSTD_BtFindBestMatch");
+ if (ip < ms->window.base + ms->nextToUpdate) return 0; /* skipped area */
+ ZSTD_updateDUBT(ms, ip, iLimit, mls);
+ return ZSTD_DUBT_findBestMatch(ms, ip, iLimit, offsetPtr, mls, dictMode);
+}
+
+
+static size_t
+ZSTD_BtFindBestMatch_selectMLS ( ZSTD_matchState_t* ms,
+ const BYTE* ip, const BYTE* const iLimit,
+ size_t* offsetPtr)
+{
+ switch(ms->cParams.minMatch)
+ {
+ default : /* includes case 3 */
+ case 4 : return ZSTD_BtFindBestMatch(ms, ip, iLimit, offsetPtr, 4, ZSTD_noDict);
+ case 5 : return ZSTD_BtFindBestMatch(ms, ip, iLimit, offsetPtr, 5, ZSTD_noDict);
+ case 7 :
+ case 6 : return ZSTD_BtFindBestMatch(ms, ip, iLimit, offsetPtr, 6, ZSTD_noDict);
+ }
+}
+
+
+static size_t ZSTD_BtFindBestMatch_dictMatchState_selectMLS (
+ ZSTD_matchState_t* ms,
+ const BYTE* ip, const BYTE* const iLimit,
+ size_t* offsetPtr)
+{
+ switch(ms->cParams.minMatch)
+ {
+ default : /* includes case 3 */
+ case 4 : return ZSTD_BtFindBestMatch(ms, ip, iLimit, offsetPtr, 4, ZSTD_dictMatchState);
+ case 5 : return ZSTD_BtFindBestMatch(ms, ip, iLimit, offsetPtr, 5, ZSTD_dictMatchState);
+ case 7 :
+ case 6 : return ZSTD_BtFindBestMatch(ms, ip, iLimit, offsetPtr, 6, ZSTD_dictMatchState);
+ }
+}
+
+
+static size_t ZSTD_BtFindBestMatch_extDict_selectMLS (
+ ZSTD_matchState_t* ms,
+ const BYTE* ip, const BYTE* const iLimit,
+ size_t* offsetPtr)
+{
+ switch(ms->cParams.minMatch)
+ {
+ default : /* includes case 3 */
+ case 4 : return ZSTD_BtFindBestMatch(ms, ip, iLimit, offsetPtr, 4, ZSTD_extDict);
+ case 5 : return ZSTD_BtFindBestMatch(ms, ip, iLimit, offsetPtr, 5, ZSTD_extDict);
+ case 7 :
+ case 6 : return ZSTD_BtFindBestMatch(ms, ip, iLimit, offsetPtr, 6, ZSTD_extDict);
+ }
+}
+
+
+
+/* *********************************
+* Hash Chain
+***********************************/
+#define NEXT_IN_CHAIN(d, mask) chainTable[(d) & (mask)]
+
+/* Update chains up to ip (excluded)
+ Assumption : always within prefix (i.e. not within extDict) */
+static U32 ZSTD_insertAndFindFirstIndex_internal(
+ ZSTD_matchState_t* ms,
+ const ZSTD_compressionParameters* const cParams,
+ const BYTE* ip, U32 const mls)
+{
+ U32* const hashTable = ms->hashTable;
+ const U32 hashLog = cParams->hashLog;
+ U32* const chainTable = ms->chainTable;
+ const U32 chainMask = (1 << cParams->chainLog) - 1;
+ const BYTE* const base = ms->window.base;
+ const U32 target = (U32)(ip - base);
+ U32 idx = ms->nextToUpdate;
+
+ while(idx < target) { /* catch up */
+ size_t const h = ZSTD_hashPtr(base+idx, hashLog, mls);
+ NEXT_IN_CHAIN(idx, chainMask) = hashTable[h];
+ hashTable[h] = idx;
+ idx++;
+ }
+
+ ms->nextToUpdate = target;
+ return hashTable[ZSTD_hashPtr(ip, hashLog, mls)];
+}
+
+U32 ZSTD_insertAndFindFirstIndex(ZSTD_matchState_t* ms, const BYTE* ip) {
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ return ZSTD_insertAndFindFirstIndex_internal(ms, cParams, ip, ms->cParams.minMatch);
+}
+
+
+/* inlining is important to hardwire a hot branch (template emulation) */
+FORCE_INLINE_TEMPLATE
+size_t ZSTD_HcFindBestMatch_generic (
+ ZSTD_matchState_t* ms,
+ const BYTE* const ip, const BYTE* const iLimit,
+ size_t* offsetPtr,
+ const U32 mls, const ZSTD_dictMode_e dictMode)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32* const chainTable = ms->chainTable;
+ const U32 chainSize = (1 << cParams->chainLog);
+ const U32 chainMask = chainSize-1;
+ const BYTE* const base = ms->window.base;
+ const BYTE* const dictBase = ms->window.dictBase;
+ const U32 dictLimit = ms->window.dictLimit;
+ const BYTE* const prefixStart = base + dictLimit;
+ const BYTE* const dictEnd = dictBase + dictLimit;
+ const U32 lowLimit = ms->window.lowLimit;
+ const U32 current = (U32)(ip-base);
+ const U32 minChain = current > chainSize ? current - chainSize : 0;
+ U32 nbAttempts = 1U << cParams->searchLog;
+ size_t ml=4-1;
+
+ /* HC4 match finder */
+ U32 matchIndex = ZSTD_insertAndFindFirstIndex_internal(ms, cParams, ip, mls);
+
+ for ( ; (matchIndex>lowLimit) & (nbAttempts>0) ; nbAttempts--) {
+ size_t currentMl=0;
+ if ((dictMode != ZSTD_extDict) || matchIndex >= dictLimit) {
+ const BYTE* const match = base + matchIndex;
+ assert(matchIndex >= dictLimit); /* ensures this is true if dictMode != ZSTD_extDict */
+ if (match[ml] == ip[ml]) /* potentially better */
+ currentMl = ZSTD_count(ip, match, iLimit);
+ } else {
+ const BYTE* const match = dictBase + matchIndex;
+ assert(match+4 <= dictEnd);
+ if (MEM_read32(match) == MEM_read32(ip)) /* assumption : matchIndex <= dictLimit-4 (by table construction) */
+ currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dictEnd, prefixStart) + 4;
+ }
+
+ /* save best solution */
+ if (currentMl > ml) {
+ ml = currentMl;
+ *offsetPtr = current - matchIndex + ZSTD_REP_MOVE;
+ if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
+ }
+
+ if (matchIndex <= minChain) break;
+ matchIndex = NEXT_IN_CHAIN(matchIndex, chainMask);
+ }
+
+ if (dictMode == ZSTD_dictMatchState) {
+ const ZSTD_matchState_t* const dms = ms->dictMatchState;
+ const U32* const dmsChainTable = dms->chainTable;
+ const U32 dmsChainSize = (1 << dms->cParams.chainLog);
+ const U32 dmsChainMask = dmsChainSize - 1;
+ const U32 dmsLowestIndex = dms->window.dictLimit;
+ const BYTE* const dmsBase = dms->window.base;
+ const BYTE* const dmsEnd = dms->window.nextSrc;
+ const U32 dmsSize = (U32)(dmsEnd - dmsBase);
+ const U32 dmsIndexDelta = dictLimit - dmsSize;
+ const U32 dmsMinChain = dmsSize > dmsChainSize ? dmsSize - dmsChainSize : 0;
+
+ matchIndex = dms->hashTable[ZSTD_hashPtr(ip, dms->cParams.hashLog, mls)];
+
+ for ( ; (matchIndex>dmsLowestIndex) & (nbAttempts>0) ; nbAttempts--) {
+ size_t currentMl=0;
+ const BYTE* const match = dmsBase + matchIndex;
+ assert(match+4 <= dmsEnd);
+ if (MEM_read32(match) == MEM_read32(ip)) /* assumption : matchIndex <= dictLimit-4 (by table construction) */
+ currentMl = ZSTD_count_2segments(ip+4, match+4, iLimit, dmsEnd, prefixStart) + 4;
+
+ /* save best solution */
+ if (currentMl > ml) {
+ ml = currentMl;
+ *offsetPtr = current - (matchIndex + dmsIndexDelta) + ZSTD_REP_MOVE;
+ if (ip+currentMl == iLimit) break; /* best possible, avoids read overflow on next attempt */
+ }
+
+ if (matchIndex <= dmsMinChain) break;
+ matchIndex = dmsChainTable[matchIndex & dmsChainMask];
+ }
+ }
+
+ return ml;
+}
+
+
+FORCE_INLINE_TEMPLATE size_t ZSTD_HcFindBestMatch_selectMLS (
+ ZSTD_matchState_t* ms,
+ const BYTE* ip, const BYTE* const iLimit,
+ size_t* offsetPtr)
+{
+ switch(ms->cParams.minMatch)
+ {
+ default : /* includes case 3 */
+ case 4 : return ZSTD_HcFindBestMatch_generic(ms, ip, iLimit, offsetPtr, 4, ZSTD_noDict);
+ case 5 : return ZSTD_HcFindBestMatch_generic(ms, ip, iLimit, offsetPtr, 5, ZSTD_noDict);
+ case 7 :
+ case 6 : return ZSTD_HcFindBestMatch_generic(ms, ip, iLimit, offsetPtr, 6, ZSTD_noDict);
+ }
+}
+
+
+static size_t ZSTD_HcFindBestMatch_dictMatchState_selectMLS (
+ ZSTD_matchState_t* ms,
+ const BYTE* ip, const BYTE* const iLimit,
+ size_t* offsetPtr)
+{
+ switch(ms->cParams.minMatch)
+ {
+ default : /* includes case 3 */
+ case 4 : return ZSTD_HcFindBestMatch_generic(ms, ip, iLimit, offsetPtr, 4, ZSTD_dictMatchState);
+ case 5 : return ZSTD_HcFindBestMatch_generic(ms, ip, iLimit, offsetPtr, 5, ZSTD_dictMatchState);
+ case 7 :
+ case 6 : return ZSTD_HcFindBestMatch_generic(ms, ip, iLimit, offsetPtr, 6, ZSTD_dictMatchState);
+ }
+}
+
+
+FORCE_INLINE_TEMPLATE size_t ZSTD_HcFindBestMatch_extDict_selectMLS (
+ ZSTD_matchState_t* ms,
+ const BYTE* ip, const BYTE* const iLimit,
+ size_t* offsetPtr)
+{
+ switch(ms->cParams.minMatch)
+ {
+ default : /* includes case 3 */
+ case 4 : return ZSTD_HcFindBestMatch_generic(ms, ip, iLimit, offsetPtr, 4, ZSTD_extDict);
+ case 5 : return ZSTD_HcFindBestMatch_generic(ms, ip, iLimit, offsetPtr, 5, ZSTD_extDict);
+ case 7 :
+ case 6 : return ZSTD_HcFindBestMatch_generic(ms, ip, iLimit, offsetPtr, 6, ZSTD_extDict);
+ }
+}
+
+
+/* *******************************
+* Common parser - lazy strategy
+*********************************/
+FORCE_INLINE_TEMPLATE
+size_t ZSTD_compressBlock_lazy_generic(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore,
+ U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize,
+ const U32 searchMethod, const U32 depth,
+ ZSTD_dictMode_e const dictMode)
+{
+ const BYTE* const istart = (const BYTE*)src;
+ const BYTE* ip = istart;
+ const BYTE* anchor = istart;
+ const BYTE* const iend = istart + srcSize;
+ const BYTE* const ilimit = iend - 8;
+ const BYTE* const base = ms->window.base;
+ const U32 prefixLowestIndex = ms->window.dictLimit;
+ const BYTE* const prefixLowest = base + prefixLowestIndex;
+
+ typedef size_t (*searchMax_f)(
+ ZSTD_matchState_t* ms,
+ const BYTE* ip, const BYTE* iLimit, size_t* offsetPtr);
+ searchMax_f const searchMax = dictMode == ZSTD_dictMatchState ?
+ (searchMethod ? ZSTD_BtFindBestMatch_dictMatchState_selectMLS : ZSTD_HcFindBestMatch_dictMatchState_selectMLS) :
+ (searchMethod ? ZSTD_BtFindBestMatch_selectMLS : ZSTD_HcFindBestMatch_selectMLS);
+ U32 offset_1 = rep[0], offset_2 = rep[1], savedOffset=0;
+
+ const ZSTD_matchState_t* const dms = ms->dictMatchState;
+ const U32 dictLowestIndex = dictMode == ZSTD_dictMatchState ?
+ dms->window.dictLimit : 0;
+ const BYTE* const dictBase = dictMode == ZSTD_dictMatchState ?
+ dms->window.base : NULL;
+ const BYTE* const dictLowest = dictMode == ZSTD_dictMatchState ?
+ dictBase + dictLowestIndex : NULL;
+ const BYTE* const dictEnd = dictMode == ZSTD_dictMatchState ?
+ dms->window.nextSrc : NULL;
+ const U32 dictIndexDelta = dictMode == ZSTD_dictMatchState ?
+ prefixLowestIndex - (U32)(dictEnd - dictBase) :
+ 0;
+ const U32 dictAndPrefixLength = (U32)(ip - prefixLowest + dictEnd - dictLowest);
+
+ /* init */
+ ip += (dictAndPrefixLength == 0);
+ ms->nextToUpdate3 = ms->nextToUpdate;
+ if (dictMode == ZSTD_noDict) {
+ U32 const maxRep = (U32)(ip - prefixLowest);
+ if (offset_2 > maxRep) savedOffset = offset_2, offset_2 = 0;
+ if (offset_1 > maxRep) savedOffset = offset_1, offset_1 = 0;
+ }
+ if (dictMode == ZSTD_dictMatchState) {
+ /* dictMatchState repCode checks don't currently handle repCode == 0
+ * disabling. */
+ assert(offset_1 <= dictAndPrefixLength);
+ assert(offset_2 <= dictAndPrefixLength);
+ }
+
+ /* Match Loop */
+ while (ip < ilimit) {
+ size_t matchLength=0;
+ size_t offset=0;
+ const BYTE* start=ip+1;
+
+ /* check repCode */
+ if (dictMode == ZSTD_dictMatchState) {
+ const U32 repIndex = (U32)(ip - base) + 1 - offset_1;
+ const BYTE* repMatch = (dictMode == ZSTD_dictMatchState
+ && repIndex < prefixLowestIndex) ?
+ dictBase + (repIndex - dictIndexDelta) :
+ base + repIndex;
+ if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
+ && (MEM_read32(repMatch) == MEM_read32(ip+1)) ) {
+ const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
+ matchLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
+ if (depth==0) goto _storeSequence;
+ }
+ }
+ if ( dictMode == ZSTD_noDict
+ && ((offset_1 > 0) & (MEM_read32(ip+1-offset_1) == MEM_read32(ip+1)))) {
+ matchLength = ZSTD_count(ip+1+4, ip+1+4-offset_1, iend) + 4;
+ if (depth==0) goto _storeSequence;
+ }
+
+ /* first search (depth 0) */
+ { size_t offsetFound = 999999999;
+ size_t const ml2 = searchMax(ms, ip, iend, &offsetFound);
+ if (ml2 > matchLength)
+ matchLength = ml2, start = ip, offset=offsetFound;
+ }
+
+ if (matchLength < 4) {
+ ip += ((ip-anchor) >> kSearchStrength) + 1; /* jump faster over incompressible sections */
+ continue;
+ }
+
+ /* let's try to find a better solution */
+ if (depth>=1)
+ while (ip<ilimit) {
+ ip ++;
+ if ( (dictMode == ZSTD_noDict)
+ && (offset) && ((offset_1>0) & (MEM_read32(ip) == MEM_read32(ip - offset_1)))) {
+ size_t const mlRep = ZSTD_count(ip+4, ip+4-offset_1, iend) + 4;
+ int const gain2 = (int)(mlRep * 3);
+ int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offset+1) + 1);
+ if ((mlRep >= 4) && (gain2 > gain1))
+ matchLength = mlRep, offset = 0, start = ip;
+ }
+ if (dictMode == ZSTD_dictMatchState) {
+ const U32 repIndex = (U32)(ip - base) - offset_1;
+ const BYTE* repMatch = repIndex < prefixLowestIndex ?
+ dictBase + (repIndex - dictIndexDelta) :
+ base + repIndex;
+ if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
+ && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
+ const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
+ size_t const mlRep = ZSTD_count_2segments(ip+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
+ int const gain2 = (int)(mlRep * 3);
+ int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offset+1) + 1);
+ if ((mlRep >= 4) && (gain2 > gain1))
+ matchLength = mlRep, offset = 0, start = ip;
+ }
+ }
+ { size_t offset2=999999999;
+ size_t const ml2 = searchMax(ms, ip, iend, &offset2);
+ int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)offset2+1)); /* raw approx */
+ int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offset+1) + 4);
+ if ((ml2 >= 4) && (gain2 > gain1)) {
+ matchLength = ml2, offset = offset2, start = ip;
+ continue; /* search a better one */
+ } }
+
+ /* let's find an even better one */
+ if ((depth==2) && (ip<ilimit)) {
+ ip ++;
+ if ( (dictMode == ZSTD_noDict)
+ && (offset) && ((offset_1>0) & (MEM_read32(ip) == MEM_read32(ip - offset_1)))) {
+ size_t const mlRep = ZSTD_count(ip+4, ip+4-offset_1, iend) + 4;
+ int const gain2 = (int)(mlRep * 4);
+ int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offset+1) + 1);
+ if ((mlRep >= 4) && (gain2 > gain1))
+ matchLength = mlRep, offset = 0, start = ip;
+ }
+ if (dictMode == ZSTD_dictMatchState) {
+ const U32 repIndex = (U32)(ip - base) - offset_1;
+ const BYTE* repMatch = repIndex < prefixLowestIndex ?
+ dictBase + (repIndex - dictIndexDelta) :
+ base + repIndex;
+ if (((U32)((prefixLowestIndex-1) - repIndex) >= 3 /* intentional underflow */)
+ && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
+ const BYTE* repMatchEnd = repIndex < prefixLowestIndex ? dictEnd : iend;
+ size_t const mlRep = ZSTD_count_2segments(ip+4, repMatch+4, iend, repMatchEnd, prefixLowest) + 4;
+ int const gain2 = (int)(mlRep * 4);
+ int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offset+1) + 1);
+ if ((mlRep >= 4) && (gain2 > gain1))
+ matchLength = mlRep, offset = 0, start = ip;
+ }
+ }
+ { size_t offset2=999999999;
+ size_t const ml2 = searchMax(ms, ip, iend, &offset2);
+ int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)offset2+1)); /* raw approx */
+ int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offset+1) + 7);
+ if ((ml2 >= 4) && (gain2 > gain1)) {
+ matchLength = ml2, offset = offset2, start = ip;
+ continue;
+ } } }
+ break; /* nothing found : store previous solution */
+ }
+
+ /* NOTE:
+ * start[-offset+ZSTD_REP_MOVE-1] is undefined behavior.
+ * (-offset+ZSTD_REP_MOVE-1) is unsigned, and is added to start, which
+ * overflows the pointer, which is undefined behavior.
+ */
+ /* catch up */
+ if (offset) {
+ if (dictMode == ZSTD_noDict) {
+ while ( ((start > anchor) & (start - (offset-ZSTD_REP_MOVE) > prefixLowest))
+ && (start[-1] == (start-(offset-ZSTD_REP_MOVE))[-1]) ) /* only search for offset within prefix */
+ { start--; matchLength++; }
+ }
+ if (dictMode == ZSTD_dictMatchState) {
+ U32 const matchIndex = (U32)((start-base) - (offset - ZSTD_REP_MOVE));
+ const BYTE* match = (matchIndex < prefixLowestIndex) ? dictBase + matchIndex - dictIndexDelta : base + matchIndex;
+ const BYTE* const mStart = (matchIndex < prefixLowestIndex) ? dictLowest : prefixLowest;
+ while ((start>anchor) && (match>mStart) && (start[-1] == match[-1])) { start--; match--; matchLength++; } /* catch up */
+ }
+ offset_2 = offset_1; offset_1 = (U32)(offset - ZSTD_REP_MOVE);
+ }
+ /* store sequence */
+_storeSequence:
+ { size_t const litLength = start - anchor;
+ ZSTD_storeSeq(seqStore, litLength, anchor, (U32)offset, matchLength-MINMATCH);
+ anchor = ip = start + matchLength;
+ }
+
+ /* check immediate repcode */
+ if (dictMode == ZSTD_dictMatchState) {
+ while (ip <= ilimit) {
+ U32 const current2 = (U32)(ip-base);
+ U32 const repIndex = current2 - offset_2;
+ const BYTE* repMatch = dictMode == ZSTD_dictMatchState
+ && repIndex < prefixLowestIndex ?
+ dictBase - dictIndexDelta + repIndex :
+ base + repIndex;
+ if ( ((U32)((prefixLowestIndex-1) - (U32)repIndex) >= 3 /* intentional overflow */)
+ && (MEM_read32(repMatch) == MEM_read32(ip)) ) {
+ const BYTE* const repEnd2 = repIndex < prefixLowestIndex ? dictEnd : iend;
+ matchLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd2, prefixLowest) + 4;
+ offset = offset_2; offset_2 = offset_1; offset_1 = (U32)offset; /* swap offset_2 <=> offset_1 */
+ ZSTD_storeSeq(seqStore, 0, anchor, 0, matchLength-MINMATCH);
+ ip += matchLength;
+ anchor = ip;
+ continue;
+ }
+ break;
+ }
+ }
+
+ if (dictMode == ZSTD_noDict) {
+ while ( ((ip <= ilimit) & (offset_2>0))
+ && (MEM_read32(ip) == MEM_read32(ip - offset_2)) ) {
+ /* store sequence */
+ matchLength = ZSTD_count(ip+4, ip+4-offset_2, iend) + 4;
+ offset = offset_2; offset_2 = offset_1; offset_1 = (U32)offset; /* swap repcodes */
+ ZSTD_storeSeq(seqStore, 0, anchor, 0, matchLength-MINMATCH);
+ ip += matchLength;
+ anchor = ip;
+ continue; /* faster when present ... (?) */
+ } } }
+
+ /* Save reps for next block */
+ rep[0] = offset_1 ? offset_1 : savedOffset;
+ rep[1] = offset_2 ? offset_2 : savedOffset;
+
+ /* Return the last literals size */
+ return iend - anchor;
+}
+
+
+size_t ZSTD_compressBlock_btlazy2(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, 1, 2, ZSTD_noDict);
+}
+
+size_t ZSTD_compressBlock_lazy2(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, 0, 2, ZSTD_noDict);
+}
+
+size_t ZSTD_compressBlock_lazy(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, 0, 1, ZSTD_noDict);
+}
+
+size_t ZSTD_compressBlock_greedy(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, 0, 0, ZSTD_noDict);
+}
+
+size_t ZSTD_compressBlock_btlazy2_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, 1, 2, ZSTD_dictMatchState);
+}
+
+size_t ZSTD_compressBlock_lazy2_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, 0, 2, ZSTD_dictMatchState);
+}
+
+size_t ZSTD_compressBlock_lazy_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, 0, 1, ZSTD_dictMatchState);
+}
+
+size_t ZSTD_compressBlock_greedy_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_lazy_generic(ms, seqStore, rep, src, srcSize, 0, 0, ZSTD_dictMatchState);
+}
+
+
+FORCE_INLINE_TEMPLATE
+size_t ZSTD_compressBlock_lazy_extDict_generic(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore,
+ U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize,
+ const U32 searchMethod, const U32 depth)
+{
+ const BYTE* const istart = (const BYTE*)src;
+ const BYTE* ip = istart;
+ const BYTE* anchor = istart;
+ const BYTE* const iend = istart + srcSize;
+ const BYTE* const ilimit = iend - 8;
+ const BYTE* const base = ms->window.base;
+ const U32 dictLimit = ms->window.dictLimit;
+ const U32 lowestIndex = ms->window.lowLimit;
+ const BYTE* const prefixStart = base + dictLimit;
+ const BYTE* const dictBase = ms->window.dictBase;
+ const BYTE* const dictEnd = dictBase + dictLimit;
+ const BYTE* const dictStart = dictBase + lowestIndex;
+
+ typedef size_t (*searchMax_f)(
+ ZSTD_matchState_t* ms,
+ const BYTE* ip, const BYTE* iLimit, size_t* offsetPtr);
+ searchMax_f searchMax = searchMethod ? ZSTD_BtFindBestMatch_extDict_selectMLS : ZSTD_HcFindBestMatch_extDict_selectMLS;
+
+ U32 offset_1 = rep[0], offset_2 = rep[1];
+
+ /* init */
+ ms->nextToUpdate3 = ms->nextToUpdate;
+ ip += (ip == prefixStart);
+
+ /* Match Loop */
+ while (ip < ilimit) {
+ size_t matchLength=0;
+ size_t offset=0;
+ const BYTE* start=ip+1;
+ U32 current = (U32)(ip-base);
+
+ /* check repCode */
+ { const U32 repIndex = (U32)(current+1 - offset_1);
+ const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
+ const BYTE* const repMatch = repBase + repIndex;
+ if (((U32)((dictLimit-1) - repIndex) >= 3) & (repIndex > lowestIndex)) /* intentional overflow */
+ if (MEM_read32(ip+1) == MEM_read32(repMatch)) {
+ /* repcode detected we should take it */
+ const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
+ matchLength = ZSTD_count_2segments(ip+1+4, repMatch+4, iend, repEnd, prefixStart) + 4;
+ if (depth==0) goto _storeSequence;
+ } }
+
+ /* first search (depth 0) */
+ { size_t offsetFound = 999999999;
+ size_t const ml2 = searchMax(ms, ip, iend, &offsetFound);
+ if (ml2 > matchLength)
+ matchLength = ml2, start = ip, offset=offsetFound;
+ }
+
+ if (matchLength < 4) {
+ ip += ((ip-anchor) >> kSearchStrength) + 1; /* jump faster over incompressible sections */
+ continue;
+ }
+
+ /* let's try to find a better solution */
+ if (depth>=1)
+ while (ip<ilimit) {
+ ip ++;
+ current++;
+ /* check repCode */
+ if (offset) {
+ const U32 repIndex = (U32)(current - offset_1);
+ const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
+ const BYTE* const repMatch = repBase + repIndex;
+ if (((U32)((dictLimit-1) - repIndex) >= 3) & (repIndex > lowestIndex)) /* intentional overflow */
+ if (MEM_read32(ip) == MEM_read32(repMatch)) {
+ /* repcode detected */
+ const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
+ size_t const repLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
+ int const gain2 = (int)(repLength * 3);
+ int const gain1 = (int)(matchLength*3 - ZSTD_highbit32((U32)offset+1) + 1);
+ if ((repLength >= 4) && (gain2 > gain1))
+ matchLength = repLength, offset = 0, start = ip;
+ } }
+
+ /* search match, depth 1 */
+ { size_t offset2=999999999;
+ size_t const ml2 = searchMax(ms, ip, iend, &offset2);
+ int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)offset2+1)); /* raw approx */
+ int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offset+1) + 4);
+ if ((ml2 >= 4) && (gain2 > gain1)) {
+ matchLength = ml2, offset = offset2, start = ip;
+ continue; /* search a better one */
+ } }
+
+ /* let's find an even better one */
+ if ((depth==2) && (ip<ilimit)) {
+ ip ++;
+ current++;
+ /* check repCode */
+ if (offset) {
+ const U32 repIndex = (U32)(current - offset_1);
+ const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
+ const BYTE* const repMatch = repBase + repIndex;
+ if (((U32)((dictLimit-1) - repIndex) >= 3) & (repIndex > lowestIndex)) /* intentional overflow */
+ if (MEM_read32(ip) == MEM_read32(repMatch)) {
+ /* repcode detected */
+ const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
+ size_t const repLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
+ int const gain2 = (int)(repLength * 4);
+ int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offset+1) + 1);
+ if ((repLength >= 4) && (gain2 > gain1))
+ matchLength = repLength, offset = 0, start = ip;
+ } }
+
+ /* search match, depth 2 */
+ { size_t offset2=999999999;
+ size_t const ml2 = searchMax(ms, ip, iend, &offset2);
+ int const gain2 = (int)(ml2*4 - ZSTD_highbit32((U32)offset2+1)); /* raw approx */
+ int const gain1 = (int)(matchLength*4 - ZSTD_highbit32((U32)offset+1) + 7);
+ if ((ml2 >= 4) && (gain2 > gain1)) {
+ matchLength = ml2, offset = offset2, start = ip;
+ continue;
+ } } }
+ break; /* nothing found : store previous solution */
+ }
+
+ /* catch up */
+ if (offset) {
+ U32 const matchIndex = (U32)((start-base) - (offset - ZSTD_REP_MOVE));
+ const BYTE* match = (matchIndex < dictLimit) ? dictBase + matchIndex : base + matchIndex;
+ const BYTE* const mStart = (matchIndex < dictLimit) ? dictStart : prefixStart;
+ while ((start>anchor) && (match>mStart) && (start[-1] == match[-1])) { start--; match--; matchLength++; } /* catch up */
+ offset_2 = offset_1; offset_1 = (U32)(offset - ZSTD_REP_MOVE);
+ }
+
+ /* store sequence */
+_storeSequence:
+ { size_t const litLength = start - anchor;
+ ZSTD_storeSeq(seqStore, litLength, anchor, (U32)offset, matchLength-MINMATCH);
+ anchor = ip = start + matchLength;
+ }
+
+ /* check immediate repcode */
+ while (ip <= ilimit) {
+ const U32 repIndex = (U32)((ip-base) - offset_2);
+ const BYTE* const repBase = repIndex < dictLimit ? dictBase : base;
+ const BYTE* const repMatch = repBase + repIndex;
+ if (((U32)((dictLimit-1) - repIndex) >= 3) & (repIndex > lowestIndex)) /* intentional overflow */
+ if (MEM_read32(ip) == MEM_read32(repMatch)) {
+ /* repcode detected we should take it */
+ const BYTE* const repEnd = repIndex < dictLimit ? dictEnd : iend;
+ matchLength = ZSTD_count_2segments(ip+4, repMatch+4, iend, repEnd, prefixStart) + 4;
+ offset = offset_2; offset_2 = offset_1; offset_1 = (U32)offset; /* swap offset history */
+ ZSTD_storeSeq(seqStore, 0, anchor, 0, matchLength-MINMATCH);
+ ip += matchLength;
+ anchor = ip;
+ continue; /* faster when present ... (?) */
+ }
+ break;
+ } }
+
+ /* Save reps for next block */
+ rep[0] = offset_1;
+ rep[1] = offset_2;
+
+ /* Return the last literals size */
+ return iend - anchor;
+}
+
+
+size_t ZSTD_compressBlock_greedy_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, 0, 0);
+}
+
+size_t ZSTD_compressBlock_lazy_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+
+{
+ return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, 0, 1);
+}
+
+size_t ZSTD_compressBlock_lazy2_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+
+{
+ return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, 0, 2);
+}
+
+size_t ZSTD_compressBlock_btlazy2_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+
+{
+ return ZSTD_compressBlock_lazy_extDict_generic(ms, seqStore, rep, src, srcSize, 1, 2);
+}
diff --git a/Utilities/cmzstd/lib/compress/zstd_lazy.h b/Utilities/cmzstd/lib/compress/zstd_lazy.h
new file mode 100644
index 000000000..ef85a6df9
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_lazy.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef ZSTD_LAZY_H
+#define ZSTD_LAZY_H
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#include "zstd_compress_internal.h"
+
+U32 ZSTD_insertAndFindFirstIndex(ZSTD_matchState_t* ms, const BYTE* ip);
+
+void ZSTD_preserveUnsortedMark (U32* const table, U32 const size, U32 const reducerValue); /*! used in ZSTD_reduceIndex(). pre-emptively increase value of ZSTD_DUBT_UNSORTED_MARK */
+
+size_t ZSTD_compressBlock_btlazy2(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_lazy2(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_lazy(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_greedy(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+
+size_t ZSTD_compressBlock_btlazy2_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_lazy2_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_lazy_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_greedy_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+
+size_t ZSTD_compressBlock_greedy_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_lazy_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_lazy2_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_btlazy2_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* ZSTD_LAZY_H */
diff --git a/Utilities/cmzstd/lib/compress/zstd_ldm.c b/Utilities/cmzstd/lib/compress/zstd_ldm.c
new file mode 100644
index 000000000..58eb2ffe4
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_ldm.c
@@ -0,0 +1,597 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ */
+
+#include "zstd_ldm.h"
+
+#include "debug.h"
+#include "zstd_fast.h" /* ZSTD_fillHashTable() */
+#include "zstd_double_fast.h" /* ZSTD_fillDoubleHashTable() */
+
+#define LDM_BUCKET_SIZE_LOG 3
+#define LDM_MIN_MATCH_LENGTH 64
+#define LDM_HASH_RLOG 7
+#define LDM_HASH_CHAR_OFFSET 10
+
+void ZSTD_ldm_adjustParameters(ldmParams_t* params,
+ ZSTD_compressionParameters const* cParams)
+{
+ params->windowLog = cParams->windowLog;
+ ZSTD_STATIC_ASSERT(LDM_BUCKET_SIZE_LOG <= ZSTD_LDM_BUCKETSIZELOG_MAX);
+ DEBUGLOG(4, "ZSTD_ldm_adjustParameters");
+ if (!params->bucketSizeLog) params->bucketSizeLog = LDM_BUCKET_SIZE_LOG;
+ if (!params->minMatchLength) params->minMatchLength = LDM_MIN_MATCH_LENGTH;
+ if (cParams->strategy >= ZSTD_btopt) {
+ /* Get out of the way of the optimal parser */
+ U32 const minMatch = MAX(cParams->targetLength, params->minMatchLength);
+ assert(minMatch >= ZSTD_LDM_MINMATCH_MIN);
+ assert(minMatch <= ZSTD_LDM_MINMATCH_MAX);
+ params->minMatchLength = minMatch;
+ }
+ if (params->hashLog == 0) {
+ params->hashLog = MAX(ZSTD_HASHLOG_MIN, params->windowLog - LDM_HASH_RLOG);
+ assert(params->hashLog <= ZSTD_HASHLOG_MAX);
+ }
+ if (params->hashRateLog == 0) {
+ params->hashRateLog = params->windowLog < params->hashLog
+ ? 0
+ : params->windowLog - params->hashLog;
+ }
+ params->bucketSizeLog = MIN(params->bucketSizeLog, params->hashLog);
+}
+
+size_t ZSTD_ldm_getTableSize(ldmParams_t params)
+{
+ size_t const ldmHSize = ((size_t)1) << params.hashLog;
+ size_t const ldmBucketSizeLog = MIN(params.bucketSizeLog, params.hashLog);
+ size_t const ldmBucketSize =
+ ((size_t)1) << (params.hashLog - ldmBucketSizeLog);
+ size_t const totalSize = ldmBucketSize + ldmHSize * sizeof(ldmEntry_t);
+ return params.enableLdm ? totalSize : 0;
+}
+
+size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize)
+{
+ return params.enableLdm ? (maxChunkSize / params.minMatchLength) : 0;
+}
+
+/** ZSTD_ldm_getSmallHash() :
+ * numBits should be <= 32
+ * If numBits==0, returns 0.
+ * @return : the most significant numBits of value. */
+static U32 ZSTD_ldm_getSmallHash(U64 value, U32 numBits)
+{
+ assert(numBits <= 32);
+ return numBits == 0 ? 0 : (U32)(value >> (64 - numBits));
+}
+
+/** ZSTD_ldm_getChecksum() :
+ * numBitsToDiscard should be <= 32
+ * @return : the next most significant 32 bits after numBitsToDiscard */
+static U32 ZSTD_ldm_getChecksum(U64 hash, U32 numBitsToDiscard)
+{
+ assert(numBitsToDiscard <= 32);
+ return (hash >> (64 - 32 - numBitsToDiscard)) & 0xFFFFFFFF;
+}
+
+/** ZSTD_ldm_getTag() ;
+ * Given the hash, returns the most significant numTagBits bits
+ * after (32 + hbits) bits.
+ *
+ * If there are not enough bits remaining, return the last
+ * numTagBits bits. */
+static U32 ZSTD_ldm_getTag(U64 hash, U32 hbits, U32 numTagBits)
+{
+ assert(numTagBits < 32 && hbits <= 32);
+ if (32 - hbits < numTagBits) {
+ return hash & (((U32)1 << numTagBits) - 1);
+ } else {
+ return (hash >> (32 - hbits - numTagBits)) & (((U32)1 << numTagBits) - 1);
+ }
+}
+
+/** ZSTD_ldm_getBucket() :
+ * Returns a pointer to the start of the bucket associated with hash. */
+static ldmEntry_t* ZSTD_ldm_getBucket(
+ ldmState_t* ldmState, size_t hash, ldmParams_t const ldmParams)
+{
+ return ldmState->hashTable + (hash << ldmParams.bucketSizeLog);
+}
+
+/** ZSTD_ldm_insertEntry() :
+ * Insert the entry with corresponding hash into the hash table */
+static void ZSTD_ldm_insertEntry(ldmState_t* ldmState,
+ size_t const hash, const ldmEntry_t entry,
+ ldmParams_t const ldmParams)
+{
+ BYTE* const bucketOffsets = ldmState->bucketOffsets;
+ *(ZSTD_ldm_getBucket(ldmState, hash, ldmParams) + bucketOffsets[hash]) = entry;
+ bucketOffsets[hash]++;
+ bucketOffsets[hash] &= ((U32)1 << ldmParams.bucketSizeLog) - 1;
+}
+
+/** ZSTD_ldm_makeEntryAndInsertByTag() :
+ *
+ * Gets the small hash, checksum, and tag from the rollingHash.
+ *
+ * If the tag matches (1 << ldmParams.hashRateLog)-1, then
+ * creates an ldmEntry from the offset, and inserts it into the hash table.
+ *
+ * hBits is the length of the small hash, which is the most significant hBits
+ * of rollingHash. The checksum is the next 32 most significant bits, followed
+ * by ldmParams.hashRateLog bits that make up the tag. */
+static void ZSTD_ldm_makeEntryAndInsertByTag(ldmState_t* ldmState,
+ U64 const rollingHash,
+ U32 const hBits,
+ U32 const offset,
+ ldmParams_t const ldmParams)
+{
+ U32 const tag = ZSTD_ldm_getTag(rollingHash, hBits, ldmParams.hashRateLog);
+ U32 const tagMask = ((U32)1 << ldmParams.hashRateLog) - 1;
+ if (tag == tagMask) {
+ U32 const hash = ZSTD_ldm_getSmallHash(rollingHash, hBits);
+ U32 const checksum = ZSTD_ldm_getChecksum(rollingHash, hBits);
+ ldmEntry_t entry;
+ entry.offset = offset;
+ entry.checksum = checksum;
+ ZSTD_ldm_insertEntry(ldmState, hash, entry, ldmParams);
+ }
+}
+
+/** ZSTD_ldm_countBackwardsMatch() :
+ * Returns the number of bytes that match backwards before pIn and pMatch.
+ *
+ * We count only bytes where pMatch >= pBase and pIn >= pAnchor. */
+static size_t ZSTD_ldm_countBackwardsMatch(
+ const BYTE* pIn, const BYTE* pAnchor,
+ const BYTE* pMatch, const BYTE* pBase)
+{
+ size_t matchLength = 0;
+ while (pIn > pAnchor && pMatch > pBase && pIn[-1] == pMatch[-1]) {
+ pIn--;
+ pMatch--;
+ matchLength++;
+ }
+ return matchLength;
+}
+
+/** ZSTD_ldm_fillFastTables() :
+ *
+ * Fills the relevant tables for the ZSTD_fast and ZSTD_dfast strategies.
+ * This is similar to ZSTD_loadDictionaryContent.
+ *
+ * The tables for the other strategies are filled within their
+ * block compressors. */
+static size_t ZSTD_ldm_fillFastTables(ZSTD_matchState_t* ms,
+ void const* end)
+{
+ const BYTE* const iend = (const BYTE*)end;
+
+ switch(ms->cParams.strategy)
+ {
+ case ZSTD_fast:
+ ZSTD_fillHashTable(ms, iend, ZSTD_dtlm_fast);
+ break;
+
+ case ZSTD_dfast:
+ ZSTD_fillDoubleHashTable(ms, iend, ZSTD_dtlm_fast);
+ break;
+
+ case ZSTD_greedy:
+ case ZSTD_lazy:
+ case ZSTD_lazy2:
+ case ZSTD_btlazy2:
+ case ZSTD_btopt:
+ case ZSTD_btultra:
+ case ZSTD_btultra2:
+ break;
+ default:
+ assert(0); /* not possible : not a valid strategy id */
+ }
+
+ return 0;
+}
+
+/** ZSTD_ldm_fillLdmHashTable() :
+ *
+ * Fills hashTable from (lastHashed + 1) to iend (non-inclusive).
+ * lastHash is the rolling hash that corresponds to lastHashed.
+ *
+ * Returns the rolling hash corresponding to position iend-1. */
+static U64 ZSTD_ldm_fillLdmHashTable(ldmState_t* state,
+ U64 lastHash, const BYTE* lastHashed,
+ const BYTE* iend, const BYTE* base,
+ U32 hBits, ldmParams_t const ldmParams)
+{
+ U64 rollingHash = lastHash;
+ const BYTE* cur = lastHashed + 1;
+
+ while (cur < iend) {
+ rollingHash = ZSTD_rollingHash_rotate(rollingHash, cur[-1],
+ cur[ldmParams.minMatchLength-1],
+ state->hashPower);
+ ZSTD_ldm_makeEntryAndInsertByTag(state,
+ rollingHash, hBits,
+ (U32)(cur - base), ldmParams);
+ ++cur;
+ }
+ return rollingHash;
+}
+
+
+/** ZSTD_ldm_limitTableUpdate() :
+ *
+ * Sets cctx->nextToUpdate to a position corresponding closer to anchor
+ * if it is far way
+ * (after a long match, only update tables a limited amount). */
+static void ZSTD_ldm_limitTableUpdate(ZSTD_matchState_t* ms, const BYTE* anchor)
+{
+ U32 const current = (U32)(anchor - ms->window.base);
+ if (current > ms->nextToUpdate + 1024) {
+ ms->nextToUpdate =
+ current - MIN(512, current - ms->nextToUpdate - 1024);
+ }
+}
+
+static size_t ZSTD_ldm_generateSequences_internal(
+ ldmState_t* ldmState, rawSeqStore_t* rawSeqStore,
+ ldmParams_t const* params, void const* src, size_t srcSize)
+{
+ /* LDM parameters */
+ int const extDict = ZSTD_window_hasExtDict(ldmState->window);
+ U32 const minMatchLength = params->minMatchLength;
+ U64 const hashPower = ldmState->hashPower;
+ U32 const hBits = params->hashLog - params->bucketSizeLog;
+ U32 const ldmBucketSize = 1U << params->bucketSizeLog;
+ U32 const hashRateLog = params->hashRateLog;
+ U32 const ldmTagMask = (1U << params->hashRateLog) - 1;
+ /* Prefix and extDict parameters */
+ U32 const dictLimit = ldmState->window.dictLimit;
+ U32 const lowestIndex = extDict ? ldmState->window.lowLimit : dictLimit;
+ BYTE const* const base = ldmState->window.base;
+ BYTE const* const dictBase = extDict ? ldmState->window.dictBase : NULL;
+ BYTE const* const dictStart = extDict ? dictBase + lowestIndex : NULL;
+ BYTE const* const dictEnd = extDict ? dictBase + dictLimit : NULL;
+ BYTE const* const lowPrefixPtr = base + dictLimit;
+ /* Input bounds */
+ BYTE const* const istart = (BYTE const*)src;
+ BYTE const* const iend = istart + srcSize;
+ BYTE const* const ilimit = iend - MAX(minMatchLength, HASH_READ_SIZE);
+ /* Input positions */
+ BYTE const* anchor = istart;
+ BYTE const* ip = istart;
+ /* Rolling hash */
+ BYTE const* lastHashed = NULL;
+ U64 rollingHash = 0;
+
+ while (ip <= ilimit) {
+ size_t mLength;
+ U32 const current = (U32)(ip - base);
+ size_t forwardMatchLength = 0, backwardMatchLength = 0;
+ ldmEntry_t* bestEntry = NULL;
+ if (ip != istart) {
+ rollingHash = ZSTD_rollingHash_rotate(rollingHash, lastHashed[0],
+ lastHashed[minMatchLength],
+ hashPower);
+ } else {
+ rollingHash = ZSTD_rollingHash_compute(ip, minMatchLength);
+ }
+ lastHashed = ip;
+
+ /* Do not insert and do not look for a match */
+ if (ZSTD_ldm_getTag(rollingHash, hBits, hashRateLog) != ldmTagMask) {
+ ip++;
+ continue;
+ }
+
+ /* Get the best entry and compute the match lengths */
+ {
+ ldmEntry_t* const bucket =
+ ZSTD_ldm_getBucket(ldmState,
+ ZSTD_ldm_getSmallHash(rollingHash, hBits),
+ *params);
+ ldmEntry_t* cur;
+ size_t bestMatchLength = 0;
+ U32 const checksum = ZSTD_ldm_getChecksum(rollingHash, hBits);
+
+ for (cur = bucket; cur < bucket + ldmBucketSize; ++cur) {
+ size_t curForwardMatchLength, curBackwardMatchLength,
+ curTotalMatchLength;
+ if (cur->checksum != checksum || cur->offset <= lowestIndex) {
+ continue;
+ }
+ if (extDict) {
+ BYTE const* const curMatchBase =
+ cur->offset < dictLimit ? dictBase : base;
+ BYTE const* const pMatch = curMatchBase + cur->offset;
+ BYTE const* const matchEnd =
+ cur->offset < dictLimit ? dictEnd : iend;
+ BYTE const* const lowMatchPtr =
+ cur->offset < dictLimit ? dictStart : lowPrefixPtr;
+
+ curForwardMatchLength = ZSTD_count_2segments(
+ ip, pMatch, iend,
+ matchEnd, lowPrefixPtr);
+ if (curForwardMatchLength < minMatchLength) {
+ continue;
+ }
+ curBackwardMatchLength =
+ ZSTD_ldm_countBackwardsMatch(ip, anchor, pMatch,
+ lowMatchPtr);
+ curTotalMatchLength = curForwardMatchLength +
+ curBackwardMatchLength;
+ } else { /* !extDict */
+ BYTE const* const pMatch = base + cur->offset;
+ curForwardMatchLength = ZSTD_count(ip, pMatch, iend);
+ if (curForwardMatchLength < minMatchLength) {
+ continue;
+ }
+ curBackwardMatchLength =
+ ZSTD_ldm_countBackwardsMatch(ip, anchor, pMatch,
+ lowPrefixPtr);
+ curTotalMatchLength = curForwardMatchLength +
+ curBackwardMatchLength;
+ }
+
+ if (curTotalMatchLength > bestMatchLength) {
+ bestMatchLength = curTotalMatchLength;
+ forwardMatchLength = curForwardMatchLength;
+ backwardMatchLength = curBackwardMatchLength;
+ bestEntry = cur;
+ }
+ }
+ }
+
+ /* No match found -- continue searching */
+ if (bestEntry == NULL) {
+ ZSTD_ldm_makeEntryAndInsertByTag(ldmState, rollingHash,
+ hBits, current,
+ *params);
+ ip++;
+ continue;
+ }
+
+ /* Match found */
+ mLength = forwardMatchLength + backwardMatchLength;
+ ip -= backwardMatchLength;
+
+ {
+ /* Store the sequence:
+ * ip = current - backwardMatchLength
+ * The match is at (bestEntry->offset - backwardMatchLength)
+ */
+ U32 const matchIndex = bestEntry->offset;
+ U32 const offset = current - matchIndex;
+ rawSeq* const seq = rawSeqStore->seq + rawSeqStore->size;
+
+ /* Out of sequence storage */
+ if (rawSeqStore->size == rawSeqStore->capacity)
+ return ERROR(dstSize_tooSmall);
+ seq->litLength = (U32)(ip - anchor);
+ seq->matchLength = (U32)mLength;
+ seq->offset = offset;
+ rawSeqStore->size++;
+ }
+
+ /* Insert the current entry into the hash table */
+ ZSTD_ldm_makeEntryAndInsertByTag(ldmState, rollingHash, hBits,
+ (U32)(lastHashed - base),
+ *params);
+
+ assert(ip + backwardMatchLength == lastHashed);
+
+ /* Fill the hash table from lastHashed+1 to ip+mLength*/
+ /* Heuristic: don't need to fill the entire table at end of block */
+ if (ip + mLength <= ilimit) {
+ rollingHash = ZSTD_ldm_fillLdmHashTable(
+ ldmState, rollingHash, lastHashed,
+ ip + mLength, base, hBits, *params);
+ lastHashed = ip + mLength - 1;
+ }
+ ip += mLength;
+ anchor = ip;
+ }
+ return iend - anchor;
+}
+
+/*! ZSTD_ldm_reduceTable() :
+ * reduce table indexes by `reducerValue` */
+static void ZSTD_ldm_reduceTable(ldmEntry_t* const table, U32 const size,
+ U32 const reducerValue)
+{
+ U32 u;
+ for (u = 0; u < size; u++) {
+ if (table[u].offset < reducerValue) table[u].offset = 0;
+ else table[u].offset -= reducerValue;
+ }
+}
+
+size_t ZSTD_ldm_generateSequences(
+ ldmState_t* ldmState, rawSeqStore_t* sequences,
+ ldmParams_t const* params, void const* src, size_t srcSize)
+{
+ U32 const maxDist = 1U << params->windowLog;
+ BYTE const* const istart = (BYTE const*)src;
+ BYTE const* const iend = istart + srcSize;
+ size_t const kMaxChunkSize = 1 << 20;
+ size_t const nbChunks = (srcSize / kMaxChunkSize) + ((srcSize % kMaxChunkSize) != 0);
+ size_t chunk;
+ size_t leftoverSize = 0;
+
+ assert(ZSTD_CHUNKSIZE_MAX >= kMaxChunkSize);
+ /* Check that ZSTD_window_update() has been called for this chunk prior
+ * to passing it to this function.
+ */
+ assert(ldmState->window.nextSrc >= (BYTE const*)src + srcSize);
+ /* The input could be very large (in zstdmt), so it must be broken up into
+ * chunks to enforce the maximmum distance and handle overflow correction.
+ */
+ assert(sequences->pos <= sequences->size);
+ assert(sequences->size <= sequences->capacity);
+ for (chunk = 0; chunk < nbChunks && sequences->size < sequences->capacity; ++chunk) {
+ BYTE const* const chunkStart = istart + chunk * kMaxChunkSize;
+ size_t const remaining = (size_t)(iend - chunkStart);
+ BYTE const *const chunkEnd =
+ (remaining < kMaxChunkSize) ? iend : chunkStart + kMaxChunkSize;
+ size_t const chunkSize = chunkEnd - chunkStart;
+ size_t newLeftoverSize;
+ size_t const prevSize = sequences->size;
+
+ assert(chunkStart < iend);
+ /* 1. Perform overflow correction if necessary. */
+ if (ZSTD_window_needOverflowCorrection(ldmState->window, chunkEnd)) {
+ U32 const ldmHSize = 1U << params->hashLog;
+ U32 const correction = ZSTD_window_correctOverflow(
+ &ldmState->window, /* cycleLog */ 0, maxDist, src);
+ ZSTD_ldm_reduceTable(ldmState->hashTable, ldmHSize, correction);
+ }
+ /* 2. We enforce the maximum offset allowed.
+ *
+ * kMaxChunkSize should be small enough that we don't lose too much of
+ * the window through early invalidation.
+ * TODO: * Test the chunk size.
+ * * Try invalidation after the sequence generation and test the
+ * the offset against maxDist directly.
+ */
+ ZSTD_window_enforceMaxDist(&ldmState->window, chunkEnd, maxDist, NULL, NULL);
+ /* 3. Generate the sequences for the chunk, and get newLeftoverSize. */
+ newLeftoverSize = ZSTD_ldm_generateSequences_internal(
+ ldmState, sequences, params, chunkStart, chunkSize);
+ if (ZSTD_isError(newLeftoverSize))
+ return newLeftoverSize;
+ /* 4. We add the leftover literals from previous iterations to the first
+ * newly generated sequence, or add the `newLeftoverSize` if none are
+ * generated.
+ */
+ /* Prepend the leftover literals from the last call */
+ if (prevSize < sequences->size) {
+ sequences->seq[prevSize].litLength += (U32)leftoverSize;
+ leftoverSize = newLeftoverSize;
+ } else {
+ assert(newLeftoverSize == chunkSize);
+ leftoverSize += chunkSize;
+ }
+ }
+ return 0;
+}
+
+void ZSTD_ldm_skipSequences(rawSeqStore_t* rawSeqStore, size_t srcSize, U32 const minMatch) {
+ while (srcSize > 0 && rawSeqStore->pos < rawSeqStore->size) {
+ rawSeq* seq = rawSeqStore->seq + rawSeqStore->pos;
+ if (srcSize <= seq->litLength) {
+ /* Skip past srcSize literals */
+ seq->litLength -= (U32)srcSize;
+ return;
+ }
+ srcSize -= seq->litLength;
+ seq->litLength = 0;
+ if (srcSize < seq->matchLength) {
+ /* Skip past the first srcSize of the match */
+ seq->matchLength -= (U32)srcSize;
+ if (seq->matchLength < minMatch) {
+ /* The match is too short, omit it */
+ if (rawSeqStore->pos + 1 < rawSeqStore->size) {
+ seq[1].litLength += seq[0].matchLength;
+ }
+ rawSeqStore->pos++;
+ }
+ return;
+ }
+ srcSize -= seq->matchLength;
+ seq->matchLength = 0;
+ rawSeqStore->pos++;
+ }
+}
+
+/**
+ * If the sequence length is longer than remaining then the sequence is split
+ * between this block and the next.
+ *
+ * Returns the current sequence to handle, or if the rest of the block should
+ * be literals, it returns a sequence with offset == 0.
+ */
+static rawSeq maybeSplitSequence(rawSeqStore_t* rawSeqStore,
+ U32 const remaining, U32 const minMatch)
+{
+ rawSeq sequence = rawSeqStore->seq[rawSeqStore->pos];
+ assert(sequence.offset > 0);
+ /* Likely: No partial sequence */
+ if (remaining >= sequence.litLength + sequence.matchLength) {
+ rawSeqStore->pos++;
+ return sequence;
+ }
+ /* Cut the sequence short (offset == 0 ==> rest is literals). */
+ if (remaining <= sequence.litLength) {
+ sequence.offset = 0;
+ } else if (remaining < sequence.litLength + sequence.matchLength) {
+ sequence.matchLength = remaining - sequence.litLength;
+ if (sequence.matchLength < minMatch) {
+ sequence.offset = 0;
+ }
+ }
+ /* Skip past `remaining` bytes for the future sequences. */
+ ZSTD_ldm_skipSequences(rawSeqStore, remaining, minMatch);
+ return sequence;
+}
+
+size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore,
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ unsigned const minMatch = cParams->minMatch;
+ ZSTD_blockCompressor const blockCompressor =
+ ZSTD_selectBlockCompressor(cParams->strategy, ZSTD_matchState_dictMode(ms));
+ /* Input bounds */
+ BYTE const* const istart = (BYTE const*)src;
+ BYTE const* const iend = istart + srcSize;
+ /* Input positions */
+ BYTE const* ip = istart;
+
+ DEBUGLOG(5, "ZSTD_ldm_blockCompress: srcSize=%zu", srcSize);
+ assert(rawSeqStore->pos <= rawSeqStore->size);
+ assert(rawSeqStore->size <= rawSeqStore->capacity);
+ /* Loop through each sequence and apply the block compressor to the lits */
+ while (rawSeqStore->pos < rawSeqStore->size && ip < iend) {
+ /* maybeSplitSequence updates rawSeqStore->pos */
+ rawSeq const sequence = maybeSplitSequence(rawSeqStore,
+ (U32)(iend - ip), minMatch);
+ int i;
+ /* End signal */
+ if (sequence.offset == 0)
+ break;
+
+ assert(sequence.offset <= (1U << cParams->windowLog));
+ assert(ip + sequence.litLength + sequence.matchLength <= iend);
+
+ /* Fill tables for block compressor */
+ ZSTD_ldm_limitTableUpdate(ms, ip);
+ ZSTD_ldm_fillFastTables(ms, ip);
+ /* Run the block compressor */
+ DEBUGLOG(5, "calling block compressor on segment of size %u", sequence.litLength);
+ {
+ size_t const newLitLength =
+ blockCompressor(ms, seqStore, rep, ip, sequence.litLength);
+ ip += sequence.litLength;
+ /* Update the repcodes */
+ for (i = ZSTD_REP_NUM - 1; i > 0; i--)
+ rep[i] = rep[i-1];
+ rep[0] = sequence.offset;
+ /* Store the sequence */
+ ZSTD_storeSeq(seqStore, newLitLength, ip - newLitLength,
+ sequence.offset + ZSTD_REP_MOVE,
+ sequence.matchLength - MINMATCH);
+ ip += sequence.matchLength;
+ }
+ }
+ /* Fill the tables for the block compressor */
+ ZSTD_ldm_limitTableUpdate(ms, ip);
+ ZSTD_ldm_fillFastTables(ms, ip);
+ /* Compress the last literals */
+ return blockCompressor(ms, seqStore, rep, ip, iend - ip);
+}
diff --git a/Utilities/cmzstd/lib/compress/zstd_ldm.h b/Utilities/cmzstd/lib/compress/zstd_ldm.h
new file mode 100644
index 000000000..a47846128
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_ldm.h
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ */
+
+#ifndef ZSTD_LDM_H
+#define ZSTD_LDM_H
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#include "zstd_compress_internal.h" /* ldmParams_t, U32 */
+#include "zstd.h" /* ZSTD_CCtx, size_t */
+
+/*-*************************************
+* Long distance matching
+***************************************/
+
+#define ZSTD_LDM_DEFAULT_WINDOW_LOG ZSTD_WINDOWLOG_LIMIT_DEFAULT
+
+/**
+ * ZSTD_ldm_generateSequences():
+ *
+ * Generates the sequences using the long distance match finder.
+ * Generates long range matching sequences in `sequences`, which parse a prefix
+ * of the source. `sequences` must be large enough to store every sequence,
+ * which can be checked with `ZSTD_ldm_getMaxNbSeq()`.
+ * @returns 0 or an error code.
+ *
+ * NOTE: The user must have called ZSTD_window_update() for all of the input
+ * they have, even if they pass it to ZSTD_ldm_generateSequences() in chunks.
+ * NOTE: This function returns an error if it runs out of space to store
+ * sequences.
+ */
+size_t ZSTD_ldm_generateSequences(
+ ldmState_t* ldms, rawSeqStore_t* sequences,
+ ldmParams_t const* params, void const* src, size_t srcSize);
+
+/**
+ * ZSTD_ldm_blockCompress():
+ *
+ * Compresses a block using the predefined sequences, along with a secondary
+ * block compressor. The literals section of every sequence is passed to the
+ * secondary block compressor, and those sequences are interspersed with the
+ * predefined sequences. Returns the length of the last literals.
+ * Updates `rawSeqStore.pos` to indicate how many sequences have been consumed.
+ * `rawSeqStore.seq` may also be updated to split the last sequence between two
+ * blocks.
+ * @return The length of the last literals.
+ *
+ * NOTE: The source must be at most the maximum block size, but the predefined
+ * sequences can be any size, and may be longer than the block. In the case that
+ * they are longer than the block, the last sequences may need to be split into
+ * two. We handle that case correctly, and update `rawSeqStore` appropriately.
+ * NOTE: This function does not return any errors.
+ */
+size_t ZSTD_ldm_blockCompress(rawSeqStore_t* rawSeqStore,
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+
+/**
+ * ZSTD_ldm_skipSequences():
+ *
+ * Skip past `srcSize` bytes worth of sequences in `rawSeqStore`.
+ * Avoids emitting matches less than `minMatch` bytes.
+ * Must be called for data with is not passed to ZSTD_ldm_blockCompress().
+ */
+void ZSTD_ldm_skipSequences(rawSeqStore_t* rawSeqStore, size_t srcSize,
+ U32 const minMatch);
+
+
+/** ZSTD_ldm_getTableSize() :
+ * Estimate the space needed for long distance matching tables or 0 if LDM is
+ * disabled.
+ */
+size_t ZSTD_ldm_getTableSize(ldmParams_t params);
+
+/** ZSTD_ldm_getSeqSpace() :
+ * Return an upper bound on the number of sequences that can be produced by
+ * the long distance matcher, or 0 if LDM is disabled.
+ */
+size_t ZSTD_ldm_getMaxNbSeq(ldmParams_t params, size_t maxChunkSize);
+
+/** ZSTD_ldm_adjustParameters() :
+ * If the params->hashRateLog is not set, set it to its default value based on
+ * windowLog and params->hashLog.
+ *
+ * Ensures that params->bucketSizeLog is <= params->hashLog (setting it to
+ * params->hashLog if it is not).
+ *
+ * Ensures that the minMatchLength >= targetLength during optimal parsing.
+ */
+void ZSTD_ldm_adjustParameters(ldmParams_t* params,
+ ZSTD_compressionParameters const* cParams);
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* ZSTD_FAST_H */
diff --git a/Utilities/cmzstd/lib/compress/zstd_opt.c b/Utilities/cmzstd/lib/compress/zstd_opt.c
new file mode 100644
index 000000000..44de6e97f
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_opt.c
@@ -0,0 +1,1217 @@
+/*
+ * Copyright (c) 2016-present, Przemyslaw Skibinski, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#include "zstd_compress_internal.h"
+#include "hist.h"
+#include "zstd_opt.h"
+
+
+#define ZSTD_LITFREQ_ADD 2 /* scaling factor for litFreq, so that frequencies adapt faster to new stats */
+#define ZSTD_FREQ_DIV 4 /* log factor when using previous stats to init next stats */
+#define ZSTD_MAX_PRICE (1<<30)
+
+#define ZSTD_PREDEF_THRESHOLD 1024 /* if srcSize < ZSTD_PREDEF_THRESHOLD, symbols' cost is assumed static, directly determined by pre-defined distributions */
+
+
+/*-*************************************
+* Price functions for optimal parser
+***************************************/
+
+#if 0 /* approximation at bit level */
+# define BITCOST_ACCURACY 0
+# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
+# define WEIGHT(stat) ((void)opt, ZSTD_bitWeight(stat))
+#elif 0 /* fractional bit accuracy */
+# define BITCOST_ACCURACY 8
+# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
+# define WEIGHT(stat,opt) ((void)opt, ZSTD_fracWeight(stat))
+#else /* opt==approx, ultra==accurate */
+# define BITCOST_ACCURACY 8
+# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)
+# define WEIGHT(stat,opt) (opt ? ZSTD_fracWeight(stat) : ZSTD_bitWeight(stat))
+#endif
+
+MEM_STATIC U32 ZSTD_bitWeight(U32 stat)
+{
+ return (ZSTD_highbit32(stat+1) * BITCOST_MULTIPLIER);
+}
+
+MEM_STATIC U32 ZSTD_fracWeight(U32 rawStat)
+{
+ U32 const stat = rawStat + 1;
+ U32 const hb = ZSTD_highbit32(stat);
+ U32 const BWeight = hb * BITCOST_MULTIPLIER;
+ U32 const FWeight = (stat << BITCOST_ACCURACY) >> hb;
+ U32 const weight = BWeight + FWeight;
+ assert(hb + BITCOST_ACCURACY < 31);
+ return weight;
+}
+
+#if (DEBUGLEVEL>=2)
+/* debugging function,
+ * @return price in bytes as fractional value
+ * for debug messages only */
+MEM_STATIC double ZSTD_fCost(U32 price)
+{
+ return (double)price / (BITCOST_MULTIPLIER*8);
+}
+#endif
+
+static void ZSTD_setBasePrices(optState_t* optPtr, int optLevel)
+{
+ optPtr->litSumBasePrice = WEIGHT(optPtr->litSum, optLevel);
+ optPtr->litLengthSumBasePrice = WEIGHT(optPtr->litLengthSum, optLevel);
+ optPtr->matchLengthSumBasePrice = WEIGHT(optPtr->matchLengthSum, optLevel);
+ optPtr->offCodeSumBasePrice = WEIGHT(optPtr->offCodeSum, optLevel);
+}
+
+
+/* ZSTD_downscaleStat() :
+ * reduce all elements in table by a factor 2^(ZSTD_FREQ_DIV+malus)
+ * return the resulting sum of elements */
+static U32 ZSTD_downscaleStat(unsigned* table, U32 lastEltIndex, int malus)
+{
+ U32 s, sum=0;
+ DEBUGLOG(5, "ZSTD_downscaleStat (nbElts=%u)", (unsigned)lastEltIndex+1);
+ assert(ZSTD_FREQ_DIV+malus > 0 && ZSTD_FREQ_DIV+malus < 31);
+ for (s=0; s<lastEltIndex+1; s++) {
+ table[s] = 1 + (table[s] >> (ZSTD_FREQ_DIV+malus));
+ sum += table[s];
+ }
+ return sum;
+}
+
+/* ZSTD_rescaleFreqs() :
+ * if first block (detected by optPtr->litLengthSum == 0) : init statistics
+ * take hints from dictionary if there is one
+ * or init from zero, using src for literals stats, or flat 1 for match symbols
+ * otherwise downscale existing stats, to be used as seed for next block.
+ */
+static void
+ZSTD_rescaleFreqs(optState_t* const optPtr,
+ const BYTE* const src, size_t const srcSize,
+ int const optLevel)
+{
+ DEBUGLOG(5, "ZSTD_rescaleFreqs (srcSize=%u)", (unsigned)srcSize);
+ optPtr->priceType = zop_dynamic;
+
+ if (optPtr->litLengthSum == 0) { /* first block : init */
+ if (srcSize <= ZSTD_PREDEF_THRESHOLD) { /* heuristic */
+ DEBUGLOG(5, "(srcSize <= ZSTD_PREDEF_THRESHOLD) => zop_predef");
+ optPtr->priceType = zop_predef;
+ }
+
+ assert(optPtr->symbolCosts != NULL);
+ if (optPtr->symbolCosts->huf.repeatMode == HUF_repeat_valid) {
+ /* huffman table presumed generated by dictionary */
+ optPtr->priceType = zop_dynamic;
+
+ assert(optPtr->litFreq != NULL);
+ optPtr->litSum = 0;
+ { unsigned lit;
+ for (lit=0; lit<=MaxLit; lit++) {
+ U32 const scaleLog = 11; /* scale to 2K */
+ U32 const bitCost = HUF_getNbBits(optPtr->symbolCosts->huf.CTable, lit);
+ assert(bitCost <= scaleLog);
+ optPtr->litFreq[lit] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
+ optPtr->litSum += optPtr->litFreq[lit];
+ } }
+
+ { unsigned ll;
+ FSE_CState_t llstate;
+ FSE_initCState(&llstate, optPtr->symbolCosts->fse.litlengthCTable);
+ optPtr->litLengthSum = 0;
+ for (ll=0; ll<=MaxLL; ll++) {
+ U32 const scaleLog = 10; /* scale to 1K */
+ U32 const bitCost = FSE_getMaxNbBits(llstate.symbolTT, ll);
+ assert(bitCost < scaleLog);
+ optPtr->litLengthFreq[ll] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
+ optPtr->litLengthSum += optPtr->litLengthFreq[ll];
+ } }
+
+ { unsigned ml;
+ FSE_CState_t mlstate;
+ FSE_initCState(&mlstate, optPtr->symbolCosts->fse.matchlengthCTable);
+ optPtr->matchLengthSum = 0;
+ for (ml=0; ml<=MaxML; ml++) {
+ U32 const scaleLog = 10;
+ U32 const bitCost = FSE_getMaxNbBits(mlstate.symbolTT, ml);
+ assert(bitCost < scaleLog);
+ optPtr->matchLengthFreq[ml] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
+ optPtr->matchLengthSum += optPtr->matchLengthFreq[ml];
+ } }
+
+ { unsigned of;
+ FSE_CState_t ofstate;
+ FSE_initCState(&ofstate, optPtr->symbolCosts->fse.offcodeCTable);
+ optPtr->offCodeSum = 0;
+ for (of=0; of<=MaxOff; of++) {
+ U32 const scaleLog = 10;
+ U32 const bitCost = FSE_getMaxNbBits(ofstate.symbolTT, of);
+ assert(bitCost < scaleLog);
+ optPtr->offCodeFreq[of] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;
+ optPtr->offCodeSum += optPtr->offCodeFreq[of];
+ } }
+
+ } else { /* not a dictionary */
+
+ assert(optPtr->litFreq != NULL);
+ { unsigned lit = MaxLit;
+ HIST_count_simple(optPtr->litFreq, &lit, src, srcSize); /* use raw first block to init statistics */
+ }
+ optPtr->litSum = ZSTD_downscaleStat(optPtr->litFreq, MaxLit, 1);
+
+ { unsigned ll;
+ for (ll=0; ll<=MaxLL; ll++)
+ optPtr->litLengthFreq[ll] = 1;
+ }
+ optPtr->litLengthSum = MaxLL+1;
+
+ { unsigned ml;
+ for (ml=0; ml<=MaxML; ml++)
+ optPtr->matchLengthFreq[ml] = 1;
+ }
+ optPtr->matchLengthSum = MaxML+1;
+
+ { unsigned of;
+ for (of=0; of<=MaxOff; of++)
+ optPtr->offCodeFreq[of] = 1;
+ }
+ optPtr->offCodeSum = MaxOff+1;
+
+ }
+
+ } else { /* new block : re-use previous statistics, scaled down */
+
+ optPtr->litSum = ZSTD_downscaleStat(optPtr->litFreq, MaxLit, 1);
+ optPtr->litLengthSum = ZSTD_downscaleStat(optPtr->litLengthFreq, MaxLL, 0);
+ optPtr->matchLengthSum = ZSTD_downscaleStat(optPtr->matchLengthFreq, MaxML, 0);
+ optPtr->offCodeSum = ZSTD_downscaleStat(optPtr->offCodeFreq, MaxOff, 0);
+ }
+
+ ZSTD_setBasePrices(optPtr, optLevel);
+}
+
+/* ZSTD_rawLiteralsCost() :
+ * price of literals (only) in specified segment (which length can be 0).
+ * does not include price of literalLength symbol */
+static U32 ZSTD_rawLiteralsCost(const BYTE* const literals, U32 const litLength,
+ const optState_t* const optPtr,
+ int optLevel)
+{
+ if (litLength == 0) return 0;
+ if (optPtr->priceType == zop_predef)
+ return (litLength*6) * BITCOST_MULTIPLIER; /* 6 bit per literal - no statistic used */
+
+ /* dynamic statistics */
+ { U32 price = litLength * optPtr->litSumBasePrice;
+ U32 u;
+ for (u=0; u < litLength; u++) {
+ assert(WEIGHT(optPtr->litFreq[literals[u]], optLevel) <= optPtr->litSumBasePrice); /* literal cost should never be negative */
+ price -= WEIGHT(optPtr->litFreq[literals[u]], optLevel);
+ }
+ return price;
+ }
+}
+
+/* ZSTD_litLengthPrice() :
+ * cost of literalLength symbol */
+static U32 ZSTD_litLengthPrice(U32 const litLength, const optState_t* const optPtr, int optLevel)
+{
+ if (optPtr->priceType == zop_predef) return WEIGHT(litLength, optLevel);
+
+ /* dynamic statistics */
+ { U32 const llCode = ZSTD_LLcode(litLength);
+ return (LL_bits[llCode] * BITCOST_MULTIPLIER)
+ + optPtr->litLengthSumBasePrice
+ - WEIGHT(optPtr->litLengthFreq[llCode], optLevel);
+ }
+}
+
+/* ZSTD_litLengthContribution() :
+ * @return ( cost(litlength) - cost(0) )
+ * this value can then be added to rawLiteralsCost()
+ * to provide a cost which is directly comparable to a match ending at same position */
+static int ZSTD_litLengthContribution(U32 const litLength, const optState_t* const optPtr, int optLevel)
+{
+ if (optPtr->priceType >= zop_predef) return WEIGHT(litLength, optLevel);
+
+ /* dynamic statistics */
+ { U32 const llCode = ZSTD_LLcode(litLength);
+ int const contribution = (LL_bits[llCode] * BITCOST_MULTIPLIER)
+ + WEIGHT(optPtr->litLengthFreq[0], optLevel) /* note: log2litLengthSum cancel out */
+ - WEIGHT(optPtr->litLengthFreq[llCode], optLevel);
+#if 1
+ return contribution;
+#else
+ return MAX(0, contribution); /* sometimes better, sometimes not ... */
+#endif
+ }
+}
+
+/* ZSTD_literalsContribution() :
+ * creates a fake cost for the literals part of a sequence
+ * which can be compared to the ending cost of a match
+ * should a new match start at this position */
+static int ZSTD_literalsContribution(const BYTE* const literals, U32 const litLength,
+ const optState_t* const optPtr,
+ int optLevel)
+{
+ int const contribution = ZSTD_rawLiteralsCost(literals, litLength, optPtr, optLevel)
+ + ZSTD_litLengthContribution(litLength, optPtr, optLevel);
+ return contribution;
+}
+
+/* ZSTD_getMatchPrice() :
+ * Provides the cost of the match part (offset + matchLength) of a sequence
+ * Must be combined with ZSTD_fullLiteralsCost() to get the full cost of a sequence.
+ * optLevel: when <2, favors small offset for decompression speed (improved cache efficiency) */
+FORCE_INLINE_TEMPLATE U32
+ZSTD_getMatchPrice(U32 const offset,
+ U32 const matchLength,
+ const optState_t* const optPtr,
+ int const optLevel)
+{
+ U32 price;
+ U32 const offCode = ZSTD_highbit32(offset+1);
+ U32 const mlBase = matchLength - MINMATCH;
+ assert(matchLength >= MINMATCH);
+
+ if (optPtr->priceType == zop_predef) /* fixed scheme, do not use statistics */
+ return WEIGHT(mlBase, optLevel) + ((16 + offCode) * BITCOST_MULTIPLIER);
+
+ /* dynamic statistics */
+ price = (offCode * BITCOST_MULTIPLIER) + (optPtr->offCodeSumBasePrice - WEIGHT(optPtr->offCodeFreq[offCode], optLevel));
+ if ((optLevel<2) /*static*/ && offCode >= 20)
+ price += (offCode-19)*2 * BITCOST_MULTIPLIER; /* handicap for long distance offsets, favor decompression speed */
+
+ /* match Length */
+ { U32 const mlCode = ZSTD_MLcode(mlBase);
+ price += (ML_bits[mlCode] * BITCOST_MULTIPLIER) + (optPtr->matchLengthSumBasePrice - WEIGHT(optPtr->matchLengthFreq[mlCode], optLevel));
+ }
+
+ price += BITCOST_MULTIPLIER / 5; /* heuristic : make matches a bit more costly to favor less sequences -> faster decompression speed */
+
+ DEBUGLOG(8, "ZSTD_getMatchPrice(ml:%u) = %u", matchLength, price);
+ return price;
+}
+
+/* ZSTD_updateStats() :
+ * assumption : literals + litLengtn <= iend */
+static void ZSTD_updateStats(optState_t* const optPtr,
+ U32 litLength, const BYTE* literals,
+ U32 offsetCode, U32 matchLength)
+{
+ /* literals */
+ { U32 u;
+ for (u=0; u < litLength; u++)
+ optPtr->litFreq[literals[u]] += ZSTD_LITFREQ_ADD;
+ optPtr->litSum += litLength*ZSTD_LITFREQ_ADD;
+ }
+
+ /* literal Length */
+ { U32 const llCode = ZSTD_LLcode(litLength);
+ optPtr->litLengthFreq[llCode]++;
+ optPtr->litLengthSum++;
+ }
+
+ /* match offset code (0-2=>repCode; 3+=>offset+2) */
+ { U32 const offCode = ZSTD_highbit32(offsetCode+1);
+ assert(offCode <= MaxOff);
+ optPtr->offCodeFreq[offCode]++;
+ optPtr->offCodeSum++;
+ }
+
+ /* match Length */
+ { U32 const mlBase = matchLength - MINMATCH;
+ U32 const mlCode = ZSTD_MLcode(mlBase);
+ optPtr->matchLengthFreq[mlCode]++;
+ optPtr->matchLengthSum++;
+ }
+}
+
+
+/* ZSTD_readMINMATCH() :
+ * function safe only for comparisons
+ * assumption : memPtr must be at least 4 bytes before end of buffer */
+MEM_STATIC U32 ZSTD_readMINMATCH(const void* memPtr, U32 length)
+{
+ switch (length)
+ {
+ default :
+ case 4 : return MEM_read32(memPtr);
+ case 3 : if (MEM_isLittleEndian())
+ return MEM_read32(memPtr)<<8;
+ else
+ return MEM_read32(memPtr)>>8;
+ }
+}
+
+
+/* Update hashTable3 up to ip (excluded)
+ Assumption : always within prefix (i.e. not within extDict) */
+static U32 ZSTD_insertAndFindFirstIndexHash3 (ZSTD_matchState_t* ms, const BYTE* const ip)
+{
+ U32* const hashTable3 = ms->hashTable3;
+ U32 const hashLog3 = ms->hashLog3;
+ const BYTE* const base = ms->window.base;
+ U32 idx = ms->nextToUpdate3;
+ U32 const target = ms->nextToUpdate3 = (U32)(ip - base);
+ size_t const hash3 = ZSTD_hash3Ptr(ip, hashLog3);
+ assert(hashLog3 > 0);
+
+ while(idx < target) {
+ hashTable3[ZSTD_hash3Ptr(base+idx, hashLog3)] = idx;
+ idx++;
+ }
+
+ return hashTable3[hash3];
+}
+
+
+/*-*************************************
+* Binary Tree search
+***************************************/
+/** ZSTD_insertBt1() : add one or multiple positions to tree.
+ * ip : assumed <= iend-8 .
+ * @return : nb of positions added */
+static U32 ZSTD_insertBt1(
+ ZSTD_matchState_t* ms,
+ const BYTE* const ip, const BYTE* const iend,
+ U32 const mls, const int extDict)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32* const hashTable = ms->hashTable;
+ U32 const hashLog = cParams->hashLog;
+ size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
+ U32* const bt = ms->chainTable;
+ U32 const btLog = cParams->chainLog - 1;
+ U32 const btMask = (1 << btLog) - 1;
+ U32 matchIndex = hashTable[h];
+ size_t commonLengthSmaller=0, commonLengthLarger=0;
+ const BYTE* const base = ms->window.base;
+ const BYTE* const dictBase = ms->window.dictBase;
+ const U32 dictLimit = ms->window.dictLimit;
+ const BYTE* const dictEnd = dictBase + dictLimit;
+ const BYTE* const prefixStart = base + dictLimit;
+ const BYTE* match;
+ const U32 current = (U32)(ip-base);
+ const U32 btLow = btMask >= current ? 0 : current - btMask;
+ U32* smallerPtr = bt + 2*(current&btMask);
+ U32* largerPtr = smallerPtr + 1;
+ U32 dummy32; /* to be nullified at the end */
+ U32 const windowLow = ms->window.lowLimit;
+ U32 matchEndIdx = current+8+1;
+ size_t bestLength = 8;
+ U32 nbCompares = 1U << cParams->searchLog;
+#ifdef ZSTD_C_PREDICT
+ U32 predictedSmall = *(bt + 2*((current-1)&btMask) + 0);
+ U32 predictedLarge = *(bt + 2*((current-1)&btMask) + 1);
+ predictedSmall += (predictedSmall>0);
+ predictedLarge += (predictedLarge>0);
+#endif /* ZSTD_C_PREDICT */
+
+ DEBUGLOG(8, "ZSTD_insertBt1 (%u)", current);
+
+ assert(ip <= iend-8); /* required for h calculation */
+ hashTable[h] = current; /* Update Hash Table */
+
+ assert(windowLow > 0);
+ while (nbCompares-- && (matchIndex >= windowLow)) {
+ U32* const nextPtr = bt + 2*(matchIndex & btMask);
+ size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
+ assert(matchIndex < current);
+
+#ifdef ZSTD_C_PREDICT /* note : can create issues when hlog small <= 11 */
+ const U32* predictPtr = bt + 2*((matchIndex-1) & btMask); /* written this way, as bt is a roll buffer */
+ if (matchIndex == predictedSmall) {
+ /* no need to check length, result known */
+ *smallerPtr = matchIndex;
+ if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
+ smallerPtr = nextPtr+1; /* new "smaller" => larger of match */
+ matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
+ predictedSmall = predictPtr[1] + (predictPtr[1]>0);
+ continue;
+ }
+ if (matchIndex == predictedLarge) {
+ *largerPtr = matchIndex;
+ if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
+ largerPtr = nextPtr;
+ matchIndex = nextPtr[0];
+ predictedLarge = predictPtr[0] + (predictPtr[0]>0);
+ continue;
+ }
+#endif
+
+ if (!extDict || (matchIndex+matchLength >= dictLimit)) {
+ assert(matchIndex+matchLength >= dictLimit); /* might be wrong if actually extDict */
+ match = base + matchIndex;
+ matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);
+ } else {
+ match = dictBase + matchIndex;
+ matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);
+ if (matchIndex+matchLength >= dictLimit)
+ match = base + matchIndex; /* to prepare for next usage of match[matchLength] */
+ }
+
+ if (matchLength > bestLength) {
+ bestLength = matchLength;
+ if (matchLength > matchEndIdx - matchIndex)
+ matchEndIdx = matchIndex + (U32)matchLength;
+ }
+
+ if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */
+ break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */
+ }
+
+ if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */
+ /* match is smaller than current */
+ *smallerPtr = matchIndex; /* update smaller idx */
+ commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
+ if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */
+ smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */
+ matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */
+ } else {
+ /* match is larger than current */
+ *largerPtr = matchIndex;
+ commonLengthLarger = matchLength;
+ if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */
+ largerPtr = nextPtr;
+ matchIndex = nextPtr[0];
+ } }
+
+ *smallerPtr = *largerPtr = 0;
+ if (bestLength > 384) return MIN(192, (U32)(bestLength - 384)); /* speed optimization */
+ assert(matchEndIdx > current + 8);
+ return matchEndIdx - (current + 8);
+}
+
+FORCE_INLINE_TEMPLATE
+void ZSTD_updateTree_internal(
+ ZSTD_matchState_t* ms,
+ const BYTE* const ip, const BYTE* const iend,
+ const U32 mls, const ZSTD_dictMode_e dictMode)
+{
+ const BYTE* const base = ms->window.base;
+ U32 const target = (U32)(ip - base);
+ U32 idx = ms->nextToUpdate;
+ DEBUGLOG(6, "ZSTD_updateTree_internal, from %u to %u (dictMode:%u)",
+ idx, target, dictMode);
+
+ while(idx < target)
+ idx += ZSTD_insertBt1(ms, base+idx, iend, mls, dictMode == ZSTD_extDict);
+ ms->nextToUpdate = target;
+}
+
+void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend) {
+ ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict);
+}
+
+FORCE_INLINE_TEMPLATE
+U32 ZSTD_insertBtAndGetAllMatches (
+ ZSTD_matchState_t* ms,
+ const BYTE* const ip, const BYTE* const iLimit, const ZSTD_dictMode_e dictMode,
+ U32 rep[ZSTD_REP_NUM],
+ U32 const ll0, /* tells if associated literal length is 0 or not. This value must be 0 or 1 */
+ ZSTD_match_t* matches,
+ const U32 lengthToBeat,
+ U32 const mls /* template */)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);
+ const BYTE* const base = ms->window.base;
+ U32 const current = (U32)(ip-base);
+ U32 const hashLog = cParams->hashLog;
+ U32 const minMatch = (mls==3) ? 3 : 4;
+ U32* const hashTable = ms->hashTable;
+ size_t const h = ZSTD_hashPtr(ip, hashLog, mls);
+ U32 matchIndex = hashTable[h];
+ U32* const bt = ms->chainTable;
+ U32 const btLog = cParams->chainLog - 1;
+ U32 const btMask= (1U << btLog) - 1;
+ size_t commonLengthSmaller=0, commonLengthLarger=0;
+ const BYTE* const dictBase = ms->window.dictBase;
+ U32 const dictLimit = ms->window.dictLimit;
+ const BYTE* const dictEnd = dictBase + dictLimit;
+ const BYTE* const prefixStart = base + dictLimit;
+ U32 const btLow = btMask >= current ? 0 : current - btMask;
+ U32 const windowLow = ms->window.lowLimit;
+ U32 const matchLow = windowLow ? windowLow : 1;
+ U32* smallerPtr = bt + 2*(current&btMask);
+ U32* largerPtr = bt + 2*(current&btMask) + 1;
+ U32 matchEndIdx = current+8+1; /* farthest referenced position of any match => detects repetitive patterns */
+ U32 dummy32; /* to be nullified at the end */
+ U32 mnum = 0;
+ U32 nbCompares = 1U << cParams->searchLog;
+
+ const ZSTD_matchState_t* dms = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL;
+ const ZSTD_compressionParameters* const dmsCParams =
+ dictMode == ZSTD_dictMatchState ? &dms->cParams : NULL;
+ const BYTE* const dmsBase = dictMode == ZSTD_dictMatchState ? dms->window.base : NULL;
+ const BYTE* const dmsEnd = dictMode == ZSTD_dictMatchState ? dms->window.nextSrc : NULL;
+ U32 const dmsHighLimit = dictMode == ZSTD_dictMatchState ? (U32)(dmsEnd - dmsBase) : 0;
+ U32 const dmsLowLimit = dictMode == ZSTD_dictMatchState ? dms->window.lowLimit : 0;
+ U32 const dmsIndexDelta = dictMode == ZSTD_dictMatchState ? windowLow - dmsHighLimit : 0;
+ U32 const dmsHashLog = dictMode == ZSTD_dictMatchState ? dmsCParams->hashLog : hashLog;
+ U32 const dmsBtLog = dictMode == ZSTD_dictMatchState ? dmsCParams->chainLog - 1 : btLog;
+ U32 const dmsBtMask = dictMode == ZSTD_dictMatchState ? (1U << dmsBtLog) - 1 : 0;
+ U32 const dmsBtLow = dictMode == ZSTD_dictMatchState && dmsBtMask < dmsHighLimit - dmsLowLimit ? dmsHighLimit - dmsBtMask : dmsLowLimit;
+
+ size_t bestLength = lengthToBeat-1;
+ DEBUGLOG(8, "ZSTD_insertBtAndGetAllMatches: current=%u", current);
+
+ /* check repCode */
+ assert(ll0 <= 1); /* necessarily 1 or 0 */
+ { U32 const lastR = ZSTD_REP_NUM + ll0;
+ U32 repCode;
+ for (repCode = ll0; repCode < lastR; repCode++) {
+ U32 const repOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
+ U32 const repIndex = current - repOffset;
+ U32 repLen = 0;
+ assert(current >= dictLimit);
+ if (repOffset-1 /* intentional overflow, discards 0 and -1 */ < current-dictLimit) { /* equivalent to `current > repIndex >= dictLimit` */
+ if (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(ip - repOffset, minMatch)) {
+ repLen = (U32)ZSTD_count(ip+minMatch, ip+minMatch-repOffset, iLimit) + minMatch;
+ }
+ } else { /* repIndex < dictLimit || repIndex >= current */
+ const BYTE* const repMatch = dictMode == ZSTD_dictMatchState ?
+ dmsBase + repIndex - dmsIndexDelta :
+ dictBase + repIndex;
+ assert(current >= windowLow);
+ if ( dictMode == ZSTD_extDict
+ && ( ((repOffset-1) /*intentional overflow*/ < current - windowLow) /* equivalent to `current > repIndex >= windowLow` */
+ & (((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */)
+ && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {
+ repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dictEnd, prefixStart) + minMatch;
+ }
+ if (dictMode == ZSTD_dictMatchState
+ && ( ((repOffset-1) /*intentional overflow*/ < current - (dmsLowLimit + dmsIndexDelta)) /* equivalent to `current > repIndex >= dmsLowLimit` */
+ & ((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */
+ && (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {
+ repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dmsEnd, prefixStart) + minMatch;
+ } }
+ /* save longer solution */
+ if (repLen > bestLength) {
+ DEBUGLOG(8, "found repCode %u (ll0:%u, offset:%u) of length %u",
+ repCode, ll0, repOffset, repLen);
+ bestLength = repLen;
+ matches[mnum].off = repCode - ll0;
+ matches[mnum].len = (U32)repLen;
+ mnum++;
+ if ( (repLen > sufficient_len)
+ | (ip+repLen == iLimit) ) { /* best possible */
+ return mnum;
+ } } } }
+
+ /* HC3 match finder */
+ if ((mls == 3) /*static*/ && (bestLength < mls)) {
+ U32 const matchIndex3 = ZSTD_insertAndFindFirstIndexHash3(ms, ip);
+ if ((matchIndex3 >= matchLow)
+ & (current - matchIndex3 < (1<<18)) /*heuristic : longer distance likely too expensive*/ ) {
+ size_t mlen;
+ if ((dictMode == ZSTD_noDict) /*static*/ || (dictMode == ZSTD_dictMatchState) /*static*/ || (matchIndex3 >= dictLimit)) {
+ const BYTE* const match = base + matchIndex3;
+ mlen = ZSTD_count(ip, match, iLimit);
+ } else {
+ const BYTE* const match = dictBase + matchIndex3;
+ mlen = ZSTD_count_2segments(ip, match, iLimit, dictEnd, prefixStart);
+ }
+
+ /* save best solution */
+ if (mlen >= mls /* == 3 > bestLength */) {
+ DEBUGLOG(8, "found small match with hlog3, of length %u",
+ (U32)mlen);
+ bestLength = mlen;
+ assert(current > matchIndex3);
+ assert(mnum==0); /* no prior solution */
+ matches[0].off = (current - matchIndex3) + ZSTD_REP_MOVE;
+ matches[0].len = (U32)mlen;
+ mnum = 1;
+ if ( (mlen > sufficient_len) |
+ (ip+mlen == iLimit) ) { /* best possible length */
+ ms->nextToUpdate = current+1; /* skip insertion */
+ return 1;
+ }
+ }
+ }
+ /* no dictMatchState lookup: dicts don't have a populated HC3 table */
+ }
+
+ hashTable[h] = current; /* Update Hash Table */
+
+ while (nbCompares-- && (matchIndex >= matchLow)) {
+ U32* const nextPtr = bt + 2*(matchIndex & btMask);
+ size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
+ const BYTE* match;
+ assert(current > matchIndex);
+
+ if ((dictMode == ZSTD_noDict) || (dictMode == ZSTD_dictMatchState) || (matchIndex+matchLength >= dictLimit)) {
+ assert(matchIndex+matchLength >= dictLimit); /* ensure the condition is correct when !extDict */
+ match = base + matchIndex;
+ matchLength += ZSTD_count(ip+matchLength, match+matchLength, iLimit);
+ } else {
+ match = dictBase + matchIndex;
+ matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dictEnd, prefixStart);
+ if (matchIndex+matchLength >= dictLimit)
+ match = base + matchIndex; /* prepare for match[matchLength] */
+ }
+
+ if (matchLength > bestLength) {
+ DEBUGLOG(8, "found match of length %u at distance %u (offCode=%u)",
+ (U32)matchLength, current - matchIndex, current - matchIndex + ZSTD_REP_MOVE);
+ assert(matchEndIdx > matchIndex);
+ if (matchLength > matchEndIdx - matchIndex)
+ matchEndIdx = matchIndex + (U32)matchLength;
+ bestLength = matchLength;
+ matches[mnum].off = (current - matchIndex) + ZSTD_REP_MOVE;
+ matches[mnum].len = (U32)matchLength;
+ mnum++;
+ if ( (matchLength > ZSTD_OPT_NUM)
+ | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {
+ if (dictMode == ZSTD_dictMatchState) nbCompares = 0; /* break should also skip searching dms */
+ break; /* drop, to preserve bt consistency (miss a little bit of compression) */
+ }
+ }
+
+ if (match[matchLength] < ip[matchLength]) {
+ /* match smaller than current */
+ *smallerPtr = matchIndex; /* update smaller idx */
+ commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
+ if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */
+ smallerPtr = nextPtr+1; /* new candidate => larger than match, which was smaller than current */
+ matchIndex = nextPtr[1]; /* new matchIndex, larger than previous, closer to current */
+ } else {
+ *largerPtr = matchIndex;
+ commonLengthLarger = matchLength;
+ if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */
+ largerPtr = nextPtr;
+ matchIndex = nextPtr[0];
+ } }
+
+ *smallerPtr = *largerPtr = 0;
+
+ if (dictMode == ZSTD_dictMatchState && nbCompares) {
+ size_t const dmsH = ZSTD_hashPtr(ip, dmsHashLog, mls);
+ U32 dictMatchIndex = dms->hashTable[dmsH];
+ const U32* const dmsBt = dms->chainTable;
+ commonLengthSmaller = commonLengthLarger = 0;
+ while (nbCompares-- && (dictMatchIndex > dmsLowLimit)) {
+ const U32* const nextPtr = dmsBt + 2*(dictMatchIndex & dmsBtMask);
+ size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */
+ const BYTE* match = dmsBase + dictMatchIndex;
+ matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dmsEnd, prefixStart);
+ if (dictMatchIndex+matchLength >= dmsHighLimit)
+ match = base + dictMatchIndex + dmsIndexDelta; /* to prepare for next usage of match[matchLength] */
+
+ if (matchLength > bestLength) {
+ matchIndex = dictMatchIndex + dmsIndexDelta;
+ DEBUGLOG(8, "found dms match of length %u at distance %u (offCode=%u)",
+ (U32)matchLength, current - matchIndex, current - matchIndex + ZSTD_REP_MOVE);
+ if (matchLength > matchEndIdx - matchIndex)
+ matchEndIdx = matchIndex + (U32)matchLength;
+ bestLength = matchLength;
+ matches[mnum].off = (current - matchIndex) + ZSTD_REP_MOVE;
+ matches[mnum].len = (U32)matchLength;
+ mnum++;
+ if ( (matchLength > ZSTD_OPT_NUM)
+ | (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {
+ break; /* drop, to guarantee consistency (miss a little bit of compression) */
+ }
+ }
+
+ if (dictMatchIndex <= dmsBtLow) { break; } /* beyond tree size, stop the search */
+ if (match[matchLength] < ip[matchLength]) {
+ commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */
+ dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */
+ } else {
+ /* match is larger than current */
+ commonLengthLarger = matchLength;
+ dictMatchIndex = nextPtr[0];
+ }
+ }
+ }
+
+ assert(matchEndIdx > current+8);
+ ms->nextToUpdate = matchEndIdx - 8; /* skip repetitive patterns */
+ return mnum;
+}
+
+
+FORCE_INLINE_TEMPLATE U32 ZSTD_BtGetAllMatches (
+ ZSTD_matchState_t* ms,
+ const BYTE* ip, const BYTE* const iHighLimit, const ZSTD_dictMode_e dictMode,
+ U32 rep[ZSTD_REP_NUM], U32 const ll0,
+ ZSTD_match_t* matches, U32 const lengthToBeat)
+{
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+ U32 const matchLengthSearch = cParams->minMatch;
+ DEBUGLOG(8, "ZSTD_BtGetAllMatches");
+ if (ip < ms->window.base + ms->nextToUpdate) return 0; /* skipped area */
+ ZSTD_updateTree_internal(ms, ip, iHighLimit, matchLengthSearch, dictMode);
+ switch(matchLengthSearch)
+ {
+ case 3 : return ZSTD_insertBtAndGetAllMatches(ms, ip, iHighLimit, dictMode, rep, ll0, matches, lengthToBeat, 3);
+ default :
+ case 4 : return ZSTD_insertBtAndGetAllMatches(ms, ip, iHighLimit, dictMode, rep, ll0, matches, lengthToBeat, 4);
+ case 5 : return ZSTD_insertBtAndGetAllMatches(ms, ip, iHighLimit, dictMode, rep, ll0, matches, lengthToBeat, 5);
+ case 7 :
+ case 6 : return ZSTD_insertBtAndGetAllMatches(ms, ip, iHighLimit, dictMode, rep, ll0, matches, lengthToBeat, 6);
+ }
+}
+
+
+/*-*******************************
+* Optimal parser
+*********************************/
+typedef struct repcodes_s {
+ U32 rep[3];
+} repcodes_t;
+
+static repcodes_t ZSTD_updateRep(U32 const rep[3], U32 const offset, U32 const ll0)
+{
+ repcodes_t newReps;
+ if (offset >= ZSTD_REP_NUM) { /* full offset */
+ newReps.rep[2] = rep[1];
+ newReps.rep[1] = rep[0];
+ newReps.rep[0] = offset - ZSTD_REP_MOVE;
+ } else { /* repcode */
+ U32 const repCode = offset + ll0;
+ if (repCode > 0) { /* note : if repCode==0, no change */
+ U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
+ newReps.rep[2] = (repCode >= 2) ? rep[1] : rep[2];
+ newReps.rep[1] = rep[0];
+ newReps.rep[0] = currentOffset;
+ } else { /* repCode == 0 */
+ memcpy(&newReps, rep, sizeof(newReps));
+ }
+ }
+ return newReps;
+}
+
+
+static U32 ZSTD_totalLen(ZSTD_optimal_t sol)
+{
+ return sol.litlen + sol.mlen;
+}
+
+#if 0 /* debug */
+
+static void
+listStats(const U32* table, int lastEltID)
+{
+ int const nbElts = lastEltID + 1;
+ int enb;
+ for (enb=0; enb < nbElts; enb++) {
+ (void)table;
+ //RAWLOG(2, "%3i:%3i, ", enb, table[enb]);
+ RAWLOG(2, "%4i,", table[enb]);
+ }
+ RAWLOG(2, " \n");
+}
+
+#endif
+
+FORCE_INLINE_TEMPLATE size_t
+ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,
+ seqStore_t* seqStore,
+ U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize,
+ const int optLevel,
+ const ZSTD_dictMode_e dictMode)
+{
+ optState_t* const optStatePtr = &ms->opt;
+ const BYTE* const istart = (const BYTE*)src;
+ const BYTE* ip = istart;
+ const BYTE* anchor = istart;
+ const BYTE* const iend = istart + srcSize;
+ const BYTE* const ilimit = iend - 8;
+ const BYTE* const base = ms->window.base;
+ const BYTE* const prefixStart = base + ms->window.dictLimit;
+ const ZSTD_compressionParameters* const cParams = &ms->cParams;
+
+ U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);
+ U32 const minMatch = (cParams->minMatch == 3) ? 3 : 4;
+
+ ZSTD_optimal_t* const opt = optStatePtr->priceTable;
+ ZSTD_match_t* const matches = optStatePtr->matchTable;
+ ZSTD_optimal_t lastSequence;
+
+ /* init */
+ DEBUGLOG(5, "ZSTD_compressBlock_opt_generic: current=%u, prefix=%u, nextToUpdate=%u",
+ (U32)(ip - base), ms->window.dictLimit, ms->nextToUpdate);
+ assert(optLevel <= 2);
+ ms->nextToUpdate3 = ms->nextToUpdate;
+ ZSTD_rescaleFreqs(optStatePtr, (const BYTE*)src, srcSize, optLevel);
+ ip += (ip==prefixStart);
+
+ /* Match Loop */
+ while (ip < ilimit) {
+ U32 cur, last_pos = 0;
+
+ /* find first match */
+ { U32 const litlen = (U32)(ip - anchor);
+ U32 const ll0 = !litlen;
+ U32 const nbMatches = ZSTD_BtGetAllMatches(ms, ip, iend, dictMode, rep, ll0, matches, minMatch);
+ if (!nbMatches) { ip++; continue; }
+
+ /* initialize opt[0] */
+ { U32 i ; for (i=0; i<ZSTD_REP_NUM; i++) opt[0].rep[i] = rep[i]; }
+ opt[0].mlen = 0; /* means is_a_literal */
+ opt[0].litlen = litlen;
+ opt[0].price = ZSTD_literalsContribution(anchor, litlen, optStatePtr, optLevel);
+
+ /* large match -> immediate encoding */
+ { U32 const maxML = matches[nbMatches-1].len;
+ U32 const maxOffset = matches[nbMatches-1].off;
+ DEBUGLOG(6, "found %u matches of maxLength=%u and maxOffCode=%u at cPos=%u => start new serie",
+ nbMatches, maxML, maxOffset, (U32)(ip-prefixStart));
+
+ if (maxML > sufficient_len) {
+ lastSequence.litlen = litlen;
+ lastSequence.mlen = maxML;
+ lastSequence.off = maxOffset;
+ DEBUGLOG(6, "large match (%u>%u), immediate encoding",
+ maxML, sufficient_len);
+ cur = 0;
+ last_pos = ZSTD_totalLen(lastSequence);
+ goto _shortestPath;
+ } }
+
+ /* set prices for first matches starting position == 0 */
+ { U32 const literalsPrice = opt[0].price + ZSTD_litLengthPrice(0, optStatePtr, optLevel);
+ U32 pos;
+ U32 matchNb;
+ for (pos = 1; pos < minMatch; pos++) {
+ opt[pos].price = ZSTD_MAX_PRICE; /* mlen, litlen and price will be fixed during forward scanning */
+ }
+ for (matchNb = 0; matchNb < nbMatches; matchNb++) {
+ U32 const offset = matches[matchNb].off;
+ U32 const end = matches[matchNb].len;
+ repcodes_t const repHistory = ZSTD_updateRep(rep, offset, ll0);
+ for ( ; pos <= end ; pos++ ) {
+ U32 const matchPrice = ZSTD_getMatchPrice(offset, pos, optStatePtr, optLevel);
+ U32 const sequencePrice = literalsPrice + matchPrice;
+ DEBUGLOG(7, "rPos:%u => set initial price : %.2f",
+ pos, ZSTD_fCost(sequencePrice));
+ opt[pos].mlen = pos;
+ opt[pos].off = offset;
+ opt[pos].litlen = litlen;
+ opt[pos].price = sequencePrice;
+ ZSTD_STATIC_ASSERT(sizeof(opt[pos].rep) == sizeof(repHistory));
+ memcpy(opt[pos].rep, &repHistory, sizeof(repHistory));
+ } }
+ last_pos = pos-1;
+ }
+ }
+
+ /* check further positions */
+ for (cur = 1; cur <= last_pos; cur++) {
+ const BYTE* const inr = ip + cur;
+ assert(cur < ZSTD_OPT_NUM);
+ DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur)
+
+ /* Fix current position with one literal if cheaper */
+ { U32 const litlen = (opt[cur-1].mlen == 0) ? opt[cur-1].litlen + 1 : 1;
+ int const price = opt[cur-1].price
+ + ZSTD_rawLiteralsCost(ip+cur-1, 1, optStatePtr, optLevel)
+ + ZSTD_litLengthPrice(litlen, optStatePtr, optLevel)
+ - ZSTD_litLengthPrice(litlen-1, optStatePtr, optLevel);
+ assert(price < 1000000000); /* overflow check */
+ if (price <= opt[cur].price) {
+ DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",
+ inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,
+ opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);
+ opt[cur].mlen = 0;
+ opt[cur].off = 0;
+ opt[cur].litlen = litlen;
+ opt[cur].price = price;
+ memcpy(opt[cur].rep, opt[cur-1].rep, sizeof(opt[cur].rep));
+ } else {
+ DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f) (hist:%u,%u,%u)",
+ inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price),
+ opt[cur].rep[0], opt[cur].rep[1], opt[cur].rep[2]);
+ }
+ }
+
+ /* last match must start at a minimum distance of 8 from oend */
+ if (inr > ilimit) continue;
+
+ if (cur == last_pos) break;
+
+ if ( (optLevel==0) /*static_test*/
+ && (opt[cur+1].price <= opt[cur].price + (BITCOST_MULTIPLIER/2)) ) {
+ DEBUGLOG(7, "move to next rPos:%u : price is <=", cur+1);
+ continue; /* skip unpromising positions; about ~+6% speed, -0.01 ratio */
+ }
+
+ { U32 const ll0 = (opt[cur].mlen != 0);
+ U32 const litlen = (opt[cur].mlen == 0) ? opt[cur].litlen : 0;
+ U32 const previousPrice = opt[cur].price;
+ U32 const basePrice = previousPrice + ZSTD_litLengthPrice(0, optStatePtr, optLevel);
+ U32 const nbMatches = ZSTD_BtGetAllMatches(ms, inr, iend, dictMode, opt[cur].rep, ll0, matches, minMatch);
+ U32 matchNb;
+ if (!nbMatches) {
+ DEBUGLOG(7, "rPos:%u : no match found", cur);
+ continue;
+ }
+
+ { U32 const maxML = matches[nbMatches-1].len;
+ DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of maxLength=%u",
+ inr-istart, cur, nbMatches, maxML);
+
+ if ( (maxML > sufficient_len)
+ || (cur + maxML >= ZSTD_OPT_NUM) ) {
+ lastSequence.mlen = maxML;
+ lastSequence.off = matches[nbMatches-1].off;
+ lastSequence.litlen = litlen;
+ cur -= (opt[cur].mlen==0) ? opt[cur].litlen : 0; /* last sequence is actually only literals, fix cur to last match - note : may underflow, in which case, it's first sequence, and it's okay */
+ last_pos = cur + ZSTD_totalLen(lastSequence);
+ if (cur > ZSTD_OPT_NUM) cur = 0; /* underflow => first match */
+ goto _shortestPath;
+ } }
+
+ /* set prices using matches found at position == cur */
+ for (matchNb = 0; matchNb < nbMatches; matchNb++) {
+ U32 const offset = matches[matchNb].off;
+ repcodes_t const repHistory = ZSTD_updateRep(opt[cur].rep, offset, ll0);
+ U32 const lastML = matches[matchNb].len;
+ U32 const startML = (matchNb>0) ? matches[matchNb-1].len+1 : minMatch;
+ U32 mlen;
+
+ DEBUGLOG(7, "testing match %u => offCode=%4u, mlen=%2u, llen=%2u",
+ matchNb, matches[matchNb].off, lastML, litlen);
+
+ for (mlen = lastML; mlen >= startML; mlen--) { /* scan downward */
+ U32 const pos = cur + mlen;
+ int const price = basePrice + ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel);
+
+ if ((pos > last_pos) || (price < opt[pos].price)) {
+ DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)",
+ pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
+ while (last_pos < pos) { opt[last_pos+1].price = ZSTD_MAX_PRICE; last_pos++; } /* fill empty positions */
+ opt[pos].mlen = mlen;
+ opt[pos].off = offset;
+ opt[pos].litlen = litlen;
+ opt[pos].price = price;
+ ZSTD_STATIC_ASSERT(sizeof(opt[pos].rep) == sizeof(repHistory));
+ memcpy(opt[pos].rep, &repHistory, sizeof(repHistory));
+ } else {
+ DEBUGLOG(7, "rPos:%u (ml=%2u) => new price is worse (%.2f>=%.2f)",
+ pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));
+ if (optLevel==0) break; /* early update abort; gets ~+10% speed for about -0.01 ratio loss */
+ }
+ } } }
+ } /* for (cur = 1; cur <= last_pos; cur++) */
+
+ lastSequence = opt[last_pos];
+ cur = last_pos > ZSTD_totalLen(lastSequence) ? last_pos - ZSTD_totalLen(lastSequence) : 0; /* single sequence, and it starts before `ip` */
+ assert(cur < ZSTD_OPT_NUM); /* control overflow*/
+
+_shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */
+ assert(opt[0].mlen == 0);
+
+ { U32 const storeEnd = cur + 1;
+ U32 storeStart = storeEnd;
+ U32 seqPos = cur;
+
+ DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",
+ last_pos, cur); (void)last_pos;
+ assert(storeEnd < ZSTD_OPT_NUM);
+ DEBUGLOG(6, "last sequence copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",
+ storeEnd, lastSequence.litlen, lastSequence.mlen, lastSequence.off);
+ opt[storeEnd] = lastSequence;
+ while (seqPos > 0) {
+ U32 const backDist = ZSTD_totalLen(opt[seqPos]);
+ storeStart--;
+ DEBUGLOG(6, "sequence from rPos=%u copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",
+ seqPos, storeStart, opt[seqPos].litlen, opt[seqPos].mlen, opt[seqPos].off);
+ opt[storeStart] = opt[seqPos];
+ seqPos = (seqPos > backDist) ? seqPos - backDist : 0;
+ }
+
+ /* save sequences */
+ DEBUGLOG(6, "sending selected sequences into seqStore")
+ { U32 storePos;
+ for (storePos=storeStart; storePos <= storeEnd; storePos++) {
+ U32 const llen = opt[storePos].litlen;
+ U32 const mlen = opt[storePos].mlen;
+ U32 const offCode = opt[storePos].off;
+ U32 const advance = llen + mlen;
+ DEBUGLOG(6, "considering seq starting at %zi, llen=%u, mlen=%u",
+ anchor - istart, (unsigned)llen, (unsigned)mlen);
+
+ if (mlen==0) { /* only literals => must be last "sequence", actually starting a new stream of sequences */
+ assert(storePos == storeEnd); /* must be last sequence */
+ ip = anchor + llen; /* last "sequence" is a bunch of literals => don't progress anchor */
+ continue; /* will finish */
+ }
+
+ /* repcodes update : like ZSTD_updateRep(), but update in place */
+ if (offCode >= ZSTD_REP_NUM) { /* full offset */
+ rep[2] = rep[1];
+ rep[1] = rep[0];
+ rep[0] = offCode - ZSTD_REP_MOVE;
+ } else { /* repcode */
+ U32 const repCode = offCode + (llen==0);
+ if (repCode) { /* note : if repCode==0, no change */
+ U32 const currentOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];
+ if (repCode >= 2) rep[2] = rep[1];
+ rep[1] = rep[0];
+ rep[0] = currentOffset;
+ } }
+
+ assert(anchor + llen <= iend);
+ ZSTD_updateStats(optStatePtr, llen, anchor, offCode, mlen);
+ ZSTD_storeSeq(seqStore, llen, anchor, offCode, mlen-MINMATCH);
+ anchor += advance;
+ ip = anchor;
+ } }
+ ZSTD_setBasePrices(optStatePtr, optLevel);
+ }
+
+ } /* while (ip < ilimit) */
+
+ /* Return the last literals size */
+ return iend - anchor;
+}
+
+
+size_t ZSTD_compressBlock_btopt(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize)
+{
+ DEBUGLOG(5, "ZSTD_compressBlock_btopt");
+ return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_noDict);
+}
+
+
+/* used in 2-pass strategy */
+static U32 ZSTD_upscaleStat(unsigned* table, U32 lastEltIndex, int bonus)
+{
+ U32 s, sum=0;
+ assert(ZSTD_FREQ_DIV+bonus >= 0);
+ for (s=0; s<lastEltIndex+1; s++) {
+ table[s] <<= ZSTD_FREQ_DIV+bonus;
+ table[s]--;
+ sum += table[s];
+ }
+ return sum;
+}
+
+/* used in 2-pass strategy */
+MEM_STATIC void ZSTD_upscaleStats(optState_t* optPtr)
+{
+ optPtr->litSum = ZSTD_upscaleStat(optPtr->litFreq, MaxLit, 0);
+ optPtr->litLengthSum = ZSTD_upscaleStat(optPtr->litLengthFreq, MaxLL, 0);
+ optPtr->matchLengthSum = ZSTD_upscaleStat(optPtr->matchLengthFreq, MaxML, 0);
+ optPtr->offCodeSum = ZSTD_upscaleStat(optPtr->offCodeFreq, MaxOff, 0);
+}
+
+/* ZSTD_initStats_ultra():
+ * make a first compression pass, just to seed stats with more accurate starting values.
+ * only works on first block, with no dictionary and no ldm.
+ * this function cannot error, hence its constract must be respected.
+ */
+static void
+ZSTD_initStats_ultra(ZSTD_matchState_t* ms,
+ seqStore_t* seqStore,
+ U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize)
+{
+ U32 tmpRep[ZSTD_REP_NUM]; /* updated rep codes will sink here */
+ memcpy(tmpRep, rep, sizeof(tmpRep));
+
+ DEBUGLOG(4, "ZSTD_initStats_ultra (srcSize=%zu)", srcSize);
+ assert(ms->opt.litLengthSum == 0); /* first block */
+ assert(seqStore->sequences == seqStore->sequencesStart); /* no ldm */
+ assert(ms->window.dictLimit == ms->window.lowLimit); /* no dictionary */
+ assert(ms->window.dictLimit - ms->nextToUpdate <= 1); /* no prefix (note: intentional overflow, defined as 2-complement) */
+
+ ZSTD_compressBlock_opt_generic(ms, seqStore, tmpRep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict); /* generate stats into ms->opt*/
+
+ /* invalidate first scan from history */
+ ZSTD_resetSeqStore(seqStore);
+ ms->window.base -= srcSize;
+ ms->window.dictLimit += (U32)srcSize;
+ ms->window.lowLimit = ms->window.dictLimit;
+ ms->nextToUpdate = ms->window.dictLimit;
+ ms->nextToUpdate3 = ms->window.dictLimit;
+
+ /* re-inforce weight of collected statistics */
+ ZSTD_upscaleStats(&ms->opt);
+}
+
+size_t ZSTD_compressBlock_btultra(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize)
+{
+ DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize);
+ return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict);
+}
+
+size_t ZSTD_compressBlock_btultra2(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize)
+{
+ U32 const current = (U32)((const BYTE*)src - ms->window.base);
+ DEBUGLOG(5, "ZSTD_compressBlock_btultra2 (srcSize=%zu)", srcSize);
+
+ /* 2-pass strategy:
+ * this strategy makes a first pass over first block to collect statistics
+ * and seed next round's statistics with it.
+ * After 1st pass, function forgets everything, and starts a new block.
+ * Consequently, this can only work if no data has been previously loaded in tables,
+ * aka, no dictionary, no prefix, no ldm preprocessing.
+ * The compression ratio gain is generally small (~0.5% on first block),
+ * the cost is 2x cpu time on first block. */
+ assert(srcSize <= ZSTD_BLOCKSIZE_MAX);
+ if ( (ms->opt.litLengthSum==0) /* first block */
+ && (seqStore->sequences == seqStore->sequencesStart) /* no ldm */
+ && (ms->window.dictLimit == ms->window.lowLimit) /* no dictionary */
+ && (current == ms->window.dictLimit) /* start of frame, nothing already loaded nor skipped */
+ && (srcSize > ZSTD_PREDEF_THRESHOLD)
+ ) {
+ ZSTD_initStats_ultra(ms, seqStore, rep, src, srcSize);
+ }
+
+ return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict);
+}
+
+size_t ZSTD_compressBlock_btopt_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_dictMatchState);
+}
+
+size_t ZSTD_compressBlock_btultra_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_dictMatchState);
+}
+
+size_t ZSTD_compressBlock_btopt_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_extDict);
+}
+
+size_t ZSTD_compressBlock_btultra_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ const void* src, size_t srcSize)
+{
+ return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_extDict);
+}
+
+/* note : no btultra2 variant for extDict nor dictMatchState,
+ * because btultra2 is not meant to work with dictionaries
+ * and is only specific for the first block (no prefix) */
diff --git a/Utilities/cmzstd/lib/compress/zstd_opt.h b/Utilities/cmzstd/lib/compress/zstd_opt.h
new file mode 100644
index 000000000..094f74766
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstd_opt.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef ZSTD_OPT_H
+#define ZSTD_OPT_H
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#include "zstd_compress_internal.h"
+
+/* used in ZSTD_loadDictionaryContent() */
+void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend);
+
+size_t ZSTD_compressBlock_btopt(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_btultra(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_btultra2(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+
+
+size_t ZSTD_compressBlock_btopt_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_btultra_dictMatchState(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+
+size_t ZSTD_compressBlock_btopt_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+size_t ZSTD_compressBlock_btultra_extDict(
+ ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],
+ void const* src, size_t srcSize);
+
+ /* note : no btultra2 variant for extDict nor dictMatchState,
+ * because btultra2 is not meant to work with dictionaries
+ * and is only specific for the first block (no prefix) */
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* ZSTD_OPT_H */
diff --git a/Utilities/cmzstd/lib/compress/zstdmt_compress.c b/Utilities/cmzstd/lib/compress/zstdmt_compress.c
new file mode 100644
index 000000000..2cbd6ffad
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstdmt_compress.c
@@ -0,0 +1,2107 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+
+/* ====== Compiler specifics ====== */
+#if defined(_MSC_VER)
+# pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
+#endif
+
+
+/* ====== Constants ====== */
+#define ZSTDMT_OVERLAPLOG_DEFAULT 0
+
+
+/* ====== Dependencies ====== */
+#include <string.h> /* memcpy, memset */
+#include <limits.h> /* INT_MAX, UINT_MAX */
+#include "pool.h" /* threadpool */
+#include "threading.h" /* mutex */
+#include "zstd_compress_internal.h" /* MIN, ERROR, ZSTD_*, ZSTD_highbit32 */
+#include "zstd_ldm.h"
+#include "zstdmt_compress.h"
+
+/* Guards code to support resizing the SeqPool.
+ * We will want to resize the SeqPool to save memory in the future.
+ * Until then, comment the code out since it is unused.
+ */
+#define ZSTD_RESIZE_SEQPOOL 0
+
+/* ====== Debug ====== */
+#if defined(DEBUGLEVEL) && (DEBUGLEVEL>=2) \
+ && !defined(_MSC_VER) \
+ && !defined(__MINGW32__)
+
+# include <stdio.h>
+# include <unistd.h>
+# include <sys/times.h>
+
+# define DEBUG_PRINTHEX(l,p,n) { \
+ unsigned debug_u; \
+ for (debug_u=0; debug_u<(n); debug_u++) \
+ RAWLOG(l, "%02X ", ((const unsigned char*)(p))[debug_u]); \
+ RAWLOG(l, " \n"); \
+}
+
+static unsigned long long GetCurrentClockTimeMicroseconds(void)
+{
+ static clock_t _ticksPerSecond = 0;
+ if (_ticksPerSecond <= 0) _ticksPerSecond = sysconf(_SC_CLK_TCK);
+
+ { struct tms junk; clock_t newTicks = (clock_t) times(&junk);
+ return ((((unsigned long long)newTicks)*(1000000))/_ticksPerSecond);
+} }
+
+#define MUTEX_WAIT_TIME_DLEVEL 6
+#define ZSTD_PTHREAD_MUTEX_LOCK(mutex) { \
+ if (DEBUGLEVEL >= MUTEX_WAIT_TIME_DLEVEL) { \
+ unsigned long long const beforeTime = GetCurrentClockTimeMicroseconds(); \
+ ZSTD_pthread_mutex_lock(mutex); \
+ { unsigned long long const afterTime = GetCurrentClockTimeMicroseconds(); \
+ unsigned long long const elapsedTime = (afterTime-beforeTime); \
+ if (elapsedTime > 1000) { /* or whatever threshold you like; I'm using 1 millisecond here */ \
+ DEBUGLOG(MUTEX_WAIT_TIME_DLEVEL, "Thread took %llu microseconds to acquire mutex %s \n", \
+ elapsedTime, #mutex); \
+ } } \
+ } else { \
+ ZSTD_pthread_mutex_lock(mutex); \
+ } \
+}
+
+#else
+
+# define ZSTD_PTHREAD_MUTEX_LOCK(m) ZSTD_pthread_mutex_lock(m)
+# define DEBUG_PRINTHEX(l,p,n) {}
+
+#endif
+
+
+/* ===== Buffer Pool ===== */
+/* a single Buffer Pool can be invoked from multiple threads in parallel */
+
+typedef struct buffer_s {
+ void* start;
+ size_t capacity;
+} buffer_t;
+
+static const buffer_t g_nullBuffer = { NULL, 0 };
+
+typedef struct ZSTDMT_bufferPool_s {
+ ZSTD_pthread_mutex_t poolMutex;
+ size_t bufferSize;
+ unsigned totalBuffers;
+ unsigned nbBuffers;
+ ZSTD_customMem cMem;
+ buffer_t bTable[1]; /* variable size */
+} ZSTDMT_bufferPool;
+
+static ZSTDMT_bufferPool* ZSTDMT_createBufferPool(unsigned nbWorkers, ZSTD_customMem cMem)
+{
+ unsigned const maxNbBuffers = 2*nbWorkers + 3;
+ ZSTDMT_bufferPool* const bufPool = (ZSTDMT_bufferPool*)ZSTD_calloc(
+ sizeof(ZSTDMT_bufferPool) + (maxNbBuffers-1) * sizeof(buffer_t), cMem);
+ if (bufPool==NULL) return NULL;
+ if (ZSTD_pthread_mutex_init(&bufPool->poolMutex, NULL)) {
+ ZSTD_free(bufPool, cMem);
+ return NULL;
+ }
+ bufPool->bufferSize = 64 KB;
+ bufPool->totalBuffers = maxNbBuffers;
+ bufPool->nbBuffers = 0;
+ bufPool->cMem = cMem;
+ return bufPool;
+}
+
+static void ZSTDMT_freeBufferPool(ZSTDMT_bufferPool* bufPool)
+{
+ unsigned u;
+ DEBUGLOG(3, "ZSTDMT_freeBufferPool (address:%08X)", (U32)(size_t)bufPool);
+ if (!bufPool) return; /* compatibility with free on NULL */
+ for (u=0; u<bufPool->totalBuffers; u++) {
+ DEBUGLOG(4, "free buffer %2u (address:%08X)", u, (U32)(size_t)bufPool->bTable[u].start);
+ ZSTD_free(bufPool->bTable[u].start, bufPool->cMem);
+ }
+ ZSTD_pthread_mutex_destroy(&bufPool->poolMutex);
+ ZSTD_free(bufPool, bufPool->cMem);
+}
+
+/* only works at initialization, not during compression */
+static size_t ZSTDMT_sizeof_bufferPool(ZSTDMT_bufferPool* bufPool)
+{
+ size_t const poolSize = sizeof(*bufPool)
+ + (bufPool->totalBuffers - 1) * sizeof(buffer_t);
+ unsigned u;
+ size_t totalBufferSize = 0;
+ ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
+ for (u=0; u<bufPool->totalBuffers; u++)
+ totalBufferSize += bufPool->bTable[u].capacity;
+ ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
+
+ return poolSize + totalBufferSize;
+}
+
+/* ZSTDMT_setBufferSize() :
+ * all future buffers provided by this buffer pool will have _at least_ this size
+ * note : it's better for all buffers to have same size,
+ * as they become freely interchangeable, reducing malloc/free usages and memory fragmentation */
+static void ZSTDMT_setBufferSize(ZSTDMT_bufferPool* const bufPool, size_t const bSize)
+{
+ ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
+ DEBUGLOG(4, "ZSTDMT_setBufferSize: bSize = %u", (U32)bSize);
+ bufPool->bufferSize = bSize;
+ ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
+}
+
+
+static ZSTDMT_bufferPool* ZSTDMT_expandBufferPool(ZSTDMT_bufferPool* srcBufPool, U32 nbWorkers)
+{
+ unsigned const maxNbBuffers = 2*nbWorkers + 3;
+ if (srcBufPool==NULL) return NULL;
+ if (srcBufPool->totalBuffers >= maxNbBuffers) /* good enough */
+ return srcBufPool;
+ /* need a larger buffer pool */
+ { ZSTD_customMem const cMem = srcBufPool->cMem;
+ size_t const bSize = srcBufPool->bufferSize; /* forward parameters */
+ ZSTDMT_bufferPool* newBufPool;
+ ZSTDMT_freeBufferPool(srcBufPool);
+ newBufPool = ZSTDMT_createBufferPool(nbWorkers, cMem);
+ if (newBufPool==NULL) return newBufPool;
+ ZSTDMT_setBufferSize(newBufPool, bSize);
+ return newBufPool;
+ }
+}
+
+/** ZSTDMT_getBuffer() :
+ * assumption : bufPool must be valid
+ * @return : a buffer, with start pointer and size
+ * note: allocation may fail, in this case, start==NULL and size==0 */
+static buffer_t ZSTDMT_getBuffer(ZSTDMT_bufferPool* bufPool)
+{
+ size_t const bSize = bufPool->bufferSize;
+ DEBUGLOG(5, "ZSTDMT_getBuffer: bSize = %u", (U32)bufPool->bufferSize);
+ ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
+ if (bufPool->nbBuffers) { /* try to use an existing buffer */
+ buffer_t const buf = bufPool->bTable[--(bufPool->nbBuffers)];
+ size_t const availBufferSize = buf.capacity;
+ bufPool->bTable[bufPool->nbBuffers] = g_nullBuffer;
+ if ((availBufferSize >= bSize) & ((availBufferSize>>3) <= bSize)) {
+ /* large enough, but not too much */
+ DEBUGLOG(5, "ZSTDMT_getBuffer: provide buffer %u of size %u",
+ bufPool->nbBuffers, (U32)buf.capacity);
+ ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
+ return buf;
+ }
+ /* size conditions not respected : scratch this buffer, create new one */
+ DEBUGLOG(5, "ZSTDMT_getBuffer: existing buffer does not meet size conditions => freeing");
+ ZSTD_free(buf.start, bufPool->cMem);
+ }
+ ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
+ /* create new buffer */
+ DEBUGLOG(5, "ZSTDMT_getBuffer: create a new buffer");
+ { buffer_t buffer;
+ void* const start = ZSTD_malloc(bSize, bufPool->cMem);
+ buffer.start = start; /* note : start can be NULL if malloc fails ! */
+ buffer.capacity = (start==NULL) ? 0 : bSize;
+ if (start==NULL) {
+ DEBUGLOG(5, "ZSTDMT_getBuffer: buffer allocation failure !!");
+ } else {
+ DEBUGLOG(5, "ZSTDMT_getBuffer: created buffer of size %u", (U32)bSize);
+ }
+ return buffer;
+ }
+}
+
+#if ZSTD_RESIZE_SEQPOOL
+/** ZSTDMT_resizeBuffer() :
+ * assumption : bufPool must be valid
+ * @return : a buffer that is at least the buffer pool buffer size.
+ * If a reallocation happens, the data in the input buffer is copied.
+ */
+static buffer_t ZSTDMT_resizeBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buffer)
+{
+ size_t const bSize = bufPool->bufferSize;
+ if (buffer.capacity < bSize) {
+ void* const start = ZSTD_malloc(bSize, bufPool->cMem);
+ buffer_t newBuffer;
+ newBuffer.start = start;
+ newBuffer.capacity = start == NULL ? 0 : bSize;
+ if (start != NULL) {
+ assert(newBuffer.capacity >= buffer.capacity);
+ memcpy(newBuffer.start, buffer.start, buffer.capacity);
+ DEBUGLOG(5, "ZSTDMT_resizeBuffer: created buffer of size %u", (U32)bSize);
+ return newBuffer;
+ }
+ DEBUGLOG(5, "ZSTDMT_resizeBuffer: buffer allocation failure !!");
+ }
+ return buffer;
+}
+#endif
+
+/* store buffer for later re-use, up to pool capacity */
+static void ZSTDMT_releaseBuffer(ZSTDMT_bufferPool* bufPool, buffer_t buf)
+{
+ DEBUGLOG(5, "ZSTDMT_releaseBuffer");
+ if (buf.start == NULL) return; /* compatible with release on NULL */
+ ZSTD_pthread_mutex_lock(&bufPool->poolMutex);
+ if (bufPool->nbBuffers < bufPool->totalBuffers) {
+ bufPool->bTable[bufPool->nbBuffers++] = buf; /* stored for later use */
+ DEBUGLOG(5, "ZSTDMT_releaseBuffer: stored buffer of size %u in slot %u",
+ (U32)buf.capacity, (U32)(bufPool->nbBuffers-1));
+ ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
+ return;
+ }
+ ZSTD_pthread_mutex_unlock(&bufPool->poolMutex);
+ /* Reached bufferPool capacity (should not happen) */
+ DEBUGLOG(5, "ZSTDMT_releaseBuffer: pool capacity reached => freeing ");
+ ZSTD_free(buf.start, bufPool->cMem);
+}
+
+
+/* ===== Seq Pool Wrapper ====== */
+
+static rawSeqStore_t kNullRawSeqStore = {NULL, 0, 0, 0};
+
+typedef ZSTDMT_bufferPool ZSTDMT_seqPool;
+
+static size_t ZSTDMT_sizeof_seqPool(ZSTDMT_seqPool* seqPool)
+{
+ return ZSTDMT_sizeof_bufferPool(seqPool);
+}
+
+static rawSeqStore_t bufferToSeq(buffer_t buffer)
+{
+ rawSeqStore_t seq = {NULL, 0, 0, 0};
+ seq.seq = (rawSeq*)buffer.start;
+ seq.capacity = buffer.capacity / sizeof(rawSeq);
+ return seq;
+}
+
+static buffer_t seqToBuffer(rawSeqStore_t seq)
+{
+ buffer_t buffer;
+ buffer.start = seq.seq;
+ buffer.capacity = seq.capacity * sizeof(rawSeq);
+ return buffer;
+}
+
+static rawSeqStore_t ZSTDMT_getSeq(ZSTDMT_seqPool* seqPool)
+{
+ if (seqPool->bufferSize == 0) {
+ return kNullRawSeqStore;
+ }
+ return bufferToSeq(ZSTDMT_getBuffer(seqPool));
+}
+
+#if ZSTD_RESIZE_SEQPOOL
+static rawSeqStore_t ZSTDMT_resizeSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq)
+{
+ return bufferToSeq(ZSTDMT_resizeBuffer(seqPool, seqToBuffer(seq)));
+}
+#endif
+
+static void ZSTDMT_releaseSeq(ZSTDMT_seqPool* seqPool, rawSeqStore_t seq)
+{
+ ZSTDMT_releaseBuffer(seqPool, seqToBuffer(seq));
+}
+
+static void ZSTDMT_setNbSeq(ZSTDMT_seqPool* const seqPool, size_t const nbSeq)
+{
+ ZSTDMT_setBufferSize(seqPool, nbSeq * sizeof(rawSeq));
+}
+
+static ZSTDMT_seqPool* ZSTDMT_createSeqPool(unsigned nbWorkers, ZSTD_customMem cMem)
+{
+ ZSTDMT_seqPool* const seqPool = ZSTDMT_createBufferPool(nbWorkers, cMem);
+ if (seqPool == NULL) return NULL;
+ ZSTDMT_setNbSeq(seqPool, 0);
+ return seqPool;
+}
+
+static void ZSTDMT_freeSeqPool(ZSTDMT_seqPool* seqPool)
+{
+ ZSTDMT_freeBufferPool(seqPool);
+}
+
+static ZSTDMT_seqPool* ZSTDMT_expandSeqPool(ZSTDMT_seqPool* pool, U32 nbWorkers)
+{
+ return ZSTDMT_expandBufferPool(pool, nbWorkers);
+}
+
+
+/* ===== CCtx Pool ===== */
+/* a single CCtx Pool can be invoked from multiple threads in parallel */
+
+typedef struct {
+ ZSTD_pthread_mutex_t poolMutex;
+ int totalCCtx;
+ int availCCtx;
+ ZSTD_customMem cMem;
+ ZSTD_CCtx* cctx[1]; /* variable size */
+} ZSTDMT_CCtxPool;
+
+/* note : all CCtx borrowed from the pool should be released back to the pool _before_ freeing the pool */
+static void ZSTDMT_freeCCtxPool(ZSTDMT_CCtxPool* pool)
+{
+ int cid;
+ for (cid=0; cid<pool->totalCCtx; cid++)
+ ZSTD_freeCCtx(pool->cctx[cid]); /* note : compatible with free on NULL */
+ ZSTD_pthread_mutex_destroy(&pool->poolMutex);
+ ZSTD_free(pool, pool->cMem);
+}
+
+/* ZSTDMT_createCCtxPool() :
+ * implies nbWorkers >= 1 , checked by caller ZSTDMT_createCCtx() */
+static ZSTDMT_CCtxPool* ZSTDMT_createCCtxPool(int nbWorkers,
+ ZSTD_customMem cMem)
+{
+ ZSTDMT_CCtxPool* const cctxPool = (ZSTDMT_CCtxPool*) ZSTD_calloc(
+ sizeof(ZSTDMT_CCtxPool) + (nbWorkers-1)*sizeof(ZSTD_CCtx*), cMem);
+ assert(nbWorkers > 0);
+ if (!cctxPool) return NULL;
+ if (ZSTD_pthread_mutex_init(&cctxPool->poolMutex, NULL)) {
+ ZSTD_free(cctxPool, cMem);
+ return NULL;
+ }
+ cctxPool->cMem = cMem;
+ cctxPool->totalCCtx = nbWorkers;
+ cctxPool->availCCtx = 1; /* at least one cctx for single-thread mode */
+ cctxPool->cctx[0] = ZSTD_createCCtx_advanced(cMem);
+ if (!cctxPool->cctx[0]) { ZSTDMT_freeCCtxPool(cctxPool); return NULL; }
+ DEBUGLOG(3, "cctxPool created, with %u workers", nbWorkers);
+ return cctxPool;
+}
+
+static ZSTDMT_CCtxPool* ZSTDMT_expandCCtxPool(ZSTDMT_CCtxPool* srcPool,
+ int nbWorkers)
+{
+ if (srcPool==NULL) return NULL;
+ if (nbWorkers <= srcPool->totalCCtx) return srcPool; /* good enough */
+ /* need a larger cctx pool */
+ { ZSTD_customMem const cMem = srcPool->cMem;
+ ZSTDMT_freeCCtxPool(srcPool);
+ return ZSTDMT_createCCtxPool(nbWorkers, cMem);
+ }
+}
+
+/* only works during initialization phase, not during compression */
+static size_t ZSTDMT_sizeof_CCtxPool(ZSTDMT_CCtxPool* cctxPool)
+{
+ ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
+ { unsigned const nbWorkers = cctxPool->totalCCtx;
+ size_t const poolSize = sizeof(*cctxPool)
+ + (nbWorkers-1) * sizeof(ZSTD_CCtx*);
+ unsigned u;
+ size_t totalCCtxSize = 0;
+ for (u=0; u<nbWorkers; u++) {
+ totalCCtxSize += ZSTD_sizeof_CCtx(cctxPool->cctx[u]);
+ }
+ ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
+ assert(nbWorkers > 0);
+ return poolSize + totalCCtxSize;
+ }
+}
+
+static ZSTD_CCtx* ZSTDMT_getCCtx(ZSTDMT_CCtxPool* cctxPool)
+{
+ DEBUGLOG(5, "ZSTDMT_getCCtx");
+ ZSTD_pthread_mutex_lock(&cctxPool->poolMutex);
+ if (cctxPool->availCCtx) {
+ cctxPool->availCCtx--;
+ { ZSTD_CCtx* const cctx = cctxPool->cctx[cctxPool->availCCtx];
+ ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
+ return cctx;
+ } }
+ ZSTD_pthread_mutex_unlock(&cctxPool->poolMutex);
+ DEBUGLOG(5, "create one more CCtx");
+ return ZSTD_createCCtx_advanced(cctxPool->cMem); /* note : can be NULL, when creation fails ! */
+}
+
+static void ZSTDMT_releaseCCtx(ZSTDMT_CCtxPool* pool, ZSTD_CCtx* cctx)
+{
+ if (cctx==NULL) return; /* compatibility with release on NULL */
+ ZSTD_pthread_mutex_lock(&pool->poolMutex);
+ if (pool->availCCtx < pool->totalCCtx)
+ pool->cctx[pool->availCCtx++] = cctx;
+ else {
+ /* pool overflow : should not happen, since totalCCtx==nbWorkers */
+ DEBUGLOG(4, "CCtx pool overflow : free cctx");
+ ZSTD_freeCCtx(cctx);
+ }
+ ZSTD_pthread_mutex_unlock(&pool->poolMutex);
+}
+
+/* ==== Serial State ==== */
+
+typedef struct {
+ void const* start;
+ size_t size;
+} range_t;
+
+typedef struct {
+ /* All variables in the struct are protected by mutex. */
+ ZSTD_pthread_mutex_t mutex;
+ ZSTD_pthread_cond_t cond;
+ ZSTD_CCtx_params params;
+ ldmState_t ldmState;
+ XXH64_state_t xxhState;
+ unsigned nextJobID;
+ /* Protects ldmWindow.
+ * Must be acquired after the main mutex when acquiring both.
+ */
+ ZSTD_pthread_mutex_t ldmWindowMutex;
+ ZSTD_pthread_cond_t ldmWindowCond; /* Signaled when ldmWindow is udpated */
+ ZSTD_window_t ldmWindow; /* A thread-safe copy of ldmState.window */
+} serialState_t;
+
+static int ZSTDMT_serialState_reset(serialState_t* serialState, ZSTDMT_seqPool* seqPool, ZSTD_CCtx_params params, size_t jobSize)
+{
+ /* Adjust parameters */
+ if (params.ldmParams.enableLdm) {
+ DEBUGLOG(4, "LDM window size = %u KB", (1U << params.cParams.windowLog) >> 10);
+ ZSTD_ldm_adjustParameters(&params.ldmParams, &params.cParams);
+ assert(params.ldmParams.hashLog >= params.ldmParams.bucketSizeLog);
+ assert(params.ldmParams.hashRateLog < 32);
+ serialState->ldmState.hashPower =
+ ZSTD_rollingHash_primePower(params.ldmParams.minMatchLength);
+ } else {
+ memset(&params.ldmParams, 0, sizeof(params.ldmParams));
+ }
+ serialState->nextJobID = 0;
+ if (params.fParams.checksumFlag)
+ XXH64_reset(&serialState->xxhState, 0);
+ if (params.ldmParams.enableLdm) {
+ ZSTD_customMem cMem = params.customMem;
+ unsigned const hashLog = params.ldmParams.hashLog;
+ size_t const hashSize = ((size_t)1 << hashLog) * sizeof(ldmEntry_t);
+ unsigned const bucketLog =
+ params.ldmParams.hashLog - params.ldmParams.bucketSizeLog;
+ size_t const bucketSize = (size_t)1 << bucketLog;
+ unsigned const prevBucketLog =
+ serialState->params.ldmParams.hashLog -
+ serialState->params.ldmParams.bucketSizeLog;
+ /* Size the seq pool tables */
+ ZSTDMT_setNbSeq(seqPool, ZSTD_ldm_getMaxNbSeq(params.ldmParams, jobSize));
+ /* Reset the window */
+ ZSTD_window_clear(&serialState->ldmState.window);
+ serialState->ldmWindow = serialState->ldmState.window;
+ /* Resize tables and output space if necessary. */
+ if (serialState->ldmState.hashTable == NULL || serialState->params.ldmParams.hashLog < hashLog) {
+ ZSTD_free(serialState->ldmState.hashTable, cMem);
+ serialState->ldmState.hashTable = (ldmEntry_t*)ZSTD_malloc(hashSize, cMem);
+ }
+ if (serialState->ldmState.bucketOffsets == NULL || prevBucketLog < bucketLog) {
+ ZSTD_free(serialState->ldmState.bucketOffsets, cMem);
+ serialState->ldmState.bucketOffsets = (BYTE*)ZSTD_malloc(bucketSize, cMem);
+ }
+ if (!serialState->ldmState.hashTable || !serialState->ldmState.bucketOffsets)
+ return 1;
+ /* Zero the tables */
+ memset(serialState->ldmState.hashTable, 0, hashSize);
+ memset(serialState->ldmState.bucketOffsets, 0, bucketSize);
+ }
+ serialState->params = params;
+ serialState->params.jobSize = (U32)jobSize;
+ return 0;
+}
+
+static int ZSTDMT_serialState_init(serialState_t* serialState)
+{
+ int initError = 0;
+ memset(serialState, 0, sizeof(*serialState));
+ initError |= ZSTD_pthread_mutex_init(&serialState->mutex, NULL);
+ initError |= ZSTD_pthread_cond_init(&serialState->cond, NULL);
+ initError |= ZSTD_pthread_mutex_init(&serialState->ldmWindowMutex, NULL);
+ initError |= ZSTD_pthread_cond_init(&serialState->ldmWindowCond, NULL);
+ return initError;
+}
+
+static void ZSTDMT_serialState_free(serialState_t* serialState)
+{
+ ZSTD_customMem cMem = serialState->params.customMem;
+ ZSTD_pthread_mutex_destroy(&serialState->mutex);
+ ZSTD_pthread_cond_destroy(&serialState->cond);
+ ZSTD_pthread_mutex_destroy(&serialState->ldmWindowMutex);
+ ZSTD_pthread_cond_destroy(&serialState->ldmWindowCond);
+ ZSTD_free(serialState->ldmState.hashTable, cMem);
+ ZSTD_free(serialState->ldmState.bucketOffsets, cMem);
+}
+
+static void ZSTDMT_serialState_update(serialState_t* serialState,
+ ZSTD_CCtx* jobCCtx, rawSeqStore_t seqStore,
+ range_t src, unsigned jobID)
+{
+ /* Wait for our turn */
+ ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);
+ while (serialState->nextJobID < jobID) {
+ DEBUGLOG(5, "wait for serialState->cond");
+ ZSTD_pthread_cond_wait(&serialState->cond, &serialState->mutex);
+ }
+ /* A future job may error and skip our job */
+ if (serialState->nextJobID == jobID) {
+ /* It is now our turn, do any processing necessary */
+ if (serialState->params.ldmParams.enableLdm) {
+ size_t error;
+ assert(seqStore.seq != NULL && seqStore.pos == 0 &&
+ seqStore.size == 0 && seqStore.capacity > 0);
+ assert(src.size <= serialState->params.jobSize);
+ ZSTD_window_update(&serialState->ldmState.window, src.start, src.size);
+ error = ZSTD_ldm_generateSequences(
+ &serialState->ldmState, &seqStore,
+ &serialState->params.ldmParams, src.start, src.size);
+ /* We provide a large enough buffer to never fail. */
+ assert(!ZSTD_isError(error)); (void)error;
+ /* Update ldmWindow to match the ldmState.window and signal the main
+ * thread if it is waiting for a buffer.
+ */
+ ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);
+ serialState->ldmWindow = serialState->ldmState.window;
+ ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);
+ ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);
+ }
+ if (serialState->params.fParams.checksumFlag && src.size > 0)
+ XXH64_update(&serialState->xxhState, src.start, src.size);
+ }
+ /* Now it is the next jobs turn */
+ serialState->nextJobID++;
+ ZSTD_pthread_cond_broadcast(&serialState->cond);
+ ZSTD_pthread_mutex_unlock(&serialState->mutex);
+
+ if (seqStore.size > 0) {
+ size_t const err = ZSTD_referenceExternalSequences(
+ jobCCtx, seqStore.seq, seqStore.size);
+ assert(serialState->params.ldmParams.enableLdm);
+ assert(!ZSTD_isError(err));
+ (void)err;
+ }
+}
+
+static void ZSTDMT_serialState_ensureFinished(serialState_t* serialState,
+ unsigned jobID, size_t cSize)
+{
+ ZSTD_PTHREAD_MUTEX_LOCK(&serialState->mutex);
+ if (serialState->nextJobID <= jobID) {
+ assert(ZSTD_isError(cSize)); (void)cSize;
+ DEBUGLOG(5, "Skipping past job %u because of error", jobID);
+ serialState->nextJobID = jobID + 1;
+ ZSTD_pthread_cond_broadcast(&serialState->cond);
+
+ ZSTD_PTHREAD_MUTEX_LOCK(&serialState->ldmWindowMutex);
+ ZSTD_window_clear(&serialState->ldmWindow);
+ ZSTD_pthread_cond_signal(&serialState->ldmWindowCond);
+ ZSTD_pthread_mutex_unlock(&serialState->ldmWindowMutex);
+ }
+ ZSTD_pthread_mutex_unlock(&serialState->mutex);
+
+}
+
+
+/* ------------------------------------------ */
+/* ===== Worker thread ===== */
+/* ------------------------------------------ */
+
+static const range_t kNullRange = { NULL, 0 };
+
+typedef struct {
+ size_t consumed; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx */
+ size_t cSize; /* SHARED - set0 by mtctx, then modified by worker AND read by mtctx, then set0 by mtctx */
+ ZSTD_pthread_mutex_t job_mutex; /* Thread-safe - used by mtctx and worker */
+ ZSTD_pthread_cond_t job_cond; /* Thread-safe - used by mtctx and worker */
+ ZSTDMT_CCtxPool* cctxPool; /* Thread-safe - used by mtctx and (all) workers */
+ ZSTDMT_bufferPool* bufPool; /* Thread-safe - used by mtctx and (all) workers */
+ ZSTDMT_seqPool* seqPool; /* Thread-safe - used by mtctx and (all) workers */
+ serialState_t* serial; /* Thread-safe - used by mtctx and (all) workers */
+ buffer_t dstBuff; /* set by worker (or mtctx), then read by worker & mtctx, then modified by mtctx => no barrier */
+ range_t prefix; /* set by mtctx, then read by worker & mtctx => no barrier */
+ range_t src; /* set by mtctx, then read by worker & mtctx => no barrier */
+ unsigned jobID; /* set by mtctx, then read by worker => no barrier */
+ unsigned firstJob; /* set by mtctx, then read by worker => no barrier */
+ unsigned lastJob; /* set by mtctx, then read by worker => no barrier */
+ ZSTD_CCtx_params params; /* set by mtctx, then read by worker => no barrier */
+ const ZSTD_CDict* cdict; /* set by mtctx, then read by worker => no barrier */
+ unsigned long long fullFrameSize; /* set by mtctx, then read by worker => no barrier */
+ size_t dstFlushed; /* used only by mtctx */
+ unsigned frameChecksumNeeded; /* used only by mtctx */
+} ZSTDMT_jobDescription;
+
+#define JOB_ERROR(e) { \
+ ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex); \
+ job->cSize = e; \
+ ZSTD_pthread_mutex_unlock(&job->job_mutex); \
+ goto _endJob; \
+}
+
+/* ZSTDMT_compressionJob() is a POOL_function type */
+static void ZSTDMT_compressionJob(void* jobDescription)
+{
+ ZSTDMT_jobDescription* const job = (ZSTDMT_jobDescription*)jobDescription;
+ ZSTD_CCtx_params jobParams = job->params; /* do not modify job->params ! copy it, modify the copy */
+ ZSTD_CCtx* const cctx = ZSTDMT_getCCtx(job->cctxPool);
+ rawSeqStore_t rawSeqStore = ZSTDMT_getSeq(job->seqPool);
+ buffer_t dstBuff = job->dstBuff;
+ size_t lastCBlockSize = 0;
+
+ /* ressources */
+ if (cctx==NULL) JOB_ERROR(ERROR(memory_allocation));
+ if (dstBuff.start == NULL) { /* streaming job : doesn't provide a dstBuffer */
+ dstBuff = ZSTDMT_getBuffer(job->bufPool);
+ if (dstBuff.start==NULL) JOB_ERROR(ERROR(memory_allocation));
+ job->dstBuff = dstBuff; /* this value can be read in ZSTDMT_flush, when it copies the whole job */
+ }
+ if (jobParams.ldmParams.enableLdm && rawSeqStore.seq == NULL)
+ JOB_ERROR(ERROR(memory_allocation));
+
+ /* Don't compute the checksum for chunks, since we compute it externally,
+ * but write it in the header.
+ */
+ if (job->jobID != 0) jobParams.fParams.checksumFlag = 0;
+ /* Don't run LDM for the chunks, since we handle it externally */
+ jobParams.ldmParams.enableLdm = 0;
+
+
+ /* init */
+ if (job->cdict) {
+ size_t const initError = ZSTD_compressBegin_advanced_internal(cctx, NULL, 0, ZSTD_dct_auto, ZSTD_dtlm_fast, job->cdict, jobParams, job->fullFrameSize);
+ assert(job->firstJob); /* only allowed for first job */
+ if (ZSTD_isError(initError)) JOB_ERROR(initError);
+ } else { /* srcStart points at reloaded section */
+ U64 const pledgedSrcSize = job->firstJob ? job->fullFrameSize : job->src.size;
+ { size_t const forceWindowError = ZSTD_CCtxParam_setParameter(&jobParams, ZSTD_c_forceMaxWindow, !job->firstJob);
+ if (ZSTD_isError(forceWindowError)) JOB_ERROR(forceWindowError);
+ }
+ { size_t const initError = ZSTD_compressBegin_advanced_internal(cctx,
+ job->prefix.start, job->prefix.size, ZSTD_dct_rawContent, /* load dictionary in "content-only" mode (no header analysis) */
+ ZSTD_dtlm_fast,
+ NULL, /*cdict*/
+ jobParams, pledgedSrcSize);
+ if (ZSTD_isError(initError)) JOB_ERROR(initError);
+ } }
+
+ /* Perform serial step as early as possible, but after CCtx initialization */
+ ZSTDMT_serialState_update(job->serial, cctx, rawSeqStore, job->src, job->jobID);
+
+ if (!job->firstJob) { /* flush and overwrite frame header when it's not first job */
+ size_t const hSize = ZSTD_compressContinue(cctx, dstBuff.start, dstBuff.capacity, job->src.start, 0);
+ if (ZSTD_isError(hSize)) JOB_ERROR(hSize);
+ DEBUGLOG(5, "ZSTDMT_compressionJob: flush and overwrite %u bytes of frame header (not first job)", (U32)hSize);
+ ZSTD_invalidateRepCodes(cctx);
+ }
+
+ /* compress */
+ { size_t const chunkSize = 4*ZSTD_BLOCKSIZE_MAX;
+ int const nbChunks = (int)((job->src.size + (chunkSize-1)) / chunkSize);
+ const BYTE* ip = (const BYTE*) job->src.start;
+ BYTE* const ostart = (BYTE*)dstBuff.start;
+ BYTE* op = ostart;
+ BYTE* oend = op + dstBuff.capacity;
+ int chunkNb;
+ if (sizeof(size_t) > sizeof(int)) assert(job->src.size < ((size_t)INT_MAX) * chunkSize); /* check overflow */
+ DEBUGLOG(5, "ZSTDMT_compressionJob: compress %u bytes in %i blocks", (U32)job->src.size, nbChunks);
+ assert(job->cSize == 0);
+ for (chunkNb = 1; chunkNb < nbChunks; chunkNb++) {
+ size_t const cSize = ZSTD_compressContinue(cctx, op, oend-op, ip, chunkSize);
+ if (ZSTD_isError(cSize)) JOB_ERROR(cSize);
+ ip += chunkSize;
+ op += cSize; assert(op < oend);
+ /* stats */
+ ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);
+ job->cSize += cSize;
+ job->consumed = chunkSize * chunkNb;
+ DEBUGLOG(5, "ZSTDMT_compressionJob: compress new block : cSize==%u bytes (total: %u)",
+ (U32)cSize, (U32)job->cSize);
+ ZSTD_pthread_cond_signal(&job->job_cond); /* warns some more data is ready to be flushed */
+ ZSTD_pthread_mutex_unlock(&job->job_mutex);
+ }
+ /* last block */
+ assert(chunkSize > 0);
+ assert((chunkSize & (chunkSize - 1)) == 0); /* chunkSize must be power of 2 for mask==(chunkSize-1) to work */
+ if ((nbChunks > 0) | job->lastJob /*must output a "last block" flag*/ ) {
+ size_t const lastBlockSize1 = job->src.size & (chunkSize-1);
+ size_t const lastBlockSize = ((lastBlockSize1==0) & (job->src.size>=chunkSize)) ? chunkSize : lastBlockSize1;
+ size_t const cSize = (job->lastJob) ?
+ ZSTD_compressEnd (cctx, op, oend-op, ip, lastBlockSize) :
+ ZSTD_compressContinue(cctx, op, oend-op, ip, lastBlockSize);
+ if (ZSTD_isError(cSize)) JOB_ERROR(cSize);
+ lastCBlockSize = cSize;
+ } }
+
+_endJob:
+ ZSTDMT_serialState_ensureFinished(job->serial, job->jobID, job->cSize);
+ if (job->prefix.size > 0)
+ DEBUGLOG(5, "Finished with prefix: %zx", (size_t)job->prefix.start);
+ DEBUGLOG(5, "Finished with source: %zx", (size_t)job->src.start);
+ /* release resources */
+ ZSTDMT_releaseSeq(job->seqPool, rawSeqStore);
+ ZSTDMT_releaseCCtx(job->cctxPool, cctx);
+ /* report */
+ ZSTD_PTHREAD_MUTEX_LOCK(&job->job_mutex);
+ if (ZSTD_isError(job->cSize)) assert(lastCBlockSize == 0);
+ job->cSize += lastCBlockSize;
+ job->consumed = job->src.size; /* when job->consumed == job->src.size , compression job is presumed completed */
+ ZSTD_pthread_cond_signal(&job->job_cond);
+ ZSTD_pthread_mutex_unlock(&job->job_mutex);
+}
+
+
+/* ------------------------------------------ */
+/* ===== Multi-threaded compression ===== */
+/* ------------------------------------------ */
+
+typedef struct {
+ range_t prefix; /* read-only non-owned prefix buffer */
+ buffer_t buffer;
+ size_t filled;
+} inBuff_t;
+
+typedef struct {
+ BYTE* buffer; /* The round input buffer. All jobs get references
+ * to pieces of the buffer. ZSTDMT_tryGetInputRange()
+ * handles handing out job input buffers, and makes
+ * sure it doesn't overlap with any pieces still in use.
+ */
+ size_t capacity; /* The capacity of buffer. */
+ size_t pos; /* The position of the current inBuff in the round
+ * buffer. Updated past the end if the inBuff once
+ * the inBuff is sent to the worker thread.
+ * pos <= capacity.
+ */
+} roundBuff_t;
+
+static const roundBuff_t kNullRoundBuff = {NULL, 0, 0};
+
+#define RSYNC_LENGTH 32
+
+typedef struct {
+ U64 hash;
+ U64 hitMask;
+ U64 primePower;
+} rsyncState_t;
+
+struct ZSTDMT_CCtx_s {
+ POOL_ctx* factory;
+ ZSTDMT_jobDescription* jobs;
+ ZSTDMT_bufferPool* bufPool;
+ ZSTDMT_CCtxPool* cctxPool;
+ ZSTDMT_seqPool* seqPool;
+ ZSTD_CCtx_params params;
+ size_t targetSectionSize;
+ size_t targetPrefixSize;
+ int jobReady; /* 1 => one job is already prepared, but pool has shortage of workers. Don't create a new job. */
+ inBuff_t inBuff;
+ roundBuff_t roundBuff;
+ serialState_t serial;
+ rsyncState_t rsync;
+ unsigned singleBlockingThread;
+ unsigned jobIDMask;
+ unsigned doneJobID;
+ unsigned nextJobID;
+ unsigned frameEnded;
+ unsigned allJobsCompleted;
+ unsigned long long frameContentSize;
+ unsigned long long consumed;
+ unsigned long long produced;
+ ZSTD_customMem cMem;
+ ZSTD_CDict* cdictLocal;
+ const ZSTD_CDict* cdict;
+};
+
+static void ZSTDMT_freeJobsTable(ZSTDMT_jobDescription* jobTable, U32 nbJobs, ZSTD_customMem cMem)
+{
+ U32 jobNb;
+ if (jobTable == NULL) return;
+ for (jobNb=0; jobNb<nbJobs; jobNb++) {
+ ZSTD_pthread_mutex_destroy(&jobTable[jobNb].job_mutex);
+ ZSTD_pthread_cond_destroy(&jobTable[jobNb].job_cond);
+ }
+ ZSTD_free(jobTable, cMem);
+}
+
+/* ZSTDMT_allocJobsTable()
+ * allocate and init a job table.
+ * update *nbJobsPtr to next power of 2 value, as size of table */
+static ZSTDMT_jobDescription* ZSTDMT_createJobsTable(U32* nbJobsPtr, ZSTD_customMem cMem)
+{
+ U32 const nbJobsLog2 = ZSTD_highbit32(*nbJobsPtr) + 1;
+ U32 const nbJobs = 1 << nbJobsLog2;
+ U32 jobNb;
+ ZSTDMT_jobDescription* const jobTable = (ZSTDMT_jobDescription*)
+ ZSTD_calloc(nbJobs * sizeof(ZSTDMT_jobDescription), cMem);
+ int initError = 0;
+ if (jobTable==NULL) return NULL;
+ *nbJobsPtr = nbJobs;
+ for (jobNb=0; jobNb<nbJobs; jobNb++) {
+ initError |= ZSTD_pthread_mutex_init(&jobTable[jobNb].job_mutex, NULL);
+ initError |= ZSTD_pthread_cond_init(&jobTable[jobNb].job_cond, NULL);
+ }
+ if (initError != 0) {
+ ZSTDMT_freeJobsTable(jobTable, nbJobs, cMem);
+ return NULL;
+ }
+ return jobTable;
+}
+
+static size_t ZSTDMT_expandJobsTable (ZSTDMT_CCtx* mtctx, U32 nbWorkers) {
+ U32 nbJobs = nbWorkers + 2;
+ if (nbJobs > mtctx->jobIDMask+1) { /* need more job capacity */
+ ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
+ mtctx->jobIDMask = 0;
+ mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, mtctx->cMem);
+ if (mtctx->jobs==NULL) return ERROR(memory_allocation);
+ assert((nbJobs != 0) && ((nbJobs & (nbJobs - 1)) == 0)); /* ensure nbJobs is a power of 2 */
+ mtctx->jobIDMask = nbJobs - 1;
+ }
+ return 0;
+}
+
+
+/* ZSTDMT_CCtxParam_setNbWorkers():
+ * Internal use only */
+size_t ZSTDMT_CCtxParam_setNbWorkers(ZSTD_CCtx_params* params, unsigned nbWorkers)
+{
+ if (nbWorkers > ZSTDMT_NBWORKERS_MAX) nbWorkers = ZSTDMT_NBWORKERS_MAX;
+ params->nbWorkers = nbWorkers;
+ params->overlapLog = ZSTDMT_OVERLAPLOG_DEFAULT;
+ params->jobSize = 0;
+ return nbWorkers;
+}
+
+ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced(unsigned nbWorkers, ZSTD_customMem cMem)
+{
+ ZSTDMT_CCtx* mtctx;
+ U32 nbJobs = nbWorkers + 2;
+ int initError;
+ DEBUGLOG(3, "ZSTDMT_createCCtx_advanced (nbWorkers = %u)", nbWorkers);
+
+ if (nbWorkers < 1) return NULL;
+ nbWorkers = MIN(nbWorkers , ZSTDMT_NBWORKERS_MAX);
+ if ((cMem.customAlloc!=NULL) ^ (cMem.customFree!=NULL))
+ /* invalid custom allocator */
+ return NULL;
+
+ mtctx = (ZSTDMT_CCtx*) ZSTD_calloc(sizeof(ZSTDMT_CCtx), cMem);
+ if (!mtctx) return NULL;
+ ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
+ mtctx->cMem = cMem;
+ mtctx->allJobsCompleted = 1;
+ mtctx->factory = POOL_create_advanced(nbWorkers, 0, cMem);
+ mtctx->jobs = ZSTDMT_createJobsTable(&nbJobs, cMem);
+ assert(nbJobs > 0); assert((nbJobs & (nbJobs - 1)) == 0); /* ensure nbJobs is a power of 2 */
+ mtctx->jobIDMask = nbJobs - 1;
+ mtctx->bufPool = ZSTDMT_createBufferPool(nbWorkers, cMem);
+ mtctx->cctxPool = ZSTDMT_createCCtxPool(nbWorkers, cMem);
+ mtctx->seqPool = ZSTDMT_createSeqPool(nbWorkers, cMem);
+ initError = ZSTDMT_serialState_init(&mtctx->serial);
+ mtctx->roundBuff = kNullRoundBuff;
+ if (!mtctx->factory | !mtctx->jobs | !mtctx->bufPool | !mtctx->cctxPool | !mtctx->seqPool | initError) {
+ ZSTDMT_freeCCtx(mtctx);
+ return NULL;
+ }
+ DEBUGLOG(3, "mt_cctx created, for %u threads", nbWorkers);
+ return mtctx;
+}
+
+ZSTDMT_CCtx* ZSTDMT_createCCtx(unsigned nbWorkers)
+{
+ return ZSTDMT_createCCtx_advanced(nbWorkers, ZSTD_defaultCMem);
+}
+
+
+/* ZSTDMT_releaseAllJobResources() :
+ * note : ensure all workers are killed first ! */
+static void ZSTDMT_releaseAllJobResources(ZSTDMT_CCtx* mtctx)
+{
+ unsigned jobID;
+ DEBUGLOG(3, "ZSTDMT_releaseAllJobResources");
+ for (jobID=0; jobID <= mtctx->jobIDMask; jobID++) {
+ DEBUGLOG(4, "job%02u: release dst address %08X", jobID, (U32)(size_t)mtctx->jobs[jobID].dstBuff.start);
+ ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);
+ mtctx->jobs[jobID].dstBuff = g_nullBuffer;
+ mtctx->jobs[jobID].cSize = 0;
+ }
+ memset(mtctx->jobs, 0, (mtctx->jobIDMask+1)*sizeof(ZSTDMT_jobDescription));
+ mtctx->inBuff.buffer = g_nullBuffer;
+ mtctx->inBuff.filled = 0;
+ mtctx->allJobsCompleted = 1;
+}
+
+static void ZSTDMT_waitForAllJobsCompleted(ZSTDMT_CCtx* mtctx)
+{
+ DEBUGLOG(4, "ZSTDMT_waitForAllJobsCompleted");
+ while (mtctx->doneJobID < mtctx->nextJobID) {
+ unsigned const jobID = mtctx->doneJobID & mtctx->jobIDMask;
+ ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex);
+ while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) {
+ DEBUGLOG(4, "waiting for jobCompleted signal from job %u", mtctx->doneJobID); /* we want to block when waiting for data to flush */
+ ZSTD_pthread_cond_wait(&mtctx->jobs[jobID].job_cond, &mtctx->jobs[jobID].job_mutex);
+ }
+ ZSTD_pthread_mutex_unlock(&mtctx->jobs[jobID].job_mutex);
+ mtctx->doneJobID++;
+ }
+}
+
+size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx)
+{
+ if (mtctx==NULL) return 0; /* compatible with free on NULL */
+ POOL_free(mtctx->factory); /* stop and free worker threads */
+ ZSTDMT_releaseAllJobResources(mtctx); /* release job resources into pools first */
+ ZSTDMT_freeJobsTable(mtctx->jobs, mtctx->jobIDMask+1, mtctx->cMem);
+ ZSTDMT_freeBufferPool(mtctx->bufPool);
+ ZSTDMT_freeCCtxPool(mtctx->cctxPool);
+ ZSTDMT_freeSeqPool(mtctx->seqPool);
+ ZSTDMT_serialState_free(&mtctx->serial);
+ ZSTD_freeCDict(mtctx->cdictLocal);
+ if (mtctx->roundBuff.buffer)
+ ZSTD_free(mtctx->roundBuff.buffer, mtctx->cMem);
+ ZSTD_free(mtctx, mtctx->cMem);
+ return 0;
+}
+
+size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx)
+{
+ if (mtctx == NULL) return 0; /* supports sizeof NULL */
+ return sizeof(*mtctx)
+ + POOL_sizeof(mtctx->factory)
+ + ZSTDMT_sizeof_bufferPool(mtctx->bufPool)
+ + (mtctx->jobIDMask+1) * sizeof(ZSTDMT_jobDescription)
+ + ZSTDMT_sizeof_CCtxPool(mtctx->cctxPool)
+ + ZSTDMT_sizeof_seqPool(mtctx->seqPool)
+ + ZSTD_sizeof_CDict(mtctx->cdictLocal)
+ + mtctx->roundBuff.capacity;
+}
+
+/* Internal only */
+size_t
+ZSTDMT_CCtxParam_setMTCtxParameter(ZSTD_CCtx_params* params,
+ ZSTDMT_parameter parameter,
+ int value)
+{
+ DEBUGLOG(4, "ZSTDMT_CCtxParam_setMTCtxParameter");
+ switch(parameter)
+ {
+ case ZSTDMT_p_jobSize :
+ DEBUGLOG(4, "ZSTDMT_CCtxParam_setMTCtxParameter : set jobSize to %i", value);
+ if ( value != 0 /* default */
+ && value < ZSTDMT_JOBSIZE_MIN)
+ value = ZSTDMT_JOBSIZE_MIN;
+ assert(value >= 0);
+ if (value > ZSTDMT_JOBSIZE_MAX) value = ZSTDMT_JOBSIZE_MAX;
+ params->jobSize = value;
+ return value;
+
+ case ZSTDMT_p_overlapLog :
+ DEBUGLOG(4, "ZSTDMT_p_overlapLog : %i", value);
+ if (value < ZSTD_OVERLAPLOG_MIN) value = ZSTD_OVERLAPLOG_MIN;
+ if (value > ZSTD_OVERLAPLOG_MAX) value = ZSTD_OVERLAPLOG_MAX;
+ params->overlapLog = value;
+ return value;
+
+ case ZSTDMT_p_rsyncable :
+ value = (value != 0);
+ params->rsyncable = value;
+ return value;
+
+ default :
+ return ERROR(parameter_unsupported);
+ }
+}
+
+size_t ZSTDMT_setMTCtxParameter(ZSTDMT_CCtx* mtctx, ZSTDMT_parameter parameter, int value)
+{
+ DEBUGLOG(4, "ZSTDMT_setMTCtxParameter");
+ return ZSTDMT_CCtxParam_setMTCtxParameter(&mtctx->params, parameter, value);
+}
+
+size_t ZSTDMT_getMTCtxParameter(ZSTDMT_CCtx* mtctx, ZSTDMT_parameter parameter, int* value)
+{
+ switch (parameter) {
+ case ZSTDMT_p_jobSize:
+ assert(mtctx->params.jobSize <= INT_MAX);
+ *value = (int)(mtctx->params.jobSize);
+ break;
+ case ZSTDMT_p_overlapLog:
+ *value = mtctx->params.overlapLog;
+ break;
+ case ZSTDMT_p_rsyncable:
+ *value = mtctx->params.rsyncable;
+ break;
+ default:
+ return ERROR(parameter_unsupported);
+ }
+ return 0;
+}
+
+/* Sets parameters relevant to the compression job,
+ * initializing others to default values. */
+static ZSTD_CCtx_params ZSTDMT_initJobCCtxParams(ZSTD_CCtx_params const params)
+{
+ ZSTD_CCtx_params jobParams;
+ memset(&jobParams, 0, sizeof(jobParams));
+
+ jobParams.cParams = params.cParams;
+ jobParams.fParams = params.fParams;
+ jobParams.compressionLevel = params.compressionLevel;
+
+ return jobParams;
+}
+
+
+/* ZSTDMT_resize() :
+ * @return : error code if fails, 0 on success */
+static size_t ZSTDMT_resize(ZSTDMT_CCtx* mtctx, unsigned nbWorkers)
+{
+ if (POOL_resize(mtctx->factory, nbWorkers)) return ERROR(memory_allocation);
+ CHECK_F( ZSTDMT_expandJobsTable(mtctx, nbWorkers) );
+ mtctx->bufPool = ZSTDMT_expandBufferPool(mtctx->bufPool, nbWorkers);
+ if (mtctx->bufPool == NULL) return ERROR(memory_allocation);
+ mtctx->cctxPool = ZSTDMT_expandCCtxPool(mtctx->cctxPool, nbWorkers);
+ if (mtctx->cctxPool == NULL) return ERROR(memory_allocation);
+ mtctx->seqPool = ZSTDMT_expandSeqPool(mtctx->seqPool, nbWorkers);
+ if (mtctx->seqPool == NULL) return ERROR(memory_allocation);
+ ZSTDMT_CCtxParam_setNbWorkers(&mtctx->params, nbWorkers);
+ return 0;
+}
+
+
+/*! ZSTDMT_updateCParams_whileCompressing() :
+ * Updates a selected set of compression parameters, remaining compatible with currently active frame.
+ * New parameters will be applied to next compression job. */
+void ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx* mtctx, const ZSTD_CCtx_params* cctxParams)
+{
+ U32 const saved_wlog = mtctx->params.cParams.windowLog; /* Do not modify windowLog while compressing */
+ int const compressionLevel = cctxParams->compressionLevel;
+ DEBUGLOG(5, "ZSTDMT_updateCParams_whileCompressing (level:%i)",
+ compressionLevel);
+ mtctx->params.compressionLevel = compressionLevel;
+ { ZSTD_compressionParameters cParams = ZSTD_getCParamsFromCCtxParams(cctxParams, 0, 0);
+ cParams.windowLog = saved_wlog;
+ mtctx->params.cParams = cParams;
+ }
+}
+
+/* ZSTDMT_getFrameProgression():
+ * tells how much data has been consumed (input) and produced (output) for current frame.
+ * able to count progression inside worker threads.
+ * Note : mutex will be acquired during statistics collection inside workers. */
+ZSTD_frameProgression ZSTDMT_getFrameProgression(ZSTDMT_CCtx* mtctx)
+{
+ ZSTD_frameProgression fps;
+ DEBUGLOG(5, "ZSTDMT_getFrameProgression");
+ fps.ingested = mtctx->consumed + mtctx->inBuff.filled;
+ fps.consumed = mtctx->consumed;
+ fps.produced = fps.flushed = mtctx->produced;
+ fps.currentJobID = mtctx->nextJobID;
+ fps.nbActiveWorkers = 0;
+ { unsigned jobNb;
+ unsigned lastJobNb = mtctx->nextJobID + mtctx->jobReady; assert(mtctx->jobReady <= 1);
+ DEBUGLOG(6, "ZSTDMT_getFrameProgression: jobs: from %u to <%u (jobReady:%u)",
+ mtctx->doneJobID, lastJobNb, mtctx->jobReady)
+ for (jobNb = mtctx->doneJobID ; jobNb < lastJobNb ; jobNb++) {
+ unsigned const wJobID = jobNb & mtctx->jobIDMask;
+ ZSTDMT_jobDescription* jobPtr = &mtctx->jobs[wJobID];
+ ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
+ { size_t const cResult = jobPtr->cSize;
+ size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
+ size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
+ assert(flushed <= produced);
+ fps.ingested += jobPtr->src.size;
+ fps.consumed += jobPtr->consumed;
+ fps.produced += produced;
+ fps.flushed += flushed;
+ fps.nbActiveWorkers += (jobPtr->consumed < jobPtr->src.size);
+ }
+ ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
+ }
+ }
+ return fps;
+}
+
+
+size_t ZSTDMT_toFlushNow(ZSTDMT_CCtx* mtctx)
+{
+ size_t toFlush;
+ unsigned const jobID = mtctx->doneJobID;
+ assert(jobID <= mtctx->nextJobID);
+ if (jobID == mtctx->nextJobID) return 0; /* no active job => nothing to flush */
+
+ /* look into oldest non-fully-flushed job */
+ { unsigned const wJobID = jobID & mtctx->jobIDMask;
+ ZSTDMT_jobDescription* const jobPtr = &mtctx->jobs[wJobID];
+ ZSTD_pthread_mutex_lock(&jobPtr->job_mutex);
+ { size_t const cResult = jobPtr->cSize;
+ size_t const produced = ZSTD_isError(cResult) ? 0 : cResult;
+ size_t const flushed = ZSTD_isError(cResult) ? 0 : jobPtr->dstFlushed;
+ assert(flushed <= produced);
+ toFlush = produced - flushed;
+ if (toFlush==0 && (jobPtr->consumed >= jobPtr->src.size)) {
+ /* doneJobID is not-fully-flushed, but toFlush==0 : doneJobID should be compressing some more data */
+ assert(jobPtr->consumed < jobPtr->src.size);
+ }
+ }
+ ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
+ }
+
+ return toFlush;
+}
+
+
+/* ------------------------------------------ */
+/* ===== Multi-threaded compression ===== */
+/* ------------------------------------------ */
+
+static unsigned ZSTDMT_computeTargetJobLog(ZSTD_CCtx_params const params)
+{
+ if (params.ldmParams.enableLdm)
+ /* In Long Range Mode, the windowLog is typically oversized.
+ * In which case, it's preferable to determine the jobSize
+ * based on chainLog instead. */
+ return MAX(21, params.cParams.chainLog + 4);
+ return MAX(20, params.cParams.windowLog + 2);
+}
+
+static int ZSTDMT_overlapLog_default(ZSTD_strategy strat)
+{
+ switch(strat)
+ {
+ case ZSTD_btultra2:
+ return 9;
+ case ZSTD_btultra:
+ case ZSTD_btopt:
+ return 8;
+ case ZSTD_btlazy2:
+ case ZSTD_lazy2:
+ return 7;
+ case ZSTD_lazy:
+ case ZSTD_greedy:
+ case ZSTD_dfast:
+ case ZSTD_fast:
+ default:;
+ }
+ return 6;
+}
+
+static int ZSTDMT_overlapLog(int ovlog, ZSTD_strategy strat)
+{
+ assert(0 <= ovlog && ovlog <= 9);
+ if (ovlog == 0) return ZSTDMT_overlapLog_default(strat);
+ return ovlog;
+}
+
+static size_t ZSTDMT_computeOverlapSize(ZSTD_CCtx_params const params)
+{
+ int const overlapRLog = 9 - ZSTDMT_overlapLog(params.overlapLog, params.cParams.strategy);
+ int ovLog = (overlapRLog >= 8) ? 0 : (params.cParams.windowLog - overlapRLog);
+ assert(0 <= overlapRLog && overlapRLog <= 8);
+ if (params.ldmParams.enableLdm) {
+ /* In Long Range Mode, the windowLog is typically oversized.
+ * In which case, it's preferable to determine the jobSize
+ * based on chainLog instead.
+ * Then, ovLog becomes a fraction of the jobSize, rather than windowSize */
+ ovLog = MIN(params.cParams.windowLog, ZSTDMT_computeTargetJobLog(params) - 2)
+ - overlapRLog;
+ }
+ assert(0 <= ovLog && ovLog <= 30);
+ DEBUGLOG(4, "overlapLog : %i", params.overlapLog);
+ DEBUGLOG(4, "overlap size : %i", 1 << ovLog);
+ return (ovLog==0) ? 0 : (size_t)1 << ovLog;
+}
+
+static unsigned
+ZSTDMT_computeNbJobs(ZSTD_CCtx_params params, size_t srcSize, unsigned nbWorkers)
+{
+ assert(nbWorkers>0);
+ { size_t const jobSizeTarget = (size_t)1 << ZSTDMT_computeTargetJobLog(params);
+ size_t const jobMaxSize = jobSizeTarget << 2;
+ size_t const passSizeMax = jobMaxSize * nbWorkers;
+ unsigned const multiplier = (unsigned)(srcSize / passSizeMax) + 1;
+ unsigned const nbJobsLarge = multiplier * nbWorkers;
+ unsigned const nbJobsMax = (unsigned)(srcSize / jobSizeTarget) + 1;
+ unsigned const nbJobsSmall = MIN(nbJobsMax, nbWorkers);
+ return (multiplier>1) ? nbJobsLarge : nbJobsSmall;
+} }
+
+/* ZSTDMT_compress_advanced_internal() :
+ * This is a blocking function : it will only give back control to caller after finishing its compression job.
+ */
+static size_t ZSTDMT_compress_advanced_internal(
+ ZSTDMT_CCtx* mtctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params)
+{
+ ZSTD_CCtx_params const jobParams = ZSTDMT_initJobCCtxParams(params);
+ size_t const overlapSize = ZSTDMT_computeOverlapSize(params);
+ unsigned const nbJobs = ZSTDMT_computeNbJobs(params, srcSize, params.nbWorkers);
+ size_t const proposedJobSize = (srcSize + (nbJobs-1)) / nbJobs;
+ size_t const avgJobSize = (((proposedJobSize-1) & 0x1FFFF) < 0x7FFF) ? proposedJobSize + 0xFFFF : proposedJobSize; /* avoid too small last block */
+ const char* const srcStart = (const char*)src;
+ size_t remainingSrcSize = srcSize;
+ unsigned const compressWithinDst = (dstCapacity >= ZSTD_compressBound(srcSize)) ? nbJobs : (unsigned)(dstCapacity / ZSTD_compressBound(avgJobSize)); /* presumes avgJobSize >= 256 KB, which should be the case */
+ size_t frameStartPos = 0, dstBufferPos = 0;
+ assert(jobParams.nbWorkers == 0);
+ assert(mtctx->cctxPool->totalCCtx == params.nbWorkers);
+
+ params.jobSize = (U32)avgJobSize;
+ DEBUGLOG(4, "ZSTDMT_compress_advanced_internal: nbJobs=%2u (rawSize=%u bytes; fixedSize=%u) ",
+ nbJobs, (U32)proposedJobSize, (U32)avgJobSize);
+
+ if ((nbJobs==1) | (params.nbWorkers<=1)) { /* fallback to single-thread mode : this is a blocking invocation anyway */
+ ZSTD_CCtx* const cctx = mtctx->cctxPool->cctx[0];
+ DEBUGLOG(4, "ZSTDMT_compress_advanced_internal: fallback to single-thread mode");
+ if (cdict) return ZSTD_compress_usingCDict_advanced(cctx, dst, dstCapacity, src, srcSize, cdict, jobParams.fParams);
+ return ZSTD_compress_advanced_internal(cctx, dst, dstCapacity, src, srcSize, NULL, 0, jobParams);
+ }
+
+ assert(avgJobSize >= 256 KB); /* condition for ZSTD_compressBound(A) + ZSTD_compressBound(B) <= ZSTD_compressBound(A+B), required to compress directly into Dst (no additional buffer) */
+ ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(avgJobSize) );
+ if (ZSTDMT_serialState_reset(&mtctx->serial, mtctx->seqPool, params, avgJobSize))
+ return ERROR(memory_allocation);
+
+ CHECK_F( ZSTDMT_expandJobsTable(mtctx, nbJobs) ); /* only expands if necessary */
+
+ { unsigned u;
+ for (u=0; u<nbJobs; u++) {
+ size_t const jobSize = MIN(remainingSrcSize, avgJobSize);
+ size_t const dstBufferCapacity = ZSTD_compressBound(jobSize);
+ buffer_t const dstAsBuffer = { (char*)dst + dstBufferPos, dstBufferCapacity };
+ buffer_t const dstBuffer = u < compressWithinDst ? dstAsBuffer : g_nullBuffer;
+ size_t dictSize = u ? overlapSize : 0;
+
+ mtctx->jobs[u].prefix.start = srcStart + frameStartPos - dictSize;
+ mtctx->jobs[u].prefix.size = dictSize;
+ mtctx->jobs[u].src.start = srcStart + frameStartPos;
+ mtctx->jobs[u].src.size = jobSize; assert(jobSize > 0); /* avoid job.src.size == 0 */
+ mtctx->jobs[u].consumed = 0;
+ mtctx->jobs[u].cSize = 0;
+ mtctx->jobs[u].cdict = (u==0) ? cdict : NULL;
+ mtctx->jobs[u].fullFrameSize = srcSize;
+ mtctx->jobs[u].params = jobParams;
+ /* do not calculate checksum within sections, but write it in header for first section */
+ mtctx->jobs[u].dstBuff = dstBuffer;
+ mtctx->jobs[u].cctxPool = mtctx->cctxPool;
+ mtctx->jobs[u].bufPool = mtctx->bufPool;
+ mtctx->jobs[u].seqPool = mtctx->seqPool;
+ mtctx->jobs[u].serial = &mtctx->serial;
+ mtctx->jobs[u].jobID = u;
+ mtctx->jobs[u].firstJob = (u==0);
+ mtctx->jobs[u].lastJob = (u==nbJobs-1);
+
+ DEBUGLOG(5, "ZSTDMT_compress_advanced_internal: posting job %u (%u bytes)", u, (U32)jobSize);
+ DEBUG_PRINTHEX(6, mtctx->jobs[u].prefix.start, 12);
+ POOL_add(mtctx->factory, ZSTDMT_compressionJob, &mtctx->jobs[u]);
+
+ frameStartPos += jobSize;
+ dstBufferPos += dstBufferCapacity;
+ remainingSrcSize -= jobSize;
+ } }
+
+ /* collect result */
+ { size_t error = 0, dstPos = 0;
+ unsigned jobID;
+ for (jobID=0; jobID<nbJobs; jobID++) {
+ DEBUGLOG(5, "waiting for job %u ", jobID);
+ ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[jobID].job_mutex);
+ while (mtctx->jobs[jobID].consumed < mtctx->jobs[jobID].src.size) {
+ DEBUGLOG(5, "waiting for jobCompleted signal from job %u", jobID);
+ ZSTD_pthread_cond_wait(&mtctx->jobs[jobID].job_cond, &mtctx->jobs[jobID].job_mutex);
+ }
+ ZSTD_pthread_mutex_unlock(&mtctx->jobs[jobID].job_mutex);
+ DEBUGLOG(5, "ready to write job %u ", jobID);
+
+ { size_t const cSize = mtctx->jobs[jobID].cSize;
+ if (ZSTD_isError(cSize)) error = cSize;
+ if ((!error) && (dstPos + cSize > dstCapacity)) error = ERROR(dstSize_tooSmall);
+ if (jobID) { /* note : job 0 is written directly at dst, which is correct position */
+ if (!error)
+ memmove((char*)dst + dstPos, mtctx->jobs[jobID].dstBuff.start, cSize); /* may overlap when job compressed within dst */
+ if (jobID >= compressWithinDst) { /* job compressed into its own buffer, which must be released */
+ DEBUGLOG(5, "releasing buffer %u>=%u", jobID, compressWithinDst);
+ ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[jobID].dstBuff);
+ } }
+ mtctx->jobs[jobID].dstBuff = g_nullBuffer;
+ mtctx->jobs[jobID].cSize = 0;
+ dstPos += cSize ;
+ }
+ } /* for (jobID=0; jobID<nbJobs; jobID++) */
+
+ DEBUGLOG(4, "checksumFlag : %u ", params.fParams.checksumFlag);
+ if (params.fParams.checksumFlag) {
+ U32 const checksum = (U32)XXH64_digest(&mtctx->serial.xxhState);
+ if (dstPos + 4 > dstCapacity) {
+ error = ERROR(dstSize_tooSmall);
+ } else {
+ DEBUGLOG(4, "writing checksum : %08X \n", checksum);
+ MEM_writeLE32((char*)dst + dstPos, checksum);
+ dstPos += 4;
+ } }
+
+ if (!error) DEBUGLOG(4, "compressed size : %u ", (U32)dstPos);
+ return error ? error : dstPos;
+ }
+}
+
+size_t ZSTDMT_compress_advanced(ZSTDMT_CCtx* mtctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const ZSTD_CDict* cdict,
+ ZSTD_parameters params,
+ int overlapLog)
+{
+ ZSTD_CCtx_params cctxParams = mtctx->params;
+ cctxParams.cParams = params.cParams;
+ cctxParams.fParams = params.fParams;
+ assert(ZSTD_OVERLAPLOG_MIN <= overlapLog && overlapLog <= ZSTD_OVERLAPLOG_MAX);
+ cctxParams.overlapLog = overlapLog;
+ return ZSTDMT_compress_advanced_internal(mtctx,
+ dst, dstCapacity,
+ src, srcSize,
+ cdict, cctxParams);
+}
+
+
+size_t ZSTDMT_compressCCtx(ZSTDMT_CCtx* mtctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ int compressionLevel)
+{
+ ZSTD_parameters params = ZSTD_getParams(compressionLevel, srcSize, 0);
+ int const overlapLog = ZSTDMT_overlapLog_default(params.cParams.strategy);
+ params.fParams.contentSizeFlag = 1;
+ return ZSTDMT_compress_advanced(mtctx, dst, dstCapacity, src, srcSize, NULL, params, overlapLog);
+}
+
+
+/* ====================================== */
+/* ======= Streaming API ======= */
+/* ====================================== */
+
+size_t ZSTDMT_initCStream_internal(
+ ZSTDMT_CCtx* mtctx,
+ const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType,
+ const ZSTD_CDict* cdict, ZSTD_CCtx_params params,
+ unsigned long long pledgedSrcSize)
+{
+ DEBUGLOG(4, "ZSTDMT_initCStream_internal (pledgedSrcSize=%u, nbWorkers=%u, cctxPool=%u)",
+ (U32)pledgedSrcSize, params.nbWorkers, mtctx->cctxPool->totalCCtx);
+
+ /* params supposed partially fully validated at this point */
+ assert(!ZSTD_isError(ZSTD_checkCParams(params.cParams)));
+ assert(!((dict) && (cdict))); /* either dict or cdict, not both */
+
+ /* init */
+ if (params.nbWorkers != mtctx->params.nbWorkers)
+ CHECK_F( ZSTDMT_resize(mtctx, params.nbWorkers) );
+
+ if (params.jobSize != 0 && params.jobSize < ZSTDMT_JOBSIZE_MIN) params.jobSize = ZSTDMT_JOBSIZE_MIN;
+ if (params.jobSize > (size_t)ZSTDMT_JOBSIZE_MAX) params.jobSize = ZSTDMT_JOBSIZE_MAX;
+
+ mtctx->singleBlockingThread = (pledgedSrcSize <= ZSTDMT_JOBSIZE_MIN); /* do not trigger multi-threading when srcSize is too small */
+ if (mtctx->singleBlockingThread) {
+ ZSTD_CCtx_params const singleThreadParams = ZSTDMT_initJobCCtxParams(params);
+ DEBUGLOG(5, "ZSTDMT_initCStream_internal: switch to single blocking thread mode");
+ assert(singleThreadParams.nbWorkers == 0);
+ return ZSTD_initCStream_internal(mtctx->cctxPool->cctx[0],
+ dict, dictSize, cdict,
+ singleThreadParams, pledgedSrcSize);
+ }
+
+ DEBUGLOG(4, "ZSTDMT_initCStream_internal: %u workers", params.nbWorkers);
+
+ if (mtctx->allJobsCompleted == 0) { /* previous compression not correctly finished */
+ ZSTDMT_waitForAllJobsCompleted(mtctx);
+ ZSTDMT_releaseAllJobResources(mtctx);
+ mtctx->allJobsCompleted = 1;
+ }
+
+ mtctx->params = params;
+ mtctx->frameContentSize = pledgedSrcSize;
+ if (dict) {
+ ZSTD_freeCDict(mtctx->cdictLocal);
+ mtctx->cdictLocal = ZSTD_createCDict_advanced(dict, dictSize,
+ ZSTD_dlm_byCopy, dictContentType, /* note : a loadPrefix becomes an internal CDict */
+ params.cParams, mtctx->cMem);
+ mtctx->cdict = mtctx->cdictLocal;
+ if (mtctx->cdictLocal == NULL) return ERROR(memory_allocation);
+ } else {
+ ZSTD_freeCDict(mtctx->cdictLocal);
+ mtctx->cdictLocal = NULL;
+ mtctx->cdict = cdict;
+ }
+
+ mtctx->targetPrefixSize = ZSTDMT_computeOverlapSize(params);
+ DEBUGLOG(4, "overlapLog=%i => %u KB", params.overlapLog, (U32)(mtctx->targetPrefixSize>>10));
+ mtctx->targetSectionSize = params.jobSize;
+ if (mtctx->targetSectionSize == 0) {
+ mtctx->targetSectionSize = 1ULL << ZSTDMT_computeTargetJobLog(params);
+ }
+ if (params.rsyncable) {
+ /* Aim for the targetsectionSize as the average job size. */
+ U32 const jobSizeMB = (U32)(mtctx->targetSectionSize >> 20);
+ U32 const rsyncBits = ZSTD_highbit32(jobSizeMB) + 20;
+ assert(jobSizeMB >= 1);
+ DEBUGLOG(4, "rsyncLog = %u", rsyncBits);
+ mtctx->rsync.hash = 0;
+ mtctx->rsync.hitMask = (1ULL << rsyncBits) - 1;
+ mtctx->rsync.primePower = ZSTD_rollingHash_primePower(RSYNC_LENGTH);
+ }
+ if (mtctx->targetSectionSize < mtctx->targetPrefixSize) mtctx->targetSectionSize = mtctx->targetPrefixSize; /* job size must be >= overlap size */
+ DEBUGLOG(4, "Job Size : %u KB (note : set to %u)", (U32)(mtctx->targetSectionSize>>10), (U32)params.jobSize);
+ DEBUGLOG(4, "inBuff Size : %u KB", (U32)(mtctx->targetSectionSize>>10));
+ ZSTDMT_setBufferSize(mtctx->bufPool, ZSTD_compressBound(mtctx->targetSectionSize));
+ {
+ /* If ldm is enabled we need windowSize space. */
+ size_t const windowSize = mtctx->params.ldmParams.enableLdm ? (1U << mtctx->params.cParams.windowLog) : 0;
+ /* Two buffers of slack, plus extra space for the overlap
+ * This is the minimum slack that LDM works with. One extra because
+ * flush might waste up to targetSectionSize-1 bytes. Another extra
+ * for the overlap (if > 0), then one to fill which doesn't overlap
+ * with the LDM window.
+ */
+ size_t const nbSlackBuffers = 2 + (mtctx->targetPrefixSize > 0);
+ size_t const slackSize = mtctx->targetSectionSize * nbSlackBuffers;
+ /* Compute the total size, and always have enough slack */
+ size_t const nbWorkers = MAX(mtctx->params.nbWorkers, 1);
+ size_t const sectionsSize = mtctx->targetSectionSize * nbWorkers;
+ size_t const capacity = MAX(windowSize, sectionsSize) + slackSize;
+ if (mtctx->roundBuff.capacity < capacity) {
+ if (mtctx->roundBuff.buffer)
+ ZSTD_free(mtctx->roundBuff.buffer, mtctx->cMem);
+ mtctx->roundBuff.buffer = (BYTE*)ZSTD_malloc(capacity, mtctx->cMem);
+ if (mtctx->roundBuff.buffer == NULL) {
+ mtctx->roundBuff.capacity = 0;
+ return ERROR(memory_allocation);
+ }
+ mtctx->roundBuff.capacity = capacity;
+ }
+ }
+ DEBUGLOG(4, "roundBuff capacity : %u KB", (U32)(mtctx->roundBuff.capacity>>10));
+ mtctx->roundBuff.pos = 0;
+ mtctx->inBuff.buffer = g_nullBuffer;
+ mtctx->inBuff.filled = 0;
+ mtctx->inBuff.prefix = kNullRange;
+ mtctx->doneJobID = 0;
+ mtctx->nextJobID = 0;
+ mtctx->frameEnded = 0;
+ mtctx->allJobsCompleted = 0;
+ mtctx->consumed = 0;
+ mtctx->produced = 0;
+ if (ZSTDMT_serialState_reset(&mtctx->serial, mtctx->seqPool, params, mtctx->targetSectionSize))
+ return ERROR(memory_allocation);
+ return 0;
+}
+
+size_t ZSTDMT_initCStream_advanced(ZSTDMT_CCtx* mtctx,
+ const void* dict, size_t dictSize,
+ ZSTD_parameters params,
+ unsigned long long pledgedSrcSize)
+{
+ ZSTD_CCtx_params cctxParams = mtctx->params; /* retrieve sticky params */
+ DEBUGLOG(4, "ZSTDMT_initCStream_advanced (pledgedSrcSize=%u)", (U32)pledgedSrcSize);
+ cctxParams.cParams = params.cParams;
+ cctxParams.fParams = params.fParams;
+ return ZSTDMT_initCStream_internal(mtctx, dict, dictSize, ZSTD_dct_auto, NULL,
+ cctxParams, pledgedSrcSize);
+}
+
+size_t ZSTDMT_initCStream_usingCDict(ZSTDMT_CCtx* mtctx,
+ const ZSTD_CDict* cdict,
+ ZSTD_frameParameters fParams,
+ unsigned long long pledgedSrcSize)
+{
+ ZSTD_CCtx_params cctxParams = mtctx->params;
+ if (cdict==NULL) return ERROR(dictionary_wrong); /* method incompatible with NULL cdict */
+ cctxParams.cParams = ZSTD_getCParamsFromCDict(cdict);
+ cctxParams.fParams = fParams;
+ return ZSTDMT_initCStream_internal(mtctx, NULL, 0 /*dictSize*/, ZSTD_dct_auto, cdict,
+ cctxParams, pledgedSrcSize);
+}
+
+
+/* ZSTDMT_resetCStream() :
+ * pledgedSrcSize can be zero == unknown (for the time being)
+ * prefer using ZSTD_CONTENTSIZE_UNKNOWN,
+ * as `0` might mean "empty" in the future */
+size_t ZSTDMT_resetCStream(ZSTDMT_CCtx* mtctx, unsigned long long pledgedSrcSize)
+{
+ if (!pledgedSrcSize) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN;
+ return ZSTDMT_initCStream_internal(mtctx, NULL, 0, ZSTD_dct_auto, 0, mtctx->params,
+ pledgedSrcSize);
+}
+
+size_t ZSTDMT_initCStream(ZSTDMT_CCtx* mtctx, int compressionLevel) {
+ ZSTD_parameters const params = ZSTD_getParams(compressionLevel, ZSTD_CONTENTSIZE_UNKNOWN, 0);
+ ZSTD_CCtx_params cctxParams = mtctx->params; /* retrieve sticky params */
+ DEBUGLOG(4, "ZSTDMT_initCStream (cLevel=%i)", compressionLevel);
+ cctxParams.cParams = params.cParams;
+ cctxParams.fParams = params.fParams;
+ return ZSTDMT_initCStream_internal(mtctx, NULL, 0, ZSTD_dct_auto, NULL, cctxParams, ZSTD_CONTENTSIZE_UNKNOWN);
+}
+
+
+/* ZSTDMT_writeLastEmptyBlock()
+ * Write a single empty block with an end-of-frame to finish a frame.
+ * Job must be created from streaming variant.
+ * This function is always successfull if expected conditions are fulfilled.
+ */
+static void ZSTDMT_writeLastEmptyBlock(ZSTDMT_jobDescription* job)
+{
+ assert(job->lastJob == 1);
+ assert(job->src.size == 0); /* last job is empty -> will be simplified into a last empty block */
+ assert(job->firstJob == 0); /* cannot be first job, as it also needs to create frame header */
+ assert(job->dstBuff.start == NULL); /* invoked from streaming variant only (otherwise, dstBuff might be user's output) */
+ job->dstBuff = ZSTDMT_getBuffer(job->bufPool);
+ if (job->dstBuff.start == NULL) {
+ job->cSize = ERROR(memory_allocation);
+ return;
+ }
+ assert(job->dstBuff.capacity >= ZSTD_blockHeaderSize); /* no buffer should ever be that small */
+ job->src = kNullRange;
+ job->cSize = ZSTD_writeLastEmptyBlock(job->dstBuff.start, job->dstBuff.capacity);
+ assert(!ZSTD_isError(job->cSize));
+ assert(job->consumed == 0);
+}
+
+static size_t ZSTDMT_createCompressionJob(ZSTDMT_CCtx* mtctx, size_t srcSize, ZSTD_EndDirective endOp)
+{
+ unsigned const jobID = mtctx->nextJobID & mtctx->jobIDMask;
+ int const endFrame = (endOp == ZSTD_e_end);
+
+ if (mtctx->nextJobID > mtctx->doneJobID + mtctx->jobIDMask) {
+ DEBUGLOG(5, "ZSTDMT_createCompressionJob: will not create new job : table is full");
+ assert((mtctx->nextJobID & mtctx->jobIDMask) == (mtctx->doneJobID & mtctx->jobIDMask));
+ return 0;
+ }
+
+ if (!mtctx->jobReady) {
+ BYTE const* src = (BYTE const*)mtctx->inBuff.buffer.start;
+ DEBUGLOG(5, "ZSTDMT_createCompressionJob: preparing job %u to compress %u bytes with %u preload ",
+ mtctx->nextJobID, (U32)srcSize, (U32)mtctx->inBuff.prefix.size);
+ mtctx->jobs[jobID].src.start = src;
+ mtctx->jobs[jobID].src.size = srcSize;
+ assert(mtctx->inBuff.filled >= srcSize);
+ mtctx->jobs[jobID].prefix = mtctx->inBuff.prefix;
+ mtctx->jobs[jobID].consumed = 0;
+ mtctx->jobs[jobID].cSize = 0;
+ mtctx->jobs[jobID].params = mtctx->params;
+ mtctx->jobs[jobID].cdict = mtctx->nextJobID==0 ? mtctx->cdict : NULL;
+ mtctx->jobs[jobID].fullFrameSize = mtctx->frameContentSize;
+ mtctx->jobs[jobID].dstBuff = g_nullBuffer;
+ mtctx->jobs[jobID].cctxPool = mtctx->cctxPool;
+ mtctx->jobs[jobID].bufPool = mtctx->bufPool;
+ mtctx->jobs[jobID].seqPool = mtctx->seqPool;
+ mtctx->jobs[jobID].serial = &mtctx->serial;
+ mtctx->jobs[jobID].jobID = mtctx->nextJobID;
+ mtctx->jobs[jobID].firstJob = (mtctx->nextJobID==0);
+ mtctx->jobs[jobID].lastJob = endFrame;
+ mtctx->jobs[jobID].frameChecksumNeeded = mtctx->params.fParams.checksumFlag && endFrame && (mtctx->nextJobID>0);
+ mtctx->jobs[jobID].dstFlushed = 0;
+
+ /* Update the round buffer pos and clear the input buffer to be reset */
+ mtctx->roundBuff.pos += srcSize;
+ mtctx->inBuff.buffer = g_nullBuffer;
+ mtctx->inBuff.filled = 0;
+ /* Set the prefix */
+ if (!endFrame) {
+ size_t const newPrefixSize = MIN(srcSize, mtctx->targetPrefixSize);
+ mtctx->inBuff.prefix.start = src + srcSize - newPrefixSize;
+ mtctx->inBuff.prefix.size = newPrefixSize;
+ } else { /* endFrame==1 => no need for another input buffer */
+ mtctx->inBuff.prefix = kNullRange;
+ mtctx->frameEnded = endFrame;
+ if (mtctx->nextJobID == 0) {
+ /* single job exception : checksum is already calculated directly within worker thread */
+ mtctx->params.fParams.checksumFlag = 0;
+ } }
+
+ if ( (srcSize == 0)
+ && (mtctx->nextJobID>0)/*single job must also write frame header*/ ) {
+ DEBUGLOG(5, "ZSTDMT_createCompressionJob: creating a last empty block to end frame");
+ assert(endOp == ZSTD_e_end); /* only possible case : need to end the frame with an empty last block */
+ ZSTDMT_writeLastEmptyBlock(mtctx->jobs + jobID);
+ mtctx->nextJobID++;
+ return 0;
+ }
+ }
+
+ DEBUGLOG(5, "ZSTDMT_createCompressionJob: posting job %u : %u bytes (end:%u, jobNb == %u (mod:%u))",
+ mtctx->nextJobID,
+ (U32)mtctx->jobs[jobID].src.size,
+ mtctx->jobs[jobID].lastJob,
+ mtctx->nextJobID,
+ jobID);
+ if (POOL_tryAdd(mtctx->factory, ZSTDMT_compressionJob, &mtctx->jobs[jobID])) {
+ mtctx->nextJobID++;
+ mtctx->jobReady = 0;
+ } else {
+ DEBUGLOG(5, "ZSTDMT_createCompressionJob: no worker available for job %u", mtctx->nextJobID);
+ mtctx->jobReady = 1;
+ }
+ return 0;
+}
+
+
+/*! ZSTDMT_flushProduced() :
+ * flush whatever data has been produced but not yet flushed in current job.
+ * move to next job if current one is fully flushed.
+ * `output` : `pos` will be updated with amount of data flushed .
+ * `blockToFlush` : if >0, the function will block and wait if there is no data available to flush .
+ * @return : amount of data remaining within internal buffer, 0 if no more, 1 if unknown but > 0, or an error code */
+static size_t ZSTDMT_flushProduced(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, unsigned blockToFlush, ZSTD_EndDirective end)
+{
+ unsigned const wJobID = mtctx->doneJobID & mtctx->jobIDMask;
+ DEBUGLOG(5, "ZSTDMT_flushProduced (blocking:%u , job %u <= %u)",
+ blockToFlush, mtctx->doneJobID, mtctx->nextJobID);
+ assert(output->size >= output->pos);
+
+ ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
+ if ( blockToFlush
+ && (mtctx->doneJobID < mtctx->nextJobID) ) {
+ assert(mtctx->jobs[wJobID].dstFlushed <= mtctx->jobs[wJobID].cSize);
+ while (mtctx->jobs[wJobID].dstFlushed == mtctx->jobs[wJobID].cSize) { /* nothing to flush */
+ if (mtctx->jobs[wJobID].consumed == mtctx->jobs[wJobID].src.size) {
+ DEBUGLOG(5, "job %u is completely consumed (%u == %u) => don't wait for cond, there will be none",
+ mtctx->doneJobID, (U32)mtctx->jobs[wJobID].consumed, (U32)mtctx->jobs[wJobID].src.size);
+ break;
+ }
+ DEBUGLOG(5, "waiting for something to flush from job %u (currently flushed: %u bytes)",
+ mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
+ ZSTD_pthread_cond_wait(&mtctx->jobs[wJobID].job_cond, &mtctx->jobs[wJobID].job_mutex); /* block when nothing to flush but some to come */
+ } }
+
+ /* try to flush something */
+ { size_t cSize = mtctx->jobs[wJobID].cSize; /* shared */
+ size_t const srcConsumed = mtctx->jobs[wJobID].consumed; /* shared */
+ size_t const srcSize = mtctx->jobs[wJobID].src.size; /* read-only, could be done after mutex lock, but no-declaration-after-statement */
+ ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
+ if (ZSTD_isError(cSize)) {
+ DEBUGLOG(5, "ZSTDMT_flushProduced: job %u : compression error detected : %s",
+ mtctx->doneJobID, ZSTD_getErrorName(cSize));
+ ZSTDMT_waitForAllJobsCompleted(mtctx);
+ ZSTDMT_releaseAllJobResources(mtctx);
+ return cSize;
+ }
+ /* add frame checksum if necessary (can only happen once) */
+ assert(srcConsumed <= srcSize);
+ if ( (srcConsumed == srcSize) /* job completed -> worker no longer active */
+ && mtctx->jobs[wJobID].frameChecksumNeeded ) {
+ U32 const checksum = (U32)XXH64_digest(&mtctx->serial.xxhState);
+ DEBUGLOG(4, "ZSTDMT_flushProduced: writing checksum : %08X \n", checksum);
+ MEM_writeLE32((char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].cSize, checksum);
+ cSize += 4;
+ mtctx->jobs[wJobID].cSize += 4; /* can write this shared value, as worker is no longer active */
+ mtctx->jobs[wJobID].frameChecksumNeeded = 0;
+ }
+
+ if (cSize > 0) { /* compression is ongoing or completed */
+ size_t const toFlush = MIN(cSize - mtctx->jobs[wJobID].dstFlushed, output->size - output->pos);
+ DEBUGLOG(5, "ZSTDMT_flushProduced: Flushing %u bytes from job %u (completion:%u/%u, generated:%u)",
+ (U32)toFlush, mtctx->doneJobID, (U32)srcConsumed, (U32)srcSize, (U32)cSize);
+ assert(mtctx->doneJobID < mtctx->nextJobID);
+ assert(cSize >= mtctx->jobs[wJobID].dstFlushed);
+ assert(mtctx->jobs[wJobID].dstBuff.start != NULL);
+ memcpy((char*)output->dst + output->pos,
+ (const char*)mtctx->jobs[wJobID].dstBuff.start + mtctx->jobs[wJobID].dstFlushed,
+ toFlush);
+ output->pos += toFlush;
+ mtctx->jobs[wJobID].dstFlushed += toFlush; /* can write : this value is only used by mtctx */
+
+ if ( (srcConsumed == srcSize) /* job is completed */
+ && (mtctx->jobs[wJobID].dstFlushed == cSize) ) { /* output buffer fully flushed => free this job position */
+ DEBUGLOG(5, "Job %u completed (%u bytes), moving to next one",
+ mtctx->doneJobID, (U32)mtctx->jobs[wJobID].dstFlushed);
+ ZSTDMT_releaseBuffer(mtctx->bufPool, mtctx->jobs[wJobID].dstBuff);
+ DEBUGLOG(5, "dstBuffer released");
+ mtctx->jobs[wJobID].dstBuff = g_nullBuffer;
+ mtctx->jobs[wJobID].cSize = 0; /* ensure this job slot is considered "not started" in future check */
+ mtctx->consumed += srcSize;
+ mtctx->produced += cSize;
+ mtctx->doneJobID++;
+ } }
+
+ /* return value : how many bytes left in buffer ; fake it to 1 when unknown but >0 */
+ if (cSize > mtctx->jobs[wJobID].dstFlushed) return (cSize - mtctx->jobs[wJobID].dstFlushed);
+ if (srcSize > srcConsumed) return 1; /* current job not completely compressed */
+ }
+ if (mtctx->doneJobID < mtctx->nextJobID) return 1; /* some more jobs ongoing */
+ if (mtctx->jobReady) return 1; /* one job is ready to push, just not yet in the list */
+ if (mtctx->inBuff.filled > 0) return 1; /* input is not empty, and still needs to be converted into a job */
+ mtctx->allJobsCompleted = mtctx->frameEnded; /* all jobs are entirely flushed => if this one is last one, frame is completed */
+ if (end == ZSTD_e_end) return !mtctx->frameEnded; /* for ZSTD_e_end, question becomes : is frame completed ? instead of : are internal buffers fully flushed ? */
+ return 0; /* internal buffers fully flushed */
+}
+
+/**
+ * Returns the range of data used by the earliest job that is not yet complete.
+ * If the data of the first job is broken up into two segments, we cover both
+ * sections.
+ */
+static range_t ZSTDMT_getInputDataInUse(ZSTDMT_CCtx* mtctx)
+{
+ unsigned const firstJobID = mtctx->doneJobID;
+ unsigned const lastJobID = mtctx->nextJobID;
+ unsigned jobID;
+
+ for (jobID = firstJobID; jobID < lastJobID; ++jobID) {
+ unsigned const wJobID = jobID & mtctx->jobIDMask;
+ size_t consumed;
+
+ ZSTD_PTHREAD_MUTEX_LOCK(&mtctx->jobs[wJobID].job_mutex);
+ consumed = mtctx->jobs[wJobID].consumed;
+ ZSTD_pthread_mutex_unlock(&mtctx->jobs[wJobID].job_mutex);
+
+ if (consumed < mtctx->jobs[wJobID].src.size) {
+ range_t range = mtctx->jobs[wJobID].prefix;
+ if (range.size == 0) {
+ /* Empty prefix */
+ range = mtctx->jobs[wJobID].src;
+ }
+ /* Job source in multiple segments not supported yet */
+ assert(range.start <= mtctx->jobs[wJobID].src.start);
+ return range;
+ }
+ }
+ return kNullRange;
+}
+
+/**
+ * Returns non-zero iff buffer and range overlap.
+ */
+static int ZSTDMT_isOverlapped(buffer_t buffer, range_t range)
+{
+ BYTE const* const bufferStart = (BYTE const*)buffer.start;
+ BYTE const* const bufferEnd = bufferStart + buffer.capacity;
+ BYTE const* const rangeStart = (BYTE const*)range.start;
+ BYTE const* const rangeEnd = rangeStart + range.size;
+
+ if (rangeStart == NULL || bufferStart == NULL)
+ return 0;
+ /* Empty ranges cannot overlap */
+ if (bufferStart == bufferEnd || rangeStart == rangeEnd)
+ return 0;
+
+ return bufferStart < rangeEnd && rangeStart < bufferEnd;
+}
+
+static int ZSTDMT_doesOverlapWindow(buffer_t buffer, ZSTD_window_t window)
+{
+ range_t extDict;
+ range_t prefix;
+
+ DEBUGLOG(5, "ZSTDMT_doesOverlapWindow");
+ extDict.start = window.dictBase + window.lowLimit;
+ extDict.size = window.dictLimit - window.lowLimit;
+
+ prefix.start = window.base + window.dictLimit;
+ prefix.size = window.nextSrc - (window.base + window.dictLimit);
+ DEBUGLOG(5, "extDict [0x%zx, 0x%zx)",
+ (size_t)extDict.start,
+ (size_t)extDict.start + extDict.size);
+ DEBUGLOG(5, "prefix [0x%zx, 0x%zx)",
+ (size_t)prefix.start,
+ (size_t)prefix.start + prefix.size);
+
+ return ZSTDMT_isOverlapped(buffer, extDict)
+ || ZSTDMT_isOverlapped(buffer, prefix);
+}
+
+static void ZSTDMT_waitForLdmComplete(ZSTDMT_CCtx* mtctx, buffer_t buffer)
+{
+ if (mtctx->params.ldmParams.enableLdm) {
+ ZSTD_pthread_mutex_t* mutex = &mtctx->serial.ldmWindowMutex;
+ DEBUGLOG(5, "ZSTDMT_waitForLdmComplete");
+ DEBUGLOG(5, "source [0x%zx, 0x%zx)",
+ (size_t)buffer.start,
+ (size_t)buffer.start + buffer.capacity);
+ ZSTD_PTHREAD_MUTEX_LOCK(mutex);
+ while (ZSTDMT_doesOverlapWindow(buffer, mtctx->serial.ldmWindow)) {
+ DEBUGLOG(5, "Waiting for LDM to finish...");
+ ZSTD_pthread_cond_wait(&mtctx->serial.ldmWindowCond, mutex);
+ }
+ DEBUGLOG(6, "Done waiting for LDM to finish");
+ ZSTD_pthread_mutex_unlock(mutex);
+ }
+}
+
+/**
+ * Attempts to set the inBuff to the next section to fill.
+ * If any part of the new section is still in use we give up.
+ * Returns non-zero if the buffer is filled.
+ */
+static int ZSTDMT_tryGetInputRange(ZSTDMT_CCtx* mtctx)
+{
+ range_t const inUse = ZSTDMT_getInputDataInUse(mtctx);
+ size_t const spaceLeft = mtctx->roundBuff.capacity - mtctx->roundBuff.pos;
+ size_t const target = mtctx->targetSectionSize;
+ buffer_t buffer;
+
+ DEBUGLOG(5, "ZSTDMT_tryGetInputRange");
+ assert(mtctx->inBuff.buffer.start == NULL);
+ assert(mtctx->roundBuff.capacity >= target);
+
+ if (spaceLeft < target) {
+ /* ZSTD_invalidateRepCodes() doesn't work for extDict variants.
+ * Simply copy the prefix to the beginning in that case.
+ */
+ BYTE* const start = (BYTE*)mtctx->roundBuff.buffer;
+ size_t const prefixSize = mtctx->inBuff.prefix.size;
+
+ buffer.start = start;
+ buffer.capacity = prefixSize;
+ if (ZSTDMT_isOverlapped(buffer, inUse)) {
+ DEBUGLOG(5, "Waiting for buffer...");
+ return 0;
+ }
+ ZSTDMT_waitForLdmComplete(mtctx, buffer);
+ memmove(start, mtctx->inBuff.prefix.start, prefixSize);
+ mtctx->inBuff.prefix.start = start;
+ mtctx->roundBuff.pos = prefixSize;
+ }
+ buffer.start = mtctx->roundBuff.buffer + mtctx->roundBuff.pos;
+ buffer.capacity = target;
+
+ if (ZSTDMT_isOverlapped(buffer, inUse)) {
+ DEBUGLOG(5, "Waiting for buffer...");
+ return 0;
+ }
+ assert(!ZSTDMT_isOverlapped(buffer, mtctx->inBuff.prefix));
+
+ ZSTDMT_waitForLdmComplete(mtctx, buffer);
+
+ DEBUGLOG(5, "Using prefix range [%zx, %zx)",
+ (size_t)mtctx->inBuff.prefix.start,
+ (size_t)mtctx->inBuff.prefix.start + mtctx->inBuff.prefix.size);
+ DEBUGLOG(5, "Using source range [%zx, %zx)",
+ (size_t)buffer.start,
+ (size_t)buffer.start + buffer.capacity);
+
+
+ mtctx->inBuff.buffer = buffer;
+ mtctx->inBuff.filled = 0;
+ assert(mtctx->roundBuff.pos + buffer.capacity <= mtctx->roundBuff.capacity);
+ return 1;
+}
+
+typedef struct {
+ size_t toLoad; /* The number of bytes to load from the input. */
+ int flush; /* Boolean declaring if we must flush because we found a synchronization point. */
+} syncPoint_t;
+
+/**
+ * Searches through the input for a synchronization point. If one is found, we
+ * will instruct the caller to flush, and return the number of bytes to load.
+ * Otherwise, we will load as many bytes as possible and instruct the caller
+ * to continue as normal.
+ */
+static syncPoint_t
+findSynchronizationPoint(ZSTDMT_CCtx const* mtctx, ZSTD_inBuffer const input)
+{
+ BYTE const* const istart = (BYTE const*)input.src + input.pos;
+ U64 const primePower = mtctx->rsync.primePower;
+ U64 const hitMask = mtctx->rsync.hitMask;
+
+ syncPoint_t syncPoint;
+ U64 hash;
+ BYTE const* prev;
+ size_t pos;
+
+ syncPoint.toLoad = MIN(input.size - input.pos, mtctx->targetSectionSize - mtctx->inBuff.filled);
+ syncPoint.flush = 0;
+ if (!mtctx->params.rsyncable)
+ /* Rsync is disabled. */
+ return syncPoint;
+ if (mtctx->inBuff.filled + syncPoint.toLoad < RSYNC_LENGTH)
+ /* Not enough to compute the hash.
+ * We will miss any synchronization points in this RSYNC_LENGTH byte
+ * window. However, since it depends only in the internal buffers, if the
+ * state is already synchronized, we will remain synchronized.
+ * Additionally, the probability that we miss a synchronization point is
+ * low: RSYNC_LENGTH / targetSectionSize.
+ */
+ return syncPoint;
+ /* Initialize the loop variables. */
+ if (mtctx->inBuff.filled >= RSYNC_LENGTH) {
+ /* We have enough bytes buffered to initialize the hash.
+ * Start scanning at the beginning of the input.
+ */
+ pos = 0;
+ prev = (BYTE const*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled - RSYNC_LENGTH;
+ hash = ZSTD_rollingHash_compute(prev, RSYNC_LENGTH);
+ } else {
+ /* We don't have enough bytes buffered to initialize the hash, but
+ * we know we have at least RSYNC_LENGTH bytes total.
+ * Start scanning after the first RSYNC_LENGTH bytes less the bytes
+ * already buffered.
+ */
+ pos = RSYNC_LENGTH - mtctx->inBuff.filled;
+ prev = (BYTE const*)mtctx->inBuff.buffer.start - pos;
+ hash = ZSTD_rollingHash_compute(mtctx->inBuff.buffer.start, mtctx->inBuff.filled);
+ hash = ZSTD_rollingHash_append(hash, istart, pos);
+ }
+ /* Starting with the hash of the previous RSYNC_LENGTH bytes, roll
+ * through the input. If we hit a synchronization point, then cut the
+ * job off, and tell the compressor to flush the job. Otherwise, load
+ * all the bytes and continue as normal.
+ * If we go too long without a synchronization point (targetSectionSize)
+ * then a block will be emitted anyways, but this is okay, since if we
+ * are already synchronized we will remain synchronized.
+ */
+ for (; pos < syncPoint.toLoad; ++pos) {
+ BYTE const toRemove = pos < RSYNC_LENGTH ? prev[pos] : istart[pos - RSYNC_LENGTH];
+ /* if (pos >= RSYNC_LENGTH) assert(ZSTD_rollingHash_compute(istart + pos - RSYNC_LENGTH, RSYNC_LENGTH) == hash); */
+ hash = ZSTD_rollingHash_rotate(hash, toRemove, istart[pos], primePower);
+ if ((hash & hitMask) == hitMask) {
+ syncPoint.toLoad = pos + 1;
+ syncPoint.flush = 1;
+ break;
+ }
+ }
+ return syncPoint;
+}
+
+size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx)
+{
+ size_t hintInSize = mtctx->targetSectionSize - mtctx->inBuff.filled;
+ if (hintInSize==0) hintInSize = mtctx->targetSectionSize;
+ return hintInSize;
+}
+
+/** ZSTDMT_compressStream_generic() :
+ * internal use only - exposed to be invoked from zstd_compress.c
+ * assumption : output and input are valid (pos <= size)
+ * @return : minimum amount of data remaining to flush, 0 if none */
+size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx,
+ ZSTD_outBuffer* output,
+ ZSTD_inBuffer* input,
+ ZSTD_EndDirective endOp)
+{
+ unsigned forwardInputProgress = 0;
+ DEBUGLOG(5, "ZSTDMT_compressStream_generic (endOp=%u, srcSize=%u)",
+ (U32)endOp, (U32)(input->size - input->pos));
+ assert(output->pos <= output->size);
+ assert(input->pos <= input->size);
+
+ if (mtctx->singleBlockingThread) { /* delegate to single-thread (synchronous) */
+ return ZSTD_compressStream_generic(mtctx->cctxPool->cctx[0], output, input, endOp);
+ }
+
+ if ((mtctx->frameEnded) && (endOp==ZSTD_e_continue)) {
+ /* current frame being ended. Only flush/end are allowed */
+ return ERROR(stage_wrong);
+ }
+
+ /* single-pass shortcut (note : synchronous-mode) */
+ if ( (!mtctx->params.rsyncable) /* rsyncable mode is disabled */
+ && (mtctx->nextJobID == 0) /* just started */
+ && (mtctx->inBuff.filled == 0) /* nothing buffered */
+ && (!mtctx->jobReady) /* no job already created */
+ && (endOp == ZSTD_e_end) /* end order */
+ && (output->size - output->pos >= ZSTD_compressBound(input->size - input->pos)) ) { /* enough space in dst */
+ size_t const cSize = ZSTDMT_compress_advanced_internal(mtctx,
+ (char*)output->dst + output->pos, output->size - output->pos,
+ (const char*)input->src + input->pos, input->size - input->pos,
+ mtctx->cdict, mtctx->params);
+ if (ZSTD_isError(cSize)) return cSize;
+ input->pos = input->size;
+ output->pos += cSize;
+ mtctx->allJobsCompleted = 1;
+ mtctx->frameEnded = 1;
+ return 0;
+ }
+
+ /* fill input buffer */
+ if ( (!mtctx->jobReady)
+ && (input->size > input->pos) ) { /* support NULL input */
+ if (mtctx->inBuff.buffer.start == NULL) {
+ assert(mtctx->inBuff.filled == 0); /* Can't fill an empty buffer */
+ if (!ZSTDMT_tryGetInputRange(mtctx)) {
+ /* It is only possible for this operation to fail if there are
+ * still compression jobs ongoing.
+ */
+ DEBUGLOG(5, "ZSTDMT_tryGetInputRange failed");
+ assert(mtctx->doneJobID != mtctx->nextJobID);
+ } else
+ DEBUGLOG(5, "ZSTDMT_tryGetInputRange completed successfully : mtctx->inBuff.buffer.start = %p", mtctx->inBuff.buffer.start);
+ }
+ if (mtctx->inBuff.buffer.start != NULL) {
+ syncPoint_t const syncPoint = findSynchronizationPoint(mtctx, *input);
+ if (syncPoint.flush && endOp == ZSTD_e_continue) {
+ endOp = ZSTD_e_flush;
+ }
+ assert(mtctx->inBuff.buffer.capacity >= mtctx->targetSectionSize);
+ DEBUGLOG(5, "ZSTDMT_compressStream_generic: adding %u bytes on top of %u to buffer of size %u",
+ (U32)syncPoint.toLoad, (U32)mtctx->inBuff.filled, (U32)mtctx->targetSectionSize);
+ memcpy((char*)mtctx->inBuff.buffer.start + mtctx->inBuff.filled, (const char*)input->src + input->pos, syncPoint.toLoad);
+ input->pos += syncPoint.toLoad;
+ mtctx->inBuff.filled += syncPoint.toLoad;
+ forwardInputProgress = syncPoint.toLoad>0;
+ }
+ if ((input->pos < input->size) && (endOp == ZSTD_e_end))
+ endOp = ZSTD_e_flush; /* can't end now : not all input consumed */
+ }
+
+ if ( (mtctx->jobReady)
+ || (mtctx->inBuff.filled >= mtctx->targetSectionSize) /* filled enough : let's compress */
+ || ((endOp != ZSTD_e_continue) && (mtctx->inBuff.filled > 0)) /* something to flush : let's go */
+ || ((endOp == ZSTD_e_end) && (!mtctx->frameEnded)) ) { /* must finish the frame with a zero-size block */
+ size_t const jobSize = mtctx->inBuff.filled;
+ assert(mtctx->inBuff.filled <= mtctx->targetSectionSize);
+ CHECK_F( ZSTDMT_createCompressionJob(mtctx, jobSize, endOp) );
+ }
+
+ /* check for potential compressed data ready to be flushed */
+ { size_t const remainingToFlush = ZSTDMT_flushProduced(mtctx, output, !forwardInputProgress, endOp); /* block if there was no forward input progress */
+ if (input->pos < input->size) return MAX(remainingToFlush, 1); /* input not consumed : do not end flush yet */
+ DEBUGLOG(5, "end of ZSTDMT_compressStream_generic: remainingToFlush = %u", (U32)remainingToFlush);
+ return remainingToFlush;
+ }
+}
+
+
+size_t ZSTDMT_compressStream(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
+{
+ CHECK_F( ZSTDMT_compressStream_generic(mtctx, output, input, ZSTD_e_continue) );
+
+ /* recommended next input size : fill current input buffer */
+ return mtctx->targetSectionSize - mtctx->inBuff.filled; /* note : could be zero when input buffer is fully filled and no more availability to create new job */
+}
+
+
+static size_t ZSTDMT_flushStream_internal(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, ZSTD_EndDirective endFrame)
+{
+ size_t const srcSize = mtctx->inBuff.filled;
+ DEBUGLOG(5, "ZSTDMT_flushStream_internal");
+
+ if ( mtctx->jobReady /* one job ready for a worker to pick up */
+ || (srcSize > 0) /* still some data within input buffer */
+ || ((endFrame==ZSTD_e_end) && !mtctx->frameEnded)) { /* need a last 0-size block to end frame */
+ DEBUGLOG(5, "ZSTDMT_flushStream_internal : create a new job (%u bytes, end:%u)",
+ (U32)srcSize, (U32)endFrame);
+ CHECK_F( ZSTDMT_createCompressionJob(mtctx, srcSize, endFrame) );
+ }
+
+ /* check if there is any data available to flush */
+ return ZSTDMT_flushProduced(mtctx, output, 1 /* blockToFlush */, endFrame);
+}
+
+
+size_t ZSTDMT_flushStream(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output)
+{
+ DEBUGLOG(5, "ZSTDMT_flushStream");
+ if (mtctx->singleBlockingThread)
+ return ZSTD_flushStream(mtctx->cctxPool->cctx[0], output);
+ return ZSTDMT_flushStream_internal(mtctx, output, ZSTD_e_flush);
+}
+
+size_t ZSTDMT_endStream(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output)
+{
+ DEBUGLOG(4, "ZSTDMT_endStream");
+ if (mtctx->singleBlockingThread)
+ return ZSTD_endStream(mtctx->cctxPool->cctx[0], output);
+ return ZSTDMT_flushStream_internal(mtctx, output, ZSTD_e_end);
+}
diff --git a/Utilities/cmzstd/lib/compress/zstdmt_compress.h b/Utilities/cmzstd/lib/compress/zstdmt_compress.h
new file mode 100644
index 000000000..ee771681f
--- /dev/null
+++ b/Utilities/cmzstd/lib/compress/zstdmt_compress.h
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+ #ifndef ZSTDMT_COMPRESS_H
+ #define ZSTDMT_COMPRESS_H
+
+ #if defined (__cplusplus)
+ extern "C" {
+ #endif
+
+
+/* Note : This is an internal API.
+ * Some methods are still exposed (ZSTDLIB_API),
+ * because it used to be the only way to invoke MT compression.
+ * Now, it's recommended to use ZSTD_compress_generic() instead.
+ * These methods will stop being exposed in a future version */
+
+/* === Dependencies === */
+#include <stddef.h> /* size_t */
+#define ZSTD_STATIC_LINKING_ONLY /* ZSTD_parameters */
+#include "zstd.h" /* ZSTD_inBuffer, ZSTD_outBuffer, ZSTDLIB_API */
+
+
+/* === Constants === */
+#ifndef ZSTDMT_NBWORKERS_MAX
+# define ZSTDMT_NBWORKERS_MAX 200
+#endif
+#ifndef ZSTDMT_JOBSIZE_MIN
+# define ZSTDMT_JOBSIZE_MIN (1 MB)
+#endif
+#define ZSTDMT_JOBSIZE_MAX (MEM_32bits() ? (512 MB) : (1024 MB))
+
+
+/* === Memory management === */
+typedef struct ZSTDMT_CCtx_s ZSTDMT_CCtx;
+ZSTDLIB_API ZSTDMT_CCtx* ZSTDMT_createCCtx(unsigned nbWorkers);
+ZSTDLIB_API ZSTDMT_CCtx* ZSTDMT_createCCtx_advanced(unsigned nbWorkers,
+ ZSTD_customMem cMem);
+ZSTDLIB_API size_t ZSTDMT_freeCCtx(ZSTDMT_CCtx* mtctx);
+
+ZSTDLIB_API size_t ZSTDMT_sizeof_CCtx(ZSTDMT_CCtx* mtctx);
+
+
+/* === Simple one-pass compression function === */
+
+ZSTDLIB_API size_t ZSTDMT_compressCCtx(ZSTDMT_CCtx* mtctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ int compressionLevel);
+
+
+
+/* === Streaming functions === */
+
+ZSTDLIB_API size_t ZSTDMT_initCStream(ZSTDMT_CCtx* mtctx, int compressionLevel);
+ZSTDLIB_API size_t ZSTDMT_resetCStream(ZSTDMT_CCtx* mtctx, unsigned long long pledgedSrcSize); /**< if srcSize is not known at reset time, use ZSTD_CONTENTSIZE_UNKNOWN. Note: for compatibility with older programs, 0 means the same as ZSTD_CONTENTSIZE_UNKNOWN, but it will change in the future to mean "empty" */
+
+ZSTDLIB_API size_t ZSTDMT_nextInputSizeHint(const ZSTDMT_CCtx* mtctx);
+ZSTDLIB_API size_t ZSTDMT_compressStream(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output, ZSTD_inBuffer* input);
+
+ZSTDLIB_API size_t ZSTDMT_flushStream(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output); /**< @return : 0 == all flushed; >0 : still some data to be flushed; or an error code (ZSTD_isError()) */
+ZSTDLIB_API size_t ZSTDMT_endStream(ZSTDMT_CCtx* mtctx, ZSTD_outBuffer* output); /**< @return : 0 == all flushed; >0 : still some data to be flushed; or an error code (ZSTD_isError()) */
+
+
+/* === Advanced functions and parameters === */
+
+ZSTDLIB_API size_t ZSTDMT_compress_advanced(ZSTDMT_CCtx* mtctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const ZSTD_CDict* cdict,
+ ZSTD_parameters params,
+ int overlapLog);
+
+ZSTDLIB_API size_t ZSTDMT_initCStream_advanced(ZSTDMT_CCtx* mtctx,
+ const void* dict, size_t dictSize, /* dict can be released after init, a local copy is preserved within zcs */
+ ZSTD_parameters params,
+ unsigned long long pledgedSrcSize); /* pledgedSrcSize is optional and can be zero == unknown */
+
+ZSTDLIB_API size_t ZSTDMT_initCStream_usingCDict(ZSTDMT_CCtx* mtctx,
+ const ZSTD_CDict* cdict,
+ ZSTD_frameParameters fparams,
+ unsigned long long pledgedSrcSize); /* note : zero means empty */
+
+/* ZSTDMT_parameter :
+ * List of parameters that can be set using ZSTDMT_setMTCtxParameter() */
+typedef enum {
+ ZSTDMT_p_jobSize, /* Each job is compressed in parallel. By default, this value is dynamically determined depending on compression parameters. Can be set explicitly here. */
+ ZSTDMT_p_overlapLog, /* Each job may reload a part of previous job to enhance compressionr ratio; 0 == no overlap, 6(default) == use 1/8th of window, >=9 == use full window. This is a "sticky" parameter : its value will be re-used on next compression job */
+ ZSTDMT_p_rsyncable /* Enables rsyncable mode. */
+} ZSTDMT_parameter;
+
+/* ZSTDMT_setMTCtxParameter() :
+ * allow setting individual parameters, one at a time, among a list of enums defined in ZSTDMT_parameter.
+ * The function must be called typically after ZSTD_createCCtx() but __before ZSTDMT_init*() !__
+ * Parameters not explicitly reset by ZSTDMT_init*() remain the same in consecutive compression sessions.
+ * @return : 0, or an error code (which can be tested using ZSTD_isError()) */
+ZSTDLIB_API size_t ZSTDMT_setMTCtxParameter(ZSTDMT_CCtx* mtctx, ZSTDMT_parameter parameter, int value);
+
+/* ZSTDMT_getMTCtxParameter() :
+ * Query the ZSTDMT_CCtx for a parameter value.
+ * @return : 0, or an error code (which can be tested using ZSTD_isError()) */
+ZSTDLIB_API size_t ZSTDMT_getMTCtxParameter(ZSTDMT_CCtx* mtctx, ZSTDMT_parameter parameter, int* value);
+
+
+/*! ZSTDMT_compressStream_generic() :
+ * Combines ZSTDMT_compressStream() with optional ZSTDMT_flushStream() or ZSTDMT_endStream()
+ * depending on flush directive.
+ * @return : minimum amount of data still to be flushed
+ * 0 if fully flushed
+ * or an error code
+ * note : needs to be init using any ZSTD_initCStream*() variant */
+ZSTDLIB_API size_t ZSTDMT_compressStream_generic(ZSTDMT_CCtx* mtctx,
+ ZSTD_outBuffer* output,
+ ZSTD_inBuffer* input,
+ ZSTD_EndDirective endOp);
+
+
+/* ========================================================
+ * === Private interface, for use by ZSTD_compress.c ===
+ * === Not exposed in libzstd. Never invoke directly ===
+ * ======================================================== */
+
+ /*! ZSTDMT_toFlushNow()
+ * Tell how many bytes are ready to be flushed immediately.
+ * Probe the oldest active job (not yet entirely flushed) and check its output buffer.
+ * If return 0, it means there is no active job,
+ * or, it means oldest job is still active, but everything produced has been flushed so far,
+ * therefore flushing is limited by speed of oldest job. */
+size_t ZSTDMT_toFlushNow(ZSTDMT_CCtx* mtctx);
+
+/*! ZSTDMT_CCtxParam_setMTCtxParameter()
+ * like ZSTDMT_setMTCtxParameter(), but into a ZSTD_CCtx_Params */
+size_t ZSTDMT_CCtxParam_setMTCtxParameter(ZSTD_CCtx_params* params, ZSTDMT_parameter parameter, int value);
+
+/*! ZSTDMT_CCtxParam_setNbWorkers()
+ * Set nbWorkers, and clamp it.
+ * Also reset jobSize and overlapLog */
+size_t ZSTDMT_CCtxParam_setNbWorkers(ZSTD_CCtx_params* params, unsigned nbWorkers);
+
+/*! ZSTDMT_updateCParams_whileCompressing() :
+ * Updates only a selected set of compression parameters, to remain compatible with current frame.
+ * New parameters will be applied to next compression job. */
+void ZSTDMT_updateCParams_whileCompressing(ZSTDMT_CCtx* mtctx, const ZSTD_CCtx_params* cctxParams);
+
+/*! ZSTDMT_getFrameProgression():
+ * tells how much data has been consumed (input) and produced (output) for current frame.
+ * able to count progression inside worker threads.
+ */
+ZSTD_frameProgression ZSTDMT_getFrameProgression(ZSTDMT_CCtx* mtctx);
+
+
+/*! ZSTDMT_initCStream_internal() :
+ * Private use only. Init streaming operation.
+ * expects params to be valid.
+ * must receive dict, or cdict, or none, but not both.
+ * @return : 0, or an error code */
+size_t ZSTDMT_initCStream_internal(ZSTDMT_CCtx* zcs,
+ const void* dict, size_t dictSize, ZSTD_dictContentType_e dictContentType,
+ const ZSTD_CDict* cdict,
+ ZSTD_CCtx_params params, unsigned long long pledgedSrcSize);
+
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* ZSTDMT_COMPRESS_H */
diff --git a/Utilities/cmzstd/lib/decompress/huf_decompress.c b/Utilities/cmzstd/lib/decompress/huf_decompress.c
new file mode 100644
index 000000000..3f8bd2973
--- /dev/null
+++ b/Utilities/cmzstd/lib/decompress/huf_decompress.c
@@ -0,0 +1,1232 @@
+/* ******************************************************************
+ huff0 huffman decoder,
+ part of Finite State Entropy library
+ Copyright (C) 2013-present, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * 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 COPYRIGHT HOLDERS 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 COPYRIGHT
+ OWNER 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.
+
+ You can contact the author at :
+ - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
+****************************************************************** */
+
+/* **************************************************************
+* Dependencies
+****************************************************************/
+#include <string.h> /* memcpy, memset */
+#include "compiler.h"
+#include "bitstream.h" /* BIT_* */
+#include "fse.h" /* to compress headers */
+#define HUF_STATIC_LINKING_ONLY
+#include "huf.h"
+#include "error_private.h"
+
+/* **************************************************************
+* Macros
+****************************************************************/
+
+/* These two optional macros force the use one way or another of the two
+ * Huffman decompression implementations. You can't force in both directions
+ * at the same time.
+ */
+#if defined(HUF_FORCE_DECOMPRESS_X1) && \
+ defined(HUF_FORCE_DECOMPRESS_X2)
+#error "Cannot force the use of the X1 and X2 decoders at the same time!"
+#endif
+
+
+/* **************************************************************
+* Error Management
+****************************************************************/
+#define HUF_isError ERR_isError
+#define CHECK_F(f) { size_t const err_ = (f); if (HUF_isError(err_)) return err_; }
+
+
+/* **************************************************************
+* Byte alignment for workSpace management
+****************************************************************/
+#define HUF_ALIGN(x, a) HUF_ALIGN_MASK((x), (a) - 1)
+#define HUF_ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask))
+
+
+/* **************************************************************
+* BMI2 Variant Wrappers
+****************************************************************/
+#if DYNAMIC_BMI2
+
+#define HUF_DGEN(fn) \
+ \
+ static size_t fn##_default( \
+ void* dst, size_t dstSize, \
+ const void* cSrc, size_t cSrcSize, \
+ const HUF_DTable* DTable) \
+ { \
+ return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \
+ } \
+ \
+ static TARGET_ATTRIBUTE("bmi2") size_t fn##_bmi2( \
+ void* dst, size_t dstSize, \
+ const void* cSrc, size_t cSrcSize, \
+ const HUF_DTable* DTable) \
+ { \
+ return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \
+ } \
+ \
+ static size_t fn(void* dst, size_t dstSize, void const* cSrc, \
+ size_t cSrcSize, HUF_DTable const* DTable, int bmi2) \
+ { \
+ if (bmi2) { \
+ return fn##_bmi2(dst, dstSize, cSrc, cSrcSize, DTable); \
+ } \
+ return fn##_default(dst, dstSize, cSrc, cSrcSize, DTable); \
+ }
+
+#else
+
+#define HUF_DGEN(fn) \
+ static size_t fn(void* dst, size_t dstSize, void const* cSrc, \
+ size_t cSrcSize, HUF_DTable const* DTable, int bmi2) \
+ { \
+ (void)bmi2; \
+ return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable); \
+ }
+
+#endif
+
+
+/*-***************************/
+/* generic DTableDesc */
+/*-***************************/
+typedef struct { BYTE maxTableLog; BYTE tableType; BYTE tableLog; BYTE reserved; } DTableDesc;
+
+static DTableDesc HUF_getDTableDesc(const HUF_DTable* table)
+{
+ DTableDesc dtd;
+ memcpy(&dtd, table, sizeof(dtd));
+ return dtd;
+}
+
+
+#ifndef HUF_FORCE_DECOMPRESS_X2
+
+/*-***************************/
+/* single-symbol decoding */
+/*-***************************/
+typedef struct { BYTE byte; BYTE nbBits; } HUF_DEltX1; /* single-symbol decoding */
+
+size_t HUF_readDTableX1_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize)
+{
+ U32 tableLog = 0;
+ U32 nbSymbols = 0;
+ size_t iSize;
+ void* const dtPtr = DTable + 1;
+ HUF_DEltX1* const dt = (HUF_DEltX1*)dtPtr;
+
+ U32* rankVal;
+ BYTE* huffWeight;
+ size_t spaceUsed32 = 0;
+
+ rankVal = (U32 *)workSpace + spaceUsed32;
+ spaceUsed32 += HUF_TABLELOG_ABSOLUTEMAX + 1;
+ huffWeight = (BYTE *)((U32 *)workSpace + spaceUsed32);
+ spaceUsed32 += HUF_ALIGN(HUF_SYMBOLVALUE_MAX + 1, sizeof(U32)) >> 2;
+
+ if ((spaceUsed32 << 2) > wkspSize) return ERROR(tableLog_tooLarge);
+
+ DEBUG_STATIC_ASSERT(sizeof(DTableDesc) == sizeof(HUF_DTable));
+ /* memset(huffWeight, 0, sizeof(huffWeight)); */ /* is not necessary, even though some analyzer complain ... */
+
+ iSize = HUF_readStats(huffWeight, HUF_SYMBOLVALUE_MAX + 1, rankVal, &nbSymbols, &tableLog, src, srcSize);
+ if (HUF_isError(iSize)) return iSize;
+
+ /* Table header */
+ { DTableDesc dtd = HUF_getDTableDesc(DTable);
+ if (tableLog > (U32)(dtd.maxTableLog+1)) return ERROR(tableLog_tooLarge); /* DTable too small, Huffman tree cannot fit in */
+ dtd.tableType = 0;
+ dtd.tableLog = (BYTE)tableLog;
+ memcpy(DTable, &dtd, sizeof(dtd));
+ }
+
+ /* Calculate starting value for each rank */
+ { U32 n, nextRankStart = 0;
+ for (n=1; n<tableLog+1; n++) {
+ U32 const current = nextRankStart;
+ nextRankStart += (rankVal[n] << (n-1));
+ rankVal[n] = current;
+ } }
+
+ /* fill DTable */
+ { U32 n;
+ for (n=0; n<nbSymbols; n++) {
+ U32 const w = huffWeight[n];
+ U32 const length = (1 << w) >> 1;
+ U32 u;
+ HUF_DEltX1 D;
+ D.byte = (BYTE)n; D.nbBits = (BYTE)(tableLog + 1 - w);
+ for (u = rankVal[w]; u < rankVal[w] + length; u++)
+ dt[u] = D;
+ rankVal[w] += length;
+ } }
+
+ return iSize;
+}
+
+size_t HUF_readDTableX1(HUF_DTable* DTable, const void* src, size_t srcSize)
+{
+ U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
+ return HUF_readDTableX1_wksp(DTable, src, srcSize,
+ workSpace, sizeof(workSpace));
+}
+
+FORCE_INLINE_TEMPLATE BYTE
+HUF_decodeSymbolX1(BIT_DStream_t* Dstream, const HUF_DEltX1* dt, const U32 dtLog)
+{
+ size_t const val = BIT_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
+ BYTE const c = dt[val].byte;
+ BIT_skipBits(Dstream, dt[val].nbBits);
+ return c;
+}
+
+#define HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr) \
+ *ptr++ = HUF_decodeSymbolX1(DStreamPtr, dt, dtLog)
+
+#define HUF_DECODE_SYMBOLX1_1(ptr, DStreamPtr) \
+ if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \
+ HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr)
+
+#define HUF_DECODE_SYMBOLX1_2(ptr, DStreamPtr) \
+ if (MEM_64bits()) \
+ HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr)
+
+HINT_INLINE size_t
+HUF_decodeStreamX1(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX1* const dt, const U32 dtLog)
+{
+ BYTE* const pStart = p;
+
+ /* up to 4 symbols at a time */
+ while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-3)) {
+ HUF_DECODE_SYMBOLX1_2(p, bitDPtr);
+ HUF_DECODE_SYMBOLX1_1(p, bitDPtr);
+ HUF_DECODE_SYMBOLX1_2(p, bitDPtr);
+ HUF_DECODE_SYMBOLX1_0(p, bitDPtr);
+ }
+
+ /* [0-3] symbols remaining */
+ if (MEM_32bits())
+ while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd))
+ HUF_DECODE_SYMBOLX1_0(p, bitDPtr);
+
+ /* no more data to retrieve from bitstream, no need to reload */
+ while (p < pEnd)
+ HUF_DECODE_SYMBOLX1_0(p, bitDPtr);
+
+ return pEnd-pStart;
+}
+
+FORCE_INLINE_TEMPLATE size_t
+HUF_decompress1X1_usingDTable_internal_body(
+ void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ const HUF_DTable* DTable)
+{
+ BYTE* op = (BYTE*)dst;
+ BYTE* const oend = op + dstSize;
+ const void* dtPtr = DTable + 1;
+ const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr;
+ BIT_DStream_t bitD;
+ DTableDesc const dtd = HUF_getDTableDesc(DTable);
+ U32 const dtLog = dtd.tableLog;
+
+ CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) );
+
+ HUF_decodeStreamX1(op, &bitD, oend, dt, dtLog);
+
+ if (!BIT_endOfDStream(&bitD)) return ERROR(corruption_detected);
+
+ return dstSize;
+}
+
+FORCE_INLINE_TEMPLATE size_t
+HUF_decompress4X1_usingDTable_internal_body(
+ void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ const HUF_DTable* DTable)
+{
+ /* Check */
+ if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
+
+ { const BYTE* const istart = (const BYTE*) cSrc;
+ BYTE* const ostart = (BYTE*) dst;
+ BYTE* const oend = ostart + dstSize;
+ const void* const dtPtr = DTable + 1;
+ const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr;
+
+ /* Init */
+ BIT_DStream_t bitD1;
+ BIT_DStream_t bitD2;
+ BIT_DStream_t bitD3;
+ BIT_DStream_t bitD4;
+ size_t const length1 = MEM_readLE16(istart);
+ size_t const length2 = MEM_readLE16(istart+2);
+ size_t const length3 = MEM_readLE16(istart+4);
+ size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6);
+ const BYTE* const istart1 = istart + 6; /* jumpTable */
+ const BYTE* const istart2 = istart1 + length1;
+ const BYTE* const istart3 = istart2 + length2;
+ const BYTE* const istart4 = istart3 + length3;
+ const size_t segmentSize = (dstSize+3) / 4;
+ BYTE* const opStart2 = ostart + segmentSize;
+ BYTE* const opStart3 = opStart2 + segmentSize;
+ BYTE* const opStart4 = opStart3 + segmentSize;
+ BYTE* op1 = ostart;
+ BYTE* op2 = opStart2;
+ BYTE* op3 = opStart3;
+ BYTE* op4 = opStart4;
+ U32 endSignal = BIT_DStream_unfinished;
+ DTableDesc const dtd = HUF_getDTableDesc(DTable);
+ U32 const dtLog = dtd.tableLog;
+
+ if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
+ CHECK_F( BIT_initDStream(&bitD1, istart1, length1) );
+ CHECK_F( BIT_initDStream(&bitD2, istart2, length2) );
+ CHECK_F( BIT_initDStream(&bitD3, istart3, length3) );
+ CHECK_F( BIT_initDStream(&bitD4, istart4, length4) );
+
+ /* up to 16 symbols per loop (4 symbols per stream) in 64-bit mode */
+ endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
+ while ( (endSignal==BIT_DStream_unfinished) && (op4<(oend-3)) ) {
+ HUF_DECODE_SYMBOLX1_2(op1, &bitD1);
+ HUF_DECODE_SYMBOLX1_2(op2, &bitD2);
+ HUF_DECODE_SYMBOLX1_2(op3, &bitD3);
+ HUF_DECODE_SYMBOLX1_2(op4, &bitD4);
+ HUF_DECODE_SYMBOLX1_1(op1, &bitD1);
+ HUF_DECODE_SYMBOLX1_1(op2, &bitD2);
+ HUF_DECODE_SYMBOLX1_1(op3, &bitD3);
+ HUF_DECODE_SYMBOLX1_1(op4, &bitD4);
+ HUF_DECODE_SYMBOLX1_2(op1, &bitD1);
+ HUF_DECODE_SYMBOLX1_2(op2, &bitD2);
+ HUF_DECODE_SYMBOLX1_2(op3, &bitD3);
+ HUF_DECODE_SYMBOLX1_2(op4, &bitD4);
+ HUF_DECODE_SYMBOLX1_0(op1, &bitD1);
+ HUF_DECODE_SYMBOLX1_0(op2, &bitD2);
+ HUF_DECODE_SYMBOLX1_0(op3, &bitD3);
+ HUF_DECODE_SYMBOLX1_0(op4, &bitD4);
+ BIT_reloadDStream(&bitD1);
+ BIT_reloadDStream(&bitD2);
+ BIT_reloadDStream(&bitD3);
+ BIT_reloadDStream(&bitD4);
+ }
+
+ /* check corruption */
+ /* note : should not be necessary : op# advance in lock step, and we control op4.
+ * but curiously, binary generated by gcc 7.2 & 7.3 with -mbmi2 runs faster when >=1 test is present */
+ if (op1 > opStart2) return ERROR(corruption_detected);
+ if (op2 > opStart3) return ERROR(corruption_detected);
+ if (op3 > opStart4) return ERROR(corruption_detected);
+ /* note : op4 supposed already verified within main loop */
+
+ /* finish bitStreams one by one */
+ HUF_decodeStreamX1(op1, &bitD1, opStart2, dt, dtLog);
+ HUF_decodeStreamX1(op2, &bitD2, opStart3, dt, dtLog);
+ HUF_decodeStreamX1(op3, &bitD3, opStart4, dt, dtLog);
+ HUF_decodeStreamX1(op4, &bitD4, oend, dt, dtLog);
+
+ /* check */
+ { U32 const endCheck = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
+ if (!endCheck) return ERROR(corruption_detected); }
+
+ /* decoded size */
+ return dstSize;
+ }
+}
+
+
+typedef size_t (*HUF_decompress_usingDTable_t)(void *dst, size_t dstSize,
+ const void *cSrc,
+ size_t cSrcSize,
+ const HUF_DTable *DTable);
+
+HUF_DGEN(HUF_decompress1X1_usingDTable_internal)
+HUF_DGEN(HUF_decompress4X1_usingDTable_internal)
+
+
+
+size_t HUF_decompress1X1_usingDTable(
+ void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ const HUF_DTable* DTable)
+{
+ DTableDesc dtd = HUF_getDTableDesc(DTable);
+ if (dtd.tableType != 0) return ERROR(GENERIC);
+ return HUF_decompress1X1_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
+}
+
+size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* DCtx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ void* workSpace, size_t wkspSize)
+{
+ const BYTE* ip = (const BYTE*) cSrc;
+
+ size_t const hSize = HUF_readDTableX1_wksp(DCtx, cSrc, cSrcSize, workSpace, wkspSize);
+ if (HUF_isError(hSize)) return hSize;
+ if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
+ ip += hSize; cSrcSize -= hSize;
+
+ return HUF_decompress1X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, DCtx, /* bmi2 */ 0);
+}
+
+
+size_t HUF_decompress1X1_DCtx(HUF_DTable* DCtx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize)
+{
+ U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
+ return HUF_decompress1X1_DCtx_wksp(DCtx, dst, dstSize, cSrc, cSrcSize,
+ workSpace, sizeof(workSpace));
+}
+
+size_t HUF_decompress1X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
+{
+ HUF_CREATE_STATIC_DTABLEX1(DTable, HUF_TABLELOG_MAX);
+ return HUF_decompress1X1_DCtx (DTable, dst, dstSize, cSrc, cSrcSize);
+}
+
+size_t HUF_decompress4X1_usingDTable(
+ void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ const HUF_DTable* DTable)
+{
+ DTableDesc dtd = HUF_getDTableDesc(DTable);
+ if (dtd.tableType != 0) return ERROR(GENERIC);
+ return HUF_decompress4X1_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
+}
+
+static size_t HUF_decompress4X1_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ void* workSpace, size_t wkspSize, int bmi2)
+{
+ const BYTE* ip = (const BYTE*) cSrc;
+
+ size_t const hSize = HUF_readDTableX1_wksp (dctx, cSrc, cSrcSize,
+ workSpace, wkspSize);
+ if (HUF_isError(hSize)) return hSize;
+ if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
+ ip += hSize; cSrcSize -= hSize;
+
+ return HUF_decompress4X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, bmi2);
+}
+
+size_t HUF_decompress4X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ void* workSpace, size_t wkspSize)
+{
+ return HUF_decompress4X1_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, 0);
+}
+
+
+size_t HUF_decompress4X1_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
+{
+ U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
+ return HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize,
+ workSpace, sizeof(workSpace));
+}
+size_t HUF_decompress4X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
+{
+ HUF_CREATE_STATIC_DTABLEX1(DTable, HUF_TABLELOG_MAX);
+ return HUF_decompress4X1_DCtx(DTable, dst, dstSize, cSrc, cSrcSize);
+}
+
+#endif /* HUF_FORCE_DECOMPRESS_X2 */
+
+
+#ifndef HUF_FORCE_DECOMPRESS_X1
+
+/* *************************/
+/* double-symbols decoding */
+/* *************************/
+
+typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUF_DEltX2; /* double-symbols decoding */
+typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t;
+typedef U32 rankValCol_t[HUF_TABLELOG_MAX + 1];
+typedef rankValCol_t rankVal_t[HUF_TABLELOG_MAX];
+
+
+/* HUF_fillDTableX2Level2() :
+ * `rankValOrigin` must be a table of at least (HUF_TABLELOG_MAX + 1) U32 */
+static void HUF_fillDTableX2Level2(HUF_DEltX2* DTable, U32 sizeLog, const U32 consumed,
+ const U32* rankValOrigin, const int minWeight,
+ const sortedSymbol_t* sortedSymbols, const U32 sortedListSize,
+ U32 nbBitsBaseline, U16 baseSeq)
+{
+ HUF_DEltX2 DElt;
+ U32 rankVal[HUF_TABLELOG_MAX + 1];
+
+ /* get pre-calculated rankVal */
+ memcpy(rankVal, rankValOrigin, sizeof(rankVal));
+
+ /* fill skipped values */
+ if (minWeight>1) {
+ U32 i, skipSize = rankVal[minWeight];
+ MEM_writeLE16(&(DElt.sequence), baseSeq);
+ DElt.nbBits = (BYTE)(consumed);
+ DElt.length = 1;
+ for (i = 0; i < skipSize; i++)
+ DTable[i] = DElt;
+ }
+
+ /* fill DTable */
+ { U32 s; for (s=0; s<sortedListSize; s++) { /* note : sortedSymbols already skipped */
+ const U32 symbol = sortedSymbols[s].symbol;
+ const U32 weight = sortedSymbols[s].weight;
+ const U32 nbBits = nbBitsBaseline - weight;
+ const U32 length = 1 << (sizeLog-nbBits);
+ const U32 start = rankVal[weight];
+ U32 i = start;
+ const U32 end = start + length;
+
+ MEM_writeLE16(&(DElt.sequence), (U16)(baseSeq + (symbol << 8)));
+ DElt.nbBits = (BYTE)(nbBits + consumed);
+ DElt.length = 2;
+ do { DTable[i++] = DElt; } while (i<end); /* since length >= 1 */
+
+ rankVal[weight] += length;
+ } }
+}
+
+
+static void HUF_fillDTableX2(HUF_DEltX2* DTable, const U32 targetLog,
+ const sortedSymbol_t* sortedList, const U32 sortedListSize,
+ const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight,
+ const U32 nbBitsBaseline)
+{
+ U32 rankVal[HUF_TABLELOG_MAX + 1];
+ const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */
+ const U32 minBits = nbBitsBaseline - maxWeight;
+ U32 s;
+
+ memcpy(rankVal, rankValOrigin, sizeof(rankVal));
+
+ /* fill DTable */
+ for (s=0; s<sortedListSize; s++) {
+ const U16 symbol = sortedList[s].symbol;
+ const U32 weight = sortedList[s].weight;
+ const U32 nbBits = nbBitsBaseline - weight;
+ const U32 start = rankVal[weight];
+ const U32 length = 1 << (targetLog-nbBits);
+
+ if (targetLog-nbBits >= minBits) { /* enough room for a second symbol */
+ U32 sortedRank;
+ int minWeight = nbBits + scaleLog;
+ if (minWeight < 1) minWeight = 1;
+ sortedRank = rankStart[minWeight];
+ HUF_fillDTableX2Level2(DTable+start, targetLog-nbBits, nbBits,
+ rankValOrigin[nbBits], minWeight,
+ sortedList+sortedRank, sortedListSize-sortedRank,
+ nbBitsBaseline, symbol);
+ } else {
+ HUF_DEltX2 DElt;
+ MEM_writeLE16(&(DElt.sequence), symbol);
+ DElt.nbBits = (BYTE)(nbBits);
+ DElt.length = 1;
+ { U32 const end = start + length;
+ U32 u;
+ for (u = start; u < end; u++) DTable[u] = DElt;
+ } }
+ rankVal[weight] += length;
+ }
+}
+
+size_t HUF_readDTableX2_wksp(HUF_DTable* DTable,
+ const void* src, size_t srcSize,
+ void* workSpace, size_t wkspSize)
+{
+ U32 tableLog, maxW, sizeOfSort, nbSymbols;
+ DTableDesc dtd = HUF_getDTableDesc(DTable);
+ U32 const maxTableLog = dtd.maxTableLog;
+ size_t iSize;
+ void* dtPtr = DTable+1; /* force compiler to avoid strict-aliasing */
+ HUF_DEltX2* const dt = (HUF_DEltX2*)dtPtr;
+ U32 *rankStart;
+
+ rankValCol_t* rankVal;
+ U32* rankStats;
+ U32* rankStart0;
+ sortedSymbol_t* sortedSymbol;
+ BYTE* weightList;
+ size_t spaceUsed32 = 0;
+
+ rankVal = (rankValCol_t *)((U32 *)workSpace + spaceUsed32);
+ spaceUsed32 += (sizeof(rankValCol_t) * HUF_TABLELOG_MAX) >> 2;
+ rankStats = (U32 *)workSpace + spaceUsed32;
+ spaceUsed32 += HUF_TABLELOG_MAX + 1;
+ rankStart0 = (U32 *)workSpace + spaceUsed32;
+ spaceUsed32 += HUF_TABLELOG_MAX + 2;
+ sortedSymbol = (sortedSymbol_t *)workSpace + (spaceUsed32 * sizeof(U32)) / sizeof(sortedSymbol_t);
+ spaceUsed32 += HUF_ALIGN(sizeof(sortedSymbol_t) * (HUF_SYMBOLVALUE_MAX + 1), sizeof(U32)) >> 2;
+ weightList = (BYTE *)((U32 *)workSpace + spaceUsed32);
+ spaceUsed32 += HUF_ALIGN(HUF_SYMBOLVALUE_MAX + 1, sizeof(U32)) >> 2;
+
+ if ((spaceUsed32 << 2) > wkspSize) return ERROR(tableLog_tooLarge);
+
+ rankStart = rankStart0 + 1;
+ memset(rankStats, 0, sizeof(U32) * (2 * HUF_TABLELOG_MAX + 2 + 1));
+
+ DEBUG_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(HUF_DTable)); /* if compiler fails here, assertion is wrong */
+ if (maxTableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
+ /* memset(weightList, 0, sizeof(weightList)); */ /* is not necessary, even though some analyzer complain ... */
+
+ iSize = HUF_readStats(weightList, HUF_SYMBOLVALUE_MAX + 1, rankStats, &nbSymbols, &tableLog, src, srcSize);
+ if (HUF_isError(iSize)) return iSize;
+
+ /* check result */
+ if (tableLog > maxTableLog) return ERROR(tableLog_tooLarge); /* DTable can't fit code depth */
+
+ /* find maxWeight */
+ for (maxW = tableLog; rankStats[maxW]==0; maxW--) {} /* necessarily finds a solution before 0 */
+
+ /* Get start index of each weight */
+ { U32 w, nextRankStart = 0;
+ for (w=1; w<maxW+1; w++) {
+ U32 current = nextRankStart;
+ nextRankStart += rankStats[w];
+ rankStart[w] = current;
+ }
+ rankStart[0] = nextRankStart; /* put all 0w symbols at the end of sorted list*/
+ sizeOfSort = nextRankStart;
+ }
+
+ /* sort symbols by weight */
+ { U32 s;
+ for (s=0; s<nbSymbols; s++) {
+ U32 const w = weightList[s];
+ U32 const r = rankStart[w]++;
+ sortedSymbol[r].symbol = (BYTE)s;
+ sortedSymbol[r].weight = (BYTE)w;
+ }
+ rankStart[0] = 0; /* forget 0w symbols; this is beginning of weight(1) */
+ }
+
+ /* Build rankVal */
+ { U32* const rankVal0 = rankVal[0];
+ { int const rescale = (maxTableLog-tableLog) - 1; /* tableLog <= maxTableLog */
+ U32 nextRankVal = 0;
+ U32 w;
+ for (w=1; w<maxW+1; w++) {
+ U32 current = nextRankVal;
+ nextRankVal += rankStats[w] << (w+rescale);
+ rankVal0[w] = current;
+ } }
+ { U32 const minBits = tableLog+1 - maxW;
+ U32 consumed;
+ for (consumed = minBits; consumed < maxTableLog - minBits + 1; consumed++) {
+ U32* const rankValPtr = rankVal[consumed];
+ U32 w;
+ for (w = 1; w < maxW+1; w++) {
+ rankValPtr[w] = rankVal0[w] >> consumed;
+ } } } }
+
+ HUF_fillDTableX2(dt, maxTableLog,
+ sortedSymbol, sizeOfSort,
+ rankStart0, rankVal, maxW,
+ tableLog+1);
+
+ dtd.tableLog = (BYTE)maxTableLog;
+ dtd.tableType = 1;
+ memcpy(DTable, &dtd, sizeof(dtd));
+ return iSize;
+}
+
+size_t HUF_readDTableX2(HUF_DTable* DTable, const void* src, size_t srcSize)
+{
+ U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
+ return HUF_readDTableX2_wksp(DTable, src, srcSize,
+ workSpace, sizeof(workSpace));
+}
+
+
+FORCE_INLINE_TEMPLATE U32
+HUF_decodeSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, const U32 dtLog)
+{
+ size_t const val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
+ memcpy(op, dt+val, 2);
+ BIT_skipBits(DStream, dt[val].nbBits);
+ return dt[val].length;
+}
+
+FORCE_INLINE_TEMPLATE U32
+HUF_decodeLastSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, const U32 dtLog)
+{
+ size_t const val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
+ memcpy(op, dt+val, 1);
+ if (dt[val].length==1) BIT_skipBits(DStream, dt[val].nbBits);
+ else {
+ if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8)) {
+ BIT_skipBits(DStream, dt[val].nbBits);
+ if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
+ /* ugly hack; works only because it's the last symbol. Note : can't easily extract nbBits from just this symbol */
+ DStream->bitsConsumed = (sizeof(DStream->bitContainer)*8);
+ } }
+ return 1;
+}
+
+#define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
+ ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)
+
+#define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
+ if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \
+ ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)
+
+#define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
+ if (MEM_64bits()) \
+ ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)
+
+HINT_INLINE size_t
+HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd,
+ const HUF_DEltX2* const dt, const U32 dtLog)
+{
+ BYTE* const pStart = p;
+
+ /* up to 8 symbols at a time */
+ while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-(sizeof(bitDPtr->bitContainer)-1))) {
+ HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
+ HUF_DECODE_SYMBOLX2_1(p, bitDPtr);
+ HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
+ HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
+ }
+
+ /* closer to end : up to 2 symbols at a time */
+ while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p <= pEnd-2))
+ HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
+
+ while (p <= pEnd-2)
+ HUF_DECODE_SYMBOLX2_0(p, bitDPtr); /* no need to reload : reached the end of DStream */
+
+ if (p < pEnd)
+ p += HUF_decodeLastSymbolX2(p, bitDPtr, dt, dtLog);
+
+ return p-pStart;
+}
+
+FORCE_INLINE_TEMPLATE size_t
+HUF_decompress1X2_usingDTable_internal_body(
+ void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ const HUF_DTable* DTable)
+{
+ BIT_DStream_t bitD;
+
+ /* Init */
+ CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) );
+
+ /* decode */
+ { BYTE* const ostart = (BYTE*) dst;
+ BYTE* const oend = ostart + dstSize;
+ const void* const dtPtr = DTable+1; /* force compiler to not use strict-aliasing */
+ const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr;
+ DTableDesc const dtd = HUF_getDTableDesc(DTable);
+ HUF_decodeStreamX2(ostart, &bitD, oend, dt, dtd.tableLog);
+ }
+
+ /* check */
+ if (!BIT_endOfDStream(&bitD)) return ERROR(corruption_detected);
+
+ /* decoded size */
+ return dstSize;
+}
+
+
+FORCE_INLINE_TEMPLATE size_t
+HUF_decompress4X2_usingDTable_internal_body(
+ void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ const HUF_DTable* DTable)
+{
+ if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
+
+ { const BYTE* const istart = (const BYTE*) cSrc;
+ BYTE* const ostart = (BYTE*) dst;
+ BYTE* const oend = ostart + dstSize;
+ const void* const dtPtr = DTable+1;
+ const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr;
+
+ /* Init */
+ BIT_DStream_t bitD1;
+ BIT_DStream_t bitD2;
+ BIT_DStream_t bitD3;
+ BIT_DStream_t bitD4;
+ size_t const length1 = MEM_readLE16(istart);
+ size_t const length2 = MEM_readLE16(istart+2);
+ size_t const length3 = MEM_readLE16(istart+4);
+ size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6);
+ const BYTE* const istart1 = istart + 6; /* jumpTable */
+ const BYTE* const istart2 = istart1 + length1;
+ const BYTE* const istart3 = istart2 + length2;
+ const BYTE* const istart4 = istart3 + length3;
+ size_t const segmentSize = (dstSize+3) / 4;
+ BYTE* const opStart2 = ostart + segmentSize;
+ BYTE* const opStart3 = opStart2 + segmentSize;
+ BYTE* const opStart4 = opStart3 + segmentSize;
+ BYTE* op1 = ostart;
+ BYTE* op2 = opStart2;
+ BYTE* op3 = opStart3;
+ BYTE* op4 = opStart4;
+ U32 endSignal;
+ DTableDesc const dtd = HUF_getDTableDesc(DTable);
+ U32 const dtLog = dtd.tableLog;
+
+ if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
+ CHECK_F( BIT_initDStream(&bitD1, istart1, length1) );
+ CHECK_F( BIT_initDStream(&bitD2, istart2, length2) );
+ CHECK_F( BIT_initDStream(&bitD3, istart3, length3) );
+ CHECK_F( BIT_initDStream(&bitD4, istart4, length4) );
+
+ /* 16-32 symbols per loop (4-8 symbols per stream) */
+ endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
+ for ( ; (endSignal==BIT_DStream_unfinished) & (op4<(oend-(sizeof(bitD4.bitContainer)-1))) ; ) {
+ HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
+ HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
+ HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
+ HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
+ HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
+ HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
+ HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
+ HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
+ HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
+ HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
+ HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
+ HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
+ HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
+ HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
+ HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
+ HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
+
+ endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
+ }
+
+ /* check corruption */
+ if (op1 > opStart2) return ERROR(corruption_detected);
+ if (op2 > opStart3) return ERROR(corruption_detected);
+ if (op3 > opStart4) return ERROR(corruption_detected);
+ /* note : op4 already verified within main loop */
+
+ /* finish bitStreams one by one */
+ HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
+ HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
+ HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
+ HUF_decodeStreamX2(op4, &bitD4, oend, dt, dtLog);
+
+ /* check */
+ { U32 const endCheck = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
+ if (!endCheck) return ERROR(corruption_detected); }
+
+ /* decoded size */
+ return dstSize;
+ }
+}
+
+HUF_DGEN(HUF_decompress1X2_usingDTable_internal)
+HUF_DGEN(HUF_decompress4X2_usingDTable_internal)
+
+size_t HUF_decompress1X2_usingDTable(
+ void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ const HUF_DTable* DTable)
+{
+ DTableDesc dtd = HUF_getDTableDesc(DTable);
+ if (dtd.tableType != 1) return ERROR(GENERIC);
+ return HUF_decompress1X2_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
+}
+
+size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* DCtx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ void* workSpace, size_t wkspSize)
+{
+ const BYTE* ip = (const BYTE*) cSrc;
+
+ size_t const hSize = HUF_readDTableX2_wksp(DCtx, cSrc, cSrcSize,
+ workSpace, wkspSize);
+ if (HUF_isError(hSize)) return hSize;
+ if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
+ ip += hSize; cSrcSize -= hSize;
+
+ return HUF_decompress1X2_usingDTable_internal(dst, dstSize, ip, cSrcSize, DCtx, /* bmi2 */ 0);
+}
+
+
+size_t HUF_decompress1X2_DCtx(HUF_DTable* DCtx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize)
+{
+ U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
+ return HUF_decompress1X2_DCtx_wksp(DCtx, dst, dstSize, cSrc, cSrcSize,
+ workSpace, sizeof(workSpace));
+}
+
+size_t HUF_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
+{
+ HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_TABLELOG_MAX);
+ return HUF_decompress1X2_DCtx(DTable, dst, dstSize, cSrc, cSrcSize);
+}
+
+size_t HUF_decompress4X2_usingDTable(
+ void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ const HUF_DTable* DTable)
+{
+ DTableDesc dtd = HUF_getDTableDesc(DTable);
+ if (dtd.tableType != 1) return ERROR(GENERIC);
+ return HUF_decompress4X2_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
+}
+
+static size_t HUF_decompress4X2_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ void* workSpace, size_t wkspSize, int bmi2)
+{
+ const BYTE* ip = (const BYTE*) cSrc;
+
+ size_t hSize = HUF_readDTableX2_wksp(dctx, cSrc, cSrcSize,
+ workSpace, wkspSize);
+ if (HUF_isError(hSize)) return hSize;
+ if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
+ ip += hSize; cSrcSize -= hSize;
+
+ return HUF_decompress4X2_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, bmi2);
+}
+
+size_t HUF_decompress4X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ void* workSpace, size_t wkspSize)
+{
+ return HUF_decompress4X2_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, /* bmi2 */ 0);
+}
+
+
+size_t HUF_decompress4X2_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize)
+{
+ U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
+ return HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize,
+ workSpace, sizeof(workSpace));
+}
+
+size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
+{
+ HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_TABLELOG_MAX);
+ return HUF_decompress4X2_DCtx(DTable, dst, dstSize, cSrc, cSrcSize);
+}
+
+#endif /* HUF_FORCE_DECOMPRESS_X1 */
+
+
+/* ***********************************/
+/* Universal decompression selectors */
+/* ***********************************/
+
+size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize,
+ const void* cSrc, size_t cSrcSize,
+ const HUF_DTable* DTable)
+{
+ DTableDesc const dtd = HUF_getDTableDesc(DTable);
+#if defined(HUF_FORCE_DECOMPRESS_X1)
+ (void)dtd;
+ assert(dtd.tableType == 0);
+ return HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
+#elif defined(HUF_FORCE_DECOMPRESS_X2)
+ (void)dtd;
+ assert(dtd.tableType == 1);
+ return HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
+#else
+ return dtd.tableType ? HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0) :
+ HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
+#endif
+}
+
+size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize,
+ const void* cSrc, size_t cSrcSize,
+ const HUF_DTable* DTable)
+{
+ DTableDesc const dtd = HUF_getDTableDesc(DTable);
+#if defined(HUF_FORCE_DECOMPRESS_X1)
+ (void)dtd;
+ assert(dtd.tableType == 0);
+ return HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
+#elif defined(HUF_FORCE_DECOMPRESS_X2)
+ (void)dtd;
+ assert(dtd.tableType == 1);
+ return HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
+#else
+ return dtd.tableType ? HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0) :
+ HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
+#endif
+}
+
+
+#if !defined(HUF_FORCE_DECOMPRESS_X1) && !defined(HUF_FORCE_DECOMPRESS_X2)
+typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t;
+static const algo_time_t algoTime[16 /* Quantization */][3 /* single, double, quad */] =
+{
+ /* single, double, quad */
+ {{0,0}, {1,1}, {2,2}}, /* Q==0 : impossible */
+ {{0,0}, {1,1}, {2,2}}, /* Q==1 : impossible */
+ {{ 38,130}, {1313, 74}, {2151, 38}}, /* Q == 2 : 12-18% */
+ {{ 448,128}, {1353, 74}, {2238, 41}}, /* Q == 3 : 18-25% */
+ {{ 556,128}, {1353, 74}, {2238, 47}}, /* Q == 4 : 25-32% */
+ {{ 714,128}, {1418, 74}, {2436, 53}}, /* Q == 5 : 32-38% */
+ {{ 883,128}, {1437, 74}, {2464, 61}}, /* Q == 6 : 38-44% */
+ {{ 897,128}, {1515, 75}, {2622, 68}}, /* Q == 7 : 44-50% */
+ {{ 926,128}, {1613, 75}, {2730, 75}}, /* Q == 8 : 50-56% */
+ {{ 947,128}, {1729, 77}, {3359, 77}}, /* Q == 9 : 56-62% */
+ {{1107,128}, {2083, 81}, {4006, 84}}, /* Q ==10 : 62-69% */
+ {{1177,128}, {2379, 87}, {4785, 88}}, /* Q ==11 : 69-75% */
+ {{1242,128}, {2415, 93}, {5155, 84}}, /* Q ==12 : 75-81% */
+ {{1349,128}, {2644,106}, {5260,106}}, /* Q ==13 : 81-87% */
+ {{1455,128}, {2422,124}, {4174,124}}, /* Q ==14 : 87-93% */
+ {{ 722,128}, {1891,145}, {1936,146}}, /* Q ==15 : 93-99% */
+};
+#endif
+
+/** HUF_selectDecoder() :
+ * Tells which decoder is likely to decode faster,
+ * based on a set of pre-computed metrics.
+ * @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 .
+ * Assumption : 0 < dstSize <= 128 KB */
+U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize)
+{
+ assert(dstSize > 0);
+ assert(dstSize <= 128*1024);
+#if defined(HUF_FORCE_DECOMPRESS_X1)
+ (void)dstSize;
+ (void)cSrcSize;
+ return 0;
+#elif defined(HUF_FORCE_DECOMPRESS_X2)
+ (void)dstSize;
+ (void)cSrcSize;
+ return 1;
+#else
+ /* decoder timing evaluation */
+ { U32 const Q = (cSrcSize >= dstSize) ? 15 : (U32)(cSrcSize * 16 / dstSize); /* Q < 16 */
+ U32 const D256 = (U32)(dstSize >> 8);
+ U32 const DTime0 = algoTime[Q][0].tableTime + (algoTime[Q][0].decode256Time * D256);
+ U32 DTime1 = algoTime[Q][1].tableTime + (algoTime[Q][1].decode256Time * D256);
+ DTime1 += DTime1 >> 3; /* advantage to algorithm using less memory, to reduce cache eviction */
+ return DTime1 < DTime0;
+ }
+#endif
+}
+
+
+typedef size_t (*decompressionAlgo)(void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
+
+size_t HUF_decompress (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
+{
+#if !defined(HUF_FORCE_DECOMPRESS_X1) && !defined(HUF_FORCE_DECOMPRESS_X2)
+ static const decompressionAlgo decompress[2] = { HUF_decompress4X1, HUF_decompress4X2 };
+#endif
+
+ /* validation checks */
+ if (dstSize == 0) return ERROR(dstSize_tooSmall);
+ if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */
+ if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */
+ if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
+
+ { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
+#if defined(HUF_FORCE_DECOMPRESS_X1)
+ (void)algoNb;
+ assert(algoNb == 0);
+ return HUF_decompress4X1(dst, dstSize, cSrc, cSrcSize);
+#elif defined(HUF_FORCE_DECOMPRESS_X2)
+ (void)algoNb;
+ assert(algoNb == 1);
+ return HUF_decompress4X2(dst, dstSize, cSrc, cSrcSize);
+#else
+ return decompress[algoNb](dst, dstSize, cSrc, cSrcSize);
+#endif
+ }
+}
+
+size_t HUF_decompress4X_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
+{
+ /* validation checks */
+ if (dstSize == 0) return ERROR(dstSize_tooSmall);
+ if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */
+ if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */
+ if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
+
+ { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
+#if defined(HUF_FORCE_DECOMPRESS_X1)
+ (void)algoNb;
+ assert(algoNb == 0);
+ return HUF_decompress4X1_DCtx(dctx, dst, dstSize, cSrc, cSrcSize);
+#elif defined(HUF_FORCE_DECOMPRESS_X2)
+ (void)algoNb;
+ assert(algoNb == 1);
+ return HUF_decompress4X2_DCtx(dctx, dst, dstSize, cSrc, cSrcSize);
+#else
+ return algoNb ? HUF_decompress4X2_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) :
+ HUF_decompress4X1_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) ;
+#endif
+ }
+}
+
+size_t HUF_decompress4X_hufOnly(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
+{
+ U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
+ return HUF_decompress4X_hufOnly_wksp(dctx, dst, dstSize, cSrc, cSrcSize,
+ workSpace, sizeof(workSpace));
+}
+
+
+size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst,
+ size_t dstSize, const void* cSrc,
+ size_t cSrcSize, void* workSpace,
+ size_t wkspSize)
+{
+ /* validation checks */
+ if (dstSize == 0) return ERROR(dstSize_tooSmall);
+ if (cSrcSize == 0) return ERROR(corruption_detected);
+
+ { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
+#if defined(HUF_FORCE_DECOMPRESS_X1)
+ (void)algoNb;
+ assert(algoNb == 0);
+ return HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize);
+#elif defined(HUF_FORCE_DECOMPRESS_X2)
+ (void)algoNb;
+ assert(algoNb == 1);
+ return HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize);
+#else
+ return algoNb ? HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc,
+ cSrcSize, workSpace, wkspSize):
+ HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize);
+#endif
+ }
+}
+
+size_t HUF_decompress1X_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize,
+ void* workSpace, size_t wkspSize)
+{
+ /* validation checks */
+ if (dstSize == 0) return ERROR(dstSize_tooSmall);
+ if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */
+ if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */
+ if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
+
+ { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
+#if defined(HUF_FORCE_DECOMPRESS_X1)
+ (void)algoNb;
+ assert(algoNb == 0);
+ return HUF_decompress1X1_DCtx_wksp(dctx, dst, dstSize, cSrc,
+ cSrcSize, workSpace, wkspSize);
+#elif defined(HUF_FORCE_DECOMPRESS_X2)
+ (void)algoNb;
+ assert(algoNb == 1);
+ return HUF_decompress1X2_DCtx_wksp(dctx, dst, dstSize, cSrc,
+ cSrcSize, workSpace, wkspSize);
+#else
+ return algoNb ? HUF_decompress1X2_DCtx_wksp(dctx, dst, dstSize, cSrc,
+ cSrcSize, workSpace, wkspSize):
+ HUF_decompress1X1_DCtx_wksp(dctx, dst, dstSize, cSrc,
+ cSrcSize, workSpace, wkspSize);
+#endif
+ }
+}
+
+size_t HUF_decompress1X_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize,
+ const void* cSrc, size_t cSrcSize)
+{
+ U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
+ return HUF_decompress1X_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize,
+ workSpace, sizeof(workSpace));
+}
+
+
+size_t HUF_decompress1X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2)
+{
+ DTableDesc const dtd = HUF_getDTableDesc(DTable);
+#if defined(HUF_FORCE_DECOMPRESS_X1)
+ (void)dtd;
+ assert(dtd.tableType == 0);
+ return HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
+#elif defined(HUF_FORCE_DECOMPRESS_X2)
+ (void)dtd;
+ assert(dtd.tableType == 1);
+ return HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
+#else
+ return dtd.tableType ? HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2) :
+ HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
+#endif
+}
+
+#ifndef HUF_FORCE_DECOMPRESS_X2
+size_t HUF_decompress1X1_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2)
+{
+ const BYTE* ip = (const BYTE*) cSrc;
+
+ size_t const hSize = HUF_readDTableX1_wksp(dctx, cSrc, cSrcSize, workSpace, wkspSize);
+ if (HUF_isError(hSize)) return hSize;
+ if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
+ ip += hSize; cSrcSize -= hSize;
+
+ return HUF_decompress1X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, bmi2);
+}
+#endif
+
+size_t HUF_decompress4X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2)
+{
+ DTableDesc const dtd = HUF_getDTableDesc(DTable);
+#if defined(HUF_FORCE_DECOMPRESS_X1)
+ (void)dtd;
+ assert(dtd.tableType == 0);
+ return HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
+#elif defined(HUF_FORCE_DECOMPRESS_X2)
+ (void)dtd;
+ assert(dtd.tableType == 1);
+ return HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
+#else
+ return dtd.tableType ? HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2) :
+ HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
+#endif
+}
+
+size_t HUF_decompress4X_hufOnly_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2)
+{
+ /* validation checks */
+ if (dstSize == 0) return ERROR(dstSize_tooSmall);
+ if (cSrcSize == 0) return ERROR(corruption_detected);
+
+ { U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
+#if defined(HUF_FORCE_DECOMPRESS_X1)
+ (void)algoNb;
+ assert(algoNb == 0);
+ return HUF_decompress4X1_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2);
+#elif defined(HUF_FORCE_DECOMPRESS_X2)
+ (void)algoNb;
+ assert(algoNb == 1);
+ return HUF_decompress4X2_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2);
+#else
+ return algoNb ? HUF_decompress4X2_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2) :
+ HUF_decompress4X1_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2);
+#endif
+ }
+}
diff --git a/Utilities/cmzstd/lib/decompress/zstd_ddict.c b/Utilities/cmzstd/lib/decompress/zstd_ddict.c
new file mode 100644
index 000000000..2ad044068
--- /dev/null
+++ b/Utilities/cmzstd/lib/decompress/zstd_ddict.c
@@ -0,0 +1,240 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+/* zstd_ddict.c :
+ * concentrates all logic that needs to know the internals of ZSTD_DDict object */
+
+/*-*******************************************************
+* Dependencies
+*********************************************************/
+#include <string.h> /* memcpy, memmove, memset */
+#include "cpu.h" /* bmi2 */
+#include "mem.h" /* low level memory routines */
+#define FSE_STATIC_LINKING_ONLY
+#include "fse.h"
+#define HUF_STATIC_LINKING_ONLY
+#include "huf.h"
+#include "zstd_decompress_internal.h"
+#include "zstd_ddict.h"
+
+#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
+# include "zstd_legacy.h"
+#endif
+
+
+
+/*-*******************************************************
+* Types
+*********************************************************/
+struct ZSTD_DDict_s {
+ void* dictBuffer;
+ const void* dictContent;
+ size_t dictSize;
+ ZSTD_entropyDTables_t entropy;
+ U32 dictID;
+ U32 entropyPresent;
+ ZSTD_customMem cMem;
+}; /* typedef'd to ZSTD_DDict within "zstd.h" */
+
+const void* ZSTD_DDict_dictContent(const ZSTD_DDict* ddict)
+{
+ assert(ddict != NULL);
+ return ddict->dictContent;
+}
+
+size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict)
+{
+ assert(ddict != NULL);
+ return ddict->dictSize;
+}
+
+void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
+{
+ DEBUGLOG(4, "ZSTD_copyDDictParameters");
+ assert(dctx != NULL);
+ assert(ddict != NULL);
+ dctx->dictID = ddict->dictID;
+ dctx->prefixStart = ddict->dictContent;
+ dctx->virtualStart = ddict->dictContent;
+ dctx->dictEnd = (const BYTE*)ddict->dictContent + ddict->dictSize;
+ dctx->previousDstEnd = dctx->dictEnd;
+ if (ddict->entropyPresent) {
+ dctx->litEntropy = 1;
+ dctx->fseEntropy = 1;
+ dctx->LLTptr = ddict->entropy.LLTable;
+ dctx->MLTptr = ddict->entropy.MLTable;
+ dctx->OFTptr = ddict->entropy.OFTable;
+ dctx->HUFptr = ddict->entropy.hufTable;
+ dctx->entropy.rep[0] = ddict->entropy.rep[0];
+ dctx->entropy.rep[1] = ddict->entropy.rep[1];
+ dctx->entropy.rep[2] = ddict->entropy.rep[2];
+ } else {
+ dctx->litEntropy = 0;
+ dctx->fseEntropy = 0;
+ }
+}
+
+
+static size_t
+ZSTD_loadEntropy_intoDDict(ZSTD_DDict* ddict,
+ ZSTD_dictContentType_e dictContentType)
+{
+ ddict->dictID = 0;
+ ddict->entropyPresent = 0;
+ if (dictContentType == ZSTD_dct_rawContent) return 0;
+
+ if (ddict->dictSize < 8) {
+ if (dictContentType == ZSTD_dct_fullDict)
+ return ERROR(dictionary_corrupted); /* only accept specified dictionaries */
+ return 0; /* pure content mode */
+ }
+ { U32 const magic = MEM_readLE32(ddict->dictContent);
+ if (magic != ZSTD_MAGIC_DICTIONARY) {
+ if (dictContentType == ZSTD_dct_fullDict)
+ return ERROR(dictionary_corrupted); /* only accept specified dictionaries */
+ return 0; /* pure content mode */
+ }
+ }
+ ddict->dictID = MEM_readLE32((const char*)ddict->dictContent + ZSTD_FRAMEIDSIZE);
+
+ /* load entropy tables */
+ CHECK_E( ZSTD_loadDEntropy(&ddict->entropy,
+ ddict->dictContent, ddict->dictSize),
+ dictionary_corrupted );
+ ddict->entropyPresent = 1;
+ return 0;
+}
+
+
+static size_t ZSTD_initDDict_internal(ZSTD_DDict* ddict,
+ const void* dict, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType)
+{
+ if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dict) || (!dictSize)) {
+ ddict->dictBuffer = NULL;
+ ddict->dictContent = dict;
+ if (!dict) dictSize = 0;
+ } else {
+ void* const internalBuffer = ZSTD_malloc(dictSize, ddict->cMem);
+ ddict->dictBuffer = internalBuffer;
+ ddict->dictContent = internalBuffer;
+ if (!internalBuffer) return ERROR(memory_allocation);
+ memcpy(internalBuffer, dict, dictSize);
+ }
+ ddict->dictSize = dictSize;
+ ddict->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */
+
+ /* parse dictionary content */
+ CHECK_F( ZSTD_loadEntropy_intoDDict(ddict, dictContentType) );
+
+ return 0;
+}
+
+ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_customMem customMem)
+{
+ if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
+
+ { ZSTD_DDict* const ddict = (ZSTD_DDict*) ZSTD_malloc(sizeof(ZSTD_DDict), customMem);
+ if (ddict == NULL) return NULL;
+ ddict->cMem = customMem;
+ { size_t const initResult = ZSTD_initDDict_internal(ddict,
+ dict, dictSize,
+ dictLoadMethod, dictContentType);
+ if (ZSTD_isError(initResult)) {
+ ZSTD_freeDDict(ddict);
+ return NULL;
+ } }
+ return ddict;
+ }
+}
+
+/*! ZSTD_createDDict() :
+* Create a digested dictionary, to start decompression without startup delay.
+* `dict` content is copied inside DDict.
+* Consequently, `dict` can be released after `ZSTD_DDict` creation */
+ZSTD_DDict* ZSTD_createDDict(const void* dict, size_t dictSize)
+{
+ ZSTD_customMem const allocator = { NULL, NULL, NULL };
+ return ZSTD_createDDict_advanced(dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto, allocator);
+}
+
+/*! ZSTD_createDDict_byReference() :
+ * Create a digested dictionary, to start decompression without startup delay.
+ * Dictionary content is simply referenced, it will be accessed during decompression.
+ * Warning : dictBuffer must outlive DDict (DDict must be freed before dictBuffer) */
+ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize)
+{
+ ZSTD_customMem const allocator = { NULL, NULL, NULL };
+ return ZSTD_createDDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto, allocator);
+}
+
+
+const ZSTD_DDict* ZSTD_initStaticDDict(
+ void* sBuffer, size_t sBufferSize,
+ const void* dict, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType)
+{
+ size_t const neededSpace = sizeof(ZSTD_DDict)
+ + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize);
+ ZSTD_DDict* const ddict = (ZSTD_DDict*)sBuffer;
+ assert(sBuffer != NULL);
+ assert(dict != NULL);
+ if ((size_t)sBuffer & 7) return NULL; /* 8-aligned */
+ if (sBufferSize < neededSpace) return NULL;
+ if (dictLoadMethod == ZSTD_dlm_byCopy) {
+ memcpy(ddict+1, dict, dictSize); /* local copy */
+ dict = ddict+1;
+ }
+ if (ZSTD_isError( ZSTD_initDDict_internal(ddict,
+ dict, dictSize,
+ ZSTD_dlm_byRef, dictContentType) ))
+ return NULL;
+ return ddict;
+}
+
+
+size_t ZSTD_freeDDict(ZSTD_DDict* ddict)
+{
+ if (ddict==NULL) return 0; /* support free on NULL */
+ { ZSTD_customMem const cMem = ddict->cMem;
+ ZSTD_free(ddict->dictBuffer, cMem);
+ ZSTD_free(ddict, cMem);
+ return 0;
+ }
+}
+
+/*! ZSTD_estimateDDictSize() :
+ * Estimate amount of memory that will be needed to create a dictionary for decompression.
+ * Note : dictionary created by reference using ZSTD_dlm_byRef are smaller */
+size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod)
+{
+ return sizeof(ZSTD_DDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize);
+}
+
+size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict)
+{
+ if (ddict==NULL) return 0; /* support sizeof on NULL */
+ return sizeof(*ddict) + (ddict->dictBuffer ? ddict->dictSize : 0) ;
+}
+
+/*! ZSTD_getDictID_fromDDict() :
+ * Provides the dictID of the dictionary loaded into `ddict`.
+ * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
+ * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
+unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict)
+{
+ if (ddict==NULL) return 0;
+ return ZSTD_getDictID_fromDict(ddict->dictContent, ddict->dictSize);
+}
diff --git a/Utilities/cmzstd/lib/decompress/zstd_ddict.h b/Utilities/cmzstd/lib/decompress/zstd_ddict.h
new file mode 100644
index 000000000..0479d11bb
--- /dev/null
+++ b/Utilities/cmzstd/lib/decompress/zstd_ddict.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+
+#ifndef ZSTD_DDICT_H
+#define ZSTD_DDICT_H
+
+/*-*******************************************************
+ * Dependencies
+ *********************************************************/
+#include <stddef.h> /* size_t */
+#include "zstd.h" /* ZSTD_DDict, and several public functions */
+
+
+/*-*******************************************************
+ * Interface
+ *********************************************************/
+
+/* note: several prototypes are already published in `zstd.h` :
+ * ZSTD_createDDict()
+ * ZSTD_createDDict_byReference()
+ * ZSTD_createDDict_advanced()
+ * ZSTD_freeDDict()
+ * ZSTD_initStaticDDict()
+ * ZSTD_sizeof_DDict()
+ * ZSTD_estimateDDictSize()
+ * ZSTD_getDictID_fromDict()
+ */
+
+const void* ZSTD_DDict_dictContent(const ZSTD_DDict* ddict);
+size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict);
+
+void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);
+
+
+
+#endif /* ZSTD_DDICT_H */
diff --git a/Utilities/cmzstd/lib/decompress/zstd_decompress.c b/Utilities/cmzstd/lib/decompress/zstd_decompress.c
new file mode 100644
index 000000000..feef1ef67
--- /dev/null
+++ b/Utilities/cmzstd/lib/decompress/zstd_decompress.c
@@ -0,0 +1,1672 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+
+/* ***************************************************************
+* Tuning parameters
+*****************************************************************/
+/*!
+ * HEAPMODE :
+ * Select how default decompression function ZSTD_decompress() allocates its context,
+ * on stack (0), or into heap (1, default; requires malloc()).
+ * Note that functions with explicit context such as ZSTD_decompressDCtx() are unaffected.
+ */
+#ifndef ZSTD_HEAPMODE
+# define ZSTD_HEAPMODE 1
+#endif
+
+/*!
+* LEGACY_SUPPORT :
+* if set to 1+, ZSTD_decompress() can decode older formats (v0.1+)
+*/
+#ifndef ZSTD_LEGACY_SUPPORT
+# define ZSTD_LEGACY_SUPPORT 0
+#endif
+
+/*!
+ * MAXWINDOWSIZE_DEFAULT :
+ * maximum window size accepted by DStream __by default__.
+ * Frames requiring more memory will be rejected.
+ * It's possible to set a different limit using ZSTD_DCtx_setMaxWindowSize().
+ */
+#ifndef ZSTD_MAXWINDOWSIZE_DEFAULT
+# define ZSTD_MAXWINDOWSIZE_DEFAULT (((U32)1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + 1)
+#endif
+
+/*!
+ * NO_FORWARD_PROGRESS_MAX :
+ * maximum allowed nb of calls to ZSTD_decompressStream()
+ * without any forward progress
+ * (defined as: no byte read from input, and no byte flushed to output)
+ * before triggering an error.
+ */
+#ifndef ZSTD_NO_FORWARD_PROGRESS_MAX
+# define ZSTD_NO_FORWARD_PROGRESS_MAX 16
+#endif
+
+
+/*-*******************************************************
+* Dependencies
+*********************************************************/
+#include <string.h> /* memcpy, memmove, memset */
+#include "cpu.h" /* bmi2 */
+#include "mem.h" /* low level memory routines */
+#define FSE_STATIC_LINKING_ONLY
+#include "fse.h"
+#define HUF_STATIC_LINKING_ONLY
+#include "huf.h"
+#include "zstd_internal.h" /* blockProperties_t */
+#include "zstd_decompress_internal.h" /* ZSTD_DCtx */
+#include "zstd_ddict.h" /* ZSTD_DDictDictContent */
+#include "zstd_decompress_block.h" /* ZSTD_decompressBlock_internal */
+
+#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
+# include "zstd_legacy.h"
+#endif
+
+
+/*-*************************************************************
+* Context management
+***************************************************************/
+size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx)
+{
+ if (dctx==NULL) return 0; /* support sizeof NULL */
+ return sizeof(*dctx)
+ + ZSTD_sizeof_DDict(dctx->ddictLocal)
+ + dctx->inBuffSize + dctx->outBuffSize;
+}
+
+size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); }
+
+
+static size_t ZSTD_startingInputLength(ZSTD_format_e format)
+{
+ size_t const startingInputLength = (format==ZSTD_f_zstd1_magicless) ?
+ ZSTD_FRAMEHEADERSIZE_PREFIX - ZSTD_FRAMEIDSIZE :
+ ZSTD_FRAMEHEADERSIZE_PREFIX;
+ ZSTD_STATIC_ASSERT(ZSTD_FRAMEHEADERSIZE_PREFIX >= ZSTD_FRAMEIDSIZE);
+ /* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */
+ assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) );
+ return startingInputLength;
+}
+
+static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx)
+{
+ dctx->format = ZSTD_f_zstd1; /* ZSTD_decompressBegin() invokes ZSTD_startingInputLength() with argument dctx->format */
+ dctx->staticSize = 0;
+ dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
+ dctx->ddict = NULL;
+ dctx->ddictLocal = NULL;
+ dctx->dictEnd = NULL;
+ dctx->ddictIsCold = 0;
+ dctx->inBuff = NULL;
+ dctx->inBuffSize = 0;
+ dctx->outBuffSize = 0;
+ dctx->streamStage = zdss_init;
+ dctx->legacyContext = NULL;
+ dctx->previousLegacyVersion = 0;
+ dctx->noForwardProgress = 0;
+ dctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
+}
+
+ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize)
+{
+ ZSTD_DCtx* const dctx = (ZSTD_DCtx*) workspace;
+
+ if ((size_t)workspace & 7) return NULL; /* 8-aligned */
+ if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL; /* minimum size */
+
+ ZSTD_initDCtx_internal(dctx);
+ dctx->staticSize = workspaceSize;
+ dctx->inBuff = (char*)(dctx+1);
+ return dctx;
+}
+
+ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem)
+{
+ if (!customMem.customAlloc ^ !customMem.customFree) return NULL;
+
+ { ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_malloc(sizeof(*dctx), customMem);
+ if (!dctx) return NULL;
+ dctx->customMem = customMem;
+ ZSTD_initDCtx_internal(dctx);
+ return dctx;
+ }
+}
+
+ZSTD_DCtx* ZSTD_createDCtx(void)
+{
+ DEBUGLOG(3, "ZSTD_createDCtx");
+ return ZSTD_createDCtx_advanced(ZSTD_defaultCMem);
+}
+
+size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
+{
+ if (dctx==NULL) return 0; /* support free on NULL */
+ if (dctx->staticSize) return ERROR(memory_allocation); /* not compatible with static DCtx */
+ { ZSTD_customMem const cMem = dctx->customMem;
+ ZSTD_freeDDict(dctx->ddictLocal);
+ dctx->ddictLocal = NULL;
+ ZSTD_free(dctx->inBuff, cMem);
+ dctx->inBuff = NULL;
+#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
+ if (dctx->legacyContext)
+ ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion);
+#endif
+ ZSTD_free(dctx, cMem);
+ return 0;
+ }
+}
+
+/* no longer useful */
+void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx)
+{
+ size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx);
+ memcpy(dstDCtx, srcDCtx, toCopy); /* no need to copy workspace */
+}
+
+
+/*-*************************************************************
+ * Frame header decoding
+ ***************************************************************/
+
+/*! ZSTD_isFrame() :
+ * Tells if the content of `buffer` starts with a valid Frame Identifier.
+ * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
+ * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
+ * Note 3 : Skippable Frame Identifiers are considered valid. */
+unsigned ZSTD_isFrame(const void* buffer, size_t size)
+{
+ if (size < ZSTD_FRAMEIDSIZE) return 0;
+ { U32 const magic = MEM_readLE32(buffer);
+ if (magic == ZSTD_MAGICNUMBER) return 1;
+ if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1;
+ }
+#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
+ if (ZSTD_isLegacy(buffer, size)) return 1;
+#endif
+ return 0;
+}
+
+/** ZSTD_frameHeaderSize_internal() :
+ * srcSize must be large enough to reach header size fields.
+ * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless.
+ * @return : size of the Frame Header
+ * or an error code, which can be tested with ZSTD_isError() */
+static size_t ZSTD_frameHeaderSize_internal(const void* src, size_t srcSize, ZSTD_format_e format)
+{
+ size_t const minInputSize = ZSTD_startingInputLength(format);
+ if (srcSize < minInputSize) return ERROR(srcSize_wrong);
+
+ { BYTE const fhd = ((const BYTE*)src)[minInputSize-1];
+ U32 const dictID= fhd & 3;
+ U32 const singleSegment = (fhd >> 5) & 1;
+ U32 const fcsId = fhd >> 6;
+ return minInputSize + !singleSegment
+ + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId]
+ + (singleSegment && !fcsId);
+ }
+}
+
+/** ZSTD_frameHeaderSize() :
+ * srcSize must be >= ZSTD_frameHeaderSize_prefix.
+ * @return : size of the Frame Header,
+ * or an error code (if srcSize is too small) */
+size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize)
+{
+ return ZSTD_frameHeaderSize_internal(src, srcSize, ZSTD_f_zstd1);
+}
+
+
+/** ZSTD_getFrameHeader_advanced() :
+ * decode Frame Header, or require larger `srcSize`.
+ * note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless
+ * @return : 0, `zfhPtr` is correctly filled,
+ * >0, `srcSize` is too small, value is wanted `srcSize` amount,
+ * or an error code, which can be tested using ZSTD_isError() */
+size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format)
+{
+ const BYTE* ip = (const BYTE*)src;
+ size_t const minInputSize = ZSTD_startingInputLength(format);
+
+ memset(zfhPtr, 0, sizeof(*zfhPtr)); /* not strictly necessary, but static analyzer do not understand that zfhPtr is only going to be read only if return value is zero, since they are 2 different signals */
+ if (srcSize < minInputSize) return minInputSize;
+ if (src==NULL) return ERROR(GENERIC); /* invalid parameter */
+
+ if ( (format != ZSTD_f_zstd1_magicless)
+ && (MEM_readLE32(src) != ZSTD_MAGICNUMBER) ) {
+ if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
+ /* skippable frame */
+ if (srcSize < ZSTD_SKIPPABLEHEADERSIZE)
+ return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */
+ memset(zfhPtr, 0, sizeof(*zfhPtr));
+ zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE);
+ zfhPtr->frameType = ZSTD_skippableFrame;
+ return 0;
+ }
+ return ERROR(prefix_unknown);
+ }
+
+ /* ensure there is enough `srcSize` to fully read/decode frame header */
+ { size_t const fhsize = ZSTD_frameHeaderSize_internal(src, srcSize, format);
+ if (srcSize < fhsize) return fhsize;
+ zfhPtr->headerSize = (U32)fhsize;
+ }
+
+ { BYTE const fhdByte = ip[minInputSize-1];
+ size_t pos = minInputSize;
+ U32 const dictIDSizeCode = fhdByte&3;
+ U32 const checksumFlag = (fhdByte>>2)&1;
+ U32 const singleSegment = (fhdByte>>5)&1;
+ U32 const fcsID = fhdByte>>6;
+ U64 windowSize = 0;
+ U32 dictID = 0;
+ U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN;
+ if ((fhdByte & 0x08) != 0)
+ return ERROR(frameParameter_unsupported); /* reserved bits, must be zero */
+
+ if (!singleSegment) {
+ BYTE const wlByte = ip[pos++];
+ U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN;
+ if (windowLog > ZSTD_WINDOWLOG_MAX)
+ return ERROR(frameParameter_windowTooLarge);
+ windowSize = (1ULL << windowLog);
+ windowSize += (windowSize >> 3) * (wlByte&7);
+ }
+ switch(dictIDSizeCode)
+ {
+ default: assert(0); /* impossible */
+ case 0 : break;
+ case 1 : dictID = ip[pos]; pos++; break;
+ case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break;
+ case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break;
+ }
+ switch(fcsID)
+ {
+ default: assert(0); /* impossible */
+ case 0 : if (singleSegment) frameContentSize = ip[pos]; break;
+ case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break;
+ case 2 : frameContentSize = MEM_readLE32(ip+pos); break;
+ case 3 : frameContentSize = MEM_readLE64(ip+pos); break;
+ }
+ if (singleSegment) windowSize = frameContentSize;
+
+ zfhPtr->frameType = ZSTD_frame;
+ zfhPtr->frameContentSize = frameContentSize;
+ zfhPtr->windowSize = windowSize;
+ zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
+ zfhPtr->dictID = dictID;
+ zfhPtr->checksumFlag = checksumFlag;
+ }
+ return 0;
+}
+
+/** ZSTD_getFrameHeader() :
+ * decode Frame Header, or require larger `srcSize`.
+ * note : this function does not consume input, it only reads it.
+ * @return : 0, `zfhPtr` is correctly filled,
+ * >0, `srcSize` is too small, value is wanted `srcSize` amount,
+ * or an error code, which can be tested using ZSTD_isError() */
+size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize)
+{
+ return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1);
+}
+
+
+/** ZSTD_getFrameContentSize() :
+ * compatible with legacy mode
+ * @return : decompressed size of the single frame pointed to be `src` if known, otherwise
+ * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
+ * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */
+unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize)
+{
+#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
+ if (ZSTD_isLegacy(src, srcSize)) {
+ unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize);
+ return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret;
+ }
+#endif
+ { ZSTD_frameHeader zfh;
+ if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0)
+ return ZSTD_CONTENTSIZE_ERROR;
+ if (zfh.frameType == ZSTD_skippableFrame) {
+ return 0;
+ } else {
+ return zfh.frameContentSize;
+ } }
+}
+
+static size_t readSkippableFrameSize(void const* src, size_t srcSize)
+{
+ size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE;
+ U32 sizeU32;
+
+ if (srcSize < ZSTD_SKIPPABLEHEADERSIZE)
+ return ERROR(srcSize_wrong);
+
+ sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE);
+ if ((U32)(sizeU32 + ZSTD_SKIPPABLEHEADERSIZE) < sizeU32)
+ return ERROR(frameParameter_unsupported);
+
+ return skippableHeaderSize + sizeU32;
+}
+
+/** ZSTD_findDecompressedSize() :
+ * compatible with legacy mode
+ * `srcSize` must be the exact length of some number of ZSTD compressed and/or
+ * skippable frames
+ * @return : decompressed size of the frames contained */
+unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize)
+{
+ unsigned long long totalDstSize = 0;
+
+ while (srcSize >= ZSTD_FRAMEHEADERSIZE_PREFIX) {
+ U32 const magicNumber = MEM_readLE32(src);
+
+ if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
+ size_t const skippableSize = readSkippableFrameSize(src, srcSize);
+ if (ZSTD_isError(skippableSize))
+ return skippableSize;
+ if (srcSize < skippableSize) {
+ return ZSTD_CONTENTSIZE_ERROR;
+ }
+
+ src = (const BYTE *)src + skippableSize;
+ srcSize -= skippableSize;
+ continue;
+ }
+
+ { unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
+ if (ret >= ZSTD_CONTENTSIZE_ERROR) return ret;
+
+ /* check for overflow */
+ if (totalDstSize + ret < totalDstSize) return ZSTD_CONTENTSIZE_ERROR;
+ totalDstSize += ret;
+ }
+ { size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize);
+ if (ZSTD_isError(frameSrcSize)) {
+ return ZSTD_CONTENTSIZE_ERROR;
+ }
+
+ src = (const BYTE *)src + frameSrcSize;
+ srcSize -= frameSrcSize;
+ }
+ } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */
+
+ if (srcSize) return ZSTD_CONTENTSIZE_ERROR;
+
+ return totalDstSize;
+}
+
+/** ZSTD_getDecompressedSize() :
+ * compatible with legacy mode
+ * @return : decompressed size if known, 0 otherwise
+ note : 0 can mean any of the following :
+ - frame content is empty
+ - decompressed size field is not present in frame header
+ - frame header unknown / not supported
+ - frame header not complete (`srcSize` too small) */
+unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize)
+{
+ unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
+ ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_ERROR < ZSTD_CONTENTSIZE_UNKNOWN);
+ return (ret >= ZSTD_CONTENTSIZE_ERROR) ? 0 : ret;
+}
+
+
+/** ZSTD_decodeFrameHeader() :
+ * `headerSize` must be the size provided by ZSTD_frameHeaderSize().
+ * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */
+static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize)
+{
+ size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format);
+ if (ZSTD_isError(result)) return result; /* invalid header */
+ if (result>0) return ERROR(srcSize_wrong); /* headerSize too small */
+ if (dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID))
+ return ERROR(dictionary_wrong);
+ if (dctx->fParams.checksumFlag) XXH64_reset(&dctx->xxhState, 0);
+ return 0;
+}
+
+
+/** ZSTD_findFrameCompressedSize() :
+ * compatible with legacy mode
+ * `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame
+ * `srcSize` must be at least as large as the frame contained
+ * @return : the compressed size of the frame starting at `src` */
+size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize)
+{
+#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
+ if (ZSTD_isLegacy(src, srcSize))
+ return ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
+#endif
+ if ( (srcSize >= ZSTD_SKIPPABLEHEADERSIZE)
+ && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START ) {
+ return readSkippableFrameSize(src, srcSize);
+ } else {
+ const BYTE* ip = (const BYTE*)src;
+ const BYTE* const ipstart = ip;
+ size_t remainingSize = srcSize;
+ ZSTD_frameHeader zfh;
+
+ /* Extract Frame Header */
+ { size_t const ret = ZSTD_getFrameHeader(&zfh, src, srcSize);
+ if (ZSTD_isError(ret)) return ret;
+ if (ret > 0) return ERROR(srcSize_wrong);
+ }
+
+ ip += zfh.headerSize;
+ remainingSize -= zfh.headerSize;
+
+ /* Loop on each block */
+ while (1) {
+ blockProperties_t blockProperties;
+ size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
+ if (ZSTD_isError(cBlockSize)) return cBlockSize;
+
+ if (ZSTD_blockHeaderSize + cBlockSize > remainingSize)
+ return ERROR(srcSize_wrong);
+
+ ip += ZSTD_blockHeaderSize + cBlockSize;
+ remainingSize -= ZSTD_blockHeaderSize + cBlockSize;
+
+ if (blockProperties.lastBlock) break;
+ }
+
+ if (zfh.checksumFlag) { /* Final frame content checksum */
+ if (remainingSize < 4) return ERROR(srcSize_wrong);
+ ip += 4;
+ }
+
+ return ip - ipstart;
+ }
+}
+
+
+
+/*-*************************************************************
+ * Frame decoding
+ ***************************************************************/
+
+
+void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst)
+{
+ if (dst != dctx->previousDstEnd) { /* not contiguous */
+ dctx->dictEnd = dctx->previousDstEnd;
+ dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
+ dctx->prefixStart = dst;
+ dctx->previousDstEnd = dst;
+ }
+}
+
+/** ZSTD_insertBlock() :
+ insert `src` block into `dctx` history. Useful to track uncompressed blocks. */
+size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize)
+{
+ ZSTD_checkContinuity(dctx, blockStart);
+ dctx->previousDstEnd = (const char*)blockStart + blockSize;
+ return blockSize;
+}
+
+
+static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize)
+{
+ DEBUGLOG(5, "ZSTD_copyRawBlock");
+ if (dst == NULL) {
+ if (srcSize == 0) return 0;
+ return ERROR(dstBuffer_null);
+ }
+ if (srcSize > dstCapacity) return ERROR(dstSize_tooSmall);
+ memcpy(dst, src, srcSize);
+ return srcSize;
+}
+
+static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity,
+ BYTE b,
+ size_t regenSize)
+{
+ if (dst == NULL) {
+ if (regenSize == 0) return 0;
+ return ERROR(dstBuffer_null);
+ }
+ if (regenSize > dstCapacity) return ERROR(dstSize_tooSmall);
+ memset(dst, b, regenSize);
+ return regenSize;
+}
+
+
+/*! ZSTD_decompressFrame() :
+ * @dctx must be properly initialized
+ * will update *srcPtr and *srcSizePtr,
+ * to make *srcPtr progress by one frame. */
+static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity,
+ const void** srcPtr, size_t *srcSizePtr)
+{
+ const BYTE* ip = (const BYTE*)(*srcPtr);
+ BYTE* const ostart = (BYTE* const)dst;
+ BYTE* const oend = ostart + dstCapacity;
+ BYTE* op = ostart;
+ size_t remainingSrcSize = *srcSizePtr;
+
+ DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr);
+
+ /* check */
+ if (remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN+ZSTD_blockHeaderSize)
+ return ERROR(srcSize_wrong);
+
+ /* Frame Header */
+ { size_t const frameHeaderSize = ZSTD_frameHeaderSize(ip, ZSTD_FRAMEHEADERSIZE_PREFIX);
+ if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize;
+ if (remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize)
+ return ERROR(srcSize_wrong);
+ CHECK_F( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) );
+ ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize;
+ }
+
+ /* Loop on each block */
+ while (1) {
+ size_t decodedSize;
+ blockProperties_t blockProperties;
+ size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties);
+ if (ZSTD_isError(cBlockSize)) return cBlockSize;
+
+ ip += ZSTD_blockHeaderSize;
+ remainingSrcSize -= ZSTD_blockHeaderSize;
+ if (cBlockSize > remainingSrcSize) return ERROR(srcSize_wrong);
+
+ switch(blockProperties.blockType)
+ {
+ case bt_compressed:
+ decodedSize = ZSTD_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize, /* frame */ 1);
+ break;
+ case bt_raw :
+ decodedSize = ZSTD_copyRawBlock(op, oend-op, ip, cBlockSize);
+ break;
+ case bt_rle :
+ decodedSize = ZSTD_setRleBlock(op, oend-op, *ip, blockProperties.origSize);
+ break;
+ case bt_reserved :
+ default:
+ return ERROR(corruption_detected);
+ }
+
+ if (ZSTD_isError(decodedSize)) return decodedSize;
+ if (dctx->fParams.checksumFlag)
+ XXH64_update(&dctx->xxhState, op, decodedSize);
+ op += decodedSize;
+ ip += cBlockSize;
+ remainingSrcSize -= cBlockSize;
+ if (blockProperties.lastBlock) break;
+ }
+
+ if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {
+ if ((U64)(op-ostart) != dctx->fParams.frameContentSize) {
+ return ERROR(corruption_detected);
+ } }
+ if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */
+ U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState);
+ U32 checkRead;
+ if (remainingSrcSize<4) return ERROR(checksum_wrong);
+ checkRead = MEM_readLE32(ip);
+ if (checkRead != checkCalc) return ERROR(checksum_wrong);
+ ip += 4;
+ remainingSrcSize -= 4;
+ }
+
+ /* Allow caller to get size read */
+ *srcPtr = ip;
+ *srcSizePtr = remainingSrcSize;
+ return op-ostart;
+}
+
+static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const void* dict, size_t dictSize,
+ const ZSTD_DDict* ddict)
+{
+ void* const dststart = dst;
+ int moreThan1Frame = 0;
+
+ DEBUGLOG(5, "ZSTD_decompressMultiFrame");
+ assert(dict==NULL || ddict==NULL); /* either dict or ddict set, not both */
+
+ if (ddict) {
+ dict = ZSTD_DDict_dictContent(ddict);
+ dictSize = ZSTD_DDict_dictSize(ddict);
+ }
+
+ while (srcSize >= ZSTD_FRAMEHEADERSIZE_PREFIX) {
+
+#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
+ if (ZSTD_isLegacy(src, srcSize)) {
+ size_t decodedSize;
+ size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
+ if (ZSTD_isError(frameSize)) return frameSize;
+ /* legacy support is not compatible with static dctx */
+ if (dctx->staticSize) return ERROR(memory_allocation);
+
+ decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize);
+ if (ZSTD_isError(decodedSize)) return decodedSize;
+
+ assert(decodedSize <=- dstCapacity);
+ dst = (BYTE*)dst + decodedSize;
+ dstCapacity -= decodedSize;
+
+ src = (const BYTE*)src + frameSize;
+ srcSize -= frameSize;
+
+ continue;
+ }
+#endif
+
+ { U32 const magicNumber = MEM_readLE32(src);
+ DEBUGLOG(4, "reading magic number %08X (expecting %08X)",
+ (unsigned)magicNumber, ZSTD_MAGICNUMBER);
+ if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
+ size_t const skippableSize = readSkippableFrameSize(src, srcSize);
+ if (ZSTD_isError(skippableSize))
+ return skippableSize;
+ if (srcSize < skippableSize) return ERROR(srcSize_wrong);
+
+ src = (const BYTE *)src + skippableSize;
+ srcSize -= skippableSize;
+ continue;
+ } }
+
+ if (ddict) {
+ /* we were called from ZSTD_decompress_usingDDict */
+ CHECK_F(ZSTD_decompressBegin_usingDDict(dctx, ddict));
+ } else {
+ /* this will initialize correctly with no dict if dict == NULL, so
+ * use this in all cases but ddict */
+ CHECK_F(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize));
+ }
+ ZSTD_checkContinuity(dctx, dst);
+
+ { const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity,
+ &src, &srcSize);
+ if ( (ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown)
+ && (moreThan1Frame==1) ) {
+ /* at least one frame successfully completed,
+ * but following bytes are garbage :
+ * it's more likely to be a srcSize error,
+ * specifying more bytes than compressed size of frame(s).
+ * This error message replaces ERROR(prefix_unknown),
+ * which would be confusing, as the first header is actually correct.
+ * Note that one could be unlucky, it might be a corruption error instead,
+ * happening right at the place where we expect zstd magic bytes.
+ * But this is _much_ less likely than a srcSize field error. */
+ return ERROR(srcSize_wrong);
+ }
+ if (ZSTD_isError(res)) return res;
+ assert(res <= dstCapacity);
+ dst = (BYTE*)dst + res;
+ dstCapacity -= res;
+ }
+ moreThan1Frame = 1;
+ } /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */
+
+ if (srcSize) return ERROR(srcSize_wrong); /* input not entirely consumed */
+
+ return (BYTE*)dst - (BYTE*)dststart;
+}
+
+size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const void* dict, size_t dictSize)
+{
+ return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL);
+}
+
+
+size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
+{
+ return ZSTD_decompress_usingDict(dctx, dst, dstCapacity, src, srcSize, NULL, 0);
+}
+
+
+size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
+{
+#if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1)
+ size_t regenSize;
+ ZSTD_DCtx* const dctx = ZSTD_createDCtx();
+ if (dctx==NULL) return ERROR(memory_allocation);
+ regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);
+ ZSTD_freeDCtx(dctx);
+ return regenSize;
+#else /* stack mode */
+ ZSTD_DCtx dctx;
+ ZSTD_initDCtx_internal(&dctx);
+ return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize);
+#endif
+}
+
+
+/*-**************************************
+* Advanced Streaming Decompression API
+* Bufferless and synchronous
+****************************************/
+size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; }
+
+ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) {
+ switch(dctx->stage)
+ {
+ default: /* should not happen */
+ assert(0);
+ case ZSTDds_getFrameHeaderSize:
+ case ZSTDds_decodeFrameHeader:
+ return ZSTDnit_frameHeader;
+ case ZSTDds_decodeBlockHeader:
+ return ZSTDnit_blockHeader;
+ case ZSTDds_decompressBlock:
+ return ZSTDnit_block;
+ case ZSTDds_decompressLastBlock:
+ return ZSTDnit_lastBlock;
+ case ZSTDds_checkChecksum:
+ return ZSTDnit_checksum;
+ case ZSTDds_decodeSkippableHeader:
+ case ZSTDds_skipFrame:
+ return ZSTDnit_skippableFrame;
+ }
+}
+
+static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; }
+
+/** ZSTD_decompressContinue() :
+ * srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress())
+ * @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity)
+ * or an error code, which can be tested using ZSTD_isError() */
+size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
+{
+ DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize);
+ /* Sanity check */
+ if (srcSize != dctx->expected)
+ return ERROR(srcSize_wrong); /* not allowed */
+ if (dstCapacity) ZSTD_checkContinuity(dctx, dst);
+
+ switch (dctx->stage)
+ {
+ case ZSTDds_getFrameHeaderSize :
+ assert(src != NULL);
+ if (dctx->format == ZSTD_f_zstd1) { /* allows header */
+ assert(srcSize >= ZSTD_FRAMEIDSIZE); /* to read skippable magic number */
+ if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */
+ memcpy(dctx->headerBuffer, src, srcSize);
+ dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize; /* remaining to load to get full skippable frame header */
+ dctx->stage = ZSTDds_decodeSkippableHeader;
+ return 0;
+ } }
+ dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format);
+ if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize;
+ memcpy(dctx->headerBuffer, src, srcSize);
+ dctx->expected = dctx->headerSize - srcSize;
+ dctx->stage = ZSTDds_decodeFrameHeader;
+ return 0;
+
+ case ZSTDds_decodeFrameHeader:
+ assert(src != NULL);
+ memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize);
+ CHECK_F(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize));
+ dctx->expected = ZSTD_blockHeaderSize;
+ dctx->stage = ZSTDds_decodeBlockHeader;
+ return 0;
+
+ case ZSTDds_decodeBlockHeader:
+ { blockProperties_t bp;
+ size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
+ if (ZSTD_isError(cBlockSize)) return cBlockSize;
+ dctx->expected = cBlockSize;
+ dctx->bType = bp.blockType;
+ dctx->rleSize = bp.origSize;
+ if (cBlockSize) {
+ dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock;
+ return 0;
+ }
+ /* empty block */
+ if (bp.lastBlock) {
+ if (dctx->fParams.checksumFlag) {
+ dctx->expected = 4;
+ dctx->stage = ZSTDds_checkChecksum;
+ } else {
+ dctx->expected = 0; /* end of frame */
+ dctx->stage = ZSTDds_getFrameHeaderSize;
+ }
+ } else {
+ dctx->expected = ZSTD_blockHeaderSize; /* jump to next header */
+ dctx->stage = ZSTDds_decodeBlockHeader;
+ }
+ return 0;
+ }
+
+ case ZSTDds_decompressLastBlock:
+ case ZSTDds_decompressBlock:
+ DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock");
+ { size_t rSize;
+ switch(dctx->bType)
+ {
+ case bt_compressed:
+ DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed");
+ rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 1);
+ break;
+ case bt_raw :
+ rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize);
+ break;
+ case bt_rle :
+ rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize);
+ break;
+ case bt_reserved : /* should never happen */
+ default:
+ return ERROR(corruption_detected);
+ }
+ if (ZSTD_isError(rSize)) return rSize;
+ DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize);
+ dctx->decodedSize += rSize;
+ if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, dst, rSize);
+
+ if (dctx->stage == ZSTDds_decompressLastBlock) { /* end of frame */
+ DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize);
+ if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {
+ if (dctx->decodedSize != dctx->fParams.frameContentSize) {
+ return ERROR(corruption_detected);
+ } }
+ if (dctx->fParams.checksumFlag) { /* another round for frame checksum */
+ dctx->expected = 4;
+ dctx->stage = ZSTDds_checkChecksum;
+ } else {
+ dctx->expected = 0; /* ends here */
+ dctx->stage = ZSTDds_getFrameHeaderSize;
+ }
+ } else {
+ dctx->stage = ZSTDds_decodeBlockHeader;
+ dctx->expected = ZSTD_blockHeaderSize;
+ dctx->previousDstEnd = (char*)dst + rSize;
+ }
+ return rSize;
+ }
+
+ case ZSTDds_checkChecksum:
+ assert(srcSize == 4); /* guaranteed by dctx->expected */
+ { U32 const h32 = (U32)XXH64_digest(&dctx->xxhState);
+ U32 const check32 = MEM_readLE32(src);
+ DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32);
+ if (check32 != h32) return ERROR(checksum_wrong);
+ dctx->expected = 0;
+ dctx->stage = ZSTDds_getFrameHeaderSize;
+ return 0;
+ }
+
+ case ZSTDds_decodeSkippableHeader:
+ assert(src != NULL);
+ assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE);
+ memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize); /* complete skippable header */
+ dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE); /* note : dctx->expected can grow seriously large, beyond local buffer size */
+ dctx->stage = ZSTDds_skipFrame;
+ return 0;
+
+ case ZSTDds_skipFrame:
+ dctx->expected = 0;
+ dctx->stage = ZSTDds_getFrameHeaderSize;
+ return 0;
+
+ default:
+ assert(0); /* impossible */
+ return ERROR(GENERIC); /* some compiler require default to do something */
+ }
+}
+
+
+static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
+{
+ dctx->dictEnd = dctx->previousDstEnd;
+ dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
+ dctx->prefixStart = dict;
+ dctx->previousDstEnd = (const char*)dict + dictSize;
+ return 0;
+}
+
+/*! ZSTD_loadDEntropy() :
+ * dict : must point at beginning of a valid zstd dictionary.
+ * @return : size of entropy tables read */
+size_t
+ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy,
+ const void* const dict, size_t const dictSize)
+{
+ const BYTE* dictPtr = (const BYTE*)dict;
+ const BYTE* const dictEnd = dictPtr + dictSize;
+
+ if (dictSize <= 8) return ERROR(dictionary_corrupted);
+ assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY); /* dict must be valid */
+ dictPtr += 8; /* skip header = magic + dictID */
+
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable));
+ ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable));
+ ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE);
+ { void* const workspace = &entropy->LLTable; /* use fse tables as temporary workspace; implies fse tables are grouped together */
+ size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable);
+#ifdef HUF_FORCE_DECOMPRESS_X1
+ /* in minimal huffman, we always use X1 variants */
+ size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable,
+ dictPtr, dictEnd - dictPtr,
+ workspace, workspaceSize);
+#else
+ size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable,
+ dictPtr, dictEnd - dictPtr,
+ workspace, workspaceSize);
+#endif
+ if (HUF_isError(hSize)) return ERROR(dictionary_corrupted);
+ dictPtr += hSize;
+ }
+
+ { short offcodeNCount[MaxOff+1];
+ unsigned offcodeMaxValue = MaxOff, offcodeLog;
+ size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
+ if (FSE_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
+ if (offcodeMaxValue > MaxOff) return ERROR(dictionary_corrupted);
+ if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted);
+ ZSTD_buildFSETable( entropy->OFTable,
+ offcodeNCount, offcodeMaxValue,
+ OF_base, OF_bits,
+ offcodeLog);
+ dictPtr += offcodeHeaderSize;
+ }
+
+ { short matchlengthNCount[MaxML+1];
+ unsigned matchlengthMaxValue = MaxML, matchlengthLog;
+ size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
+ if (FSE_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
+ if (matchlengthMaxValue > MaxML) return ERROR(dictionary_corrupted);
+ if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted);
+ ZSTD_buildFSETable( entropy->MLTable,
+ matchlengthNCount, matchlengthMaxValue,
+ ML_base, ML_bits,
+ matchlengthLog);
+ dictPtr += matchlengthHeaderSize;
+ }
+
+ { short litlengthNCount[MaxLL+1];
+ unsigned litlengthMaxValue = MaxLL, litlengthLog;
+ size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
+ if (FSE_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
+ if (litlengthMaxValue > MaxLL) return ERROR(dictionary_corrupted);
+ if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted);
+ ZSTD_buildFSETable( entropy->LLTable,
+ litlengthNCount, litlengthMaxValue,
+ LL_base, LL_bits,
+ litlengthLog);
+ dictPtr += litlengthHeaderSize;
+ }
+
+ if (dictPtr+12 > dictEnd) return ERROR(dictionary_corrupted);
+ { int i;
+ size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12));
+ for (i=0; i<3; i++) {
+ U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4;
+ if (rep==0 || rep >= dictContentSize) return ERROR(dictionary_corrupted);
+ entropy->rep[i] = rep;
+ } }
+
+ return dictPtr - (const BYTE*)dict;
+}
+
+static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
+{
+ if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize);
+ { U32 const magic = MEM_readLE32(dict);
+ if (magic != ZSTD_MAGIC_DICTIONARY) {
+ return ZSTD_refDictContent(dctx, dict, dictSize); /* pure content mode */
+ } }
+ dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);
+
+ /* load entropy tables */
+ { size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize);
+ if (ZSTD_isError(eSize)) return ERROR(dictionary_corrupted);
+ dict = (const char*)dict + eSize;
+ dictSize -= eSize;
+ }
+ dctx->litEntropy = dctx->fseEntropy = 1;
+
+ /* reference dictionary content */
+ return ZSTD_refDictContent(dctx, dict, dictSize);
+}
+
+size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx)
+{
+ assert(dctx != NULL);
+ dctx->expected = ZSTD_startingInputLength(dctx->format); /* dctx->format must be properly set */
+ dctx->stage = ZSTDds_getFrameHeaderSize;
+ dctx->decodedSize = 0;
+ dctx->previousDstEnd = NULL;
+ dctx->prefixStart = NULL;
+ dctx->virtualStart = NULL;
+ dctx->dictEnd = NULL;
+ dctx->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001); /* cover both little and big endian */
+ dctx->litEntropy = dctx->fseEntropy = 0;
+ dctx->dictID = 0;
+ ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue));
+ memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue)); /* initial repcodes */
+ dctx->LLTptr = dctx->entropy.LLTable;
+ dctx->MLTptr = dctx->entropy.MLTable;
+ dctx->OFTptr = dctx->entropy.OFTable;
+ dctx->HUFptr = dctx->entropy.hufTable;
+ return 0;
+}
+
+size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
+{
+ CHECK_F( ZSTD_decompressBegin(dctx) );
+ if (dict && dictSize)
+ CHECK_E(ZSTD_decompress_insertDictionary(dctx, dict, dictSize), dictionary_corrupted);
+ return 0;
+}
+
+
+/* ====== ZSTD_DDict ====== */
+
+size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
+{
+ DEBUGLOG(4, "ZSTD_decompressBegin_usingDDict");
+ assert(dctx != NULL);
+ if (ddict) {
+ const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict);
+ size_t const dictSize = ZSTD_DDict_dictSize(ddict);
+ const void* const dictEnd = dictStart + dictSize;
+ dctx->ddictIsCold = (dctx->dictEnd != dictEnd);
+ DEBUGLOG(4, "DDict is %s",
+ dctx->ddictIsCold ? "~cold~" : "hot!");
+ }
+ CHECK_F( ZSTD_decompressBegin(dctx) );
+ if (ddict) { /* NULL ddict is equivalent to no dictionary */
+ ZSTD_copyDDictParameters(dctx, ddict);
+ }
+ return 0;
+}
+
+/*! ZSTD_getDictID_fromDict() :
+ * Provides the dictID stored within dictionary.
+ * if @return == 0, the dictionary is not conformant with Zstandard specification.
+ * It can still be loaded, but as a content-only dictionary. */
+unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize)
+{
+ if (dictSize < 8) return 0;
+ if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0;
+ return MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);
+}
+
+/*! ZSTD_getDictID_fromFrame() :
+ * Provides the dictID required to decompresse frame stored within `src`.
+ * If @return == 0, the dictID could not be decoded.
+ * This could for one of the following reasons :
+ * - The frame does not require a dictionary (most common case).
+ * - The frame was built with dictID intentionally removed.
+ * Needed dictionary is a hidden information.
+ * Note : this use case also happens when using a non-conformant dictionary.
+ * - `srcSize` is too small, and as a result, frame header could not be decoded.
+ * Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`.
+ * - This is not a Zstandard frame.
+ * When identifying the exact failure cause, it's possible to use
+ * ZSTD_getFrameHeader(), which will provide a more precise error code. */
+unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize)
+{
+ ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0 };
+ size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize);
+ if (ZSTD_isError(hError)) return 0;
+ return zfp.dictID;
+}
+
+
+/*! ZSTD_decompress_usingDDict() :
+* Decompression using a pre-digested Dictionary
+* Use dictionary without significant overhead. */
+size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const ZSTD_DDict* ddict)
+{
+ /* pass content and size in case legacy frames are encountered */
+ return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize,
+ NULL, 0,
+ ddict);
+}
+
+
+/*=====================================
+* Streaming decompression
+*====================================*/
+
+ZSTD_DStream* ZSTD_createDStream(void)
+{
+ DEBUGLOG(3, "ZSTD_createDStream");
+ return ZSTD_createDStream_advanced(ZSTD_defaultCMem);
+}
+
+ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize)
+{
+ return ZSTD_initStaticDCtx(workspace, workspaceSize);
+}
+
+ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem)
+{
+ return ZSTD_createDCtx_advanced(customMem);
+}
+
+size_t ZSTD_freeDStream(ZSTD_DStream* zds)
+{
+ return ZSTD_freeDCtx(zds);
+}
+
+
+/* *** Initialization *** */
+
+size_t ZSTD_DStreamInSize(void) { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; }
+size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; }
+
+size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx,
+ const void* dict, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType)
+{
+ if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
+ ZSTD_freeDDict(dctx->ddictLocal);
+ if (dict && dictSize >= 8) {
+ dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem);
+ if (dctx->ddictLocal == NULL) return ERROR(memory_allocation);
+ } else {
+ dctx->ddictLocal = NULL;
+ }
+ dctx->ddict = dctx->ddictLocal;
+ return 0;
+}
+
+size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
+{
+ return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
+}
+
+size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
+{
+ return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
+}
+
+size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
+{
+ return ZSTD_DCtx_loadDictionary_advanced(dctx, prefix, prefixSize, ZSTD_dlm_byRef, dictContentType);
+}
+
+size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize)
+{
+ return ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent);
+}
+
+
+/* ZSTD_initDStream_usingDict() :
+ * return : expected size, aka ZSTD_FRAMEHEADERSIZE_PREFIX.
+ * this function cannot fail */
+size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize)
+{
+ DEBUGLOG(4, "ZSTD_initDStream_usingDict");
+ zds->streamStage = zdss_init;
+ zds->noForwardProgress = 0;
+ CHECK_F( ZSTD_DCtx_loadDictionary(zds, dict, dictSize) );
+ return ZSTD_FRAMEHEADERSIZE_PREFIX;
+}
+
+/* note : this variant can't fail */
+size_t ZSTD_initDStream(ZSTD_DStream* zds)
+{
+ DEBUGLOG(4, "ZSTD_initDStream");
+ return ZSTD_initDStream_usingDict(zds, NULL, 0);
+}
+
+/* ZSTD_initDStream_usingDDict() :
+ * ddict will just be referenced, and must outlive decompression session
+ * this function cannot fail */
+size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* dctx, const ZSTD_DDict* ddict)
+{
+ size_t const initResult = ZSTD_initDStream(dctx);
+ dctx->ddict = ddict;
+ return initResult;
+}
+
+/* ZSTD_resetDStream() :
+ * return : expected size, aka ZSTD_FRAMEHEADERSIZE_PREFIX.
+ * this function cannot fail */
+size_t ZSTD_resetDStream(ZSTD_DStream* dctx)
+{
+ DEBUGLOG(4, "ZSTD_resetDStream");
+ dctx->streamStage = zdss_loadHeader;
+ dctx->lhSize = dctx->inPos = dctx->outStart = dctx->outEnd = 0;
+ dctx->legacyVersion = 0;
+ dctx->hostageByte = 0;
+ return ZSTD_FRAMEHEADERSIZE_PREFIX;
+}
+
+
+size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
+{
+ if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
+ dctx->ddict = ddict;
+ return 0;
+}
+
+/* ZSTD_DCtx_setMaxWindowSize() :
+ * note : no direct equivalence in ZSTD_DCtx_setParameter,
+ * since this version sets windowSize, and the other sets windowLog */
+size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize)
+{
+ ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax);
+ size_t const min = (size_t)1 << bounds.lowerBound;
+ size_t const max = (size_t)1 << bounds.upperBound;
+ if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
+ if (maxWindowSize < min) return ERROR(parameter_outOfBound);
+ if (maxWindowSize > max) return ERROR(parameter_outOfBound);
+ dctx->maxWindowSize = maxWindowSize;
+ return 0;
+}
+
+size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format)
+{
+ return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, format);
+}
+
+ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam)
+{
+ ZSTD_bounds bounds = { 0, 0, 0 };
+ switch(dParam) {
+ case ZSTD_d_windowLogMax:
+ bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN;
+ bounds.upperBound = ZSTD_WINDOWLOG_MAX;
+ return bounds;
+ case ZSTD_d_format:
+ bounds.lowerBound = (int)ZSTD_f_zstd1;
+ bounds.upperBound = (int)ZSTD_f_zstd1_magicless;
+ ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
+ return bounds;
+ default:;
+ }
+ bounds.error = ERROR(parameter_unsupported);
+ return bounds;
+}
+
+/* ZSTD_dParam_withinBounds:
+ * @return 1 if value is within dParam bounds,
+ * 0 otherwise */
+static int ZSTD_dParam_withinBounds(ZSTD_dParameter dParam, int value)
+{
+ ZSTD_bounds const bounds = ZSTD_dParam_getBounds(dParam);
+ if (ZSTD_isError(bounds.error)) return 0;
+ if (value < bounds.lowerBound) return 0;
+ if (value > bounds.upperBound) return 0;
+ return 1;
+}
+
+#define CHECK_DBOUNDS(p,v) { \
+ if (!ZSTD_dParam_withinBounds(p, v)) \
+ return ERROR(parameter_outOfBound); \
+}
+
+size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value)
+{
+ if (dctx->streamStage != zdss_init) return ERROR(stage_wrong);
+ switch(dParam) {
+ case ZSTD_d_windowLogMax:
+ CHECK_DBOUNDS(ZSTD_d_windowLogMax, value);
+ dctx->maxWindowSize = ((size_t)1) << value;
+ return 0;
+ case ZSTD_d_format:
+ CHECK_DBOUNDS(ZSTD_d_format, value);
+ dctx->format = (ZSTD_format_e)value;
+ return 0;
+ default:;
+ }
+ return ERROR(parameter_unsupported);
+}
+
+size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset)
+{
+ if ( (reset == ZSTD_reset_session_only)
+ || (reset == ZSTD_reset_session_and_parameters) ) {
+ (void)ZSTD_initDStream(dctx);
+ }
+ if ( (reset == ZSTD_reset_parameters)
+ || (reset == ZSTD_reset_session_and_parameters) ) {
+ if (dctx->streamStage != zdss_init)
+ return ERROR(stage_wrong);
+ dctx->format = ZSTD_f_zstd1;
+ dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
+ }
+ return 0;
+}
+
+
+size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx)
+{
+ return ZSTD_sizeof_DCtx(dctx);
+}
+
+size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize)
+{
+ size_t const blockSize = (size_t) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
+ unsigned long long const neededRBSize = windowSize + blockSize + (WILDCOPY_OVERLENGTH * 2);
+ unsigned long long const neededSize = MIN(frameContentSize, neededRBSize);
+ size_t const minRBSize = (size_t) neededSize;
+ if ((unsigned long long)minRBSize != neededSize) return ERROR(frameParameter_windowTooLarge);
+ return minRBSize;
+}
+
+size_t ZSTD_estimateDStreamSize(size_t windowSize)
+{
+ size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
+ size_t const inBuffSize = blockSize; /* no block can be larger */
+ size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN);
+ return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize;
+}
+
+size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize)
+{
+ U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX; /* note : should be user-selectable, but requires an additional parameter (or a dctx) */
+ ZSTD_frameHeader zfh;
+ size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize);
+ if (ZSTD_isError(err)) return err;
+ if (err>0) return ERROR(srcSize_wrong);
+ if (zfh.windowSize > windowSizeMax)
+ return ERROR(frameParameter_windowTooLarge);
+ return ZSTD_estimateDStreamSize((size_t)zfh.windowSize);
+}
+
+
+/* ***** Decompression ***** */
+
+MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
+{
+ size_t const length = MIN(dstCapacity, srcSize);
+ memcpy(dst, src, length);
+ return length;
+}
+
+
+size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
+{
+ const char* const istart = (const char*)(input->src) + input->pos;
+ const char* const iend = (const char*)(input->src) + input->size;
+ const char* ip = istart;
+ char* const ostart = (char*)(output->dst) + output->pos;
+ char* const oend = (char*)(output->dst) + output->size;
+ char* op = ostart;
+ U32 someMoreWork = 1;
+
+ DEBUGLOG(5, "ZSTD_decompressStream");
+ if (input->pos > input->size) { /* forbidden */
+ DEBUGLOG(5, "in: pos: %u vs size: %u",
+ (U32)input->pos, (U32)input->size);
+ return ERROR(srcSize_wrong);
+ }
+ if (output->pos > output->size) { /* forbidden */
+ DEBUGLOG(5, "out: pos: %u vs size: %u",
+ (U32)output->pos, (U32)output->size);
+ return ERROR(dstSize_tooSmall);
+ }
+ DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos));
+
+ while (someMoreWork) {
+ switch(zds->streamStage)
+ {
+ case zdss_init :
+ DEBUGLOG(5, "stage zdss_init => transparent reset ");
+ ZSTD_resetDStream(zds); /* transparent reset on starting decoding a new frame */
+ /* fall-through */
+
+ case zdss_loadHeader :
+ DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip));
+#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
+ if (zds->legacyVersion) {
+ /* legacy support is incompatible with static dctx */
+ if (zds->staticSize) return ERROR(memory_allocation);
+ { size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, zds->legacyVersion, output, input);
+ if (hint==0) zds->streamStage = zdss_init;
+ return hint;
+ } }
+#endif
+ { size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format);
+ DEBUGLOG(5, "header size : %u", (U32)hSize);
+ if (ZSTD_isError(hSize)) {
+#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
+ U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart);
+ if (legacyVersion) {
+ const void* const dict = zds->ddict ? ZSTD_DDict_dictContent(zds->ddict) : NULL;
+ size_t const dictSize = zds->ddict ? ZSTD_DDict_dictSize(zds->ddict) : 0;
+ DEBUGLOG(5, "ZSTD_decompressStream: detected legacy version v0.%u", legacyVersion);
+ /* legacy support is incompatible with static dctx */
+ if (zds->staticSize) return ERROR(memory_allocation);
+ CHECK_F(ZSTD_initLegacyStream(&zds->legacyContext,
+ zds->previousLegacyVersion, legacyVersion,
+ dict, dictSize));
+ zds->legacyVersion = zds->previousLegacyVersion = legacyVersion;
+ { size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, legacyVersion, output, input);
+ if (hint==0) zds->streamStage = zdss_init; /* or stay in stage zdss_loadHeader */
+ return hint;
+ } }
+#endif
+ return hSize; /* error */
+ }
+ if (hSize != 0) { /* need more input */
+ size_t const toLoad = hSize - zds->lhSize; /* if hSize!=0, hSize > zds->lhSize */
+ size_t const remainingInput = (size_t)(iend-ip);
+ assert(iend >= ip);
+ if (toLoad > remainingInput) { /* not enough input to load full header */
+ if (remainingInput > 0) {
+ memcpy(zds->headerBuffer + zds->lhSize, ip, remainingInput);
+ zds->lhSize += remainingInput;
+ }
+ input->pos = input->size;
+ return (MAX(ZSTD_FRAMEHEADERSIZE_MIN, hSize) - zds->lhSize) + ZSTD_blockHeaderSize; /* remaining header bytes + next block header */
+ }
+ assert(ip != NULL);
+ memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad;
+ break;
+ } }
+
+ /* check for single-pass mode opportunity */
+ if (zds->fParams.frameContentSize && zds->fParams.windowSize /* skippable frame if == 0 */
+ && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) {
+ size_t const cSize = ZSTD_findFrameCompressedSize(istart, iend-istart);
+ if (cSize <= (size_t)(iend-istart)) {
+ /* shortcut : using single-pass mode */
+ size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, oend-op, istart, cSize, zds->ddict);
+ if (ZSTD_isError(decompressedSize)) return decompressedSize;
+ DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()")
+ ip = istart + cSize;
+ op += decompressedSize;
+ zds->expected = 0;
+ zds->streamStage = zdss_init;
+ someMoreWork = 0;
+ break;
+ } }
+
+ /* Consume header (see ZSTDds_decodeFrameHeader) */
+ DEBUGLOG(4, "Consume header");
+ CHECK_F(ZSTD_decompressBegin_usingDDict(zds, zds->ddict));
+
+ if ((MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) { /* skippable frame */
+ zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE);
+ zds->stage = ZSTDds_skipFrame;
+ } else {
+ CHECK_F(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize));
+ zds->expected = ZSTD_blockHeaderSize;
+ zds->stage = ZSTDds_decodeBlockHeader;
+ }
+
+ /* control buffer memory usage */
+ DEBUGLOG(4, "Control max memory usage (%u KB <= max %u KB)",
+ (U32)(zds->fParams.windowSize >>10),
+ (U32)(zds->maxWindowSize >> 10) );
+ zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN);
+ if (zds->fParams.windowSize > zds->maxWindowSize) return ERROR(frameParameter_windowTooLarge);
+
+ /* Adapt buffer sizes to frame header instructions */
+ { size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */);
+ size_t const neededOutBuffSize = ZSTD_decodingBufferSize_min(zds->fParams.windowSize, zds->fParams.frameContentSize);
+ if ((zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize)) {
+ size_t const bufferSize = neededInBuffSize + neededOutBuffSize;
+ DEBUGLOG(4, "inBuff : from %u to %u",
+ (U32)zds->inBuffSize, (U32)neededInBuffSize);
+ DEBUGLOG(4, "outBuff : from %u to %u",
+ (U32)zds->outBuffSize, (U32)neededOutBuffSize);
+ if (zds->staticSize) { /* static DCtx */
+ DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize);
+ assert(zds->staticSize >= sizeof(ZSTD_DCtx)); /* controlled at init */
+ if (bufferSize > zds->staticSize - sizeof(ZSTD_DCtx))
+ return ERROR(memory_allocation);
+ } else {
+ ZSTD_free(zds->inBuff, zds->customMem);
+ zds->inBuffSize = 0;
+ zds->outBuffSize = 0;
+ zds->inBuff = (char*)ZSTD_malloc(bufferSize, zds->customMem);
+ if (zds->inBuff == NULL) return ERROR(memory_allocation);
+ }
+ zds->inBuffSize = neededInBuffSize;
+ zds->outBuff = zds->inBuff + zds->inBuffSize;
+ zds->outBuffSize = neededOutBuffSize;
+ } }
+ zds->streamStage = zdss_read;
+ /* fall-through */
+
+ case zdss_read:
+ DEBUGLOG(5, "stage zdss_read");
+ { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
+ DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize);
+ if (neededInSize==0) { /* end of frame */
+ zds->streamStage = zdss_init;
+ someMoreWork = 0;
+ break;
+ }
+ if ((size_t)(iend-ip) >= neededInSize) { /* decode directly from src */
+ int const isSkipFrame = ZSTD_isSkipFrame(zds);
+ size_t const decodedSize = ZSTD_decompressContinue(zds,
+ zds->outBuff + zds->outStart, (isSkipFrame ? 0 : zds->outBuffSize - zds->outStart),
+ ip, neededInSize);
+ if (ZSTD_isError(decodedSize)) return decodedSize;
+ ip += neededInSize;
+ if (!decodedSize && !isSkipFrame) break; /* this was just a header */
+ zds->outEnd = zds->outStart + decodedSize;
+ zds->streamStage = zdss_flush;
+ break;
+ } }
+ if (ip==iend) { someMoreWork = 0; break; } /* no more input */
+ zds->streamStage = zdss_load;
+ /* fall-through */
+
+ case zdss_load:
+ { size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
+ size_t const toLoad = neededInSize - zds->inPos;
+ int const isSkipFrame = ZSTD_isSkipFrame(zds);
+ size_t loadedSize;
+ if (isSkipFrame) {
+ loadedSize = MIN(toLoad, (size_t)(iend-ip));
+ } else {
+ if (toLoad > zds->inBuffSize - zds->inPos) return ERROR(corruption_detected); /* should never happen */
+ loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, iend-ip);
+ }
+ ip += loadedSize;
+ zds->inPos += loadedSize;
+ if (loadedSize < toLoad) { someMoreWork = 0; break; } /* not enough input, wait for more */
+
+ /* decode loaded input */
+ { size_t const decodedSize = ZSTD_decompressContinue(zds,
+ zds->outBuff + zds->outStart, zds->outBuffSize - zds->outStart,
+ zds->inBuff, neededInSize);
+ if (ZSTD_isError(decodedSize)) return decodedSize;
+ zds->inPos = 0; /* input is consumed */
+ if (!decodedSize && !isSkipFrame) { zds->streamStage = zdss_read; break; } /* this was just a header */
+ zds->outEnd = zds->outStart + decodedSize;
+ } }
+ zds->streamStage = zdss_flush;
+ /* fall-through */
+
+ case zdss_flush:
+ { size_t const toFlushSize = zds->outEnd - zds->outStart;
+ size_t const flushedSize = ZSTD_limitCopy(op, oend-op, zds->outBuff + zds->outStart, toFlushSize);
+ op += flushedSize;
+ zds->outStart += flushedSize;
+ if (flushedSize == toFlushSize) { /* flush completed */
+ zds->streamStage = zdss_read;
+ if ( (zds->outBuffSize < zds->fParams.frameContentSize)
+ && (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) {
+ DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)",
+ (int)(zds->outBuffSize - zds->outStart),
+ (U32)zds->fParams.blockSizeMax);
+ zds->outStart = zds->outEnd = 0;
+ }
+ break;
+ } }
+ /* cannot complete flush */
+ someMoreWork = 0;
+ break;
+
+ default:
+ assert(0); /* impossible */
+ return ERROR(GENERIC); /* some compiler require default to do something */
+ } }
+
+ /* result */
+ input->pos = (size_t)(ip - (const char*)(input->src));
+ output->pos = (size_t)(op - (char*)(output->dst));
+ if ((ip==istart) && (op==ostart)) { /* no forward progress */
+ zds->noForwardProgress ++;
+ if (zds->noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX) {
+ if (op==oend) return ERROR(dstSize_tooSmall);
+ if (ip==iend) return ERROR(srcSize_wrong);
+ assert(0);
+ }
+ } else {
+ zds->noForwardProgress = 0;
+ }
+ { size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds);
+ if (!nextSrcSizeHint) { /* frame fully decoded */
+ if (zds->outEnd == zds->outStart) { /* output fully flushed */
+ if (zds->hostageByte) {
+ if (input->pos >= input->size) {
+ /* can't release hostage (not present) */
+ zds->streamStage = zdss_read;
+ return 1;
+ }
+ input->pos++; /* release hostage */
+ } /* zds->hostageByte */
+ return 0;
+ } /* zds->outEnd == zds->outStart */
+ if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */
+ input->pos--; /* note : pos > 0, otherwise, impossible to finish reading last block */
+ zds->hostageByte=1;
+ }
+ return 1;
+ } /* nextSrcSizeHint==0 */
+ nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block); /* preload header of next block */
+ assert(zds->inPos <= nextSrcSizeHint);
+ nextSrcSizeHint -= zds->inPos; /* part already loaded*/
+ return nextSrcSizeHint;
+ }
+}
+
+size_t ZSTD_decompressStream_simpleArgs (
+ ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity, size_t* dstPos,
+ const void* src, size_t srcSize, size_t* srcPos)
+{
+ ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
+ ZSTD_inBuffer input = { src, srcSize, *srcPos };
+ /* ZSTD_compress_generic() will check validity of dstPos and srcPos */
+ size_t const cErr = ZSTD_decompressStream(dctx, &output, &input);
+ *dstPos = output.pos;
+ *srcPos = input.pos;
+ return cErr;
+}
diff --git a/Utilities/cmzstd/lib/decompress/zstd_decompress_block.c b/Utilities/cmzstd/lib/decompress/zstd_decompress_block.c
new file mode 100644
index 000000000..32baad9fb
--- /dev/null
+++ b/Utilities/cmzstd/lib/decompress/zstd_decompress_block.c
@@ -0,0 +1,1307 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+/* zstd_decompress_block :
+ * this module takes care of decompressing _compressed_ block */
+
+/*-*******************************************************
+* Dependencies
+*********************************************************/
+#include <string.h> /* memcpy, memmove, memset */
+#include "compiler.h" /* prefetch */
+#include "cpu.h" /* bmi2 */
+#include "mem.h" /* low level memory routines */
+#define FSE_STATIC_LINKING_ONLY
+#include "fse.h"
+#define HUF_STATIC_LINKING_ONLY
+#include "huf.h"
+#include "zstd_internal.h"
+#include "zstd_decompress_internal.h" /* ZSTD_DCtx */
+#include "zstd_ddict.h" /* ZSTD_DDictDictContent */
+#include "zstd_decompress_block.h"
+
+/*_*******************************************************
+* Macros
+**********************************************************/
+
+/* These two optional macros force the use one way or another of the two
+ * ZSTD_decompressSequences implementations. You can't force in both directions
+ * at the same time.
+ */
+#if defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
+ defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
+#error "Cannot force the use of the short and the long ZSTD_decompressSequences variants!"
+#endif
+
+
+/*_*******************************************************
+* Memory operations
+**********************************************************/
+static void ZSTD_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
+
+
+/*-*************************************************************
+ * Block decoding
+ ***************************************************************/
+
+/*! ZSTD_getcBlockSize() :
+ * Provides the size of compressed block from block header `src` */
+size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
+ blockProperties_t* bpPtr)
+{
+ if (srcSize < ZSTD_blockHeaderSize) return ERROR(srcSize_wrong);
+ { U32 const cBlockHeader = MEM_readLE24(src);
+ U32 const cSize = cBlockHeader >> 3;
+ bpPtr->lastBlock = cBlockHeader & 1;
+ bpPtr->blockType = (blockType_e)((cBlockHeader >> 1) & 3);
+ bpPtr->origSize = cSize; /* only useful for RLE */
+ if (bpPtr->blockType == bt_rle) return 1;
+ if (bpPtr->blockType == bt_reserved) return ERROR(corruption_detected);
+ return cSize;
+ }
+}
+
+
+/* Hidden declaration for fullbench */
+size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
+ const void* src, size_t srcSize);
+/*! ZSTD_decodeLiteralsBlock() :
+ * @return : nb of bytes read from src (< srcSize )
+ * note : symbol not declared but exposed for fullbench */
+size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
+ const void* src, size_t srcSize) /* note : srcSize < BLOCKSIZE */
+{
+ if (srcSize < MIN_CBLOCK_SIZE) return ERROR(corruption_detected);
+
+ { const BYTE* const istart = (const BYTE*) src;
+ symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3);
+
+ switch(litEncType)
+ {
+ case set_repeat:
+ if (dctx->litEntropy==0) return ERROR(dictionary_corrupted);
+ /* fall-through */
+
+ case set_compressed:
+ if (srcSize < 5) return ERROR(corruption_detected); /* srcSize >= MIN_CBLOCK_SIZE == 3; here we need up to 5 for case 3 */
+ { size_t lhSize, litSize, litCSize;
+ U32 singleStream=0;
+ U32 const lhlCode = (istart[0] >> 2) & 3;
+ U32 const lhc = MEM_readLE32(istart);
+ size_t hufSuccess;
+ switch(lhlCode)
+ {
+ case 0: case 1: default: /* note : default is impossible, since lhlCode into [0..3] */
+ /* 2 - 2 - 10 - 10 */
+ singleStream = !lhlCode;
+ lhSize = 3;
+ litSize = (lhc >> 4) & 0x3FF;
+ litCSize = (lhc >> 14) & 0x3FF;
+ break;
+ case 2:
+ /* 2 - 2 - 14 - 14 */
+ lhSize = 4;
+ litSize = (lhc >> 4) & 0x3FFF;
+ litCSize = lhc >> 18;
+ break;
+ case 3:
+ /* 2 - 2 - 18 - 18 */
+ lhSize = 5;
+ litSize = (lhc >> 4) & 0x3FFFF;
+ litCSize = (lhc >> 22) + (istart[4] << 10);
+ break;
+ }
+ if (litSize > ZSTD_BLOCKSIZE_MAX) return ERROR(corruption_detected);
+ if (litCSize + lhSize > srcSize) return ERROR(corruption_detected);
+
+ /* prefetch huffman table if cold */
+ if (dctx->ddictIsCold && (litSize > 768 /* heuristic */)) {
+ PREFETCH_AREA(dctx->HUFptr, sizeof(dctx->entropy.hufTable));
+ }
+
+ if (litEncType==set_repeat) {
+ if (singleStream) {
+ hufSuccess = HUF_decompress1X_usingDTable_bmi2(
+ dctx->litBuffer, litSize, istart+lhSize, litCSize,
+ dctx->HUFptr, dctx->bmi2);
+ } else {
+ hufSuccess = HUF_decompress4X_usingDTable_bmi2(
+ dctx->litBuffer, litSize, istart+lhSize, litCSize,
+ dctx->HUFptr, dctx->bmi2);
+ }
+ } else {
+ if (singleStream) {
+#if defined(HUF_FORCE_DECOMPRESS_X2)
+ hufSuccess = HUF_decompress1X_DCtx_wksp(
+ dctx->entropy.hufTable, dctx->litBuffer, litSize,
+ istart+lhSize, litCSize, dctx->workspace,
+ sizeof(dctx->workspace));
+#else
+ hufSuccess = HUF_decompress1X1_DCtx_wksp_bmi2(
+ dctx->entropy.hufTable, dctx->litBuffer, litSize,
+ istart+lhSize, litCSize, dctx->workspace,
+ sizeof(dctx->workspace), dctx->bmi2);
+#endif
+ } else {
+ hufSuccess = HUF_decompress4X_hufOnly_wksp_bmi2(
+ dctx->entropy.hufTable, dctx->litBuffer, litSize,
+ istart+lhSize, litCSize, dctx->workspace,
+ sizeof(dctx->workspace), dctx->bmi2);
+ }
+ }
+
+ if (HUF_isError(hufSuccess)) return ERROR(corruption_detected);
+
+ dctx->litPtr = dctx->litBuffer;
+ dctx->litSize = litSize;
+ dctx->litEntropy = 1;
+ if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable;
+ memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
+ return litCSize + lhSize;
+ }
+
+ case set_basic:
+ { size_t litSize, lhSize;
+ U32 const lhlCode = ((istart[0]) >> 2) & 3;
+ switch(lhlCode)
+ {
+ case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */
+ lhSize = 1;
+ litSize = istart[0] >> 3;
+ break;
+ case 1:
+ lhSize = 2;
+ litSize = MEM_readLE16(istart) >> 4;
+ break;
+ case 3:
+ lhSize = 3;
+ litSize = MEM_readLE24(istart) >> 4;
+ break;
+ }
+
+ if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */
+ if (litSize+lhSize > srcSize) return ERROR(corruption_detected);
+ memcpy(dctx->litBuffer, istart+lhSize, litSize);
+ dctx->litPtr = dctx->litBuffer;
+ dctx->litSize = litSize;
+ memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
+ return lhSize+litSize;
+ }
+ /* direct reference into compressed stream */
+ dctx->litPtr = istart+lhSize;
+ dctx->litSize = litSize;
+ return lhSize+litSize;
+ }
+
+ case set_rle:
+ { U32 const lhlCode = ((istart[0]) >> 2) & 3;
+ size_t litSize, lhSize;
+ switch(lhlCode)
+ {
+ case 0: case 2: default: /* note : default is impossible, since lhlCode into [0..3] */
+ lhSize = 1;
+ litSize = istart[0] >> 3;
+ break;
+ case 1:
+ lhSize = 2;
+ litSize = MEM_readLE16(istart) >> 4;
+ break;
+ case 3:
+ lhSize = 3;
+ litSize = MEM_readLE24(istart) >> 4;
+ if (srcSize<4) return ERROR(corruption_detected); /* srcSize >= MIN_CBLOCK_SIZE == 3; here we need lhSize+1 = 4 */
+ break;
+ }
+ if (litSize > ZSTD_BLOCKSIZE_MAX) return ERROR(corruption_detected);
+ memset(dctx->litBuffer, istart[lhSize], litSize + WILDCOPY_OVERLENGTH);
+ dctx->litPtr = dctx->litBuffer;
+ dctx->litSize = litSize;
+ return lhSize+1;
+ }
+ default:
+ return ERROR(corruption_detected); /* impossible */
+ }
+ }
+}
+
+/* Default FSE distribution tables.
+ * These are pre-calculated FSE decoding tables using default distributions as defined in specification :
+ * https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#default-distributions
+ * They were generated programmatically with following method :
+ * - start from default distributions, present in /lib/common/zstd_internal.h
+ * - generate tables normally, using ZSTD_buildFSETable()
+ * - printout the content of tables
+ * - pretify output, report below, test with fuzzer to ensure it's correct */
+
+/* Default FSE distribution table for Literal Lengths */
+static const ZSTD_seqSymbol LL_defaultDTable[(1<<LL_DEFAULTNORMLOG)+1] = {
+ { 1, 1, 1, LL_DEFAULTNORMLOG}, /* header : fastMode, tableLog */
+ /* nextState, nbAddBits, nbBits, baseVal */
+ { 0, 0, 4, 0}, { 16, 0, 4, 0},
+ { 32, 0, 5, 1}, { 0, 0, 5, 3},
+ { 0, 0, 5, 4}, { 0, 0, 5, 6},
+ { 0, 0, 5, 7}, { 0, 0, 5, 9},
+ { 0, 0, 5, 10}, { 0, 0, 5, 12},
+ { 0, 0, 6, 14}, { 0, 1, 5, 16},
+ { 0, 1, 5, 20}, { 0, 1, 5, 22},
+ { 0, 2, 5, 28}, { 0, 3, 5, 32},
+ { 0, 4, 5, 48}, { 32, 6, 5, 64},
+ { 0, 7, 5, 128}, { 0, 8, 6, 256},
+ { 0, 10, 6, 1024}, { 0, 12, 6, 4096},
+ { 32, 0, 4, 0}, { 0, 0, 4, 1},
+ { 0, 0, 5, 2}, { 32, 0, 5, 4},
+ { 0, 0, 5, 5}, { 32, 0, 5, 7},
+ { 0, 0, 5, 8}, { 32, 0, 5, 10},
+ { 0, 0, 5, 11}, { 0, 0, 6, 13},
+ { 32, 1, 5, 16}, { 0, 1, 5, 18},
+ { 32, 1, 5, 22}, { 0, 2, 5, 24},
+ { 32, 3, 5, 32}, { 0, 3, 5, 40},
+ { 0, 6, 4, 64}, { 16, 6, 4, 64},
+ { 32, 7, 5, 128}, { 0, 9, 6, 512},
+ { 0, 11, 6, 2048}, { 48, 0, 4, 0},
+ { 16, 0, 4, 1}, { 32, 0, 5, 2},
+ { 32, 0, 5, 3}, { 32, 0, 5, 5},
+ { 32, 0, 5, 6}, { 32, 0, 5, 8},
+ { 32, 0, 5, 9}, { 32, 0, 5, 11},
+ { 32, 0, 5, 12}, { 0, 0, 6, 15},
+ { 32, 1, 5, 18}, { 32, 1, 5, 20},
+ { 32, 2, 5, 24}, { 32, 2, 5, 28},
+ { 32, 3, 5, 40}, { 32, 4, 5, 48},
+ { 0, 16, 6,65536}, { 0, 15, 6,32768},
+ { 0, 14, 6,16384}, { 0, 13, 6, 8192},
+}; /* LL_defaultDTable */
+
+/* Default FSE distribution table for Offset Codes */
+static const ZSTD_seqSymbol OF_defaultDTable[(1<<OF_DEFAULTNORMLOG)+1] = {
+ { 1, 1, 1, OF_DEFAULTNORMLOG}, /* header : fastMode, tableLog */
+ /* nextState, nbAddBits, nbBits, baseVal */
+ { 0, 0, 5, 0}, { 0, 6, 4, 61},
+ { 0, 9, 5, 509}, { 0, 15, 5,32765},
+ { 0, 21, 5,2097149}, { 0, 3, 5, 5},
+ { 0, 7, 4, 125}, { 0, 12, 5, 4093},
+ { 0, 18, 5,262141}, { 0, 23, 5,8388605},
+ { 0, 5, 5, 29}, { 0, 8, 4, 253},
+ { 0, 14, 5,16381}, { 0, 20, 5,1048573},
+ { 0, 2, 5, 1}, { 16, 7, 4, 125},
+ { 0, 11, 5, 2045}, { 0, 17, 5,131069},
+ { 0, 22, 5,4194301}, { 0, 4, 5, 13},
+ { 16, 8, 4, 253}, { 0, 13, 5, 8189},
+ { 0, 19, 5,524285}, { 0, 1, 5, 1},
+ { 16, 6, 4, 61}, { 0, 10, 5, 1021},
+ { 0, 16, 5,65533}, { 0, 28, 5,268435453},
+ { 0, 27, 5,134217725}, { 0, 26, 5,67108861},
+ { 0, 25, 5,33554429}, { 0, 24, 5,16777213},
+}; /* OF_defaultDTable */
+
+
+/* Default FSE distribution table for Match Lengths */
+static const ZSTD_seqSymbol ML_defaultDTable[(1<<ML_DEFAULTNORMLOG)+1] = {
+ { 1, 1, 1, ML_DEFAULTNORMLOG}, /* header : fastMode, tableLog */
+ /* nextState, nbAddBits, nbBits, baseVal */
+ { 0, 0, 6, 3}, { 0, 0, 4, 4},
+ { 32, 0, 5, 5}, { 0, 0, 5, 6},
+ { 0, 0, 5, 8}, { 0, 0, 5, 9},
+ { 0, 0, 5, 11}, { 0, 0, 6, 13},
+ { 0, 0, 6, 16}, { 0, 0, 6, 19},
+ { 0, 0, 6, 22}, { 0, 0, 6, 25},
+ { 0, 0, 6, 28}, { 0, 0, 6, 31},
+ { 0, 0, 6, 34}, { 0, 1, 6, 37},
+ { 0, 1, 6, 41}, { 0, 2, 6, 47},
+ { 0, 3, 6, 59}, { 0, 4, 6, 83},
+ { 0, 7, 6, 131}, { 0, 9, 6, 515},
+ { 16, 0, 4, 4}, { 0, 0, 4, 5},
+ { 32, 0, 5, 6}, { 0, 0, 5, 7},
+ { 32, 0, 5, 9}, { 0, 0, 5, 10},
+ { 0, 0, 6, 12}, { 0, 0, 6, 15},
+ { 0, 0, 6, 18}, { 0, 0, 6, 21},
+ { 0, 0, 6, 24}, { 0, 0, 6, 27},
+ { 0, 0, 6, 30}, { 0, 0, 6, 33},
+ { 0, 1, 6, 35}, { 0, 1, 6, 39},
+ { 0, 2, 6, 43}, { 0, 3, 6, 51},
+ { 0, 4, 6, 67}, { 0, 5, 6, 99},
+ { 0, 8, 6, 259}, { 32, 0, 4, 4},
+ { 48, 0, 4, 4}, { 16, 0, 4, 5},
+ { 32, 0, 5, 7}, { 32, 0, 5, 8},
+ { 32, 0, 5, 10}, { 32, 0, 5, 11},
+ { 0, 0, 6, 14}, { 0, 0, 6, 17},
+ { 0, 0, 6, 20}, { 0, 0, 6, 23},
+ { 0, 0, 6, 26}, { 0, 0, 6, 29},
+ { 0, 0, 6, 32}, { 0, 16, 6,65539},
+ { 0, 15, 6,32771}, { 0, 14, 6,16387},
+ { 0, 13, 6, 8195}, { 0, 12, 6, 4099},
+ { 0, 11, 6, 2051}, { 0, 10, 6, 1027},
+}; /* ML_defaultDTable */
+
+
+static void ZSTD_buildSeqTable_rle(ZSTD_seqSymbol* dt, U32 baseValue, U32 nbAddBits)
+{
+ void* ptr = dt;
+ ZSTD_seqSymbol_header* const DTableH = (ZSTD_seqSymbol_header*)ptr;
+ ZSTD_seqSymbol* const cell = dt + 1;
+
+ DTableH->tableLog = 0;
+ DTableH->fastMode = 0;
+
+ cell->nbBits = 0;
+ cell->nextState = 0;
+ assert(nbAddBits < 255);
+ cell->nbAdditionalBits = (BYTE)nbAddBits;
+ cell->baseValue = baseValue;
+}
+
+
+/* ZSTD_buildFSETable() :
+ * generate FSE decoding table for one symbol (ll, ml or off)
+ * cannot fail if input is valid =>
+ * all inputs are presumed validated at this stage */
+void
+ZSTD_buildFSETable(ZSTD_seqSymbol* dt,
+ const short* normalizedCounter, unsigned maxSymbolValue,
+ const U32* baseValue, const U32* nbAdditionalBits,
+ unsigned tableLog)
+{
+ ZSTD_seqSymbol* const tableDecode = dt+1;
+ U16 symbolNext[MaxSeq+1];
+
+ U32 const maxSV1 = maxSymbolValue + 1;
+ U32 const tableSize = 1 << tableLog;
+ U32 highThreshold = tableSize-1;
+
+ /* Sanity Checks */
+ assert(maxSymbolValue <= MaxSeq);
+ assert(tableLog <= MaxFSELog);
+
+ /* Init, lay down lowprob symbols */
+ { ZSTD_seqSymbol_header DTableH;
+ DTableH.tableLog = tableLog;
+ DTableH.fastMode = 1;
+ { S16 const largeLimit= (S16)(1 << (tableLog-1));
+ U32 s;
+ for (s=0; s<maxSV1; s++) {
+ if (normalizedCounter[s]==-1) {
+ tableDecode[highThreshold--].baseValue = s;
+ symbolNext[s] = 1;
+ } else {
+ if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
+ symbolNext[s] = normalizedCounter[s];
+ } } }
+ memcpy(dt, &DTableH, sizeof(DTableH));
+ }
+
+ /* Spread symbols */
+ { U32 const tableMask = tableSize-1;
+ U32 const step = FSE_TABLESTEP(tableSize);
+ U32 s, position = 0;
+ for (s=0; s<maxSV1; s++) {
+ int i;
+ for (i=0; i<normalizedCounter[s]; i++) {
+ tableDecode[position].baseValue = s;
+ position = (position + step) & tableMask;
+ while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
+ } }
+ assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
+ }
+
+ /* Build Decoding table */
+ { U32 u;
+ for (u=0; u<tableSize; u++) {
+ U32 const symbol = tableDecode[u].baseValue;
+ U32 const nextState = symbolNext[symbol]++;
+ tableDecode[u].nbBits = (BYTE) (tableLog - BIT_highbit32(nextState) );
+ tableDecode[u].nextState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
+ assert(nbAdditionalBits[symbol] < 255);
+ tableDecode[u].nbAdditionalBits = (BYTE)nbAdditionalBits[symbol];
+ tableDecode[u].baseValue = baseValue[symbol];
+ } }
+}
+
+
+/*! ZSTD_buildSeqTable() :
+ * @return : nb bytes read from src,
+ * or an error code if it fails */
+static size_t ZSTD_buildSeqTable(ZSTD_seqSymbol* DTableSpace, const ZSTD_seqSymbol** DTablePtr,
+ symbolEncodingType_e type, unsigned max, U32 maxLog,
+ const void* src, size_t srcSize,
+ const U32* baseValue, const U32* nbAdditionalBits,
+ const ZSTD_seqSymbol* defaultTable, U32 flagRepeatTable,
+ int ddictIsCold, int nbSeq)
+{
+ switch(type)
+ {
+ case set_rle :
+ if (!srcSize) return ERROR(srcSize_wrong);
+ if ( (*(const BYTE*)src) > max) return ERROR(corruption_detected);
+ { U32 const symbol = *(const BYTE*)src;
+ U32 const baseline = baseValue[symbol];
+ U32 const nbBits = nbAdditionalBits[symbol];
+ ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits);
+ }
+ *DTablePtr = DTableSpace;
+ return 1;
+ case set_basic :
+ *DTablePtr = defaultTable;
+ return 0;
+ case set_repeat:
+ if (!flagRepeatTable) return ERROR(corruption_detected);
+ /* prefetch FSE table if used */
+ if (ddictIsCold && (nbSeq > 24 /* heuristic */)) {
+ const void* const pStart = *DTablePtr;
+ size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog));
+ PREFETCH_AREA(pStart, pSize);
+ }
+ return 0;
+ case set_compressed :
+ { unsigned tableLog;
+ S16 norm[MaxSeq+1];
+ size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);
+ if (FSE_isError(headerSize)) return ERROR(corruption_detected);
+ if (tableLog > maxLog) return ERROR(corruption_detected);
+ ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog);
+ *DTablePtr = DTableSpace;
+ return headerSize;
+ }
+ default : /* impossible */
+ assert(0);
+ return ERROR(GENERIC);
+ }
+}
+
+size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
+ const void* src, size_t srcSize)
+{
+ const BYTE* const istart = (const BYTE* const)src;
+ const BYTE* const iend = istart + srcSize;
+ const BYTE* ip = istart;
+ int nbSeq;
+ DEBUGLOG(5, "ZSTD_decodeSeqHeaders");
+
+ /* check */
+ if (srcSize < MIN_SEQUENCES_SIZE) return ERROR(srcSize_wrong);
+
+ /* SeqHead */
+ nbSeq = *ip++;
+ if (!nbSeq) {
+ *nbSeqPtr=0;
+ if (srcSize != 1) return ERROR(srcSize_wrong);
+ return 1;
+ }
+ if (nbSeq > 0x7F) {
+ if (nbSeq == 0xFF) {
+ if (ip+2 > iend) return ERROR(srcSize_wrong);
+ nbSeq = MEM_readLE16(ip) + LONGNBSEQ, ip+=2;
+ } else {
+ if (ip >= iend) return ERROR(srcSize_wrong);
+ nbSeq = ((nbSeq-0x80)<<8) + *ip++;
+ }
+ }
+ *nbSeqPtr = nbSeq;
+
+ /* FSE table descriptors */
+ if (ip+4 > iend) return ERROR(srcSize_wrong); /* minimum possible size */
+ { symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6);
+ symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3);
+ symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3);
+ ip++;
+
+ /* Build DTables */
+ { size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr,
+ LLtype, MaxLL, LLFSELog,
+ ip, iend-ip,
+ LL_base, LL_bits,
+ LL_defaultDTable, dctx->fseEntropy,
+ dctx->ddictIsCold, nbSeq);
+ if (ZSTD_isError(llhSize)) return ERROR(corruption_detected);
+ ip += llhSize;
+ }
+
+ { size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr,
+ OFtype, MaxOff, OffFSELog,
+ ip, iend-ip,
+ OF_base, OF_bits,
+ OF_defaultDTable, dctx->fseEntropy,
+ dctx->ddictIsCold, nbSeq);
+ if (ZSTD_isError(ofhSize)) return ERROR(corruption_detected);
+ ip += ofhSize;
+ }
+
+ { size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr,
+ MLtype, MaxML, MLFSELog,
+ ip, iend-ip,
+ ML_base, ML_bits,
+ ML_defaultDTable, dctx->fseEntropy,
+ dctx->ddictIsCold, nbSeq);
+ if (ZSTD_isError(mlhSize)) return ERROR(corruption_detected);
+ ip += mlhSize;
+ }
+ }
+
+ return ip-istart;
+}
+
+
+typedef struct {
+ size_t litLength;
+ size_t matchLength;
+ size_t offset;
+ const BYTE* match;
+} seq_t;
+
+typedef struct {
+ size_t state;
+ const ZSTD_seqSymbol* table;
+} ZSTD_fseState;
+
+typedef struct {
+ BIT_DStream_t DStream;
+ ZSTD_fseState stateLL;
+ ZSTD_fseState stateOffb;
+ ZSTD_fseState stateML;
+ size_t prevOffset[ZSTD_REP_NUM];
+ const BYTE* prefixStart;
+ const BYTE* dictEnd;
+ size_t pos;
+} seqState_t;
+
+
+/* ZSTD_execSequenceLast7():
+ * exceptional case : decompress a match starting within last 7 bytes of output buffer.
+ * requires more careful checks, to ensure there is no overflow.
+ * performance does not matter though.
+ * note : this case is supposed to be never generated "naturally" by reference encoder,
+ * since in most cases it needs at least 8 bytes to look for a match.
+ * but it's allowed by the specification. */
+FORCE_NOINLINE
+size_t ZSTD_execSequenceLast7(BYTE* op,
+ BYTE* const oend, seq_t sequence,
+ const BYTE** litPtr, const BYTE* const litLimit,
+ const BYTE* const base, const BYTE* const vBase, const BYTE* const dictEnd)
+{
+ BYTE* const oLitEnd = op + sequence.litLength;
+ size_t const sequenceLength = sequence.litLength + sequence.matchLength;
+ BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
+ const BYTE* const iLitEnd = *litPtr + sequence.litLength;
+ const BYTE* match = oLitEnd - sequence.offset;
+
+ /* check */
+ if (oMatchEnd>oend) return ERROR(dstSize_tooSmall); /* last match must fit within dstBuffer */
+ if (iLitEnd > litLimit) return ERROR(corruption_detected); /* try to read beyond literal buffer */
+
+ /* copy literals */
+ while (op < oLitEnd) *op++ = *(*litPtr)++;
+
+ /* copy Match */
+ if (sequence.offset > (size_t)(oLitEnd - base)) {
+ /* offset beyond prefix */
+ if (sequence.offset > (size_t)(oLitEnd - vBase)) return ERROR(corruption_detected);
+ match = dictEnd - (base-match);
+ if (match + sequence.matchLength <= dictEnd) {
+ memmove(oLitEnd, match, sequence.matchLength);
+ return sequenceLength;
+ }
+ /* span extDict & currentPrefixSegment */
+ { size_t const length1 = dictEnd - match;
+ memmove(oLitEnd, match, length1);
+ op = oLitEnd + length1;
+ sequence.matchLength -= length1;
+ match = base;
+ } }
+ while (op < oMatchEnd) *op++ = *match++;
+ return sequenceLength;
+}
+
+
+HINT_INLINE
+size_t ZSTD_execSequence(BYTE* op,
+ BYTE* const oend, seq_t sequence,
+ const BYTE** litPtr, const BYTE* const litLimit,
+ const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
+{
+ BYTE* const oLitEnd = op + sequence.litLength;
+ size_t const sequenceLength = sequence.litLength + sequence.matchLength;
+ BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
+ BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
+ const BYTE* const iLitEnd = *litPtr + sequence.litLength;
+ const BYTE* match = oLitEnd - sequence.offset;
+
+ /* check */
+ if (oMatchEnd>oend) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend */
+ if (iLitEnd > litLimit) return ERROR(corruption_detected); /* over-read beyond lit buffer */
+ if (oLitEnd>oend_w) return ZSTD_execSequenceLast7(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);
+
+ /* copy Literals */
+ ZSTD_copy8(op, *litPtr);
+ if (sequence.litLength > 8)
+ ZSTD_wildcopy(op+8, (*litPtr)+8, sequence.litLength - 8); /* note : since oLitEnd <= oend-WILDCOPY_OVERLENGTH, no risk of overwrite beyond oend */
+ op = oLitEnd;
+ *litPtr = iLitEnd; /* update for next sequence */
+
+ /* copy Match */
+ if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
+ /* offset beyond prefix -> go into extDict */
+ if (sequence.offset > (size_t)(oLitEnd - virtualStart))
+ return ERROR(corruption_detected);
+ match = dictEnd + (match - prefixStart);
+ if (match + sequence.matchLength <= dictEnd) {
+ memmove(oLitEnd, match, sequence.matchLength);
+ return sequenceLength;
+ }
+ /* span extDict & currentPrefixSegment */
+ { size_t const length1 = dictEnd - match;
+ memmove(oLitEnd, match, length1);
+ op = oLitEnd + length1;
+ sequence.matchLength -= length1;
+ match = prefixStart;
+ if (op > oend_w || sequence.matchLength < MINMATCH) {
+ U32 i;
+ for (i = 0; i < sequence.matchLength; ++i) op[i] = match[i];
+ return sequenceLength;
+ }
+ } }
+ /* Requirement: op <= oend_w && sequence.matchLength >= MINMATCH */
+
+ /* match within prefix */
+ if (sequence.offset < 8) {
+ /* close range match, overlap */
+ static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
+ static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */
+ int const sub2 = dec64table[sequence.offset];
+ op[0] = match[0];
+ op[1] = match[1];
+ op[2] = match[2];
+ op[3] = match[3];
+ match += dec32table[sequence.offset];
+ ZSTD_copy4(op+4, match);
+ match -= sub2;
+ } else {
+ ZSTD_copy8(op, match);
+ }
+ op += 8; match += 8;
+
+ if (oMatchEnd > oend-(16-MINMATCH)) {
+ if (op < oend_w) {
+ ZSTD_wildcopy(op, match, oend_w - op);
+ match += oend_w - op;
+ op = oend_w;
+ }
+ while (op < oMatchEnd) *op++ = *match++;
+ } else {
+ ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8); /* works even if matchLength < 8 */
+ }
+ return sequenceLength;
+}
+
+
+HINT_INLINE
+size_t ZSTD_execSequenceLong(BYTE* op,
+ BYTE* const oend, seq_t sequence,
+ const BYTE** litPtr, const BYTE* const litLimit,
+ const BYTE* const prefixStart, const BYTE* const dictStart, const BYTE* const dictEnd)
+{
+ BYTE* const oLitEnd = op + sequence.litLength;
+ size_t const sequenceLength = sequence.litLength + sequence.matchLength;
+ BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
+ BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;
+ const BYTE* const iLitEnd = *litPtr + sequence.litLength;
+ const BYTE* match = sequence.match;
+
+ /* check */
+ if (oMatchEnd > oend) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend */
+ if (iLitEnd > litLimit) return ERROR(corruption_detected); /* over-read beyond lit buffer */
+ if (oLitEnd > oend_w) return ZSTD_execSequenceLast7(op, oend, sequence, litPtr, litLimit, prefixStart, dictStart, dictEnd);
+
+ /* copy Literals */
+ ZSTD_copy8(op, *litPtr); /* note : op <= oLitEnd <= oend_w == oend - 8 */
+ if (sequence.litLength > 8)
+ ZSTD_wildcopy(op+8, (*litPtr)+8, sequence.litLength - 8); /* note : since oLitEnd <= oend-WILDCOPY_OVERLENGTH, no risk of overwrite beyond oend */
+ op = oLitEnd;
+ *litPtr = iLitEnd; /* update for next sequence */
+
+ /* copy Match */
+ if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
+ /* offset beyond prefix */
+ if (sequence.offset > (size_t)(oLitEnd - dictStart)) return ERROR(corruption_detected);
+ if (match + sequence.matchLength <= dictEnd) {
+ memmove(oLitEnd, match, sequence.matchLength);
+ return sequenceLength;
+ }
+ /* span extDict & currentPrefixSegment */
+ { size_t const length1 = dictEnd - match;
+ memmove(oLitEnd, match, length1);
+ op = oLitEnd + length1;
+ sequence.matchLength -= length1;
+ match = prefixStart;
+ if (op > oend_w || sequence.matchLength < MINMATCH) {
+ U32 i;
+ for (i = 0; i < sequence.matchLength; ++i) op[i] = match[i];
+ return sequenceLength;
+ }
+ } }
+ assert(op <= oend_w);
+ assert(sequence.matchLength >= MINMATCH);
+
+ /* match within prefix */
+ if (sequence.offset < 8) {
+ /* close range match, overlap */
+ static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
+ static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */
+ int const sub2 = dec64table[sequence.offset];
+ op[0] = match[0];
+ op[1] = match[1];
+ op[2] = match[2];
+ op[3] = match[3];
+ match += dec32table[sequence.offset];
+ ZSTD_copy4(op+4, match);
+ match -= sub2;
+ } else {
+ ZSTD_copy8(op, match);
+ }
+ op += 8; match += 8;
+
+ if (oMatchEnd > oend-(16-MINMATCH)) {
+ if (op < oend_w) {
+ ZSTD_wildcopy(op, match, oend_w - op);
+ match += oend_w - op;
+ op = oend_w;
+ }
+ while (op < oMatchEnd) *op++ = *match++;
+ } else {
+ ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8); /* works even if matchLength < 8 */
+ }
+ return sequenceLength;
+}
+
+static void
+ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt)
+{
+ const void* ptr = dt;
+ const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr;
+ DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
+ DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits",
+ (U32)DStatePtr->state, DTableH->tableLog);
+ BIT_reloadDStream(bitD);
+ DStatePtr->table = dt + 1;
+}
+
+FORCE_INLINE_TEMPLATE void
+ZSTD_updateFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD)
+{
+ ZSTD_seqSymbol const DInfo = DStatePtr->table[DStatePtr->state];
+ U32 const nbBits = DInfo.nbBits;
+ size_t const lowBits = BIT_readBits(bitD, nbBits);
+ DStatePtr->state = DInfo.nextState + lowBits;
+}
+
+/* We need to add at most (ZSTD_WINDOWLOG_MAX_32 - 1) bits to read the maximum
+ * offset bits. But we can only read at most (STREAM_ACCUMULATOR_MIN_32 - 1)
+ * bits before reloading. This value is the maximum number of bytes we read
+ * after reloading when we are decoding long offets.
+ */
+#define LONG_OFFSETS_MAX_EXTRA_BITS_32 \
+ (ZSTD_WINDOWLOG_MAX_32 > STREAM_ACCUMULATOR_MIN_32 \
+ ? ZSTD_WINDOWLOG_MAX_32 - STREAM_ACCUMULATOR_MIN_32 \
+ : 0)
+
+typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e;
+
+#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
+FORCE_INLINE_TEMPLATE seq_t
+ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets)
+{
+ seq_t seq;
+ U32 const llBits = seqState->stateLL.table[seqState->stateLL.state].nbAdditionalBits;
+ U32 const mlBits = seqState->stateML.table[seqState->stateML.state].nbAdditionalBits;
+ U32 const ofBits = seqState->stateOffb.table[seqState->stateOffb.state].nbAdditionalBits;
+ U32 const totalBits = llBits+mlBits+ofBits;
+ U32 const llBase = seqState->stateLL.table[seqState->stateLL.state].baseValue;
+ U32 const mlBase = seqState->stateML.table[seqState->stateML.state].baseValue;
+ U32 const ofBase = seqState->stateOffb.table[seqState->stateOffb.state].baseValue;
+
+ /* sequence */
+ { size_t offset;
+ if (!ofBits)
+ offset = 0;
+ else {
+ ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
+ ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
+ assert(ofBits <= MaxOff);
+ if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {
+ U32 const extraBits = ofBits - MIN(ofBits, 32 - seqState->DStream.bitsConsumed);
+ offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
+ BIT_reloadDStream(&seqState->DStream);
+ if (extraBits) offset += BIT_readBitsFast(&seqState->DStream, extraBits);
+ assert(extraBits <= LONG_OFFSETS_MAX_EXTRA_BITS_32); /* to avoid another reload */
+ } else {
+ offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
+ if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
+ }
+ }
+
+ if (ofBits <= 1) {
+ offset += (llBase==0);
+ if (offset) {
+ size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
+ temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */
+ if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
+ seqState->prevOffset[1] = seqState->prevOffset[0];
+ seqState->prevOffset[0] = offset = temp;
+ } else { /* offset == 0 */
+ offset = seqState->prevOffset[0];
+ }
+ } else {
+ seqState->prevOffset[2] = seqState->prevOffset[1];
+ seqState->prevOffset[1] = seqState->prevOffset[0];
+ seqState->prevOffset[0] = offset;
+ }
+ seq.offset = offset;
+ }
+
+ seq.matchLength = mlBase
+ + ((mlBits>0) ? BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/) : 0); /* <= 16 bits */
+ if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
+ BIT_reloadDStream(&seqState->DStream);
+ if (MEM_64bits() && (totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
+ BIT_reloadDStream(&seqState->DStream);
+ /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
+ ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
+
+ seq.litLength = llBase
+ + ((llBits>0) ? BIT_readBitsFast(&seqState->DStream, llBits/*>0*/) : 0); /* <= 16 bits */
+ if (MEM_32bits())
+ BIT_reloadDStream(&seqState->DStream);
+
+ DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
+ (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
+
+ /* ANS state update */
+ ZSTD_updateFseState(&seqState->stateLL, &seqState->DStream); /* <= 9 bits */
+ ZSTD_updateFseState(&seqState->stateML, &seqState->DStream); /* <= 9 bits */
+ if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
+ ZSTD_updateFseState(&seqState->stateOffb, &seqState->DStream); /* <= 8 bits */
+
+ return seq;
+}
+
+FORCE_INLINE_TEMPLATE size_t
+ZSTD_decompressSequences_body( ZSTD_DCtx* dctx,
+ void* dst, size_t maxDstSize,
+ const void* seqStart, size_t seqSize, int nbSeq,
+ const ZSTD_longOffset_e isLongOffset)
+{
+ const BYTE* ip = (const BYTE*)seqStart;
+ const BYTE* const iend = ip + seqSize;
+ BYTE* const ostart = (BYTE* const)dst;
+ BYTE* const oend = ostart + maxDstSize;
+ BYTE* op = ostart;
+ const BYTE* litPtr = dctx->litPtr;
+ const BYTE* const litEnd = litPtr + dctx->litSize;
+ const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
+ const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);
+ const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
+ DEBUGLOG(5, "ZSTD_decompressSequences_body");
+
+ /* Regen sequences */
+ if (nbSeq) {
+ seqState_t seqState;
+ dctx->fseEntropy = 1;
+ { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
+ CHECK_E(BIT_initDStream(&seqState.DStream, ip, iend-ip), corruption_detected);
+ ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
+ ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
+ ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
+
+ for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && nbSeq ; ) {
+ nbSeq--;
+ { seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset);
+ size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);
+ DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
+ if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
+ op += oneSeqSize;
+ } }
+
+ /* check if reached exact end */
+ DEBUGLOG(5, "ZSTD_decompressSequences_body: after decode loop, remaining nbSeq : %i", nbSeq);
+ if (nbSeq) return ERROR(corruption_detected);
+ /* save reps for next block */
+ { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
+ }
+
+ /* last literal segment */
+ { size_t const lastLLSize = litEnd - litPtr;
+ if (lastLLSize > (size_t)(oend-op)) return ERROR(dstSize_tooSmall);
+ memcpy(op, litPtr, lastLLSize);
+ op += lastLLSize;
+ }
+
+ return op-ostart;
+}
+
+static size_t
+ZSTD_decompressSequences_default(ZSTD_DCtx* dctx,
+ void* dst, size_t maxDstSize,
+ const void* seqStart, size_t seqSize, int nbSeq,
+ const ZSTD_longOffset_e isLongOffset)
+{
+ return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
+}
+#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
+
+
+
+#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
+FORCE_INLINE_TEMPLATE seq_t
+ZSTD_decodeSequenceLong(seqState_t* seqState, ZSTD_longOffset_e const longOffsets)
+{
+ seq_t seq;
+ U32 const llBits = seqState->stateLL.table[seqState->stateLL.state].nbAdditionalBits;
+ U32 const mlBits = seqState->stateML.table[seqState->stateML.state].nbAdditionalBits;
+ U32 const ofBits = seqState->stateOffb.table[seqState->stateOffb.state].nbAdditionalBits;
+ U32 const totalBits = llBits+mlBits+ofBits;
+ U32 const llBase = seqState->stateLL.table[seqState->stateLL.state].baseValue;
+ U32 const mlBase = seqState->stateML.table[seqState->stateML.state].baseValue;
+ U32 const ofBase = seqState->stateOffb.table[seqState->stateOffb.state].baseValue;
+
+ /* sequence */
+ { size_t offset;
+ if (!ofBits)
+ offset = 0;
+ else {
+ ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
+ ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
+ assert(ofBits <= MaxOff);
+ if (MEM_32bits() && longOffsets) {
+ U32 const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN_32-1);
+ offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
+ if (MEM_32bits() || extraBits) BIT_reloadDStream(&seqState->DStream);
+ if (extraBits) offset += BIT_readBitsFast(&seqState->DStream, extraBits);
+ } else {
+ offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits); /* <= (ZSTD_WINDOWLOG_MAX-1) bits */
+ if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
+ }
+ }
+
+ if (ofBits <= 1) {
+ offset += (llBase==0);
+ if (offset) {
+ size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
+ temp += !temp; /* 0 is not valid; input is corrupted; force offset to 1 */
+ if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
+ seqState->prevOffset[1] = seqState->prevOffset[0];
+ seqState->prevOffset[0] = offset = temp;
+ } else {
+ offset = seqState->prevOffset[0];
+ }
+ } else {
+ seqState->prevOffset[2] = seqState->prevOffset[1];
+ seqState->prevOffset[1] = seqState->prevOffset[0];
+ seqState->prevOffset[0] = offset;
+ }
+ seq.offset = offset;
+ }
+
+ seq.matchLength = mlBase + ((mlBits>0) ? BIT_readBitsFast(&seqState->DStream, mlBits) : 0); /* <= 16 bits */
+ if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
+ BIT_reloadDStream(&seqState->DStream);
+ if (MEM_64bits() && (totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
+ BIT_reloadDStream(&seqState->DStream);
+ /* Verify that there is enough bits to read the rest of the data in 64-bit mode. */
+ ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);
+
+ seq.litLength = llBase + ((llBits>0) ? BIT_readBitsFast(&seqState->DStream, llBits) : 0); /* <= 16 bits */
+ if (MEM_32bits())
+ BIT_reloadDStream(&seqState->DStream);
+
+ { size_t const pos = seqState->pos + seq.litLength;
+ const BYTE* const matchBase = (seq.offset > pos) ? seqState->dictEnd : seqState->prefixStart;
+ seq.match = matchBase + pos - seq.offset; /* note : this operation can overflow when seq.offset is really too large, which can only happen when input is corrupted.
+ * No consequence though : no memory access will occur, overly large offset will be detected in ZSTD_execSequenceLong() */
+ seqState->pos = pos + seq.matchLength;
+ }
+
+ /* ANS state update */
+ ZSTD_updateFseState(&seqState->stateLL, &seqState->DStream); /* <= 9 bits */
+ ZSTD_updateFseState(&seqState->stateML, &seqState->DStream); /* <= 9 bits */
+ if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream); /* <= 18 bits */
+ ZSTD_updateFseState(&seqState->stateOffb, &seqState->DStream); /* <= 8 bits */
+
+ return seq;
+}
+
+FORCE_INLINE_TEMPLATE size_t
+ZSTD_decompressSequencesLong_body(
+ ZSTD_DCtx* dctx,
+ void* dst, size_t maxDstSize,
+ const void* seqStart, size_t seqSize, int nbSeq,
+ const ZSTD_longOffset_e isLongOffset)
+{
+ const BYTE* ip = (const BYTE*)seqStart;
+ const BYTE* const iend = ip + seqSize;
+ BYTE* const ostart = (BYTE* const)dst;
+ BYTE* const oend = ostart + maxDstSize;
+ BYTE* op = ostart;
+ const BYTE* litPtr = dctx->litPtr;
+ const BYTE* const litEnd = litPtr + dctx->litSize;
+ const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
+ const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
+ const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
+
+ /* Regen sequences */
+ if (nbSeq) {
+#define STORED_SEQS 4
+#define STORED_SEQS_MASK (STORED_SEQS-1)
+#define ADVANCED_SEQS 4
+ seq_t sequences[STORED_SEQS];
+ int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
+ seqState_t seqState;
+ int seqNb;
+ dctx->fseEntropy = 1;
+ { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
+ seqState.prefixStart = prefixStart;
+ seqState.pos = (size_t)(op-prefixStart);
+ seqState.dictEnd = dictEnd;
+ assert(iend >= ip);
+ CHECK_E(BIT_initDStream(&seqState.DStream, ip, iend-ip), corruption_detected);
+ ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
+ ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
+ ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
+
+ /* prepare in advance */
+ for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && (seqNb<seqAdvance); seqNb++) {
+ sequences[seqNb] = ZSTD_decodeSequenceLong(&seqState, isLongOffset);
+ PREFETCH_L1(sequences[seqNb].match); PREFETCH_L1(sequences[seqNb].match + sequences[seqNb].matchLength - 1); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
+ }
+ if (seqNb<seqAdvance) return ERROR(corruption_detected);
+
+ /* decode and decompress */
+ for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (seqNb<nbSeq) ; seqNb++) {
+ seq_t const sequence = ZSTD_decodeSequenceLong(&seqState, isLongOffset);
+ size_t const oneSeqSize = ZSTD_execSequenceLong(op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
+ if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
+ PREFETCH_L1(sequence.match); PREFETCH_L1(sequence.match + sequence.matchLength - 1); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
+ sequences[seqNb & STORED_SEQS_MASK] = sequence;
+ op += oneSeqSize;
+ }
+ if (seqNb<nbSeq) return ERROR(corruption_detected);
+
+ /* finish queue */
+ seqNb -= seqAdvance;
+ for ( ; seqNb<nbSeq ; seqNb++) {
+ size_t const oneSeqSize = ZSTD_execSequenceLong(op, oend, sequences[seqNb&STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
+ if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
+ op += oneSeqSize;
+ }
+
+ /* save reps for next block */
+ { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
+ }
+
+ /* last literal segment */
+ { size_t const lastLLSize = litEnd - litPtr;
+ if (lastLLSize > (size_t)(oend-op)) return ERROR(dstSize_tooSmall);
+ memcpy(op, litPtr, lastLLSize);
+ op += lastLLSize;
+ }
+
+ return op-ostart;
+}
+
+static size_t
+ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx,
+ void* dst, size_t maxDstSize,
+ const void* seqStart, size_t seqSize, int nbSeq,
+ const ZSTD_longOffset_e isLongOffset)
+{
+ return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
+}
+#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
+
+
+
+#if DYNAMIC_BMI2
+
+#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
+static TARGET_ATTRIBUTE("bmi2") size_t
+ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx,
+ void* dst, size_t maxDstSize,
+ const void* seqStart, size_t seqSize, int nbSeq,
+ const ZSTD_longOffset_e isLongOffset)
+{
+ return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
+}
+#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
+
+#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
+static TARGET_ATTRIBUTE("bmi2") size_t
+ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx,
+ void* dst, size_t maxDstSize,
+ const void* seqStart, size_t seqSize, int nbSeq,
+ const ZSTD_longOffset_e isLongOffset)
+{
+ return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
+}
+#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
+
+#endif /* DYNAMIC_BMI2 */
+
+typedef size_t (*ZSTD_decompressSequences_t)(
+ ZSTD_DCtx* dctx,
+ void* dst, size_t maxDstSize,
+ const void* seqStart, size_t seqSize, int nbSeq,
+ const ZSTD_longOffset_e isLongOffset);
+
+#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
+static size_t
+ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
+ const void* seqStart, size_t seqSize, int nbSeq,
+ const ZSTD_longOffset_e isLongOffset)
+{
+ DEBUGLOG(5, "ZSTD_decompressSequences");
+#if DYNAMIC_BMI2
+ if (dctx->bmi2) {
+ return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
+ }
+#endif
+ return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
+}
+#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */
+
+
+#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
+/* ZSTD_decompressSequencesLong() :
+ * decompression function triggered when a minimum share of offsets is considered "long",
+ * aka out of cache.
+ * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes mearning "farther than memory cache distance".
+ * This function will try to mitigate main memory latency through the use of prefetching */
+static size_t
+ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx,
+ void* dst, size_t maxDstSize,
+ const void* seqStart, size_t seqSize, int nbSeq,
+ const ZSTD_longOffset_e isLongOffset)
+{
+ DEBUGLOG(5, "ZSTD_decompressSequencesLong");
+#if DYNAMIC_BMI2
+ if (dctx->bmi2) {
+ return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
+ }
+#endif
+ return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset);
+}
+#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */
+
+
+
+#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
+ !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
+/* ZSTD_getLongOffsetsShare() :
+ * condition : offTable must be valid
+ * @return : "share" of long offsets (arbitrarily defined as > (1<<23))
+ * compared to maximum possible of (1<<OffFSELog) */
+static unsigned
+ZSTD_getLongOffsetsShare(const ZSTD_seqSymbol* offTable)
+{
+ const void* ptr = offTable;
+ U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;
+ const ZSTD_seqSymbol* table = offTable + 1;
+ U32 const max = 1 << tableLog;
+ U32 u, total = 0;
+ DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);
+
+ assert(max <= (1 << OffFSELog)); /* max not too large */
+ for (u=0; u<max; u++) {
+ if (table[u].nbAdditionalBits > 22) total += 1;
+ }
+
+ assert(tableLog <= OffFSELog);
+ total <<= (OffFSELog - tableLog); /* scale to OffFSELog */
+
+ return total;
+}
+#endif
+
+
+size_t
+ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize, const int frame)
+{ /* blockType == blockCompressed */
+ const BYTE* ip = (const BYTE*)src;
+ /* isLongOffset must be true if there are long offsets.
+ * Offsets are long if they are larger than 2^STREAM_ACCUMULATOR_MIN.
+ * We don't expect that to be the case in 64-bit mode.
+ * In block mode, window size is not known, so we have to be conservative.
+ * (note: but it could be evaluated from current-lowLimit)
+ */
+ ZSTD_longOffset_e const isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (!frame || (dctx->fParams.windowSize > (1ULL << STREAM_ACCUMULATOR_MIN))));
+ DEBUGLOG(5, "ZSTD_decompressBlock_internal (size : %u)", (U32)srcSize);
+
+ if (srcSize >= ZSTD_BLOCKSIZE_MAX) return ERROR(srcSize_wrong);
+
+ /* Decode literals section */
+ { size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize);
+ DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : %u", (U32)litCSize);
+ if (ZSTD_isError(litCSize)) return litCSize;
+ ip += litCSize;
+ srcSize -= litCSize;
+ }
+
+ /* Build Decoding Tables */
+ {
+ /* These macros control at build-time which decompressor implementation
+ * we use. If neither is defined, we do some inspection and dispatch at
+ * runtime.
+ */
+#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
+ !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
+ int usePrefetchDecoder = dctx->ddictIsCold;
+#endif
+ int nbSeq;
+ size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);
+ if (ZSTD_isError(seqHSize)) return seqHSize;
+ ip += seqHSize;
+ srcSize -= seqHSize;
+
+#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
+ !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
+ if ( !usePrefetchDecoder
+ && (!frame || (dctx->fParams.windowSize > (1<<24)))
+ && (nbSeq>ADVANCED_SEQS) ) { /* could probably use a larger nbSeq limit */
+ U32 const shareLongOffsets = ZSTD_getLongOffsetsShare(dctx->OFTptr);
+ U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */
+ usePrefetchDecoder = (shareLongOffsets >= minShare);
+ }
+#endif
+
+ dctx->ddictIsCold = 0;
+
+#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
+ !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
+ if (usePrefetchDecoder)
+#endif
+#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
+ return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);
+#endif
+
+#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
+ /* else */
+ return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset);
+#endif
+ }
+}
+
+
+size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize)
+{
+ size_t dSize;
+ ZSTD_checkContinuity(dctx, dst);
+ dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 0);
+ dctx->previousDstEnd = (char*)dst + dSize;
+ return dSize;
+}
diff --git a/Utilities/cmzstd/lib/decompress/zstd_decompress_block.h b/Utilities/cmzstd/lib/decompress/zstd_decompress_block.h
new file mode 100644
index 000000000..7e9296041
--- /dev/null
+++ b/Utilities/cmzstd/lib/decompress/zstd_decompress_block.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+
+#ifndef ZSTD_DEC_BLOCK_H
+#define ZSTD_DEC_BLOCK_H
+
+/*-*******************************************************
+ * Dependencies
+ *********************************************************/
+#include <stddef.h> /* size_t */
+#include "zstd.h" /* DCtx, and some public functions */
+#include "zstd_internal.h" /* blockProperties_t, and some public functions */
+#include "zstd_decompress_internal.h" /* ZSTD_seqSymbol */
+
+
+/* === Prototypes === */
+
+/* note: prototypes already published within `zstd.h` :
+ * ZSTD_decompressBlock()
+ */
+
+/* note: prototypes already published within `zstd_internal.h` :
+ * ZSTD_getcBlockSize()
+ * ZSTD_decodeSeqHeaders()
+ */
+
+
+/* ZSTD_decompressBlock_internal() :
+ * decompress block, starting at `src`,
+ * into destination buffer `dst`.
+ * @return : decompressed block size,
+ * or an error code (which can be tested using ZSTD_isError())
+ */
+size_t ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize, const int frame);
+
+/* ZSTD_buildFSETable() :
+ * generate FSE decoding table for one symbol (ll, ml or off)
+ * this function must be called with valid parameters only
+ * (dt is large enough, normalizedCounter distribution total is a power of 2, max is within range, etc.)
+ * in which case it cannot fail.
+ * Internal use only.
+ */
+void ZSTD_buildFSETable(ZSTD_seqSymbol* dt,
+ const short* normalizedCounter, unsigned maxSymbolValue,
+ const U32* baseValue, const U32* nbAdditionalBits,
+ unsigned tableLog);
+
+
+#endif /* ZSTD_DEC_BLOCK_H */
diff --git a/Utilities/cmzstd/lib/decompress/zstd_decompress_internal.h b/Utilities/cmzstd/lib/decompress/zstd_decompress_internal.h
new file mode 100644
index 000000000..abd003051
--- /dev/null
+++ b/Utilities/cmzstd/lib/decompress/zstd_decompress_internal.h
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+
+/* zstd_decompress_internal:
+ * objects and definitions shared within lib/decompress modules */
+
+ #ifndef ZSTD_DECOMPRESS_INTERNAL_H
+ #define ZSTD_DECOMPRESS_INTERNAL_H
+
+
+/*-*******************************************************
+ * Dependencies
+ *********************************************************/
+#include "mem.h" /* BYTE, U16, U32 */
+#include "zstd_internal.h" /* ZSTD_seqSymbol */
+
+
+
+/*-*******************************************************
+ * Constants
+ *********************************************************/
+static const U32 LL_base[MaxLL+1] = {
+ 0, 1, 2, 3, 4, 5, 6, 7,
+ 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 18, 20, 22, 24, 28, 32, 40,
+ 48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000,
+ 0x2000, 0x4000, 0x8000, 0x10000 };
+
+static const U32 OF_base[MaxOff+1] = {
+ 0, 1, 1, 5, 0xD, 0x1D, 0x3D, 0x7D,
+ 0xFD, 0x1FD, 0x3FD, 0x7FD, 0xFFD, 0x1FFD, 0x3FFD, 0x7FFD,
+ 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD, 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD,
+ 0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD, 0x1FFFFFFD, 0x3FFFFFFD, 0x7FFFFFFD };
+
+static const U32 OF_bits[MaxOff+1] = {
+ 0, 1, 2, 3, 4, 5, 6, 7,
+ 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, 18, 19, 20, 21, 22, 23,
+ 24, 25, 26, 27, 28, 29, 30, 31 };
+
+static const U32 ML_base[MaxML+1] = {
+ 3, 4, 5, 6, 7, 8, 9, 10,
+ 11, 12, 13, 14, 15, 16, 17, 18,
+ 19, 20, 21, 22, 23, 24, 25, 26,
+ 27, 28, 29, 30, 31, 32, 33, 34,
+ 35, 37, 39, 41, 43, 47, 51, 59,
+ 67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803,
+ 0x1003, 0x2003, 0x4003, 0x8003, 0x10003 };
+
+
+/*-*******************************************************
+ * Decompression types
+ *********************************************************/
+ typedef struct {
+ U32 fastMode;
+ U32 tableLog;
+ } ZSTD_seqSymbol_header;
+
+ typedef struct {
+ U16 nextState;
+ BYTE nbAdditionalBits;
+ BYTE nbBits;
+ U32 baseValue;
+ } ZSTD_seqSymbol;
+
+ #define SEQSYMBOL_TABLE_SIZE(log) (1 + (1 << (log)))
+
+typedef struct {
+ ZSTD_seqSymbol LLTable[SEQSYMBOL_TABLE_SIZE(LLFSELog)]; /* Note : Space reserved for FSE Tables */
+ ZSTD_seqSymbol OFTable[SEQSYMBOL_TABLE_SIZE(OffFSELog)]; /* is also used as temporary workspace while building hufTable during DDict creation */
+ ZSTD_seqSymbol MLTable[SEQSYMBOL_TABLE_SIZE(MLFSELog)]; /* and therefore must be at least HUF_DECOMPRESS_WORKSPACE_SIZE large */
+ HUF_DTable hufTable[HUF_DTABLE_SIZE(HufLog)]; /* can accommodate HUF_decompress4X */
+ U32 rep[ZSTD_REP_NUM];
+} ZSTD_entropyDTables_t;
+
+typedef enum { ZSTDds_getFrameHeaderSize, ZSTDds_decodeFrameHeader,
+ ZSTDds_decodeBlockHeader, ZSTDds_decompressBlock,
+ ZSTDds_decompressLastBlock, ZSTDds_checkChecksum,
+ ZSTDds_decodeSkippableHeader, ZSTDds_skipFrame } ZSTD_dStage;
+
+typedef enum { zdss_init=0, zdss_loadHeader,
+ zdss_read, zdss_load, zdss_flush } ZSTD_dStreamStage;
+
+struct ZSTD_DCtx_s
+{
+ const ZSTD_seqSymbol* LLTptr;
+ const ZSTD_seqSymbol* MLTptr;
+ const ZSTD_seqSymbol* OFTptr;
+ const HUF_DTable* HUFptr;
+ ZSTD_entropyDTables_t entropy;
+ U32 workspace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32]; /* space needed when building huffman tables */
+ const void* previousDstEnd; /* detect continuity */
+ const void* prefixStart; /* start of current segment */
+ const void* virtualStart; /* virtual start of previous segment if it was just before current one */
+ const void* dictEnd; /* end of previous segment */
+ size_t expected;
+ ZSTD_frameHeader fParams;
+ U64 decodedSize;
+ blockType_e bType; /* used in ZSTD_decompressContinue(), store blockType between block header decoding and block decompression stages */
+ ZSTD_dStage stage;
+ U32 litEntropy;
+ U32 fseEntropy;
+ XXH64_state_t xxhState;
+ size_t headerSize;
+ ZSTD_format_e format;
+ const BYTE* litPtr;
+ ZSTD_customMem customMem;
+ size_t litSize;
+ size_t rleSize;
+ size_t staticSize;
+ int bmi2; /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */
+
+ /* dictionary */
+ ZSTD_DDict* ddictLocal;
+ const ZSTD_DDict* ddict; /* set by ZSTD_initDStream_usingDDict(), or ZSTD_DCtx_refDDict() */
+ U32 dictID;
+ int ddictIsCold; /* if == 1 : dictionary is "new" for working context, and presumed "cold" (not in cpu cache) */
+
+ /* streaming */
+ ZSTD_dStreamStage streamStage;
+ char* inBuff;
+ size_t inBuffSize;
+ size_t inPos;
+ size_t maxWindowSize;
+ char* outBuff;
+ size_t outBuffSize;
+ size_t outStart;
+ size_t outEnd;
+ size_t lhSize;
+ void* legacyContext;
+ U32 previousLegacyVersion;
+ U32 legacyVersion;
+ U32 hostageByte;
+ int noForwardProgress;
+
+ /* workspace */
+ BYTE litBuffer[ZSTD_BLOCKSIZE_MAX + WILDCOPY_OVERLENGTH];
+ BYTE headerBuffer[ZSTD_FRAMEHEADERSIZE_MAX];
+}; /* typedef'd to ZSTD_DCtx within "zstd.h" */
+
+
+/*-*******************************************************
+ * Shared internal functions
+ *********************************************************/
+
+/*! ZSTD_loadDEntropy() :
+ * dict : must point at beginning of a valid zstd dictionary.
+ * @return : size of entropy tables read */
+size_t ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy,
+ const void* const dict, size_t const dictSize);
+
+/*! ZSTD_checkContinuity() :
+ * check if next `dst` follows previous position, where decompression ended.
+ * If yes, do nothing (continue on current segment).
+ * If not, classify previous segment as "external dictionary", and start a new segment.
+ * This function cannot fail. */
+void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst);
+
+
+#endif /* ZSTD_DECOMPRESS_INTERNAL_H */
diff --git a/Utilities/cmzstd/lib/deprecated/zbuff.h b/Utilities/cmzstd/lib/deprecated/zbuff.h
new file mode 100644
index 000000000..a93115da4
--- /dev/null
+++ b/Utilities/cmzstd/lib/deprecated/zbuff.h
@@ -0,0 +1,213 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+/* ***************************************************************
+* NOTES/WARNINGS
+******************************************************************/
+/* The streaming API defined here is deprecated.
+ * Consider migrating towards ZSTD_compressStream() API in `zstd.h`
+ * See 'lib/README.md'.
+ *****************************************************************/
+
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#ifndef ZSTD_BUFFERED_H_23987
+#define ZSTD_BUFFERED_H_23987
+
+/* *************************************
+* Dependencies
+***************************************/
+#include <stddef.h> /* size_t */
+#include "zstd.h" /* ZSTD_CStream, ZSTD_DStream, ZSTDLIB_API */
+
+
+/* ***************************************************************
+* Compiler specifics
+*****************************************************************/
+/* Deprecation warnings */
+/* Should these warnings be a problem,
+ it is generally possible to disable them,
+ typically with -Wno-deprecated-declarations for gcc
+ or _CRT_SECURE_NO_WARNINGS in Visual.
+ Otherwise, it's also possible to define ZBUFF_DISABLE_DEPRECATE_WARNINGS */
+#ifdef ZBUFF_DISABLE_DEPRECATE_WARNINGS
+# define ZBUFF_DEPRECATED(message) ZSTDLIB_API /* disable deprecation warnings */
+#else
+# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */
+# define ZBUFF_DEPRECATED(message) [[deprecated(message)]] ZSTDLIB_API
+# elif (defined(__GNUC__) && (__GNUC__ >= 5)) || defined(__clang__)
+# define ZBUFF_DEPRECATED(message) ZSTDLIB_API __attribute__((deprecated(message)))
+# elif defined(__GNUC__) && (__GNUC__ >= 3)
+# define ZBUFF_DEPRECATED(message) ZSTDLIB_API __attribute__((deprecated))
+# elif defined(_MSC_VER)
+# define ZBUFF_DEPRECATED(message) ZSTDLIB_API __declspec(deprecated(message))
+# else
+# pragma message("WARNING: You need to implement ZBUFF_DEPRECATED for this compiler")
+# define ZBUFF_DEPRECATED(message) ZSTDLIB_API
+# endif
+#endif /* ZBUFF_DISABLE_DEPRECATE_WARNINGS */
+
+
+/* *************************************
+* Streaming functions
+***************************************/
+/* This is the easier "buffered" streaming API,
+* using an internal buffer to lift all restrictions on user-provided buffers
+* which can be any size, any place, for both input and output.
+* ZBUFF and ZSTD are 100% interoperable,
+* frames created by one can be decoded by the other one */
+
+typedef ZSTD_CStream ZBUFF_CCtx;
+ZBUFF_DEPRECATED("use ZSTD_createCStream") ZBUFF_CCtx* ZBUFF_createCCtx(void);
+ZBUFF_DEPRECATED("use ZSTD_freeCStream") size_t ZBUFF_freeCCtx(ZBUFF_CCtx* cctx);
+
+ZBUFF_DEPRECATED("use ZSTD_initCStream") size_t ZBUFF_compressInit(ZBUFF_CCtx* cctx, int compressionLevel);
+ZBUFF_DEPRECATED("use ZSTD_initCStream_usingDict") size_t ZBUFF_compressInitDictionary(ZBUFF_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel);
+
+ZBUFF_DEPRECATED("use ZSTD_compressStream") size_t ZBUFF_compressContinue(ZBUFF_CCtx* cctx, void* dst, size_t* dstCapacityPtr, const void* src, size_t* srcSizePtr);
+ZBUFF_DEPRECATED("use ZSTD_flushStream") size_t ZBUFF_compressFlush(ZBUFF_CCtx* cctx, void* dst, size_t* dstCapacityPtr);
+ZBUFF_DEPRECATED("use ZSTD_endStream") size_t ZBUFF_compressEnd(ZBUFF_CCtx* cctx, void* dst, size_t* dstCapacityPtr);
+
+/*-*************************************************
+* Streaming compression - howto
+*
+* A ZBUFF_CCtx object is required to track streaming operation.
+* Use ZBUFF_createCCtx() and ZBUFF_freeCCtx() to create/release resources.
+* ZBUFF_CCtx objects can be reused multiple times.
+*
+* Start by initializing ZBUF_CCtx.
+* Use ZBUFF_compressInit() to start a new compression operation.
+* Use ZBUFF_compressInitDictionary() for a compression which requires a dictionary.
+*
+* Use ZBUFF_compressContinue() repetitively to consume input stream.
+* *srcSizePtr and *dstCapacityPtr can be any size.
+* The function will report how many bytes were read or written within *srcSizePtr and *dstCapacityPtr.
+* Note that it may not consume the entire input, in which case it's up to the caller to present again remaining data.
+* The content of `dst` will be overwritten (up to *dstCapacityPtr) at each call, so save its content if it matters or change @dst .
+* @return : a hint to preferred nb of bytes to use as input for next function call (it's just a hint, to improve latency)
+* or an error code, which can be tested using ZBUFF_isError().
+*
+* At any moment, it's possible to flush whatever data remains within buffer, using ZBUFF_compressFlush().
+* The nb of bytes written into `dst` will be reported into *dstCapacityPtr.
+* Note that the function cannot output more than *dstCapacityPtr,
+* therefore, some content might still be left into internal buffer if *dstCapacityPtr is too small.
+* @return : nb of bytes still present into internal buffer (0 if it's empty)
+* or an error code, which can be tested using ZBUFF_isError().
+*
+* ZBUFF_compressEnd() instructs to finish a frame.
+* It will perform a flush and write frame epilogue.
+* The epilogue is required for decoders to consider a frame completed.
+* Similar to ZBUFF_compressFlush(), it may not be able to output the entire internal buffer content if *dstCapacityPtr is too small.
+* In which case, call again ZBUFF_compressFlush() to complete the flush.
+* @return : nb of bytes still present into internal buffer (0 if it's empty)
+* or an error code, which can be tested using ZBUFF_isError().
+*
+* Hint : _recommended buffer_ sizes (not compulsory) : ZBUFF_recommendedCInSize() / ZBUFF_recommendedCOutSize()
+* input : ZBUFF_recommendedCInSize==128 KB block size is the internal unit, use this value to reduce intermediate stages (better latency)
+* output : ZBUFF_recommendedCOutSize==ZSTD_compressBound(128 KB) + 3 + 3 : ensures it's always possible to write/flush/end a full block. Skip some buffering.
+* By using both, it ensures that input will be entirely consumed, and output will always contain the result, reducing intermediate buffering.
+* **************************************************/
+
+
+typedef ZSTD_DStream ZBUFF_DCtx;
+ZBUFF_DEPRECATED("use ZSTD_createDStream") ZBUFF_DCtx* ZBUFF_createDCtx(void);
+ZBUFF_DEPRECATED("use ZSTD_freeDStream") size_t ZBUFF_freeDCtx(ZBUFF_DCtx* dctx);
+
+ZBUFF_DEPRECATED("use ZSTD_initDStream") size_t ZBUFF_decompressInit(ZBUFF_DCtx* dctx);
+ZBUFF_DEPRECATED("use ZSTD_initDStream_usingDict") size_t ZBUFF_decompressInitDictionary(ZBUFF_DCtx* dctx, const void* dict, size_t dictSize);
+
+ZBUFF_DEPRECATED("use ZSTD_decompressStream") size_t ZBUFF_decompressContinue(ZBUFF_DCtx* dctx,
+ void* dst, size_t* dstCapacityPtr,
+ const void* src, size_t* srcSizePtr);
+
+/*-***************************************************************************
+* Streaming decompression howto
+*
+* A ZBUFF_DCtx object is required to track streaming operations.
+* Use ZBUFF_createDCtx() and ZBUFF_freeDCtx() to create/release resources.
+* Use ZBUFF_decompressInit() to start a new decompression operation,
+* or ZBUFF_decompressInitDictionary() if decompression requires a dictionary.
+* Note that ZBUFF_DCtx objects can be re-init multiple times.
+*
+* Use ZBUFF_decompressContinue() repetitively to consume your input.
+* *srcSizePtr and *dstCapacityPtr can be any size.
+* The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr.
+* Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again.
+* The content of `dst` will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters, or change `dst`.
+* @return : 0 when a frame is completely decoded and fully flushed,
+* 1 when there is still some data left within internal buffer to flush,
+* >1 when more data is expected, with value being a suggested next input size (it's just a hint, which helps latency),
+* or an error code, which can be tested using ZBUFF_isError().
+*
+* Hint : recommended buffer sizes (not compulsory) : ZBUFF_recommendedDInSize() and ZBUFF_recommendedDOutSize()
+* output : ZBUFF_recommendedDOutSize== 128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded.
+* input : ZBUFF_recommendedDInSize == 128KB + 3;
+* just follow indications from ZBUFF_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 .
+* *******************************************************************************/
+
+
+/* *************************************
+* Tool functions
+***************************************/
+ZBUFF_DEPRECATED("use ZSTD_isError") unsigned ZBUFF_isError(size_t errorCode);
+ZBUFF_DEPRECATED("use ZSTD_getErrorName") const char* ZBUFF_getErrorName(size_t errorCode);
+
+/** Functions below provide recommended buffer sizes for Compression or Decompression operations.
+* These sizes are just hints, they tend to offer better latency */
+ZBUFF_DEPRECATED("use ZSTD_CStreamInSize") size_t ZBUFF_recommendedCInSize(void);
+ZBUFF_DEPRECATED("use ZSTD_CStreamOutSize") size_t ZBUFF_recommendedCOutSize(void);
+ZBUFF_DEPRECATED("use ZSTD_DStreamInSize") size_t ZBUFF_recommendedDInSize(void);
+ZBUFF_DEPRECATED("use ZSTD_DStreamOutSize") size_t ZBUFF_recommendedDOutSize(void);
+
+#endif /* ZSTD_BUFFERED_H_23987 */
+
+
+#ifdef ZBUFF_STATIC_LINKING_ONLY
+#ifndef ZBUFF_STATIC_H_30298098432
+#define ZBUFF_STATIC_H_30298098432
+
+/* ====================================================================================
+ * The definitions in this section are considered experimental.
+ * They should never be used in association with a dynamic library, as they may change in the future.
+ * They are provided for advanced usages.
+ * Use them only in association with static linking.
+ * ==================================================================================== */
+
+/*--- Dependency ---*/
+#define ZSTD_STATIC_LINKING_ONLY /* ZSTD_parameters, ZSTD_customMem */
+#include "zstd.h"
+
+
+/*--- Custom memory allocator ---*/
+/*! ZBUFF_createCCtx_advanced() :
+ * Create a ZBUFF compression context using external alloc and free functions */
+ZBUFF_DEPRECATED("use ZSTD_createCStream_advanced") ZBUFF_CCtx* ZBUFF_createCCtx_advanced(ZSTD_customMem customMem);
+
+/*! ZBUFF_createDCtx_advanced() :
+ * Create a ZBUFF decompression context using external alloc and free functions */
+ZBUFF_DEPRECATED("use ZSTD_createDStream_advanced") ZBUFF_DCtx* ZBUFF_createDCtx_advanced(ZSTD_customMem customMem);
+
+
+/*--- Advanced Streaming Initialization ---*/
+ZBUFF_DEPRECATED("use ZSTD_initDStream_usingDict") size_t ZBUFF_compressInit_advanced(ZBUFF_CCtx* zbc,
+ const void* dict, size_t dictSize,
+ ZSTD_parameters params, unsigned long long pledgedSrcSize);
+
+
+#endif /* ZBUFF_STATIC_H_30298098432 */
+#endif /* ZBUFF_STATIC_LINKING_ONLY */
+
+
+#if defined (__cplusplus)
+}
+#endif
diff --git a/Utilities/cmzstd/lib/deprecated/zbuff_common.c b/Utilities/cmzstd/lib/deprecated/zbuff_common.c
new file mode 100644
index 000000000..661b9b0e1
--- /dev/null
+++ b/Utilities/cmzstd/lib/deprecated/zbuff_common.c
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+/*-*************************************
+* Dependencies
+***************************************/
+#include "error_private.h"
+#include "zbuff.h"
+
+/*-****************************************
+* ZBUFF Error Management (deprecated)
+******************************************/
+
+/*! ZBUFF_isError() :
+* tells if a return value is an error code */
+unsigned ZBUFF_isError(size_t errorCode) { return ERR_isError(errorCode); }
+/*! ZBUFF_getErrorName() :
+* provides error code string from function result (useful for debugging) */
+const char* ZBUFF_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
diff --git a/Utilities/cmzstd/lib/deprecated/zbuff_compress.c b/Utilities/cmzstd/lib/deprecated/zbuff_compress.c
new file mode 100644
index 000000000..f39c60d89
--- /dev/null
+++ b/Utilities/cmzstd/lib/deprecated/zbuff_compress.c
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+
+
+/* *************************************
+* Dependencies
+***************************************/
+#define ZBUFF_STATIC_LINKING_ONLY
+#include "zbuff.h"
+
+
+/*-***********************************************************
+* Streaming compression
+*
+* A ZBUFF_CCtx object is required to track streaming operation.
+* Use ZBUFF_createCCtx() and ZBUFF_freeCCtx() to create/release resources.
+* Use ZBUFF_compressInit() to start a new compression operation.
+* ZBUFF_CCtx objects can be reused multiple times.
+*
+* Use ZBUFF_compressContinue() repetitively to consume your input.
+* *srcSizePtr and *dstCapacityPtr can be any size.
+* The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr.
+* Note that it may not consume the entire input, in which case it's up to the caller to call again the function with remaining input.
+* The content of dst will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters or change dst .
+* @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to improve latency)
+* or an error code, which can be tested using ZBUFF_isError().
+*
+* ZBUFF_compressFlush() can be used to instruct ZBUFF to compress and output whatever remains within its buffer.
+* Note that it will not output more than *dstCapacityPtr.
+* Therefore, some content might still be left into its internal buffer if dst buffer is too small.
+* @return : nb of bytes still present into internal buffer (0 if it's empty)
+* or an error code, which can be tested using ZBUFF_isError().
+*
+* ZBUFF_compressEnd() instructs to finish a frame.
+* It will perform a flush and write frame epilogue.
+* Similar to ZBUFF_compressFlush(), it may not be able to output the entire internal buffer content if *dstCapacityPtr is too small.
+* @return : nb of bytes still present into internal buffer (0 if it's empty)
+* or an error code, which can be tested using ZBUFF_isError().
+*
+* Hint : recommended buffer sizes (not compulsory)
+* input : ZSTD_BLOCKSIZE_MAX (128 KB), internal unit size, it improves latency to use this value.
+* output : ZSTD_compressBound(ZSTD_BLOCKSIZE_MAX) + ZSTD_blockHeaderSize + ZBUFF_endFrameSize : ensures it's always possible to write/flush/end a full block at best speed.
+* ***********************************************************/
+
+ZBUFF_CCtx* ZBUFF_createCCtx(void)
+{
+ return ZSTD_createCStream();
+}
+
+ZBUFF_CCtx* ZBUFF_createCCtx_advanced(ZSTD_customMem customMem)
+{
+ return ZSTD_createCStream_advanced(customMem);
+}
+
+size_t ZBUFF_freeCCtx(ZBUFF_CCtx* zbc)
+{
+ return ZSTD_freeCStream(zbc);
+}
+
+
+/* ====== Initialization ====== */
+
+size_t ZBUFF_compressInit_advanced(ZBUFF_CCtx* zbc,
+ const void* dict, size_t dictSize,
+ ZSTD_parameters params, unsigned long long pledgedSrcSize)
+{
+ if (pledgedSrcSize==0) pledgedSrcSize = ZSTD_CONTENTSIZE_UNKNOWN; /* preserve "0 == unknown" behavior */
+ return ZSTD_initCStream_advanced(zbc, dict, dictSize, params, pledgedSrcSize);
+}
+
+
+size_t ZBUFF_compressInitDictionary(ZBUFF_CCtx* zbc, const void* dict, size_t dictSize, int compressionLevel)
+{
+ return ZSTD_initCStream_usingDict(zbc, dict, dictSize, compressionLevel);
+}
+
+size_t ZBUFF_compressInit(ZBUFF_CCtx* zbc, int compressionLevel)
+{
+ return ZSTD_initCStream(zbc, compressionLevel);
+}
+
+/* ====== Compression ====== */
+
+
+size_t ZBUFF_compressContinue(ZBUFF_CCtx* zbc,
+ void* dst, size_t* dstCapacityPtr,
+ const void* src, size_t* srcSizePtr)
+{
+ size_t result;
+ ZSTD_outBuffer outBuff;
+ ZSTD_inBuffer inBuff;
+ outBuff.dst = dst;
+ outBuff.pos = 0;
+ outBuff.size = *dstCapacityPtr;
+ inBuff.src = src;
+ inBuff.pos = 0;
+ inBuff.size = *srcSizePtr;
+ result = ZSTD_compressStream(zbc, &outBuff, &inBuff);
+ *dstCapacityPtr = outBuff.pos;
+ *srcSizePtr = inBuff.pos;
+ return result;
+}
+
+
+
+/* ====== Finalize ====== */
+
+size_t ZBUFF_compressFlush(ZBUFF_CCtx* zbc, void* dst, size_t* dstCapacityPtr)
+{
+ size_t result;
+ ZSTD_outBuffer outBuff;
+ outBuff.dst = dst;
+ outBuff.pos = 0;
+ outBuff.size = *dstCapacityPtr;
+ result = ZSTD_flushStream(zbc, &outBuff);
+ *dstCapacityPtr = outBuff.pos;
+ return result;
+}
+
+
+size_t ZBUFF_compressEnd(ZBUFF_CCtx* zbc, void* dst, size_t* dstCapacityPtr)
+{
+ size_t result;
+ ZSTD_outBuffer outBuff;
+ outBuff.dst = dst;
+ outBuff.pos = 0;
+ outBuff.size = *dstCapacityPtr;
+ result = ZSTD_endStream(zbc, &outBuff);
+ *dstCapacityPtr = outBuff.pos;
+ return result;
+}
+
+
+
+/* *************************************
+* Tool functions
+***************************************/
+size_t ZBUFF_recommendedCInSize(void) { return ZSTD_CStreamInSize(); }
+size_t ZBUFF_recommendedCOutSize(void) { return ZSTD_CStreamOutSize(); }
diff --git a/Utilities/cmzstd/lib/deprecated/zbuff_decompress.c b/Utilities/cmzstd/lib/deprecated/zbuff_decompress.c
new file mode 100644
index 000000000..923c22b73
--- /dev/null
+++ b/Utilities/cmzstd/lib/deprecated/zbuff_decompress.c
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+
+
+/* *************************************
+* Dependencies
+***************************************/
+#define ZBUFF_STATIC_LINKING_ONLY
+#include "zbuff.h"
+
+
+ZBUFF_DCtx* ZBUFF_createDCtx(void)
+{
+ return ZSTD_createDStream();
+}
+
+ZBUFF_DCtx* ZBUFF_createDCtx_advanced(ZSTD_customMem customMem)
+{
+ return ZSTD_createDStream_advanced(customMem);
+}
+
+size_t ZBUFF_freeDCtx(ZBUFF_DCtx* zbd)
+{
+ return ZSTD_freeDStream(zbd);
+}
+
+
+/* *** Initialization *** */
+
+size_t ZBUFF_decompressInitDictionary(ZBUFF_DCtx* zbd, const void* dict, size_t dictSize)
+{
+ return ZSTD_initDStream_usingDict(zbd, dict, dictSize);
+}
+
+size_t ZBUFF_decompressInit(ZBUFF_DCtx* zbd)
+{
+ return ZSTD_initDStream(zbd);
+}
+
+
+/* *** Decompression *** */
+
+size_t ZBUFF_decompressContinue(ZBUFF_DCtx* zbd,
+ void* dst, size_t* dstCapacityPtr,
+ const void* src, size_t* srcSizePtr)
+{
+ ZSTD_outBuffer outBuff;
+ ZSTD_inBuffer inBuff;
+ size_t result;
+ outBuff.dst = dst;
+ outBuff.pos = 0;
+ outBuff.size = *dstCapacityPtr;
+ inBuff.src = src;
+ inBuff.pos = 0;
+ inBuff.size = *srcSizePtr;
+ result = ZSTD_decompressStream(zbd, &outBuff, &inBuff);
+ *dstCapacityPtr = outBuff.pos;
+ *srcSizePtr = inBuff.pos;
+ return result;
+}
+
+
+/* *************************************
+* Tool functions
+***************************************/
+size_t ZBUFF_recommendedDInSize(void) { return ZSTD_DStreamInSize(); }
+size_t ZBUFF_recommendedDOutSize(void) { return ZSTD_DStreamOutSize(); }
diff --git a/Utilities/cmzstd/lib/dictBuilder/cover.c b/Utilities/cmzstd/lib/dictBuilder/cover.c
new file mode 100644
index 000000000..b55bfb510
--- /dev/null
+++ b/Utilities/cmzstd/lib/dictBuilder/cover.c
@@ -0,0 +1,1081 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+/* *****************************************************************************
+ * Constructs a dictionary using a heuristic based on the following paper:
+ *
+ * Liao, Petri, Moffat, Wirth
+ * Effective Construction of Relative Lempel-Ziv Dictionaries
+ * Published in WWW 2016.
+ *
+ * Adapted from code originally written by @ot (Giuseppe Ottaviano).
+ ******************************************************************************/
+
+/*-*************************************
+* Dependencies
+***************************************/
+#include <stdio.h> /* fprintf */
+#include <stdlib.h> /* malloc, free, qsort */
+#include <string.h> /* memset */
+#include <time.h> /* clock */
+
+#include "mem.h" /* read */
+#include "pool.h"
+#include "threading.h"
+#include "cover.h"
+#include "zstd_internal.h" /* includes zstd.h */
+#ifndef ZDICT_STATIC_LINKING_ONLY
+#define ZDICT_STATIC_LINKING_ONLY
+#endif
+#include "zdict.h"
+
+/*-*************************************
+* Constants
+***************************************/
+#define COVER_MAX_SAMPLES_SIZE (sizeof(size_t) == 8 ? ((unsigned)-1) : ((unsigned)1 GB))
+#define DEFAULT_SPLITPOINT 1.0
+
+/*-*************************************
+* Console display
+***************************************/
+static int g_displayLevel = 2;
+#define DISPLAY(...) \
+ { \
+ fprintf(stderr, __VA_ARGS__); \
+ fflush(stderr); \
+ }
+#define LOCALDISPLAYLEVEL(displayLevel, l, ...) \
+ if (displayLevel >= l) { \
+ DISPLAY(__VA_ARGS__); \
+ } /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */
+#define DISPLAYLEVEL(l, ...) LOCALDISPLAYLEVEL(g_displayLevel, l, __VA_ARGS__)
+
+#define LOCALDISPLAYUPDATE(displayLevel, l, ...) \
+ if (displayLevel >= l) { \
+ if ((clock() - g_time > refreshRate) || (displayLevel >= 4)) { \
+ g_time = clock(); \
+ DISPLAY(__VA_ARGS__); \
+ } \
+ }
+#define DISPLAYUPDATE(l, ...) LOCALDISPLAYUPDATE(g_displayLevel, l, __VA_ARGS__)
+static const clock_t refreshRate = CLOCKS_PER_SEC * 15 / 100;
+static clock_t g_time = 0;
+
+/*-*************************************
+* Hash table
+***************************************
+* A small specialized hash map for storing activeDmers.
+* The map does not resize, so if it becomes full it will loop forever.
+* Thus, the map must be large enough to store every value.
+* The map implements linear probing and keeps its load less than 0.5.
+*/
+
+#define MAP_EMPTY_VALUE ((U32)-1)
+typedef struct COVER_map_pair_t_s {
+ U32 key;
+ U32 value;
+} COVER_map_pair_t;
+
+typedef struct COVER_map_s {
+ COVER_map_pair_t *data;
+ U32 sizeLog;
+ U32 size;
+ U32 sizeMask;
+} COVER_map_t;
+
+/**
+ * Clear the map.
+ */
+static void COVER_map_clear(COVER_map_t *map) {
+ memset(map->data, MAP_EMPTY_VALUE, map->size * sizeof(COVER_map_pair_t));
+}
+
+/**
+ * Initializes a map of the given size.
+ * Returns 1 on success and 0 on failure.
+ * The map must be destroyed with COVER_map_destroy().
+ * The map is only guaranteed to be large enough to hold size elements.
+ */
+static int COVER_map_init(COVER_map_t *map, U32 size) {
+ map->sizeLog = ZSTD_highbit32(size) + 2;
+ map->size = (U32)1 << map->sizeLog;
+ map->sizeMask = map->size - 1;
+ map->data = (COVER_map_pair_t *)malloc(map->size * sizeof(COVER_map_pair_t));
+ if (!map->data) {
+ map->sizeLog = 0;
+ map->size = 0;
+ return 0;
+ }
+ COVER_map_clear(map);
+ return 1;
+}
+
+/**
+ * Internal hash function
+ */
+static const U32 prime4bytes = 2654435761U;
+static U32 COVER_map_hash(COVER_map_t *map, U32 key) {
+ return (key * prime4bytes) >> (32 - map->sizeLog);
+}
+
+/**
+ * Helper function that returns the index that a key should be placed into.
+ */
+static U32 COVER_map_index(COVER_map_t *map, U32 key) {
+ const U32 hash = COVER_map_hash(map, key);
+ U32 i;
+ for (i = hash;; i = (i + 1) & map->sizeMask) {
+ COVER_map_pair_t *pos = &map->data[i];
+ if (pos->value == MAP_EMPTY_VALUE) {
+ return i;
+ }
+ if (pos->key == key) {
+ return i;
+ }
+ }
+}
+
+/**
+ * Returns the pointer to the value for key.
+ * If key is not in the map, it is inserted and the value is set to 0.
+ * The map must not be full.
+ */
+static U32 *COVER_map_at(COVER_map_t *map, U32 key) {
+ COVER_map_pair_t *pos = &map->data[COVER_map_index(map, key)];
+ if (pos->value == MAP_EMPTY_VALUE) {
+ pos->key = key;
+ pos->value = 0;
+ }
+ return &pos->value;
+}
+
+/**
+ * Deletes key from the map if present.
+ */
+static void COVER_map_remove(COVER_map_t *map, U32 key) {
+ U32 i = COVER_map_index(map, key);
+ COVER_map_pair_t *del = &map->data[i];
+ U32 shift = 1;
+ if (del->value == MAP_EMPTY_VALUE) {
+ return;
+ }
+ for (i = (i + 1) & map->sizeMask;; i = (i + 1) & map->sizeMask) {
+ COVER_map_pair_t *const pos = &map->data[i];
+ /* If the position is empty we are done */
+ if (pos->value == MAP_EMPTY_VALUE) {
+ del->value = MAP_EMPTY_VALUE;
+ return;
+ }
+ /* If pos can be moved to del do so */
+ if (((i - COVER_map_hash(map, pos->key)) & map->sizeMask) >= shift) {
+ del->key = pos->key;
+ del->value = pos->value;
+ del = pos;
+ shift = 1;
+ } else {
+ ++shift;
+ }
+ }
+}
+
+/**
+ * Destroys a map that is inited with COVER_map_init().
+ */
+static void COVER_map_destroy(COVER_map_t *map) {
+ if (map->data) {
+ free(map->data);
+ }
+ map->data = NULL;
+ map->size = 0;
+}
+
+/*-*************************************
+* Context
+***************************************/
+
+typedef struct {
+ const BYTE *samples;
+ size_t *offsets;
+ const size_t *samplesSizes;
+ size_t nbSamples;
+ size_t nbTrainSamples;
+ size_t nbTestSamples;
+ U32 *suffix;
+ size_t suffixSize;
+ U32 *freqs;
+ U32 *dmerAt;
+ unsigned d;
+} COVER_ctx_t;
+
+/* We need a global context for qsort... */
+static COVER_ctx_t *g_ctx = NULL;
+
+/*-*************************************
+* Helper functions
+***************************************/
+
+/**
+ * Returns the sum of the sample sizes.
+ */
+size_t COVER_sum(const size_t *samplesSizes, unsigned nbSamples) {
+ size_t sum = 0;
+ unsigned i;
+ for (i = 0; i < nbSamples; ++i) {
+ sum += samplesSizes[i];
+ }
+ return sum;
+}
+
+/**
+ * Returns -1 if the dmer at lp is less than the dmer at rp.
+ * Return 0 if the dmers at lp and rp are equal.
+ * Returns 1 if the dmer at lp is greater than the dmer at rp.
+ */
+static int COVER_cmp(COVER_ctx_t *ctx, const void *lp, const void *rp) {
+ U32 const lhs = *(U32 const *)lp;
+ U32 const rhs = *(U32 const *)rp;
+ return memcmp(ctx->samples + lhs, ctx->samples + rhs, ctx->d);
+}
+/**
+ * Faster version for d <= 8.
+ */
+static int COVER_cmp8(COVER_ctx_t *ctx, const void *lp, const void *rp) {
+ U64 const mask = (ctx->d == 8) ? (U64)-1 : (((U64)1 << (8 * ctx->d)) - 1);
+ U64 const lhs = MEM_readLE64(ctx->samples + *(U32 const *)lp) & mask;
+ U64 const rhs = MEM_readLE64(ctx->samples + *(U32 const *)rp) & mask;
+ if (lhs < rhs) {
+ return -1;
+ }
+ return (lhs > rhs);
+}
+
+/**
+ * Same as COVER_cmp() except ties are broken by pointer value
+ * NOTE: g_ctx must be set to call this function. A global is required because
+ * qsort doesn't take an opaque pointer.
+ */
+static int COVER_strict_cmp(const void *lp, const void *rp) {
+ int result = COVER_cmp(g_ctx, lp, rp);
+ if (result == 0) {
+ result = lp < rp ? -1 : 1;
+ }
+ return result;
+}
+/**
+ * Faster version for d <= 8.
+ */
+static int COVER_strict_cmp8(const void *lp, const void *rp) {
+ int result = COVER_cmp8(g_ctx, lp, rp);
+ if (result == 0) {
+ result = lp < rp ? -1 : 1;
+ }
+ return result;
+}
+
+/**
+ * Returns the first pointer in [first, last) whose element does not compare
+ * less than value. If no such element exists it returns last.
+ */
+static const size_t *COVER_lower_bound(const size_t *first, const size_t *last,
+ size_t value) {
+ size_t count = last - first;
+ while (count != 0) {
+ size_t step = count / 2;
+ const size_t *ptr = first;
+ ptr += step;
+ if (*ptr < value) {
+ first = ++ptr;
+ count -= step + 1;
+ } else {
+ count = step;
+ }
+ }
+ return first;
+}
+
+/**
+ * Generic groupBy function.
+ * Groups an array sorted by cmp into groups with equivalent values.
+ * Calls grp for each group.
+ */
+static void
+COVER_groupBy(const void *data, size_t count, size_t size, COVER_ctx_t *ctx,
+ int (*cmp)(COVER_ctx_t *, const void *, const void *),
+ void (*grp)(COVER_ctx_t *, const void *, const void *)) {
+ const BYTE *ptr = (const BYTE *)data;
+ size_t num = 0;
+ while (num < count) {
+ const BYTE *grpEnd = ptr + size;
+ ++num;
+ while (num < count && cmp(ctx, ptr, grpEnd) == 0) {
+ grpEnd += size;
+ ++num;
+ }
+ grp(ctx, ptr, grpEnd);
+ ptr = grpEnd;
+ }
+}
+
+/*-*************************************
+* Cover functions
+***************************************/
+
+/**
+ * Called on each group of positions with the same dmer.
+ * Counts the frequency of each dmer and saves it in the suffix array.
+ * Fills `ctx->dmerAt`.
+ */
+static void COVER_group(COVER_ctx_t *ctx, const void *group,
+ const void *groupEnd) {
+ /* The group consists of all the positions with the same first d bytes. */
+ const U32 *grpPtr = (const U32 *)group;
+ const U32 *grpEnd = (const U32 *)groupEnd;
+ /* The dmerId is how we will reference this dmer.
+ * This allows us to map the whole dmer space to a much smaller space, the
+ * size of the suffix array.
+ */
+ const U32 dmerId = (U32)(grpPtr - ctx->suffix);
+ /* Count the number of samples this dmer shows up in */
+ U32 freq = 0;
+ /* Details */
+ const size_t *curOffsetPtr = ctx->offsets;
+ const size_t *offsetsEnd = ctx->offsets + ctx->nbSamples;
+ /* Once *grpPtr >= curSampleEnd this occurrence of the dmer is in a
+ * different sample than the last.
+ */
+ size_t curSampleEnd = ctx->offsets[0];
+ for (; grpPtr != grpEnd; ++grpPtr) {
+ /* Save the dmerId for this position so we can get back to it. */
+ ctx->dmerAt[*grpPtr] = dmerId;
+ /* Dictionaries only help for the first reference to the dmer.
+ * After that zstd can reference the match from the previous reference.
+ * So only count each dmer once for each sample it is in.
+ */
+ if (*grpPtr < curSampleEnd) {
+ continue;
+ }
+ freq += 1;
+ /* Binary search to find the end of the sample *grpPtr is in.
+ * In the common case that grpPtr + 1 == grpEnd we can skip the binary
+ * search because the loop is over.
+ */
+ if (grpPtr + 1 != grpEnd) {
+ const size_t *sampleEndPtr =
+ COVER_lower_bound(curOffsetPtr, offsetsEnd, *grpPtr);
+ curSampleEnd = *sampleEndPtr;
+ curOffsetPtr = sampleEndPtr + 1;
+ }
+ }
+ /* At this point we are never going to look at this segment of the suffix
+ * array again. We take advantage of this fact to save memory.
+ * We store the frequency of the dmer in the first position of the group,
+ * which is dmerId.
+ */
+ ctx->suffix[dmerId] = freq;
+}
+
+
+/**
+ * Selects the best segment in an epoch.
+ * Segments of are scored according to the function:
+ *
+ * Let F(d) be the frequency of dmer d.
+ * Let S_i be the dmer at position i of segment S which has length k.
+ *
+ * Score(S) = F(S_1) + F(S_2) + ... + F(S_{k-d+1})
+ *
+ * Once the dmer d is in the dictionay we set F(d) = 0.
+ */
+static COVER_segment_t COVER_selectSegment(const COVER_ctx_t *ctx, U32 *freqs,
+ COVER_map_t *activeDmers, U32 begin,
+ U32 end,
+ ZDICT_cover_params_t parameters) {
+ /* Constants */
+ const U32 k = parameters.k;
+ const U32 d = parameters.d;
+ const U32 dmersInK = k - d + 1;
+ /* Try each segment (activeSegment) and save the best (bestSegment) */
+ COVER_segment_t bestSegment = {0, 0, 0};
+ COVER_segment_t activeSegment;
+ /* Reset the activeDmers in the segment */
+ COVER_map_clear(activeDmers);
+ /* The activeSegment starts at the beginning of the epoch. */
+ activeSegment.begin = begin;
+ activeSegment.end = begin;
+ activeSegment.score = 0;
+ /* Slide the activeSegment through the whole epoch.
+ * Save the best segment in bestSegment.
+ */
+ while (activeSegment.end < end) {
+ /* The dmerId for the dmer at the next position */
+ U32 newDmer = ctx->dmerAt[activeSegment.end];
+ /* The entry in activeDmers for this dmerId */
+ U32 *newDmerOcc = COVER_map_at(activeDmers, newDmer);
+ /* If the dmer isn't already present in the segment add its score. */
+ if (*newDmerOcc == 0) {
+ /* The paper suggest using the L-0.5 norm, but experiments show that it
+ * doesn't help.
+ */
+ activeSegment.score += freqs[newDmer];
+ }
+ /* Add the dmer to the segment */
+ activeSegment.end += 1;
+ *newDmerOcc += 1;
+
+ /* If the window is now too large, drop the first position */
+ if (activeSegment.end - activeSegment.begin == dmersInK + 1) {
+ U32 delDmer = ctx->dmerAt[activeSegment.begin];
+ U32 *delDmerOcc = COVER_map_at(activeDmers, delDmer);
+ activeSegment.begin += 1;
+ *delDmerOcc -= 1;
+ /* If this is the last occurence of the dmer, subtract its score */
+ if (*delDmerOcc == 0) {
+ COVER_map_remove(activeDmers, delDmer);
+ activeSegment.score -= freqs[delDmer];
+ }
+ }
+
+ /* If this segment is the best so far save it */
+ if (activeSegment.score > bestSegment.score) {
+ bestSegment = activeSegment;
+ }
+ }
+ {
+ /* Trim off the zero frequency head and tail from the segment. */
+ U32 newBegin = bestSegment.end;
+ U32 newEnd = bestSegment.begin;
+ U32 pos;
+ for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
+ U32 freq = freqs[ctx->dmerAt[pos]];
+ if (freq != 0) {
+ newBegin = MIN(newBegin, pos);
+ newEnd = pos + 1;
+ }
+ }
+ bestSegment.begin = newBegin;
+ bestSegment.end = newEnd;
+ }
+ {
+ /* Zero out the frequency of each dmer covered by the chosen segment. */
+ U32 pos;
+ for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
+ freqs[ctx->dmerAt[pos]] = 0;
+ }
+ }
+ return bestSegment;
+}
+
+/**
+ * Check the validity of the parameters.
+ * Returns non-zero if the parameters are valid and 0 otherwise.
+ */
+static int COVER_checkParameters(ZDICT_cover_params_t parameters,
+ size_t maxDictSize) {
+ /* k and d are required parameters */
+ if (parameters.d == 0 || parameters.k == 0) {
+ return 0;
+ }
+ /* k <= maxDictSize */
+ if (parameters.k > maxDictSize) {
+ return 0;
+ }
+ /* d <= k */
+ if (parameters.d > parameters.k) {
+ return 0;
+ }
+ /* 0 < splitPoint <= 1 */
+ if (parameters.splitPoint <= 0 || parameters.splitPoint > 1){
+ return 0;
+ }
+ return 1;
+}
+
+/**
+ * Clean up a context initialized with `COVER_ctx_init()`.
+ */
+static void COVER_ctx_destroy(COVER_ctx_t *ctx) {
+ if (!ctx) {
+ return;
+ }
+ if (ctx->suffix) {
+ free(ctx->suffix);
+ ctx->suffix = NULL;
+ }
+ if (ctx->freqs) {
+ free(ctx->freqs);
+ ctx->freqs = NULL;
+ }
+ if (ctx->dmerAt) {
+ free(ctx->dmerAt);
+ ctx->dmerAt = NULL;
+ }
+ if (ctx->offsets) {
+ free(ctx->offsets);
+ ctx->offsets = NULL;
+ }
+}
+
+/**
+ * Prepare a context for dictionary building.
+ * The context is only dependent on the parameter `d` and can used multiple
+ * times.
+ * Returns 1 on success or zero on error.
+ * The context must be destroyed with `COVER_ctx_destroy()`.
+ */
+static int COVER_ctx_init(COVER_ctx_t *ctx, const void *samplesBuffer,
+ const size_t *samplesSizes, unsigned nbSamples,
+ unsigned d, double splitPoint) {
+ const BYTE *const samples = (const BYTE *)samplesBuffer;
+ const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples);
+ /* Split samples into testing and training sets */
+ const unsigned nbTrainSamples = splitPoint < 1.0 ? (unsigned)((double)nbSamples * splitPoint) : nbSamples;
+ const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples;
+ const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize;
+ const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize;
+ /* Checks */
+ if (totalSamplesSize < MAX(d, sizeof(U64)) ||
+ totalSamplesSize >= (size_t)COVER_MAX_SAMPLES_SIZE) {
+ DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n",
+ (unsigned)(totalSamplesSize>>20), (COVER_MAX_SAMPLES_SIZE >> 20));
+ return 0;
+ }
+ /* Check if there are at least 5 training samples */
+ if (nbTrainSamples < 5) {
+ DISPLAYLEVEL(1, "Total number of training samples is %u and is invalid.", nbTrainSamples);
+ return 0;
+ }
+ /* Check if there's testing sample */
+ if (nbTestSamples < 1) {
+ DISPLAYLEVEL(1, "Total number of testing samples is %u and is invalid.", nbTestSamples);
+ return 0;
+ }
+ /* Zero the context */
+ memset(ctx, 0, sizeof(*ctx));
+ DISPLAYLEVEL(2, "Training on %u samples of total size %u\n", nbTrainSamples,
+ (unsigned)trainingSamplesSize);
+ DISPLAYLEVEL(2, "Testing on %u samples of total size %u\n", nbTestSamples,
+ (unsigned)testSamplesSize);
+ ctx->samples = samples;
+ ctx->samplesSizes = samplesSizes;
+ ctx->nbSamples = nbSamples;
+ ctx->nbTrainSamples = nbTrainSamples;
+ ctx->nbTestSamples = nbTestSamples;
+ /* Partial suffix array */
+ ctx->suffixSize = trainingSamplesSize - MAX(d, sizeof(U64)) + 1;
+ ctx->suffix = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
+ /* Maps index to the dmerID */
+ ctx->dmerAt = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
+ /* The offsets of each file */
+ ctx->offsets = (size_t *)malloc((nbSamples + 1) * sizeof(size_t));
+ if (!ctx->suffix || !ctx->dmerAt || !ctx->offsets) {
+ DISPLAYLEVEL(1, "Failed to allocate scratch buffers\n");
+ COVER_ctx_destroy(ctx);
+ return 0;
+ }
+ ctx->freqs = NULL;
+ ctx->d = d;
+
+ /* Fill offsets from the samplesSizes */
+ {
+ U32 i;
+ ctx->offsets[0] = 0;
+ for (i = 1; i <= nbSamples; ++i) {
+ ctx->offsets[i] = ctx->offsets[i - 1] + samplesSizes[i - 1];
+ }
+ }
+ DISPLAYLEVEL(2, "Constructing partial suffix array\n");
+ {
+ /* suffix is a partial suffix array.
+ * It only sorts suffixes by their first parameters.d bytes.
+ * The sort is stable, so each dmer group is sorted by position in input.
+ */
+ U32 i;
+ for (i = 0; i < ctx->suffixSize; ++i) {
+ ctx->suffix[i] = i;
+ }
+ /* qsort doesn't take an opaque pointer, so pass as a global.
+ * On OpenBSD qsort() is not guaranteed to be stable, their mergesort() is.
+ */
+ g_ctx = ctx;
+#if defined(__OpenBSD__)
+ mergesort(ctx->suffix, ctx->suffixSize, sizeof(U32),
+ (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
+#else
+ qsort(ctx->suffix, ctx->suffixSize, sizeof(U32),
+ (ctx->d <= 8 ? &COVER_strict_cmp8 : &COVER_strict_cmp));
+#endif
+ }
+ DISPLAYLEVEL(2, "Computing frequencies\n");
+ /* For each dmer group (group of positions with the same first d bytes):
+ * 1. For each position we set dmerAt[position] = dmerID. The dmerID is
+ * (groupBeginPtr - suffix). This allows us to go from position to
+ * dmerID so we can look up values in freq.
+ * 2. We calculate how many samples the dmer occurs in and save it in
+ * freqs[dmerId].
+ */
+ COVER_groupBy(ctx->suffix, ctx->suffixSize, sizeof(U32), ctx,
+ (ctx->d <= 8 ? &COVER_cmp8 : &COVER_cmp), &COVER_group);
+ ctx->freqs = ctx->suffix;
+ ctx->suffix = NULL;
+ return 1;
+}
+
+/**
+ * Given the prepared context build the dictionary.
+ */
+static size_t COVER_buildDictionary(const COVER_ctx_t *ctx, U32 *freqs,
+ COVER_map_t *activeDmers, void *dictBuffer,
+ size_t dictBufferCapacity,
+ ZDICT_cover_params_t parameters) {
+ BYTE *const dict = (BYTE *)dictBuffer;
+ size_t tail = dictBufferCapacity;
+ /* Divide the data up into epochs of equal size.
+ * We will select at least one segment from each epoch.
+ */
+ const unsigned epochs = MAX(1, (U32)(dictBufferCapacity / parameters.k / 4));
+ const unsigned epochSize = (U32)(ctx->suffixSize / epochs);
+ size_t epoch;
+ DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n",
+ epochs, epochSize);
+ /* Loop through the epochs until there are no more segments or the dictionary
+ * is full.
+ */
+ for (epoch = 0; tail > 0; epoch = (epoch + 1) % epochs) {
+ const U32 epochBegin = (U32)(epoch * epochSize);
+ const U32 epochEnd = epochBegin + epochSize;
+ size_t segmentSize;
+ /* Select a segment */
+ COVER_segment_t segment = COVER_selectSegment(
+ ctx, freqs, activeDmers, epochBegin, epochEnd, parameters);
+ /* If the segment covers no dmers, then we are out of content */
+ if (segment.score == 0) {
+ break;
+ }
+ /* Trim the segment if necessary and if it is too small then we are done */
+ segmentSize = MIN(segment.end - segment.begin + parameters.d - 1, tail);
+ if (segmentSize < parameters.d) {
+ break;
+ }
+ /* We fill the dictionary from the back to allow the best segments to be
+ * referenced with the smallest offsets.
+ */
+ tail -= segmentSize;
+ memcpy(dict + tail, ctx->samples + segment.begin, segmentSize);
+ DISPLAYUPDATE(
+ 2, "\r%u%% ",
+ (unsigned)(((dictBufferCapacity - tail) * 100) / dictBufferCapacity));
+ }
+ DISPLAYLEVEL(2, "\r%79s\r", "");
+ return tail;
+}
+
+ZDICTLIB_API size_t ZDICT_trainFromBuffer_cover(
+ void *dictBuffer, size_t dictBufferCapacity,
+ const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,
+ ZDICT_cover_params_t parameters)
+{
+ BYTE* const dict = (BYTE*)dictBuffer;
+ COVER_ctx_t ctx;
+ COVER_map_t activeDmers;
+ parameters.splitPoint = 1.0;
+ /* Initialize global data */
+ g_displayLevel = parameters.zParams.notificationLevel;
+ /* Checks */
+ if (!COVER_checkParameters(parameters, dictBufferCapacity)) {
+ DISPLAYLEVEL(1, "Cover parameters incorrect\n");
+ return ERROR(GENERIC);
+ }
+ if (nbSamples == 0) {
+ DISPLAYLEVEL(1, "Cover must have at least one input file\n");
+ return ERROR(GENERIC);
+ }
+ if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
+ DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
+ ZDICT_DICTSIZE_MIN);
+ return ERROR(dstSize_tooSmall);
+ }
+ /* Initialize context and activeDmers */
+ if (!COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples,
+ parameters.d, parameters.splitPoint)) {
+ return ERROR(GENERIC);
+ }
+ if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
+ DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
+ COVER_ctx_destroy(&ctx);
+ return ERROR(GENERIC);
+ }
+
+ DISPLAYLEVEL(2, "Building dictionary\n");
+ {
+ const size_t tail =
+ COVER_buildDictionary(&ctx, ctx.freqs, &activeDmers, dictBuffer,
+ dictBufferCapacity, parameters);
+ const size_t dictionarySize = ZDICT_finalizeDictionary(
+ dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
+ samplesBuffer, samplesSizes, nbSamples, parameters.zParams);
+ if (!ZSTD_isError(dictionarySize)) {
+ DISPLAYLEVEL(2, "Constructed dictionary of size %u\n",
+ (unsigned)dictionarySize);
+ }
+ COVER_ctx_destroy(&ctx);
+ COVER_map_destroy(&activeDmers);
+ return dictionarySize;
+ }
+}
+
+
+
+size_t COVER_checkTotalCompressedSize(const ZDICT_cover_params_t parameters,
+ const size_t *samplesSizes, const BYTE *samples,
+ size_t *offsets,
+ size_t nbTrainSamples, size_t nbSamples,
+ BYTE *const dict, size_t dictBufferCapacity) {
+ size_t totalCompressedSize = ERROR(GENERIC);
+ /* Pointers */
+ ZSTD_CCtx *cctx;
+ ZSTD_CDict *cdict;
+ void *dst;
+ /* Local variables */
+ size_t dstCapacity;
+ size_t i;
+ /* Allocate dst with enough space to compress the maximum sized sample */
+ {
+ size_t maxSampleSize = 0;
+ i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
+ for (; i < nbSamples; ++i) {
+ maxSampleSize = MAX(samplesSizes[i], maxSampleSize);
+ }
+ dstCapacity = ZSTD_compressBound(maxSampleSize);
+ dst = malloc(dstCapacity);
+ }
+ /* Create the cctx and cdict */
+ cctx = ZSTD_createCCtx();
+ cdict = ZSTD_createCDict(dict, dictBufferCapacity,
+ parameters.zParams.compressionLevel);
+ if (!dst || !cctx || !cdict) {
+ goto _compressCleanup;
+ }
+ /* Compress each sample and sum their sizes (or error) */
+ totalCompressedSize = dictBufferCapacity;
+ i = parameters.splitPoint < 1.0 ? nbTrainSamples : 0;
+ for (; i < nbSamples; ++i) {
+ const size_t size = ZSTD_compress_usingCDict(
+ cctx, dst, dstCapacity, samples + offsets[i],
+ samplesSizes[i], cdict);
+ if (ZSTD_isError(size)) {
+ totalCompressedSize = ERROR(GENERIC);
+ goto _compressCleanup;
+ }
+ totalCompressedSize += size;
+ }
+_compressCleanup:
+ ZSTD_freeCCtx(cctx);
+ ZSTD_freeCDict(cdict);
+ if (dst) {
+ free(dst);
+ }
+ return totalCompressedSize;
+}
+
+
+/**
+ * Initialize the `COVER_best_t`.
+ */
+void COVER_best_init(COVER_best_t *best) {
+ if (best==NULL) return; /* compatible with init on NULL */
+ (void)ZSTD_pthread_mutex_init(&best->mutex, NULL);
+ (void)ZSTD_pthread_cond_init(&best->cond, NULL);
+ best->liveJobs = 0;
+ best->dict = NULL;
+ best->dictSize = 0;
+ best->compressedSize = (size_t)-1;
+ memset(&best->parameters, 0, sizeof(best->parameters));
+}
+
+/**
+ * Wait until liveJobs == 0.
+ */
+void COVER_best_wait(COVER_best_t *best) {
+ if (!best) {
+ return;
+ }
+ ZSTD_pthread_mutex_lock(&best->mutex);
+ while (best->liveJobs != 0) {
+ ZSTD_pthread_cond_wait(&best->cond, &best->mutex);
+ }
+ ZSTD_pthread_mutex_unlock(&best->mutex);
+}
+
+/**
+ * Call COVER_best_wait() and then destroy the COVER_best_t.
+ */
+void COVER_best_destroy(COVER_best_t *best) {
+ if (!best) {
+ return;
+ }
+ COVER_best_wait(best);
+ if (best->dict) {
+ free(best->dict);
+ }
+ ZSTD_pthread_mutex_destroy(&best->mutex);
+ ZSTD_pthread_cond_destroy(&best->cond);
+}
+
+/**
+ * Called when a thread is about to be launched.
+ * Increments liveJobs.
+ */
+void COVER_best_start(COVER_best_t *best) {
+ if (!best) {
+ return;
+ }
+ ZSTD_pthread_mutex_lock(&best->mutex);
+ ++best->liveJobs;
+ ZSTD_pthread_mutex_unlock(&best->mutex);
+}
+
+/**
+ * Called when a thread finishes executing, both on error or success.
+ * Decrements liveJobs and signals any waiting threads if liveJobs == 0.
+ * If this dictionary is the best so far save it and its parameters.
+ */
+void COVER_best_finish(COVER_best_t *best, size_t compressedSize,
+ ZDICT_cover_params_t parameters, void *dict,
+ size_t dictSize) {
+ if (!best) {
+ return;
+ }
+ {
+ size_t liveJobs;
+ ZSTD_pthread_mutex_lock(&best->mutex);
+ --best->liveJobs;
+ liveJobs = best->liveJobs;
+ /* If the new dictionary is better */
+ if (compressedSize < best->compressedSize) {
+ /* Allocate space if necessary */
+ if (!best->dict || best->dictSize < dictSize) {
+ if (best->dict) {
+ free(best->dict);
+ }
+ best->dict = malloc(dictSize);
+ if (!best->dict) {
+ best->compressedSize = ERROR(GENERIC);
+ best->dictSize = 0;
+ ZSTD_pthread_cond_signal(&best->cond);
+ ZSTD_pthread_mutex_unlock(&best->mutex);
+ return;
+ }
+ }
+ /* Save the dictionary, parameters, and size */
+ memcpy(best->dict, dict, dictSize);
+ best->dictSize = dictSize;
+ best->parameters = parameters;
+ best->compressedSize = compressedSize;
+ }
+ if (liveJobs == 0) {
+ ZSTD_pthread_cond_broadcast(&best->cond);
+ }
+ ZSTD_pthread_mutex_unlock(&best->mutex);
+ }
+}
+
+/**
+ * Parameters for COVER_tryParameters().
+ */
+typedef struct COVER_tryParameters_data_s {
+ const COVER_ctx_t *ctx;
+ COVER_best_t *best;
+ size_t dictBufferCapacity;
+ ZDICT_cover_params_t parameters;
+} COVER_tryParameters_data_t;
+
+/**
+ * Tries a set of parameters and updates the COVER_best_t with the results.
+ * This function is thread safe if zstd is compiled with multithreaded support.
+ * It takes its parameters as an *OWNING* opaque pointer to support threading.
+ */
+static void COVER_tryParameters(void *opaque) {
+ /* Save parameters as local variables */
+ COVER_tryParameters_data_t *const data = (COVER_tryParameters_data_t *)opaque;
+ const COVER_ctx_t *const ctx = data->ctx;
+ const ZDICT_cover_params_t parameters = data->parameters;
+ size_t dictBufferCapacity = data->dictBufferCapacity;
+ size_t totalCompressedSize = ERROR(GENERIC);
+ /* Allocate space for hash table, dict, and freqs */
+ COVER_map_t activeDmers;
+ BYTE *const dict = (BYTE * const)malloc(dictBufferCapacity);
+ U32 *freqs = (U32 *)malloc(ctx->suffixSize * sizeof(U32));
+ if (!COVER_map_init(&activeDmers, parameters.k - parameters.d + 1)) {
+ DISPLAYLEVEL(1, "Failed to allocate dmer map: out of memory\n");
+ goto _cleanup;
+ }
+ if (!dict || !freqs) {
+ DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n");
+ goto _cleanup;
+ }
+ /* Copy the frequencies because we need to modify them */
+ memcpy(freqs, ctx->freqs, ctx->suffixSize * sizeof(U32));
+ /* Build the dictionary */
+ {
+ const size_t tail = COVER_buildDictionary(ctx, freqs, &activeDmers, dict,
+ dictBufferCapacity, parameters);
+ dictBufferCapacity = ZDICT_finalizeDictionary(
+ dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
+ ctx->samples, ctx->samplesSizes, (unsigned)ctx->nbTrainSamples,
+ parameters.zParams);
+ if (ZDICT_isError(dictBufferCapacity)) {
+ DISPLAYLEVEL(1, "Failed to finalize dictionary\n");
+ goto _cleanup;
+ }
+ }
+ /* Check total compressed size */
+ totalCompressedSize = COVER_checkTotalCompressedSize(parameters, ctx->samplesSizes,
+ ctx->samples, ctx->offsets,
+ ctx->nbTrainSamples, ctx->nbSamples,
+ dict, dictBufferCapacity);
+
+_cleanup:
+ COVER_best_finish(data->best, totalCompressedSize, parameters, dict,
+ dictBufferCapacity);
+ free(data);
+ COVER_map_destroy(&activeDmers);
+ if (dict) {
+ free(dict);
+ }
+ if (freqs) {
+ free(freqs);
+ }
+}
+
+ZDICTLIB_API size_t ZDICT_optimizeTrainFromBuffer_cover(
+ void *dictBuffer, size_t dictBufferCapacity, const void *samplesBuffer,
+ const size_t *samplesSizes, unsigned nbSamples,
+ ZDICT_cover_params_t *parameters) {
+ /* constants */
+ const unsigned nbThreads = parameters->nbThreads;
+ const double splitPoint =
+ parameters->splitPoint <= 0.0 ? DEFAULT_SPLITPOINT : parameters->splitPoint;
+ const unsigned kMinD = parameters->d == 0 ? 6 : parameters->d;
+ const unsigned kMaxD = parameters->d == 0 ? 8 : parameters->d;
+ const unsigned kMinK = parameters->k == 0 ? 50 : parameters->k;
+ const unsigned kMaxK = parameters->k == 0 ? 2000 : parameters->k;
+ const unsigned kSteps = parameters->steps == 0 ? 40 : parameters->steps;
+ const unsigned kStepSize = MAX((kMaxK - kMinK) / kSteps, 1);
+ const unsigned kIterations =
+ (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize);
+ /* Local variables */
+ const int displayLevel = parameters->zParams.notificationLevel;
+ unsigned iteration = 1;
+ unsigned d;
+ unsigned k;
+ COVER_best_t best;
+ POOL_ctx *pool = NULL;
+
+ /* Checks */
+ if (splitPoint <= 0 || splitPoint > 1) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
+ return ERROR(GENERIC);
+ }
+ if (kMinK < kMaxD || kMaxK < kMinK) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect parameters\n");
+ return ERROR(GENERIC);
+ }
+ if (nbSamples == 0) {
+ DISPLAYLEVEL(1, "Cover must have at least one input file\n");
+ return ERROR(GENERIC);
+ }
+ if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
+ DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
+ ZDICT_DICTSIZE_MIN);
+ return ERROR(dstSize_tooSmall);
+ }
+ if (nbThreads > 1) {
+ pool = POOL_create(nbThreads, 1);
+ if (!pool) {
+ return ERROR(memory_allocation);
+ }
+ }
+ /* Initialization */
+ COVER_best_init(&best);
+ /* Turn down global display level to clean up display at level 2 and below */
+ g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1;
+ /* Loop through d first because each new value needs a new context */
+ LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n",
+ kIterations);
+ for (d = kMinD; d <= kMaxD; d += 2) {
+ /* Initialize the context for this value of d */
+ COVER_ctx_t ctx;
+ LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d);
+ if (!COVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint)) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n");
+ COVER_best_destroy(&best);
+ POOL_free(pool);
+ return ERROR(GENERIC);
+ }
+ /* Loop through k reusing the same context */
+ for (k = kMinK; k <= kMaxK; k += kStepSize) {
+ /* Prepare the arguments */
+ COVER_tryParameters_data_t *data = (COVER_tryParameters_data_t *)malloc(
+ sizeof(COVER_tryParameters_data_t));
+ LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k);
+ if (!data) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n");
+ COVER_best_destroy(&best);
+ COVER_ctx_destroy(&ctx);
+ POOL_free(pool);
+ return ERROR(GENERIC);
+ }
+ data->ctx = &ctx;
+ data->best = &best;
+ data->dictBufferCapacity = dictBufferCapacity;
+ data->parameters = *parameters;
+ data->parameters.k = k;
+ data->parameters.d = d;
+ data->parameters.splitPoint = splitPoint;
+ data->parameters.steps = kSteps;
+ data->parameters.zParams.notificationLevel = g_displayLevel;
+ /* Check the parameters */
+ if (!COVER_checkParameters(data->parameters, dictBufferCapacity)) {
+ DISPLAYLEVEL(1, "Cover parameters incorrect\n");
+ free(data);
+ continue;
+ }
+ /* Call the function and pass ownership of data to it */
+ COVER_best_start(&best);
+ if (pool) {
+ POOL_add(pool, &COVER_tryParameters, data);
+ } else {
+ COVER_tryParameters(data);
+ }
+ /* Print status */
+ LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ",
+ (unsigned)((iteration * 100) / kIterations));
+ ++iteration;
+ }
+ COVER_best_wait(&best);
+ COVER_ctx_destroy(&ctx);
+ }
+ LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", "");
+ /* Fill the output buffer and parameters with output of the best parameters */
+ {
+ const size_t dictSize = best.dictSize;
+ if (ZSTD_isError(best.compressedSize)) {
+ const size_t compressedSize = best.compressedSize;
+ COVER_best_destroy(&best);
+ POOL_free(pool);
+ return compressedSize;
+ }
+ *parameters = best.parameters;
+ memcpy(dictBuffer, best.dict, dictSize);
+ COVER_best_destroy(&best);
+ POOL_free(pool);
+ return dictSize;
+ }
+}
diff --git a/Utilities/cmzstd/lib/dictBuilder/cover.h b/Utilities/cmzstd/lib/dictBuilder/cover.h
new file mode 100644
index 000000000..82e2e1cea
--- /dev/null
+++ b/Utilities/cmzstd/lib/dictBuilder/cover.h
@@ -0,0 +1,83 @@
+#include <stdio.h> /* fprintf */
+#include <stdlib.h> /* malloc, free, qsort */
+#include <string.h> /* memset */
+#include <time.h> /* clock */
+#include "mem.h" /* read */
+#include "pool.h"
+#include "threading.h"
+#include "zstd_internal.h" /* includes zstd.h */
+#ifndef ZDICT_STATIC_LINKING_ONLY
+#define ZDICT_STATIC_LINKING_ONLY
+#endif
+#include "zdict.h"
+
+/**
+ * COVER_best_t is used for two purposes:
+ * 1. Synchronizing threads.
+ * 2. Saving the best parameters and dictionary.
+ *
+ * All of the methods except COVER_best_init() are thread safe if zstd is
+ * compiled with multithreaded support.
+ */
+typedef struct COVER_best_s {
+ ZSTD_pthread_mutex_t mutex;
+ ZSTD_pthread_cond_t cond;
+ size_t liveJobs;
+ void *dict;
+ size_t dictSize;
+ ZDICT_cover_params_t parameters;
+ size_t compressedSize;
+} COVER_best_t;
+
+/**
+ * A segment is a range in the source as well as the score of the segment.
+ */
+typedef struct {
+ U32 begin;
+ U32 end;
+ U32 score;
+} COVER_segment_t;
+
+/**
+ * Checks total compressed size of a dictionary
+ */
+size_t COVER_checkTotalCompressedSize(const ZDICT_cover_params_t parameters,
+ const size_t *samplesSizes, const BYTE *samples,
+ size_t *offsets,
+ size_t nbTrainSamples, size_t nbSamples,
+ BYTE *const dict, size_t dictBufferCapacity);
+
+/**
+ * Returns the sum of the sample sizes.
+ */
+size_t COVER_sum(const size_t *samplesSizes, unsigned nbSamples) ;
+
+/**
+ * Initialize the `COVER_best_t`.
+ */
+void COVER_best_init(COVER_best_t *best);
+
+/**
+ * Wait until liveJobs == 0.
+ */
+void COVER_best_wait(COVER_best_t *best);
+
+/**
+ * Call COVER_best_wait() and then destroy the COVER_best_t.
+ */
+void COVER_best_destroy(COVER_best_t *best);
+
+/**
+ * Called when a thread is about to be launched.
+ * Increments liveJobs.
+ */
+void COVER_best_start(COVER_best_t *best);
+
+/**
+ * Called when a thread finishes executing, both on error or success.
+ * Decrements liveJobs and signals any waiting threads if liveJobs == 0.
+ * If this dictionary is the best so far save it and its parameters.
+ */
+void COVER_best_finish(COVER_best_t *best, size_t compressedSize,
+ ZDICT_cover_params_t parameters, void *dict,
+ size_t dictSize);
diff --git a/Utilities/cmzstd/lib/dictBuilder/divsufsort.c b/Utilities/cmzstd/lib/dictBuilder/divsufsort.c
new file mode 100644
index 000000000..ead922044
--- /dev/null
+++ b/Utilities/cmzstd/lib/dictBuilder/divsufsort.c
@@ -0,0 +1,1913 @@
+/*
+ * divsufsort.c for libdivsufsort-lite
+ * Copyright (c) 2003-2008 Yuta Mori All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following
+ * conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*- Compiler specifics -*/
+#ifdef __clang__
+#pragma clang diagnostic ignored "-Wshorten-64-to-32"
+#endif
+
+#if defined(_MSC_VER)
+# pragma warning(disable : 4244)
+# pragma warning(disable : 4127) /* C4127 : Condition expression is constant */
+#endif
+
+
+/*- Dependencies -*/
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "divsufsort.h"
+
+/*- Constants -*/
+#if defined(INLINE)
+# undef INLINE
+#endif
+#if !defined(INLINE)
+# define INLINE __inline
+#endif
+#if defined(ALPHABET_SIZE) && (ALPHABET_SIZE < 1)
+# undef ALPHABET_SIZE
+#endif
+#if !defined(ALPHABET_SIZE)
+# define ALPHABET_SIZE (256)
+#endif
+#define BUCKET_A_SIZE (ALPHABET_SIZE)
+#define BUCKET_B_SIZE (ALPHABET_SIZE * ALPHABET_SIZE)
+#if defined(SS_INSERTIONSORT_THRESHOLD)
+# if SS_INSERTIONSORT_THRESHOLD < 1
+# undef SS_INSERTIONSORT_THRESHOLD
+# define SS_INSERTIONSORT_THRESHOLD (1)
+# endif
+#else
+# define SS_INSERTIONSORT_THRESHOLD (8)
+#endif
+#if defined(SS_BLOCKSIZE)
+# if SS_BLOCKSIZE < 0
+# undef SS_BLOCKSIZE
+# define SS_BLOCKSIZE (0)
+# elif 32768 <= SS_BLOCKSIZE
+# undef SS_BLOCKSIZE
+# define SS_BLOCKSIZE (32767)
+# endif
+#else
+# define SS_BLOCKSIZE (1024)
+#endif
+/* minstacksize = log(SS_BLOCKSIZE) / log(3) * 2 */
+#if SS_BLOCKSIZE == 0
+# define SS_MISORT_STACKSIZE (96)
+#elif SS_BLOCKSIZE <= 4096
+# define SS_MISORT_STACKSIZE (16)
+#else
+# define SS_MISORT_STACKSIZE (24)
+#endif
+#define SS_SMERGE_STACKSIZE (32)
+#define TR_INSERTIONSORT_THRESHOLD (8)
+#define TR_STACKSIZE (64)
+
+
+/*- Macros -*/
+#ifndef SWAP
+# define SWAP(_a, _b) do { t = (_a); (_a) = (_b); (_b) = t; } while(0)
+#endif /* SWAP */
+#ifndef MIN
+# define MIN(_a, _b) (((_a) < (_b)) ? (_a) : (_b))
+#endif /* MIN */
+#ifndef MAX
+# define MAX(_a, _b) (((_a) > (_b)) ? (_a) : (_b))
+#endif /* MAX */
+#define STACK_PUSH(_a, _b, _c, _d)\
+ do {\
+ assert(ssize < STACK_SIZE);\
+ stack[ssize].a = (_a), stack[ssize].b = (_b),\
+ stack[ssize].c = (_c), stack[ssize++].d = (_d);\
+ } while(0)
+#define STACK_PUSH5(_a, _b, _c, _d, _e)\
+ do {\
+ assert(ssize < STACK_SIZE);\
+ stack[ssize].a = (_a), stack[ssize].b = (_b),\
+ stack[ssize].c = (_c), stack[ssize].d = (_d), stack[ssize++].e = (_e);\
+ } while(0)
+#define STACK_POP(_a, _b, _c, _d)\
+ do {\
+ assert(0 <= ssize);\
+ if(ssize == 0) { return; }\
+ (_a) = stack[--ssize].a, (_b) = stack[ssize].b,\
+ (_c) = stack[ssize].c, (_d) = stack[ssize].d;\
+ } while(0)
+#define STACK_POP5(_a, _b, _c, _d, _e)\
+ do {\
+ assert(0 <= ssize);\
+ if(ssize == 0) { return; }\
+ (_a) = stack[--ssize].a, (_b) = stack[ssize].b,\
+ (_c) = stack[ssize].c, (_d) = stack[ssize].d, (_e) = stack[ssize].e;\
+ } while(0)
+#define BUCKET_A(_c0) bucket_A[(_c0)]
+#if ALPHABET_SIZE == 256
+#define BUCKET_B(_c0, _c1) (bucket_B[((_c1) << 8) | (_c0)])
+#define BUCKET_BSTAR(_c0, _c1) (bucket_B[((_c0) << 8) | (_c1)])
+#else
+#define BUCKET_B(_c0, _c1) (bucket_B[(_c1) * ALPHABET_SIZE + (_c0)])
+#define BUCKET_BSTAR(_c0, _c1) (bucket_B[(_c0) * ALPHABET_SIZE + (_c1)])
+#endif
+
+
+/*- Private Functions -*/
+
+static const int lg_table[256]= {
+ -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
+ 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+ 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,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,
+ 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
+};
+
+#if (SS_BLOCKSIZE == 0) || (SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE)
+
+static INLINE
+int
+ss_ilg(int n) {
+#if SS_BLOCKSIZE == 0
+ return (n & 0xffff0000) ?
+ ((n & 0xff000000) ?
+ 24 + lg_table[(n >> 24) & 0xff] :
+ 16 + lg_table[(n >> 16) & 0xff]) :
+ ((n & 0x0000ff00) ?
+ 8 + lg_table[(n >> 8) & 0xff] :
+ 0 + lg_table[(n >> 0) & 0xff]);
+#elif SS_BLOCKSIZE < 256
+ return lg_table[n];
+#else
+ return (n & 0xff00) ?
+ 8 + lg_table[(n >> 8) & 0xff] :
+ 0 + lg_table[(n >> 0) & 0xff];
+#endif
+}
+
+#endif /* (SS_BLOCKSIZE == 0) || (SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE) */
+
+#if SS_BLOCKSIZE != 0
+
+static const int sqq_table[256] = {
+ 0, 16, 22, 27, 32, 35, 39, 42, 45, 48, 50, 53, 55, 57, 59, 61,
+ 64, 65, 67, 69, 71, 73, 75, 76, 78, 80, 81, 83, 84, 86, 87, 89,
+ 90, 91, 93, 94, 96, 97, 98, 99, 101, 102, 103, 104, 106, 107, 108, 109,
+110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
+128, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
+143, 144, 144, 145, 146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155,
+156, 157, 158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166, 167, 167, 168,
+169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178, 179, 180,
+181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188, 189, 189, 190, 191,
+192, 192, 193, 193, 194, 195, 195, 196, 197, 197, 198, 199, 199, 200, 201, 201,
+202, 203, 203, 204, 204, 205, 206, 206, 207, 208, 208, 209, 209, 210, 211, 211,
+212, 212, 213, 214, 214, 215, 215, 216, 217, 217, 218, 218, 219, 219, 220, 221,
+221, 222, 222, 223, 224, 224, 225, 225, 226, 226, 227, 227, 228, 229, 229, 230,
+230, 231, 231, 232, 232, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238,
+239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246, 246, 247,
+247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253, 253, 254, 254, 255
+};
+
+static INLINE
+int
+ss_isqrt(int x) {
+ int y, e;
+
+ if(x >= (SS_BLOCKSIZE * SS_BLOCKSIZE)) { return SS_BLOCKSIZE; }
+ e = (x & 0xffff0000) ?
+ ((x & 0xff000000) ?
+ 24 + lg_table[(x >> 24) & 0xff] :
+ 16 + lg_table[(x >> 16) & 0xff]) :
+ ((x & 0x0000ff00) ?
+ 8 + lg_table[(x >> 8) & 0xff] :
+ 0 + lg_table[(x >> 0) & 0xff]);
+
+ if(e >= 16) {
+ y = sqq_table[x >> ((e - 6) - (e & 1))] << ((e >> 1) - 7);
+ if(e >= 24) { y = (y + 1 + x / y) >> 1; }
+ y = (y + 1 + x / y) >> 1;
+ } else if(e >= 8) {
+ y = (sqq_table[x >> ((e - 6) - (e & 1))] >> (7 - (e >> 1))) + 1;
+ } else {
+ return sqq_table[x] >> 4;
+ }
+
+ return (x < (y * y)) ? y - 1 : y;
+}
+
+#endif /* SS_BLOCKSIZE != 0 */
+
+
+/*---------------------------------------------------------------------------*/
+
+/* Compares two suffixes. */
+static INLINE
+int
+ss_compare(const unsigned char *T,
+ const int *p1, const int *p2,
+ int depth) {
+ const unsigned char *U1, *U2, *U1n, *U2n;
+
+ for(U1 = T + depth + *p1,
+ U2 = T + depth + *p2,
+ U1n = T + *(p1 + 1) + 2,
+ U2n = T + *(p2 + 1) + 2;
+ (U1 < U1n) && (U2 < U2n) && (*U1 == *U2);
+ ++U1, ++U2) {
+ }
+
+ return U1 < U1n ?
+ (U2 < U2n ? *U1 - *U2 : 1) :
+ (U2 < U2n ? -1 : 0);
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+#if (SS_BLOCKSIZE != 1) && (SS_INSERTIONSORT_THRESHOLD != 1)
+
+/* Insertionsort for small size groups */
+static
+void
+ss_insertionsort(const unsigned char *T, const int *PA,
+ int *first, int *last, int depth) {
+ int *i, *j;
+ int t;
+ int r;
+
+ for(i = last - 2; first <= i; --i) {
+ for(t = *i, j = i + 1; 0 < (r = ss_compare(T, PA + t, PA + *j, depth));) {
+ do { *(j - 1) = *j; } while((++j < last) && (*j < 0));
+ if(last <= j) { break; }
+ }
+ if(r == 0) { *j = ~*j; }
+ *(j - 1) = t;
+ }
+}
+
+#endif /* (SS_BLOCKSIZE != 1) && (SS_INSERTIONSORT_THRESHOLD != 1) */
+
+
+/*---------------------------------------------------------------------------*/
+
+#if (SS_BLOCKSIZE == 0) || (SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE)
+
+static INLINE
+void
+ss_fixdown(const unsigned char *Td, const int *PA,
+ int *SA, int i, int size) {
+ int j, k;
+ int v;
+ int c, d, e;
+
+ for(v = SA[i], c = Td[PA[v]]; (j = 2 * i + 1) < size; SA[i] = SA[k], i = k) {
+ d = Td[PA[SA[k = j++]]];
+ if(d < (e = Td[PA[SA[j]]])) { k = j; d = e; }
+ if(d <= c) { break; }
+ }
+ SA[i] = v;
+}
+
+/* Simple top-down heapsort. */
+static
+void
+ss_heapsort(const unsigned char *Td, const int *PA, int *SA, int size) {
+ int i, m;
+ int t;
+
+ m = size;
+ if((size % 2) == 0) {
+ m--;
+ if(Td[PA[SA[m / 2]]] < Td[PA[SA[m]]]) { SWAP(SA[m], SA[m / 2]); }
+ }
+
+ for(i = m / 2 - 1; 0 <= i; --i) { ss_fixdown(Td, PA, SA, i, m); }
+ if((size % 2) == 0) { SWAP(SA[0], SA[m]); ss_fixdown(Td, PA, SA, 0, m); }
+ for(i = m - 1; 0 < i; --i) {
+ t = SA[0], SA[0] = SA[i];
+ ss_fixdown(Td, PA, SA, 0, i);
+ SA[i] = t;
+ }
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+/* Returns the median of three elements. */
+static INLINE
+int *
+ss_median3(const unsigned char *Td, const int *PA,
+ int *v1, int *v2, int *v3) {
+ int *t;
+ if(Td[PA[*v1]] > Td[PA[*v2]]) { SWAP(v1, v2); }
+ if(Td[PA[*v2]] > Td[PA[*v3]]) {
+ if(Td[PA[*v1]] > Td[PA[*v3]]) { return v1; }
+ else { return v3; }
+ }
+ return v2;
+}
+
+/* Returns the median of five elements. */
+static INLINE
+int *
+ss_median5(const unsigned char *Td, const int *PA,
+ int *v1, int *v2, int *v3, int *v4, int *v5) {
+ int *t;
+ if(Td[PA[*v2]] > Td[PA[*v3]]) { SWAP(v2, v3); }
+ if(Td[PA[*v4]] > Td[PA[*v5]]) { SWAP(v4, v5); }
+ if(Td[PA[*v2]] > Td[PA[*v4]]) { SWAP(v2, v4); SWAP(v3, v5); }
+ if(Td[PA[*v1]] > Td[PA[*v3]]) { SWAP(v1, v3); }
+ if(Td[PA[*v1]] > Td[PA[*v4]]) { SWAP(v1, v4); SWAP(v3, v5); }
+ if(Td[PA[*v3]] > Td[PA[*v4]]) { return v4; }
+ return v3;
+}
+
+/* Returns the pivot element. */
+static INLINE
+int *
+ss_pivot(const unsigned char *Td, const int *PA, int *first, int *last) {
+ int *middle;
+ int t;
+
+ t = last - first;
+ middle = first + t / 2;
+
+ if(t <= 512) {
+ if(t <= 32) {
+ return ss_median3(Td, PA, first, middle, last - 1);
+ } else {
+ t >>= 2;
+ return ss_median5(Td, PA, first, first + t, middle, last - 1 - t, last - 1);
+ }
+ }
+ t >>= 3;
+ first = ss_median3(Td, PA, first, first + t, first + (t << 1));
+ middle = ss_median3(Td, PA, middle - t, middle, middle + t);
+ last = ss_median3(Td, PA, last - 1 - (t << 1), last - 1 - t, last - 1);
+ return ss_median3(Td, PA, first, middle, last);
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+/* Binary partition for substrings. */
+static INLINE
+int *
+ss_partition(const int *PA,
+ int *first, int *last, int depth) {
+ int *a, *b;
+ int t;
+ for(a = first - 1, b = last;;) {
+ for(; (++a < b) && ((PA[*a] + depth) >= (PA[*a + 1] + 1));) { *a = ~*a; }
+ for(; (a < --b) && ((PA[*b] + depth) < (PA[*b + 1] + 1));) { }
+ if(b <= a) { break; }
+ t = ~*b;
+ *b = *a;
+ *a = t;
+ }
+ if(first < a) { *first = ~*first; }
+ return a;
+}
+
+/* Multikey introsort for medium size groups. */
+static
+void
+ss_mintrosort(const unsigned char *T, const int *PA,
+ int *first, int *last,
+ int depth) {
+#define STACK_SIZE SS_MISORT_STACKSIZE
+ struct { int *a, *b, c; int d; } stack[STACK_SIZE];
+ const unsigned char *Td;
+ int *a, *b, *c, *d, *e, *f;
+ int s, t;
+ int ssize;
+ int limit;
+ int v, x = 0;
+
+ for(ssize = 0, limit = ss_ilg(last - first);;) {
+
+ if((last - first) <= SS_INSERTIONSORT_THRESHOLD) {
+#if 1 < SS_INSERTIONSORT_THRESHOLD
+ if(1 < (last - first)) { ss_insertionsort(T, PA, first, last, depth); }
+#endif
+ STACK_POP(first, last, depth, limit);
+ continue;
+ }
+
+ Td = T + depth;
+ if(limit-- == 0) { ss_heapsort(Td, PA, first, last - first); }
+ if(limit < 0) {
+ for(a = first + 1, v = Td[PA[*first]]; a < last; ++a) {
+ if((x = Td[PA[*a]]) != v) {
+ if(1 < (a - first)) { break; }
+ v = x;
+ first = a;
+ }
+ }
+ if(Td[PA[*first] - 1] < v) {
+ first = ss_partition(PA, first, a, depth);
+ }
+ if((a - first) <= (last - a)) {
+ if(1 < (a - first)) {
+ STACK_PUSH(a, last, depth, -1);
+ last = a, depth += 1, limit = ss_ilg(a - first);
+ } else {
+ first = a, limit = -1;
+ }
+ } else {
+ if(1 < (last - a)) {
+ STACK_PUSH(first, a, depth + 1, ss_ilg(a - first));
+ first = a, limit = -1;
+ } else {
+ last = a, depth += 1, limit = ss_ilg(a - first);
+ }
+ }
+ continue;
+ }
+
+ /* choose pivot */
+ a = ss_pivot(Td, PA, first, last);
+ v = Td[PA[*a]];
+ SWAP(*first, *a);
+
+ /* partition */
+ for(b = first; (++b < last) && ((x = Td[PA[*b]]) == v);) { }
+ if(((a = b) < last) && (x < v)) {
+ for(; (++b < last) && ((x = Td[PA[*b]]) <= v);) {
+ if(x == v) { SWAP(*b, *a); ++a; }
+ }
+ }
+ for(c = last; (b < --c) && ((x = Td[PA[*c]]) == v);) { }
+ if((b < (d = c)) && (x > v)) {
+ for(; (b < --c) && ((x = Td[PA[*c]]) >= v);) {
+ if(x == v) { SWAP(*c, *d); --d; }
+ }
+ }
+ for(; b < c;) {
+ SWAP(*b, *c);
+ for(; (++b < c) && ((x = Td[PA[*b]]) <= v);) {
+ if(x == v) { SWAP(*b, *a); ++a; }
+ }
+ for(; (b < --c) && ((x = Td[PA[*c]]) >= v);) {
+ if(x == v) { SWAP(*c, *d); --d; }
+ }
+ }
+
+ if(a <= d) {
+ c = b - 1;
+
+ if((s = a - first) > (t = b - a)) { s = t; }
+ for(e = first, f = b - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); }
+ if((s = d - c) > (t = last - d - 1)) { s = t; }
+ for(e = b, f = last - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); }
+
+ a = first + (b - a), c = last - (d - c);
+ b = (v <= Td[PA[*a] - 1]) ? a : ss_partition(PA, a, c, depth);
+
+ if((a - first) <= (last - c)) {
+ if((last - c) <= (c - b)) {
+ STACK_PUSH(b, c, depth + 1, ss_ilg(c - b));
+ STACK_PUSH(c, last, depth, limit);
+ last = a;
+ } else if((a - first) <= (c - b)) {
+ STACK_PUSH(c, last, depth, limit);
+ STACK_PUSH(b, c, depth + 1, ss_ilg(c - b));
+ last = a;
+ } else {
+ STACK_PUSH(c, last, depth, limit);
+ STACK_PUSH(first, a, depth, limit);
+ first = b, last = c, depth += 1, limit = ss_ilg(c - b);
+ }
+ } else {
+ if((a - first) <= (c - b)) {
+ STACK_PUSH(b, c, depth + 1, ss_ilg(c - b));
+ STACK_PUSH(first, a, depth, limit);
+ first = c;
+ } else if((last - c) <= (c - b)) {
+ STACK_PUSH(first, a, depth, limit);
+ STACK_PUSH(b, c, depth + 1, ss_ilg(c - b));
+ first = c;
+ } else {
+ STACK_PUSH(first, a, depth, limit);
+ STACK_PUSH(c, last, depth, limit);
+ first = b, last = c, depth += 1, limit = ss_ilg(c - b);
+ }
+ }
+ } else {
+ limit += 1;
+ if(Td[PA[*first] - 1] < v) {
+ first = ss_partition(PA, first, last, depth);
+ limit = ss_ilg(last - first);
+ }
+ depth += 1;
+ }
+ }
+#undef STACK_SIZE
+}
+
+#endif /* (SS_BLOCKSIZE == 0) || (SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE) */
+
+
+/*---------------------------------------------------------------------------*/
+
+#if SS_BLOCKSIZE != 0
+
+static INLINE
+void
+ss_blockswap(int *a, int *b, int n) {
+ int t;
+ for(; 0 < n; --n, ++a, ++b) {
+ t = *a, *a = *b, *b = t;
+ }
+}
+
+static INLINE
+void
+ss_rotate(int *first, int *middle, int *last) {
+ int *a, *b, t;
+ int l, r;
+ l = middle - first, r = last - middle;
+ for(; (0 < l) && (0 < r);) {
+ if(l == r) { ss_blockswap(first, middle, l); break; }
+ if(l < r) {
+ a = last - 1, b = middle - 1;
+ t = *a;
+ do {
+ *a-- = *b, *b-- = *a;
+ if(b < first) {
+ *a = t;
+ last = a;
+ if((r -= l + 1) <= l) { break; }
+ a -= 1, b = middle - 1;
+ t = *a;
+ }
+ } while(1);
+ } else {
+ a = first, b = middle;
+ t = *a;
+ do {
+ *a++ = *b, *b++ = *a;
+ if(last <= b) {
+ *a = t;
+ first = a + 1;
+ if((l -= r + 1) <= r) { break; }
+ a += 1, b = middle;
+ t = *a;
+ }
+ } while(1);
+ }
+ }
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+static
+void
+ss_inplacemerge(const unsigned char *T, const int *PA,
+ int *first, int *middle, int *last,
+ int depth) {
+ const int *p;
+ int *a, *b;
+ int len, half;
+ int q, r;
+ int x;
+
+ for(;;) {
+ if(*(last - 1) < 0) { x = 1; p = PA + ~*(last - 1); }
+ else { x = 0; p = PA + *(last - 1); }
+ for(a = first, len = middle - first, half = len >> 1, r = -1;
+ 0 < len;
+ len = half, half >>= 1) {
+ b = a + half;
+ q = ss_compare(T, PA + ((0 <= *b) ? *b : ~*b), p, depth);
+ if(q < 0) {
+ a = b + 1;
+ half -= (len & 1) ^ 1;
+ } else {
+ r = q;
+ }
+ }
+ if(a < middle) {
+ if(r == 0) { *a = ~*a; }
+ ss_rotate(a, middle, last);
+ last -= middle - a;
+ middle = a;
+ if(first == middle) { break; }
+ }
+ --last;
+ if(x != 0) { while(*--last < 0) { } }
+ if(middle == last) { break; }
+ }
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+/* Merge-forward with internal buffer. */
+static
+void
+ss_mergeforward(const unsigned char *T, const int *PA,
+ int *first, int *middle, int *last,
+ int *buf, int depth) {
+ int *a, *b, *c, *bufend;
+ int t;
+ int r;
+
+ bufend = buf + (middle - first) - 1;
+ ss_blockswap(buf, first, middle - first);
+
+ for(t = *(a = first), b = buf, c = middle;;) {
+ r = ss_compare(T, PA + *b, PA + *c, depth);
+ if(r < 0) {
+ do {
+ *a++ = *b;
+ if(bufend <= b) { *bufend = t; return; }
+ *b++ = *a;
+ } while(*b < 0);
+ } else if(r > 0) {
+ do {
+ *a++ = *c, *c++ = *a;
+ if(last <= c) {
+ while(b < bufend) { *a++ = *b, *b++ = *a; }
+ *a = *b, *b = t;
+ return;
+ }
+ } while(*c < 0);
+ } else {
+ *c = ~*c;
+ do {
+ *a++ = *b;
+ if(bufend <= b) { *bufend = t; return; }
+ *b++ = *a;
+ } while(*b < 0);
+
+ do {
+ *a++ = *c, *c++ = *a;
+ if(last <= c) {
+ while(b < bufend) { *a++ = *b, *b++ = *a; }
+ *a = *b, *b = t;
+ return;
+ }
+ } while(*c < 0);
+ }
+ }
+}
+
+/* Merge-backward with internal buffer. */
+static
+void
+ss_mergebackward(const unsigned char *T, const int *PA,
+ int *first, int *middle, int *last,
+ int *buf, int depth) {
+ const int *p1, *p2;
+ int *a, *b, *c, *bufend;
+ int t;
+ int r;
+ int x;
+
+ bufend = buf + (last - middle) - 1;
+ ss_blockswap(buf, middle, last - middle);
+
+ x = 0;
+ if(*bufend < 0) { p1 = PA + ~*bufend; x |= 1; }
+ else { p1 = PA + *bufend; }
+ if(*(middle - 1) < 0) { p2 = PA + ~*(middle - 1); x |= 2; }
+ else { p2 = PA + *(middle - 1); }
+ for(t = *(a = last - 1), b = bufend, c = middle - 1;;) {
+ r = ss_compare(T, p1, p2, depth);
+ if(0 < r) {
+ if(x & 1) { do { *a-- = *b, *b-- = *a; } while(*b < 0); x ^= 1; }
+ *a-- = *b;
+ if(b <= buf) { *buf = t; break; }
+ *b-- = *a;
+ if(*b < 0) { p1 = PA + ~*b; x |= 1; }
+ else { p1 = PA + *b; }
+ } else if(r < 0) {
+ if(x & 2) { do { *a-- = *c, *c-- = *a; } while(*c < 0); x ^= 2; }
+ *a-- = *c, *c-- = *a;
+ if(c < first) {
+ while(buf < b) { *a-- = *b, *b-- = *a; }
+ *a = *b, *b = t;
+ break;
+ }
+ if(*c < 0) { p2 = PA + ~*c; x |= 2; }
+ else { p2 = PA + *c; }
+ } else {
+ if(x & 1) { do { *a-- = *b, *b-- = *a; } while(*b < 0); x ^= 1; }
+ *a-- = ~*b;
+ if(b <= buf) { *buf = t; break; }
+ *b-- = *a;
+ if(x & 2) { do { *a-- = *c, *c-- = *a; } while(*c < 0); x ^= 2; }
+ *a-- = *c, *c-- = *a;
+ if(c < first) {
+ while(buf < b) { *a-- = *b, *b-- = *a; }
+ *a = *b, *b = t;
+ break;
+ }
+ if(*b < 0) { p1 = PA + ~*b; x |= 1; }
+ else { p1 = PA + *b; }
+ if(*c < 0) { p2 = PA + ~*c; x |= 2; }
+ else { p2 = PA + *c; }
+ }
+ }
+}
+
+/* D&C based merge. */
+static
+void
+ss_swapmerge(const unsigned char *T, const int *PA,
+ int *first, int *middle, int *last,
+ int *buf, int bufsize, int depth) {
+#define STACK_SIZE SS_SMERGE_STACKSIZE
+#define GETIDX(a) ((0 <= (a)) ? (a) : (~(a)))
+#define MERGE_CHECK(a, b, c)\
+ do {\
+ if(((c) & 1) ||\
+ (((c) & 2) && (ss_compare(T, PA + GETIDX(*((a) - 1)), PA + *(a), depth) == 0))) {\
+ *(a) = ~*(a);\
+ }\
+ if(((c) & 4) && ((ss_compare(T, PA + GETIDX(*((b) - 1)), PA + *(b), depth) == 0))) {\
+ *(b) = ~*(b);\
+ }\
+ } while(0)
+ struct { int *a, *b, *c; int d; } stack[STACK_SIZE];
+ int *l, *r, *lm, *rm;
+ int m, len, half;
+ int ssize;
+ int check, next;
+
+ for(check = 0, ssize = 0;;) {
+ if((last - middle) <= bufsize) {
+ if((first < middle) && (middle < last)) {
+ ss_mergebackward(T, PA, first, middle, last, buf, depth);
+ }
+ MERGE_CHECK(first, last, check);
+ STACK_POP(first, middle, last, check);
+ continue;
+ }
+
+ if((middle - first) <= bufsize) {
+ if(first < middle) {
+ ss_mergeforward(T, PA, first, middle, last, buf, depth);
+ }
+ MERGE_CHECK(first, last, check);
+ STACK_POP(first, middle, last, check);
+ continue;
+ }
+
+ for(m = 0, len = MIN(middle - first, last - middle), half = len >> 1;
+ 0 < len;
+ len = half, half >>= 1) {
+ if(ss_compare(T, PA + GETIDX(*(middle + m + half)),
+ PA + GETIDX(*(middle - m - half - 1)), depth) < 0) {
+ m += half + 1;
+ half -= (len & 1) ^ 1;
+ }
+ }
+
+ if(0 < m) {
+ lm = middle - m, rm = middle + m;
+ ss_blockswap(lm, middle, m);
+ l = r = middle, next = 0;
+ if(rm < last) {
+ if(*rm < 0) {
+ *rm = ~*rm;
+ if(first < lm) { for(; *--l < 0;) { } next |= 4; }
+ next |= 1;
+ } else if(first < lm) {
+ for(; *r < 0; ++r) { }
+ next |= 2;
+ }
+ }
+
+ if((l - first) <= (last - r)) {
+ STACK_PUSH(r, rm, last, (next & 3) | (check & 4));
+ middle = lm, last = l, check = (check & 3) | (next & 4);
+ } else {
+ if((next & 2) && (r == middle)) { next ^= 6; }
+ STACK_PUSH(first, lm, l, (check & 3) | (next & 4));
+ first = r, middle = rm, check = (next & 3) | (check & 4);
+ }
+ } else {
+ if(ss_compare(T, PA + GETIDX(*(middle - 1)), PA + *middle, depth) == 0) {
+ *middle = ~*middle;
+ }
+ MERGE_CHECK(first, last, check);
+ STACK_POP(first, middle, last, check);
+ }
+ }
+#undef STACK_SIZE
+}
+
+#endif /* SS_BLOCKSIZE != 0 */
+
+
+/*---------------------------------------------------------------------------*/
+
+/* Substring sort */
+static
+void
+sssort(const unsigned char *T, const int *PA,
+ int *first, int *last,
+ int *buf, int bufsize,
+ int depth, int n, int lastsuffix) {
+ int *a;
+#if SS_BLOCKSIZE != 0
+ int *b, *middle, *curbuf;
+ int j, k, curbufsize, limit;
+#endif
+ int i;
+
+ if(lastsuffix != 0) { ++first; }
+
+#if SS_BLOCKSIZE == 0
+ ss_mintrosort(T, PA, first, last, depth);
+#else
+ if((bufsize < SS_BLOCKSIZE) &&
+ (bufsize < (last - first)) &&
+ (bufsize < (limit = ss_isqrt(last - first)))) {
+ if(SS_BLOCKSIZE < limit) { limit = SS_BLOCKSIZE; }
+ buf = middle = last - limit, bufsize = limit;
+ } else {
+ middle = last, limit = 0;
+ }
+ for(a = first, i = 0; SS_BLOCKSIZE < (middle - a); a += SS_BLOCKSIZE, ++i) {
+#if SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE
+ ss_mintrosort(T, PA, a, a + SS_BLOCKSIZE, depth);
+#elif 1 < SS_BLOCKSIZE
+ ss_insertionsort(T, PA, a, a + SS_BLOCKSIZE, depth);
+#endif
+ curbufsize = last - (a + SS_BLOCKSIZE);
+ curbuf = a + SS_BLOCKSIZE;
+ if(curbufsize <= bufsize) { curbufsize = bufsize, curbuf = buf; }
+ for(b = a, k = SS_BLOCKSIZE, j = i; j & 1; b -= k, k <<= 1, j >>= 1) {
+ ss_swapmerge(T, PA, b - k, b, b + k, curbuf, curbufsize, depth);
+ }
+ }
+#if SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE
+ ss_mintrosort(T, PA, a, middle, depth);
+#elif 1 < SS_BLOCKSIZE
+ ss_insertionsort(T, PA, a, middle, depth);
+#endif
+ for(k = SS_BLOCKSIZE; i != 0; k <<= 1, i >>= 1) {
+ if(i & 1) {
+ ss_swapmerge(T, PA, a - k, a, middle, buf, bufsize, depth);
+ a -= k;
+ }
+ }
+ if(limit != 0) {
+#if SS_INSERTIONSORT_THRESHOLD < SS_BLOCKSIZE
+ ss_mintrosort(T, PA, middle, last, depth);
+#elif 1 < SS_BLOCKSIZE
+ ss_insertionsort(T, PA, middle, last, depth);
+#endif
+ ss_inplacemerge(T, PA, first, middle, last, depth);
+ }
+#endif
+
+ if(lastsuffix != 0) {
+ /* Insert last type B* suffix. */
+ int PAi[2]; PAi[0] = PA[*(first - 1)], PAi[1] = n - 2;
+ for(a = first, i = *(first - 1);
+ (a < last) && ((*a < 0) || (0 < ss_compare(T, &(PAi[0]), PA + *a, depth)));
+ ++a) {
+ *(a - 1) = *a;
+ }
+ *(a - 1) = i;
+ }
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+static INLINE
+int
+tr_ilg(int n) {
+ return (n & 0xffff0000) ?
+ ((n & 0xff000000) ?
+ 24 + lg_table[(n >> 24) & 0xff] :
+ 16 + lg_table[(n >> 16) & 0xff]) :
+ ((n & 0x0000ff00) ?
+ 8 + lg_table[(n >> 8) & 0xff] :
+ 0 + lg_table[(n >> 0) & 0xff]);
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+/* Simple insertionsort for small size groups. */
+static
+void
+tr_insertionsort(const int *ISAd, int *first, int *last) {
+ int *a, *b;
+ int t, r;
+
+ for(a = first + 1; a < last; ++a) {
+ for(t = *a, b = a - 1; 0 > (r = ISAd[t] - ISAd[*b]);) {
+ do { *(b + 1) = *b; } while((first <= --b) && (*b < 0));
+ if(b < first) { break; }
+ }
+ if(r == 0) { *b = ~*b; }
+ *(b + 1) = t;
+ }
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+static INLINE
+void
+tr_fixdown(const int *ISAd, int *SA, int i, int size) {
+ int j, k;
+ int v;
+ int c, d, e;
+
+ for(v = SA[i], c = ISAd[v]; (j = 2 * i + 1) < size; SA[i] = SA[k], i = k) {
+ d = ISAd[SA[k = j++]];
+ if(d < (e = ISAd[SA[j]])) { k = j; d = e; }
+ if(d <= c) { break; }
+ }
+ SA[i] = v;
+}
+
+/* Simple top-down heapsort. */
+static
+void
+tr_heapsort(const int *ISAd, int *SA, int size) {
+ int i, m;
+ int t;
+
+ m = size;
+ if((size % 2) == 0) {
+ m--;
+ if(ISAd[SA[m / 2]] < ISAd[SA[m]]) { SWAP(SA[m], SA[m / 2]); }
+ }
+
+ for(i = m / 2 - 1; 0 <= i; --i) { tr_fixdown(ISAd, SA, i, m); }
+ if((size % 2) == 0) { SWAP(SA[0], SA[m]); tr_fixdown(ISAd, SA, 0, m); }
+ for(i = m - 1; 0 < i; --i) {
+ t = SA[0], SA[0] = SA[i];
+ tr_fixdown(ISAd, SA, 0, i);
+ SA[i] = t;
+ }
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+/* Returns the median of three elements. */
+static INLINE
+int *
+tr_median3(const int *ISAd, int *v1, int *v2, int *v3) {
+ int *t;
+ if(ISAd[*v1] > ISAd[*v2]) { SWAP(v1, v2); }
+ if(ISAd[*v2] > ISAd[*v3]) {
+ if(ISAd[*v1] > ISAd[*v3]) { return v1; }
+ else { return v3; }
+ }
+ return v2;
+}
+
+/* Returns the median of five elements. */
+static INLINE
+int *
+tr_median5(const int *ISAd,
+ int *v1, int *v2, int *v3, int *v4, int *v5) {
+ int *t;
+ if(ISAd[*v2] > ISAd[*v3]) { SWAP(v2, v3); }
+ if(ISAd[*v4] > ISAd[*v5]) { SWAP(v4, v5); }
+ if(ISAd[*v2] > ISAd[*v4]) { SWAP(v2, v4); SWAP(v3, v5); }
+ if(ISAd[*v1] > ISAd[*v3]) { SWAP(v1, v3); }
+ if(ISAd[*v1] > ISAd[*v4]) { SWAP(v1, v4); SWAP(v3, v5); }
+ if(ISAd[*v3] > ISAd[*v4]) { return v4; }
+ return v3;
+}
+
+/* Returns the pivot element. */
+static INLINE
+int *
+tr_pivot(const int *ISAd, int *first, int *last) {
+ int *middle;
+ int t;
+
+ t = last - first;
+ middle = first + t / 2;
+
+ if(t <= 512) {
+ if(t <= 32) {
+ return tr_median3(ISAd, first, middle, last - 1);
+ } else {
+ t >>= 2;
+ return tr_median5(ISAd, first, first + t, middle, last - 1 - t, last - 1);
+ }
+ }
+ t >>= 3;
+ first = tr_median3(ISAd, first, first + t, first + (t << 1));
+ middle = tr_median3(ISAd, middle - t, middle, middle + t);
+ last = tr_median3(ISAd, last - 1 - (t << 1), last - 1 - t, last - 1);
+ return tr_median3(ISAd, first, middle, last);
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+typedef struct _trbudget_t trbudget_t;
+struct _trbudget_t {
+ int chance;
+ int remain;
+ int incval;
+ int count;
+};
+
+static INLINE
+void
+trbudget_init(trbudget_t *budget, int chance, int incval) {
+ budget->chance = chance;
+ budget->remain = budget->incval = incval;
+}
+
+static INLINE
+int
+trbudget_check(trbudget_t *budget, int size) {
+ if(size <= budget->remain) { budget->remain -= size; return 1; }
+ if(budget->chance == 0) { budget->count += size; return 0; }
+ budget->remain += budget->incval - size;
+ budget->chance -= 1;
+ return 1;
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+static INLINE
+void
+tr_partition(const int *ISAd,
+ int *first, int *middle, int *last,
+ int **pa, int **pb, int v) {
+ int *a, *b, *c, *d, *e, *f;
+ int t, s;
+ int x = 0;
+
+ for(b = middle - 1; (++b < last) && ((x = ISAd[*b]) == v);) { }
+ if(((a = b) < last) && (x < v)) {
+ for(; (++b < last) && ((x = ISAd[*b]) <= v);) {
+ if(x == v) { SWAP(*b, *a); ++a; }
+ }
+ }
+ for(c = last; (b < --c) && ((x = ISAd[*c]) == v);) { }
+ if((b < (d = c)) && (x > v)) {
+ for(; (b < --c) && ((x = ISAd[*c]) >= v);) {
+ if(x == v) { SWAP(*c, *d); --d; }
+ }
+ }
+ for(; b < c;) {
+ SWAP(*b, *c);
+ for(; (++b < c) && ((x = ISAd[*b]) <= v);) {
+ if(x == v) { SWAP(*b, *a); ++a; }
+ }
+ for(; (b < --c) && ((x = ISAd[*c]) >= v);) {
+ if(x == v) { SWAP(*c, *d); --d; }
+ }
+ }
+
+ if(a <= d) {
+ c = b - 1;
+ if((s = a - first) > (t = b - a)) { s = t; }
+ for(e = first, f = b - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); }
+ if((s = d - c) > (t = last - d - 1)) { s = t; }
+ for(e = b, f = last - s; 0 < s; --s, ++e, ++f) { SWAP(*e, *f); }
+ first += (b - a), last -= (d - c);
+ }
+ *pa = first, *pb = last;
+}
+
+static
+void
+tr_copy(int *ISA, const int *SA,
+ int *first, int *a, int *b, int *last,
+ int depth) {
+ /* sort suffixes of middle partition
+ by using sorted order of suffixes of left and right partition. */
+ int *c, *d, *e;
+ int s, v;
+
+ v = b - SA - 1;
+ for(c = first, d = a - 1; c <= d; ++c) {
+ if((0 <= (s = *c - depth)) && (ISA[s] == v)) {
+ *++d = s;
+ ISA[s] = d - SA;
+ }
+ }
+ for(c = last - 1, e = d + 1, d = b; e < d; --c) {
+ if((0 <= (s = *c - depth)) && (ISA[s] == v)) {
+ *--d = s;
+ ISA[s] = d - SA;
+ }
+ }
+}
+
+static
+void
+tr_partialcopy(int *ISA, const int *SA,
+ int *first, int *a, int *b, int *last,
+ int depth) {
+ int *c, *d, *e;
+ int s, v;
+ int rank, lastrank, newrank = -1;
+
+ v = b - SA - 1;
+ lastrank = -1;
+ for(c = first, d = a - 1; c <= d; ++c) {
+ if((0 <= (s = *c - depth)) && (ISA[s] == v)) {
+ *++d = s;
+ rank = ISA[s + depth];
+ if(lastrank != rank) { lastrank = rank; newrank = d - SA; }
+ ISA[s] = newrank;
+ }
+ }
+
+ lastrank = -1;
+ for(e = d; first <= e; --e) {
+ rank = ISA[*e];
+ if(lastrank != rank) { lastrank = rank; newrank = e - SA; }
+ if(newrank != rank) { ISA[*e] = newrank; }
+ }
+
+ lastrank = -1;
+ for(c = last - 1, e = d + 1, d = b; e < d; --c) {
+ if((0 <= (s = *c - depth)) && (ISA[s] == v)) {
+ *--d = s;
+ rank = ISA[s + depth];
+ if(lastrank != rank) { lastrank = rank; newrank = d - SA; }
+ ISA[s] = newrank;
+ }
+ }
+}
+
+static
+void
+tr_introsort(int *ISA, const int *ISAd,
+ int *SA, int *first, int *last,
+ trbudget_t *budget) {
+#define STACK_SIZE TR_STACKSIZE
+ struct { const int *a; int *b, *c; int d, e; }stack[STACK_SIZE];
+ int *a, *b, *c;
+ int t;
+ int v, x = 0;
+ int incr = ISAd - ISA;
+ int limit, next;
+ int ssize, trlink = -1;
+
+ for(ssize = 0, limit = tr_ilg(last - first);;) {
+
+ if(limit < 0) {
+ if(limit == -1) {
+ /* tandem repeat partition */
+ tr_partition(ISAd - incr, first, first, last, &a, &b, last - SA - 1);
+
+ /* update ranks */
+ if(a < last) {
+ for(c = first, v = a - SA - 1; c < a; ++c) { ISA[*c] = v; }
+ }
+ if(b < last) {
+ for(c = a, v = b - SA - 1; c < b; ++c) { ISA[*c] = v; }
+ }
+
+ /* push */
+ if(1 < (b - a)) {
+ STACK_PUSH5(NULL, a, b, 0, 0);
+ STACK_PUSH5(ISAd - incr, first, last, -2, trlink);
+ trlink = ssize - 2;
+ }
+ if((a - first) <= (last - b)) {
+ if(1 < (a - first)) {
+ STACK_PUSH5(ISAd, b, last, tr_ilg(last - b), trlink);
+ last = a, limit = tr_ilg(a - first);
+ } else if(1 < (last - b)) {
+ first = b, limit = tr_ilg(last - b);
+ } else {
+ STACK_POP5(ISAd, first, last, limit, trlink);
+ }
+ } else {
+ if(1 < (last - b)) {
+ STACK_PUSH5(ISAd, first, a, tr_ilg(a - first), trlink);
+ first = b, limit = tr_ilg(last - b);
+ } else if(1 < (a - first)) {
+ last = a, limit = tr_ilg(a - first);
+ } else {
+ STACK_POP5(ISAd, first, last, limit, trlink);
+ }
+ }
+ } else if(limit == -2) {
+ /* tandem repeat copy */
+ a = stack[--ssize].b, b = stack[ssize].c;
+ if(stack[ssize].d == 0) {
+ tr_copy(ISA, SA, first, a, b, last, ISAd - ISA);
+ } else {
+ if(0 <= trlink) { stack[trlink].d = -1; }
+ tr_partialcopy(ISA, SA, first, a, b, last, ISAd - ISA);
+ }
+ STACK_POP5(ISAd, first, last, limit, trlink);
+ } else {
+ /* sorted partition */
+ if(0 <= *first) {
+ a = first;
+ do { ISA[*a] = a - SA; } while((++a < last) && (0 <= *a));
+ first = a;
+ }
+ if(first < last) {
+ a = first; do { *a = ~*a; } while(*++a < 0);
+ next = (ISA[*a] != ISAd[*a]) ? tr_ilg(a - first + 1) : -1;
+ if(++a < last) { for(b = first, v = a - SA - 1; b < a; ++b) { ISA[*b] = v; } }
+
+ /* push */
+ if(trbudget_check(budget, a - first)) {
+ if((a - first) <= (last - a)) {
+ STACK_PUSH5(ISAd, a, last, -3, trlink);
+ ISAd += incr, last = a, limit = next;
+ } else {
+ if(1 < (last - a)) {
+ STACK_PUSH5(ISAd + incr, first, a, next, trlink);
+ first = a, limit = -3;
+ } else {
+ ISAd += incr, last = a, limit = next;
+ }
+ }
+ } else {
+ if(0 <= trlink) { stack[trlink].d = -1; }
+ if(1 < (last - a)) {
+ first = a, limit = -3;
+ } else {
+ STACK_POP5(ISAd, first, last, limit, trlink);
+ }
+ }
+ } else {
+ STACK_POP5(ISAd, first, last, limit, trlink);
+ }
+ }
+ continue;
+ }
+
+ if((last - first) <= TR_INSERTIONSORT_THRESHOLD) {
+ tr_insertionsort(ISAd, first, last);
+ limit = -3;
+ continue;
+ }
+
+ if(limit-- == 0) {
+ tr_heapsort(ISAd, first, last - first);
+ for(a = last - 1; first < a; a = b) {
+ for(x = ISAd[*a], b = a - 1; (first <= b) && (ISAd[*b] == x); --b) { *b = ~*b; }
+ }
+ limit = -3;
+ continue;
+ }
+
+ /* choose pivot */
+ a = tr_pivot(ISAd, first, last);
+ SWAP(*first, *a);
+ v = ISAd[*first];
+
+ /* partition */
+ tr_partition(ISAd, first, first + 1, last, &a, &b, v);
+ if((last - first) != (b - a)) {
+ next = (ISA[*a] != v) ? tr_ilg(b - a) : -1;
+
+ /* update ranks */
+ for(c = first, v = a - SA - 1; c < a; ++c) { ISA[*c] = v; }
+ if(b < last) { for(c = a, v = b - SA - 1; c < b; ++c) { ISA[*c] = v; } }
+
+ /* push */
+ if((1 < (b - a)) && (trbudget_check(budget, b - a))) {
+ if((a - first) <= (last - b)) {
+ if((last - b) <= (b - a)) {
+ if(1 < (a - first)) {
+ STACK_PUSH5(ISAd + incr, a, b, next, trlink);
+ STACK_PUSH5(ISAd, b, last, limit, trlink);
+ last = a;
+ } else if(1 < (last - b)) {
+ STACK_PUSH5(ISAd + incr, a, b, next, trlink);
+ first = b;
+ } else {
+ ISAd += incr, first = a, last = b, limit = next;
+ }
+ } else if((a - first) <= (b - a)) {
+ if(1 < (a - first)) {
+ STACK_PUSH5(ISAd, b, last, limit, trlink);
+ STACK_PUSH5(ISAd + incr, a, b, next, trlink);
+ last = a;
+ } else {
+ STACK_PUSH5(ISAd, b, last, limit, trlink);
+ ISAd += incr, first = a, last = b, limit = next;
+ }
+ } else {
+ STACK_PUSH5(ISAd, b, last, limit, trlink);
+ STACK_PUSH5(ISAd, first, a, limit, trlink);
+ ISAd += incr, first = a, last = b, limit = next;
+ }
+ } else {
+ if((a - first) <= (b - a)) {
+ if(1 < (last - b)) {
+ STACK_PUSH5(ISAd + incr, a, b, next, trlink);
+ STACK_PUSH5(ISAd, first, a, limit, trlink);
+ first = b;
+ } else if(1 < (a - first)) {
+ STACK_PUSH5(ISAd + incr, a, b, next, trlink);
+ last = a;
+ } else {
+ ISAd += incr, first = a, last = b, limit = next;
+ }
+ } else if((last - b) <= (b - a)) {
+ if(1 < (last - b)) {
+ STACK_PUSH5(ISAd, first, a, limit, trlink);
+ STACK_PUSH5(ISAd + incr, a, b, next, trlink);
+ first = b;
+ } else {
+ STACK_PUSH5(ISAd, first, a, limit, trlink);
+ ISAd += incr, first = a, last = b, limit = next;
+ }
+ } else {
+ STACK_PUSH5(ISAd, first, a, limit, trlink);
+ STACK_PUSH5(ISAd, b, last, limit, trlink);
+ ISAd += incr, first = a, last = b, limit = next;
+ }
+ }
+ } else {
+ if((1 < (b - a)) && (0 <= trlink)) { stack[trlink].d = -1; }
+ if((a - first) <= (last - b)) {
+ if(1 < (a - first)) {
+ STACK_PUSH5(ISAd, b, last, limit, trlink);
+ last = a;
+ } else if(1 < (last - b)) {
+ first = b;
+ } else {
+ STACK_POP5(ISAd, first, last, limit, trlink);
+ }
+ } else {
+ if(1 < (last - b)) {
+ STACK_PUSH5(ISAd, first, a, limit, trlink);
+ first = b;
+ } else if(1 < (a - first)) {
+ last = a;
+ } else {
+ STACK_POP5(ISAd, first, last, limit, trlink);
+ }
+ }
+ }
+ } else {
+ if(trbudget_check(budget, last - first)) {
+ limit = tr_ilg(last - first), ISAd += incr;
+ } else {
+ if(0 <= trlink) { stack[trlink].d = -1; }
+ STACK_POP5(ISAd, first, last, limit, trlink);
+ }
+ }
+ }
+#undef STACK_SIZE
+}
+
+
+
+/*---------------------------------------------------------------------------*/
+
+/* Tandem repeat sort */
+static
+void
+trsort(int *ISA, int *SA, int n, int depth) {
+ int *ISAd;
+ int *first, *last;
+ trbudget_t budget;
+ int t, skip, unsorted;
+
+ trbudget_init(&budget, tr_ilg(n) * 2 / 3, n);
+/* trbudget_init(&budget, tr_ilg(n) * 3 / 4, n); */
+ for(ISAd = ISA + depth; -n < *SA; ISAd += ISAd - ISA) {
+ first = SA;
+ skip = 0;
+ unsorted = 0;
+ do {
+ if((t = *first) < 0) { first -= t; skip += t; }
+ else {
+ if(skip != 0) { *(first + skip) = skip; skip = 0; }
+ last = SA + ISA[t] + 1;
+ if(1 < (last - first)) {
+ budget.count = 0;
+ tr_introsort(ISA, ISAd, SA, first, last, &budget);
+ if(budget.count != 0) { unsorted += budget.count; }
+ else { skip = first - last; }
+ } else if((last - first) == 1) {
+ skip = -1;
+ }
+ first = last;
+ }
+ } while(first < (SA + n));
+ if(skip != 0) { *(first + skip) = skip; }
+ if(unsorted == 0) { break; }
+ }
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+/* Sorts suffixes of type B*. */
+static
+int
+sort_typeBstar(const unsigned char *T, int *SA,
+ int *bucket_A, int *bucket_B,
+ int n, int openMP) {
+ int *PAb, *ISAb, *buf;
+#ifdef LIBBSC_OPENMP
+ int *curbuf;
+ int l;
+#endif
+ int i, j, k, t, m, bufsize;
+ int c0, c1;
+#ifdef LIBBSC_OPENMP
+ int d0, d1;
+#endif
+ (void)openMP;
+
+ /* Initialize bucket arrays. */
+ for(i = 0; i < BUCKET_A_SIZE; ++i) { bucket_A[i] = 0; }
+ for(i = 0; i < BUCKET_B_SIZE; ++i) { bucket_B[i] = 0; }
+
+ /* Count the number of occurrences of the first one or two characters of each
+ type A, B and B* suffix. Moreover, store the beginning position of all
+ type B* suffixes into the array SA. */
+ for(i = n - 1, m = n, c0 = T[n - 1]; 0 <= i;) {
+ /* type A suffix. */
+ do { ++BUCKET_A(c1 = c0); } while((0 <= --i) && ((c0 = T[i]) >= c1));
+ if(0 <= i) {
+ /* type B* suffix. */
+ ++BUCKET_BSTAR(c0, c1);
+ SA[--m] = i;
+ /* type B suffix. */
+ for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) {
+ ++BUCKET_B(c0, c1);
+ }
+ }
+ }
+ m = n - m;
+/*
+note:
+ A type B* suffix is lexicographically smaller than a type B suffix that
+ begins with the same first two characters.
+*/
+
+ /* Calculate the index of start/end point of each bucket. */
+ for(c0 = 0, i = 0, j = 0; c0 < ALPHABET_SIZE; ++c0) {
+ t = i + BUCKET_A(c0);
+ BUCKET_A(c0) = i + j; /* start point */
+ i = t + BUCKET_B(c0, c0);
+ for(c1 = c0 + 1; c1 < ALPHABET_SIZE; ++c1) {
+ j += BUCKET_BSTAR(c0, c1);
+ BUCKET_BSTAR(c0, c1) = j; /* end point */
+ i += BUCKET_B(c0, c1);
+ }
+ }
+
+ if(0 < m) {
+ /* Sort the type B* suffixes by their first two characters. */
+ PAb = SA + n - m; ISAb = SA + m;
+ for(i = m - 2; 0 <= i; --i) {
+ t = PAb[i], c0 = T[t], c1 = T[t + 1];
+ SA[--BUCKET_BSTAR(c0, c1)] = i;
+ }
+ t = PAb[m - 1], c0 = T[t], c1 = T[t + 1];
+ SA[--BUCKET_BSTAR(c0, c1)] = m - 1;
+
+ /* Sort the type B* substrings using sssort. */
+#ifdef LIBBSC_OPENMP
+ if (openMP)
+ {
+ buf = SA + m;
+ c0 = ALPHABET_SIZE - 2, c1 = ALPHABET_SIZE - 1, j = m;
+#pragma omp parallel default(shared) private(bufsize, curbuf, k, l, d0, d1)
+ {
+ bufsize = (n - (2 * m)) / omp_get_num_threads();
+ curbuf = buf + omp_get_thread_num() * bufsize;
+ k = 0;
+ for(;;) {
+ #pragma omp critical(sssort_lock)
+ {
+ if(0 < (l = j)) {
+ d0 = c0, d1 = c1;
+ do {
+ k = BUCKET_BSTAR(d0, d1);
+ if(--d1 <= d0) {
+ d1 = ALPHABET_SIZE - 1;
+ if(--d0 < 0) { break; }
+ }
+ } while(((l - k) <= 1) && (0 < (l = k)));
+ c0 = d0, c1 = d1, j = k;
+ }
+ }
+ if(l == 0) { break; }
+ sssort(T, PAb, SA + k, SA + l,
+ curbuf, bufsize, 2, n, *(SA + k) == (m - 1));
+ }
+ }
+ }
+ else
+ {
+ buf = SA + m, bufsize = n - (2 * m);
+ for(c0 = ALPHABET_SIZE - 2, j = m; 0 < j; --c0) {
+ for(c1 = ALPHABET_SIZE - 1; c0 < c1; j = i, --c1) {
+ i = BUCKET_BSTAR(c0, c1);
+ if(1 < (j - i)) {
+ sssort(T, PAb, SA + i, SA + j,
+ buf, bufsize, 2, n, *(SA + i) == (m - 1));
+ }
+ }
+ }
+ }
+#else
+ buf = SA + m, bufsize = n - (2 * m);
+ for(c0 = ALPHABET_SIZE - 2, j = m; 0 < j; --c0) {
+ for(c1 = ALPHABET_SIZE - 1; c0 < c1; j = i, --c1) {
+ i = BUCKET_BSTAR(c0, c1);
+ if(1 < (j - i)) {
+ sssort(T, PAb, SA + i, SA + j,
+ buf, bufsize, 2, n, *(SA + i) == (m - 1));
+ }
+ }
+ }
+#endif
+
+ /* Compute ranks of type B* substrings. */
+ for(i = m - 1; 0 <= i; --i) {
+ if(0 <= SA[i]) {
+ j = i;
+ do { ISAb[SA[i]] = i; } while((0 <= --i) && (0 <= SA[i]));
+ SA[i + 1] = i - j;
+ if(i <= 0) { break; }
+ }
+ j = i;
+ do { ISAb[SA[i] = ~SA[i]] = j; } while(SA[--i] < 0);
+ ISAb[SA[i]] = j;
+ }
+
+ /* Construct the inverse suffix array of type B* suffixes using trsort. */
+ trsort(ISAb, SA, m, 1);
+
+ /* Set the sorted order of tyoe B* suffixes. */
+ for(i = n - 1, j = m, c0 = T[n - 1]; 0 <= i;) {
+ for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) >= c1); --i, c1 = c0) { }
+ if(0 <= i) {
+ t = i;
+ for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) { }
+ SA[ISAb[--j]] = ((t == 0) || (1 < (t - i))) ? t : ~t;
+ }
+ }
+
+ /* Calculate the index of start/end point of each bucket. */
+ BUCKET_B(ALPHABET_SIZE - 1, ALPHABET_SIZE - 1) = n; /* end point */
+ for(c0 = ALPHABET_SIZE - 2, k = m - 1; 0 <= c0; --c0) {
+ i = BUCKET_A(c0 + 1) - 1;
+ for(c1 = ALPHABET_SIZE - 1; c0 < c1; --c1) {
+ t = i - BUCKET_B(c0, c1);
+ BUCKET_B(c0, c1) = i; /* end point */
+
+ /* Move all type B* suffixes to the correct position. */
+ for(i = t, j = BUCKET_BSTAR(c0, c1);
+ j <= k;
+ --i, --k) { SA[i] = SA[k]; }
+ }
+ BUCKET_BSTAR(c0, c0 + 1) = i - BUCKET_B(c0, c0) + 1; /* start point */
+ BUCKET_B(c0, c0) = i; /* end point */
+ }
+ }
+
+ return m;
+}
+
+/* Constructs the suffix array by using the sorted order of type B* suffixes. */
+static
+void
+construct_SA(const unsigned char *T, int *SA,
+ int *bucket_A, int *bucket_B,
+ int n, int m) {
+ int *i, *j, *k;
+ int s;
+ int c0, c1, c2;
+
+ if(0 < m) {
+ /* Construct the sorted order of type B suffixes by using
+ the sorted order of type B* suffixes. */
+ for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) {
+ /* Scan the suffix array from right to left. */
+ for(i = SA + BUCKET_BSTAR(c1, c1 + 1),
+ j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1;
+ i <= j;
+ --j) {
+ if(0 < (s = *j)) {
+ assert(T[s] == c1);
+ assert(((s + 1) < n) && (T[s] <= T[s + 1]));
+ assert(T[s - 1] <= T[s]);
+ *j = ~s;
+ c0 = T[--s];
+ if((0 < s) && (T[s - 1] > c0)) { s = ~s; }
+ if(c0 != c2) {
+ if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; }
+ k = SA + BUCKET_B(c2 = c0, c1);
+ }
+ assert(k < j); assert(k != NULL);
+ *k-- = s;
+ } else {
+ assert(((s == 0) && (T[s] == c1)) || (s < 0));
+ *j = ~s;
+ }
+ }
+ }
+ }
+
+ /* Construct the suffix array by using
+ the sorted order of type B suffixes. */
+ k = SA + BUCKET_A(c2 = T[n - 1]);
+ *k++ = (T[n - 2] < c2) ? ~(n - 1) : (n - 1);
+ /* Scan the suffix array from left to right. */
+ for(i = SA, j = SA + n; i < j; ++i) {
+ if(0 < (s = *i)) {
+ assert(T[s - 1] >= T[s]);
+ c0 = T[--s];
+ if((s == 0) || (T[s - 1] < c0)) { s = ~s; }
+ if(c0 != c2) {
+ BUCKET_A(c2) = k - SA;
+ k = SA + BUCKET_A(c2 = c0);
+ }
+ assert(i < k);
+ *k++ = s;
+ } else {
+ assert(s < 0);
+ *i = ~s;
+ }
+ }
+}
+
+/* Constructs the burrows-wheeler transformed string directly
+ by using the sorted order of type B* suffixes. */
+static
+int
+construct_BWT(const unsigned char *T, int *SA,
+ int *bucket_A, int *bucket_B,
+ int n, int m) {
+ int *i, *j, *k, *orig;
+ int s;
+ int c0, c1, c2;
+
+ if(0 < m) {
+ /* Construct the sorted order of type B suffixes by using
+ the sorted order of type B* suffixes. */
+ for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) {
+ /* Scan the suffix array from right to left. */
+ for(i = SA + BUCKET_BSTAR(c1, c1 + 1),
+ j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1;
+ i <= j;
+ --j) {
+ if(0 < (s = *j)) {
+ assert(T[s] == c1);
+ assert(((s + 1) < n) && (T[s] <= T[s + 1]));
+ assert(T[s - 1] <= T[s]);
+ c0 = T[--s];
+ *j = ~((int)c0);
+ if((0 < s) && (T[s - 1] > c0)) { s = ~s; }
+ if(c0 != c2) {
+ if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; }
+ k = SA + BUCKET_B(c2 = c0, c1);
+ }
+ assert(k < j); assert(k != NULL);
+ *k-- = s;
+ } else if(s != 0) {
+ *j = ~s;
+#ifndef NDEBUG
+ } else {
+ assert(T[s] == c1);
+#endif
+ }
+ }
+ }
+ }
+
+ /* Construct the BWTed string by using
+ the sorted order of type B suffixes. */
+ k = SA + BUCKET_A(c2 = T[n - 1]);
+ *k++ = (T[n - 2] < c2) ? ~((int)T[n - 2]) : (n - 1);
+ /* Scan the suffix array from left to right. */
+ for(i = SA, j = SA + n, orig = SA; i < j; ++i) {
+ if(0 < (s = *i)) {
+ assert(T[s - 1] >= T[s]);
+ c0 = T[--s];
+ *i = c0;
+ if((0 < s) && (T[s - 1] < c0)) { s = ~((int)T[s - 1]); }
+ if(c0 != c2) {
+ BUCKET_A(c2) = k - SA;
+ k = SA + BUCKET_A(c2 = c0);
+ }
+ assert(i < k);
+ *k++ = s;
+ } else if(s != 0) {
+ *i = ~s;
+ } else {
+ orig = i;
+ }
+ }
+
+ return orig - SA;
+}
+
+/* Constructs the burrows-wheeler transformed string directly
+ by using the sorted order of type B* suffixes. */
+static
+int
+construct_BWT_indexes(const unsigned char *T, int *SA,
+ int *bucket_A, int *bucket_B,
+ int n, int m,
+ unsigned char * num_indexes, int * indexes) {
+ int *i, *j, *k, *orig;
+ int s;
+ int c0, c1, c2;
+
+ int mod = n / 8;
+ {
+ mod |= mod >> 1; mod |= mod >> 2;
+ mod |= mod >> 4; mod |= mod >> 8;
+ mod |= mod >> 16; mod >>= 1;
+
+ *num_indexes = (unsigned char)((n - 1) / (mod + 1));
+ }
+
+ if(0 < m) {
+ /* Construct the sorted order of type B suffixes by using
+ the sorted order of type B* suffixes. */
+ for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) {
+ /* Scan the suffix array from right to left. */
+ for(i = SA + BUCKET_BSTAR(c1, c1 + 1),
+ j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1;
+ i <= j;
+ --j) {
+ if(0 < (s = *j)) {
+ assert(T[s] == c1);
+ assert(((s + 1) < n) && (T[s] <= T[s + 1]));
+ assert(T[s - 1] <= T[s]);
+
+ if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = j - SA;
+
+ c0 = T[--s];
+ *j = ~((int)c0);
+ if((0 < s) && (T[s - 1] > c0)) { s = ~s; }
+ if(c0 != c2) {
+ if(0 <= c2) { BUCKET_B(c2, c1) = k - SA; }
+ k = SA + BUCKET_B(c2 = c0, c1);
+ }
+ assert(k < j); assert(k != NULL);
+ *k-- = s;
+ } else if(s != 0) {
+ *j = ~s;
+#ifndef NDEBUG
+ } else {
+ assert(T[s] == c1);
+#endif
+ }
+ }
+ }
+ }
+
+ /* Construct the BWTed string by using
+ the sorted order of type B suffixes. */
+ k = SA + BUCKET_A(c2 = T[n - 1]);
+ if (T[n - 2] < c2) {
+ if (((n - 1) & mod) == 0) indexes[(n - 1) / (mod + 1) - 1] = k - SA;
+ *k++ = ~((int)T[n - 2]);
+ }
+ else {
+ *k++ = n - 1;
+ }
+
+ /* Scan the suffix array from left to right. */
+ for(i = SA, j = SA + n, orig = SA; i < j; ++i) {
+ if(0 < (s = *i)) {
+ assert(T[s - 1] >= T[s]);
+
+ if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = i - SA;
+
+ c0 = T[--s];
+ *i = c0;
+ if(c0 != c2) {
+ BUCKET_A(c2) = k - SA;
+ k = SA + BUCKET_A(c2 = c0);
+ }
+ assert(i < k);
+ if((0 < s) && (T[s - 1] < c0)) {
+ if ((s & mod) == 0) indexes[s / (mod + 1) - 1] = k - SA;
+ *k++ = ~((int)T[s - 1]);
+ } else
+ *k++ = s;
+ } else if(s != 0) {
+ *i = ~s;
+ } else {
+ orig = i;
+ }
+ }
+
+ return orig - SA;
+}
+
+
+/*---------------------------------------------------------------------------*/
+
+/*- Function -*/
+
+int
+divsufsort(const unsigned char *T, int *SA, int n, int openMP) {
+ int *bucket_A, *bucket_B;
+ int m;
+ int err = 0;
+
+ /* Check arguments. */
+ if((T == NULL) || (SA == NULL) || (n < 0)) { return -1; }
+ else if(n == 0) { return 0; }
+ else if(n == 1) { SA[0] = 0; return 0; }
+ else if(n == 2) { m = (T[0] < T[1]); SA[m ^ 1] = 0, SA[m] = 1; return 0; }
+
+ bucket_A = (int *)malloc(BUCKET_A_SIZE * sizeof(int));
+ bucket_B = (int *)malloc(BUCKET_B_SIZE * sizeof(int));
+
+ /* Suffixsort. */
+ if((bucket_A != NULL) && (bucket_B != NULL)) {
+ m = sort_typeBstar(T, SA, bucket_A, bucket_B, n, openMP);
+ construct_SA(T, SA, bucket_A, bucket_B, n, m);
+ } else {
+ err = -2;
+ }
+
+ free(bucket_B);
+ free(bucket_A);
+
+ return err;
+}
+
+int
+divbwt(const unsigned char *T, unsigned char *U, int *A, int n, unsigned char * num_indexes, int * indexes, int openMP) {
+ int *B;
+ int *bucket_A, *bucket_B;
+ int m, pidx, i;
+
+ /* Check arguments. */
+ if((T == NULL) || (U == NULL) || (n < 0)) { return -1; }
+ else if(n <= 1) { if(n == 1) { U[0] = T[0]; } return n; }
+
+ if((B = A) == NULL) { B = (int *)malloc((size_t)(n + 1) * sizeof(int)); }
+ bucket_A = (int *)malloc(BUCKET_A_SIZE * sizeof(int));
+ bucket_B = (int *)malloc(BUCKET_B_SIZE * sizeof(int));
+
+ /* Burrows-Wheeler Transform. */
+ if((B != NULL) && (bucket_A != NULL) && (bucket_B != NULL)) {
+ m = sort_typeBstar(T, B, bucket_A, bucket_B, n, openMP);
+
+ if (num_indexes == NULL || indexes == NULL) {
+ pidx = construct_BWT(T, B, bucket_A, bucket_B, n, m);
+ } else {
+ pidx = construct_BWT_indexes(T, B, bucket_A, bucket_B, n, m, num_indexes, indexes);
+ }
+
+ /* Copy to output string. */
+ U[0] = T[n - 1];
+ for(i = 0; i < pidx; ++i) { U[i + 1] = (unsigned char)B[i]; }
+ for(i += 1; i < n; ++i) { U[i] = (unsigned char)B[i]; }
+ pidx += 1;
+ } else {
+ pidx = -2;
+ }
+
+ free(bucket_B);
+ free(bucket_A);
+ if(A == NULL) { free(B); }
+
+ return pidx;
+}
diff --git a/Utilities/cmzstd/lib/dictBuilder/divsufsort.h b/Utilities/cmzstd/lib/dictBuilder/divsufsort.h
new file mode 100644
index 000000000..5440994af
--- /dev/null
+++ b/Utilities/cmzstd/lib/dictBuilder/divsufsort.h
@@ -0,0 +1,67 @@
+/*
+ * divsufsort.h for libdivsufsort-lite
+ * Copyright (c) 2003-2008 Yuta Mori All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following
+ * conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef _DIVSUFSORT_H
+#define _DIVSUFSORT_H 1
+
+#ifdef __cplusplus
+extern "C" {
+#endif /* __cplusplus */
+
+
+/*- Prototypes -*/
+
+/**
+ * Constructs the suffix array of a given string.
+ * @param T [0..n-1] The input string.
+ * @param SA [0..n-1] The output array of suffixes.
+ * @param n The length of the given string.
+ * @param openMP enables OpenMP optimization.
+ * @return 0 if no error occurred, -1 or -2 otherwise.
+ */
+int
+divsufsort(const unsigned char *T, int *SA, int n, int openMP);
+
+/**
+ * Constructs the burrows-wheeler transformed string of a given string.
+ * @param T [0..n-1] The input string.
+ * @param U [0..n-1] The output string. (can be T)
+ * @param A [0..n-1] The temporary array. (can be NULL)
+ * @param n The length of the given string.
+ * @param num_indexes The length of secondary indexes array. (can be NULL)
+ * @param indexes The secondary indexes array. (can be NULL)
+ * @param openMP enables OpenMP optimization.
+ * @return The primary index if no error occurred, -1 or -2 otherwise.
+ */
+int
+divbwt(const unsigned char *T, unsigned char *U, int *A, int n, unsigned char * num_indexes, int * indexes, int openMP);
+
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif /* __cplusplus */
+
+#endif /* _DIVSUFSORT_H */
diff --git a/Utilities/cmzstd/lib/dictBuilder/fastcover.c b/Utilities/cmzstd/lib/dictBuilder/fastcover.c
new file mode 100644
index 000000000..c289c0690
--- /dev/null
+++ b/Utilities/cmzstd/lib/dictBuilder/fastcover.c
@@ -0,0 +1,728 @@
+/*-*************************************
+* Dependencies
+***************************************/
+#include <stdio.h> /* fprintf */
+#include <stdlib.h> /* malloc, free, qsort */
+#include <string.h> /* memset */
+#include <time.h> /* clock */
+
+#include "mem.h" /* read */
+#include "pool.h"
+#include "threading.h"
+#include "cover.h"
+#include "zstd_internal.h" /* includes zstd.h */
+#ifndef ZDICT_STATIC_LINKING_ONLY
+#define ZDICT_STATIC_LINKING_ONLY
+#endif
+#include "zdict.h"
+
+
+/*-*************************************
+* Constants
+***************************************/
+#define FASTCOVER_MAX_SAMPLES_SIZE (sizeof(size_t) == 8 ? ((unsigned)-1) : ((unsigned)1 GB))
+#define FASTCOVER_MAX_F 31
+#define FASTCOVER_MAX_ACCEL 10
+#define DEFAULT_SPLITPOINT 0.75
+#define DEFAULT_F 20
+#define DEFAULT_ACCEL 1
+
+
+/*-*************************************
+* Console display
+***************************************/
+static int g_displayLevel = 2;
+#define DISPLAY(...) \
+ { \
+ fprintf(stderr, __VA_ARGS__); \
+ fflush(stderr); \
+ }
+#define LOCALDISPLAYLEVEL(displayLevel, l, ...) \
+ if (displayLevel >= l) { \
+ DISPLAY(__VA_ARGS__); \
+ } /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */
+#define DISPLAYLEVEL(l, ...) LOCALDISPLAYLEVEL(g_displayLevel, l, __VA_ARGS__)
+
+#define LOCALDISPLAYUPDATE(displayLevel, l, ...) \
+ if (displayLevel >= l) { \
+ if ((clock() - g_time > refreshRate) || (displayLevel >= 4)) { \
+ g_time = clock(); \
+ DISPLAY(__VA_ARGS__); \
+ } \
+ }
+#define DISPLAYUPDATE(l, ...) LOCALDISPLAYUPDATE(g_displayLevel, l, __VA_ARGS__)
+static const clock_t refreshRate = CLOCKS_PER_SEC * 15 / 100;
+static clock_t g_time = 0;
+
+
+/*-*************************************
+* Hash Functions
+***************************************/
+static const U64 prime6bytes = 227718039650203ULL;
+static size_t ZSTD_hash6(U64 u, U32 h) { return (size_t)(((u << (64-48)) * prime6bytes) >> (64-h)) ; }
+static size_t ZSTD_hash6Ptr(const void* p, U32 h) { return ZSTD_hash6(MEM_readLE64(p), h); }
+
+static const U64 prime8bytes = 0xCF1BBCDCB7A56463ULL;
+static size_t ZSTD_hash8(U64 u, U32 h) { return (size_t)(((u) * prime8bytes) >> (64-h)) ; }
+static size_t ZSTD_hash8Ptr(const void* p, U32 h) { return ZSTD_hash8(MEM_readLE64(p), h); }
+
+
+/**
+ * Hash the d-byte value pointed to by p and mod 2^f
+ */
+static size_t FASTCOVER_hashPtrToIndex(const void* p, U32 h, unsigned d) {
+ if (d == 6) {
+ return ZSTD_hash6Ptr(p, h) & ((1 << h) - 1);
+ }
+ return ZSTD_hash8Ptr(p, h) & ((1 << h) - 1);
+}
+
+
+/*-*************************************
+* Acceleration
+***************************************/
+typedef struct {
+ unsigned finalize; /* Percentage of training samples used for ZDICT_finalizeDictionary */
+ unsigned skip; /* Number of dmer skipped between each dmer counted in computeFrequency */
+} FASTCOVER_accel_t;
+
+
+static const FASTCOVER_accel_t FASTCOVER_defaultAccelParameters[FASTCOVER_MAX_ACCEL+1] = {
+ { 100, 0 }, /* accel = 0, should not happen because accel = 0 defaults to accel = 1 */
+ { 100, 0 }, /* accel = 1 */
+ { 50, 1 }, /* accel = 2 */
+ { 34, 2 }, /* accel = 3 */
+ { 25, 3 }, /* accel = 4 */
+ { 20, 4 }, /* accel = 5 */
+ { 17, 5 }, /* accel = 6 */
+ { 14, 6 }, /* accel = 7 */
+ { 13, 7 }, /* accel = 8 */
+ { 11, 8 }, /* accel = 9 */
+ { 10, 9 }, /* accel = 10 */
+};
+
+
+/*-*************************************
+* Context
+***************************************/
+typedef struct {
+ const BYTE *samples;
+ size_t *offsets;
+ const size_t *samplesSizes;
+ size_t nbSamples;
+ size_t nbTrainSamples;
+ size_t nbTestSamples;
+ size_t nbDmers;
+ U32 *freqs;
+ unsigned d;
+ unsigned f;
+ FASTCOVER_accel_t accelParams;
+} FASTCOVER_ctx_t;
+
+
+/*-*************************************
+* Helper functions
+***************************************/
+/**
+ * Selects the best segment in an epoch.
+ * Segments of are scored according to the function:
+ *
+ * Let F(d) be the frequency of all dmers with hash value d.
+ * Let S_i be hash value of the dmer at position i of segment S which has length k.
+ *
+ * Score(S) = F(S_1) + F(S_2) + ... + F(S_{k-d+1})
+ *
+ * Once the dmer with hash value d is in the dictionay we set F(d) = 0.
+ */
+static COVER_segment_t FASTCOVER_selectSegment(const FASTCOVER_ctx_t *ctx,
+ U32 *freqs, U32 begin, U32 end,
+ ZDICT_cover_params_t parameters,
+ U16* segmentFreqs) {
+ /* Constants */
+ const U32 k = parameters.k;
+ const U32 d = parameters.d;
+ const U32 f = ctx->f;
+ const U32 dmersInK = k - d + 1;
+
+ /* Try each segment (activeSegment) and save the best (bestSegment) */
+ COVER_segment_t bestSegment = {0, 0, 0};
+ COVER_segment_t activeSegment;
+
+ /* Reset the activeDmers in the segment */
+ /* The activeSegment starts at the beginning of the epoch. */
+ activeSegment.begin = begin;
+ activeSegment.end = begin;
+ activeSegment.score = 0;
+
+ /* Slide the activeSegment through the whole epoch.
+ * Save the best segment in bestSegment.
+ */
+ while (activeSegment.end < end) {
+ /* Get hash value of current dmer */
+ const size_t idx = FASTCOVER_hashPtrToIndex(ctx->samples + activeSegment.end, f, d);
+
+ /* Add frequency of this index to score if this is the first occurence of index in active segment */
+ if (segmentFreqs[idx] == 0) {
+ activeSegment.score += freqs[idx];
+ }
+ /* Increment end of segment and segmentFreqs*/
+ activeSegment.end += 1;
+ segmentFreqs[idx] += 1;
+ /* If the window is now too large, drop the first position */
+ if (activeSegment.end - activeSegment.begin == dmersInK + 1) {
+ /* Get hash value of the dmer to be eliminated from active segment */
+ const size_t delIndex = FASTCOVER_hashPtrToIndex(ctx->samples + activeSegment.begin, f, d);
+ segmentFreqs[delIndex] -= 1;
+ /* Subtract frequency of this index from score if this is the last occurrence of this index in active segment */
+ if (segmentFreqs[delIndex] == 0) {
+ activeSegment.score -= freqs[delIndex];
+ }
+ /* Increment start of segment */
+ activeSegment.begin += 1;
+ }
+
+ /* If this segment is the best so far save it */
+ if (activeSegment.score > bestSegment.score) {
+ bestSegment = activeSegment;
+ }
+ }
+
+ /* Zero out rest of segmentFreqs array */
+ while (activeSegment.begin < end) {
+ const size_t delIndex = FASTCOVER_hashPtrToIndex(ctx->samples + activeSegment.begin, f, d);
+ segmentFreqs[delIndex] -= 1;
+ activeSegment.begin += 1;
+ }
+
+ {
+ /* Zero the frequency of hash value of each dmer covered by the chosen segment. */
+ U32 pos;
+ for (pos = bestSegment.begin; pos != bestSegment.end; ++pos) {
+ const size_t i = FASTCOVER_hashPtrToIndex(ctx->samples + pos, f, d);
+ freqs[i] = 0;
+ }
+ }
+
+ return bestSegment;
+}
+
+
+static int FASTCOVER_checkParameters(ZDICT_cover_params_t parameters,
+ size_t maxDictSize, unsigned f,
+ unsigned accel) {
+ /* k, d, and f are required parameters */
+ if (parameters.d == 0 || parameters.k == 0) {
+ return 0;
+ }
+ /* d has to be 6 or 8 */
+ if (parameters.d != 6 && parameters.d != 8) {
+ return 0;
+ }
+ /* k <= maxDictSize */
+ if (parameters.k > maxDictSize) {
+ return 0;
+ }
+ /* d <= k */
+ if (parameters.d > parameters.k) {
+ return 0;
+ }
+ /* 0 < f <= FASTCOVER_MAX_F*/
+ if (f > FASTCOVER_MAX_F || f == 0) {
+ return 0;
+ }
+ /* 0 < splitPoint <= 1 */
+ if (parameters.splitPoint <= 0 || parameters.splitPoint > 1) {
+ return 0;
+ }
+ /* 0 < accel <= 10 */
+ if (accel > 10 || accel == 0) {
+ return 0;
+ }
+ return 1;
+}
+
+
+/**
+ * Clean up a context initialized with `FASTCOVER_ctx_init()`.
+ */
+static void
+FASTCOVER_ctx_destroy(FASTCOVER_ctx_t* ctx)
+{
+ if (!ctx) return;
+
+ free(ctx->freqs);
+ ctx->freqs = NULL;
+
+ free(ctx->offsets);
+ ctx->offsets = NULL;
+}
+
+
+/**
+ * Calculate for frequency of hash value of each dmer in ctx->samples
+ */
+static void
+FASTCOVER_computeFrequency(U32* freqs, const FASTCOVER_ctx_t* ctx)
+{
+ const unsigned f = ctx->f;
+ const unsigned d = ctx->d;
+ const unsigned skip = ctx->accelParams.skip;
+ const unsigned readLength = MAX(d, 8);
+ size_t i;
+ assert(ctx->nbTrainSamples >= 5);
+ assert(ctx->nbTrainSamples <= ctx->nbSamples);
+ for (i = 0; i < ctx->nbTrainSamples; i++) {
+ size_t start = ctx->offsets[i]; /* start of current dmer */
+ size_t const currSampleEnd = ctx->offsets[i+1];
+ while (start + readLength <= currSampleEnd) {
+ const size_t dmerIndex = FASTCOVER_hashPtrToIndex(ctx->samples + start, f, d);
+ freqs[dmerIndex]++;
+ start = start + skip + 1;
+ }
+ }
+}
+
+
+/**
+ * Prepare a context for dictionary building.
+ * The context is only dependent on the parameter `d` and can used multiple
+ * times.
+ * Returns 1 on success or zero on error.
+ * The context must be destroyed with `FASTCOVER_ctx_destroy()`.
+ */
+static int
+FASTCOVER_ctx_init(FASTCOVER_ctx_t* ctx,
+ const void* samplesBuffer,
+ const size_t* samplesSizes, unsigned nbSamples,
+ unsigned d, double splitPoint, unsigned f,
+ FASTCOVER_accel_t accelParams)
+{
+ const BYTE* const samples = (const BYTE*)samplesBuffer;
+ const size_t totalSamplesSize = COVER_sum(samplesSizes, nbSamples);
+ /* Split samples into testing and training sets */
+ const unsigned nbTrainSamples = splitPoint < 1.0 ? (unsigned)((double)nbSamples * splitPoint) : nbSamples;
+ const unsigned nbTestSamples = splitPoint < 1.0 ? nbSamples - nbTrainSamples : nbSamples;
+ const size_t trainingSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes, nbTrainSamples) : totalSamplesSize;
+ const size_t testSamplesSize = splitPoint < 1.0 ? COVER_sum(samplesSizes + nbTrainSamples, nbTestSamples) : totalSamplesSize;
+
+ /* Checks */
+ if (totalSamplesSize < MAX(d, sizeof(U64)) ||
+ totalSamplesSize >= (size_t)FASTCOVER_MAX_SAMPLES_SIZE) {
+ DISPLAYLEVEL(1, "Total samples size is too large (%u MB), maximum size is %u MB\n",
+ (unsigned)(totalSamplesSize >> 20), (FASTCOVER_MAX_SAMPLES_SIZE >> 20));
+ return 0;
+ }
+
+ /* Check if there are at least 5 training samples */
+ if (nbTrainSamples < 5) {
+ DISPLAYLEVEL(1, "Total number of training samples is %u and is invalid\n", nbTrainSamples);
+ return 0;
+ }
+
+ /* Check if there's testing sample */
+ if (nbTestSamples < 1) {
+ DISPLAYLEVEL(1, "Total number of testing samples is %u and is invalid.\n", nbTestSamples);
+ return 0;
+ }
+
+ /* Zero the context */
+ memset(ctx, 0, sizeof(*ctx));
+ DISPLAYLEVEL(2, "Training on %u samples of total size %u\n", nbTrainSamples,
+ (unsigned)trainingSamplesSize);
+ DISPLAYLEVEL(2, "Testing on %u samples of total size %u\n", nbTestSamples,
+ (unsigned)testSamplesSize);
+
+ ctx->samples = samples;
+ ctx->samplesSizes = samplesSizes;
+ ctx->nbSamples = nbSamples;
+ ctx->nbTrainSamples = nbTrainSamples;
+ ctx->nbTestSamples = nbTestSamples;
+ ctx->nbDmers = trainingSamplesSize - MAX(d, sizeof(U64)) + 1;
+ ctx->d = d;
+ ctx->f = f;
+ ctx->accelParams = accelParams;
+
+ /* The offsets of each file */
+ ctx->offsets = (size_t*)calloc((nbSamples + 1), sizeof(size_t));
+ if (ctx->offsets == NULL) {
+ DISPLAYLEVEL(1, "Failed to allocate scratch buffers \n");
+ FASTCOVER_ctx_destroy(ctx);
+ return 0;
+ }
+
+ /* Fill offsets from the samplesSizes */
+ { U32 i;
+ ctx->offsets[0] = 0;
+ assert(nbSamples >= 5);
+ for (i = 1; i <= nbSamples; ++i) {
+ ctx->offsets[i] = ctx->offsets[i - 1] + samplesSizes[i - 1];
+ }
+ }
+
+ /* Initialize frequency array of size 2^f */
+ ctx->freqs = (U32*)calloc(((U64)1 << f), sizeof(U32));
+ if (ctx->freqs == NULL) {
+ DISPLAYLEVEL(1, "Failed to allocate frequency table \n");
+ FASTCOVER_ctx_destroy(ctx);
+ return 0;
+ }
+
+ DISPLAYLEVEL(2, "Computing frequencies\n");
+ FASTCOVER_computeFrequency(ctx->freqs, ctx);
+
+ return 1;
+}
+
+
+/**
+ * Given the prepared context build the dictionary.
+ */
+static size_t
+FASTCOVER_buildDictionary(const FASTCOVER_ctx_t* ctx,
+ U32* freqs,
+ void* dictBuffer, size_t dictBufferCapacity,
+ ZDICT_cover_params_t parameters,
+ U16* segmentFreqs)
+{
+ BYTE *const dict = (BYTE *)dictBuffer;
+ size_t tail = dictBufferCapacity;
+ /* Divide the data up into epochs of equal size.
+ * We will select at least one segment from each epoch.
+ */
+ const unsigned epochs = MAX(1, (U32)(dictBufferCapacity / parameters.k));
+ const unsigned epochSize = (U32)(ctx->nbDmers / epochs);
+ size_t epoch;
+ DISPLAYLEVEL(2, "Breaking content into %u epochs of size %u\n",
+ epochs, epochSize);
+ /* Loop through the epochs until there are no more segments or the dictionary
+ * is full.
+ */
+ for (epoch = 0; tail > 0; epoch = (epoch + 1) % epochs) {
+ const U32 epochBegin = (U32)(epoch * epochSize);
+ const U32 epochEnd = epochBegin + epochSize;
+ size_t segmentSize;
+ /* Select a segment */
+ COVER_segment_t segment = FASTCOVER_selectSegment(
+ ctx, freqs, epochBegin, epochEnd, parameters, segmentFreqs);
+
+ /* If the segment covers no dmers, then we are out of content */
+ if (segment.score == 0) {
+ break;
+ }
+
+ /* Trim the segment if necessary and if it is too small then we are done */
+ segmentSize = MIN(segment.end - segment.begin + parameters.d - 1, tail);
+ if (segmentSize < parameters.d) {
+ break;
+ }
+
+ /* We fill the dictionary from the back to allow the best segments to be
+ * referenced with the smallest offsets.
+ */
+ tail -= segmentSize;
+ memcpy(dict + tail, ctx->samples + segment.begin, segmentSize);
+ DISPLAYUPDATE(
+ 2, "\r%u%% ",
+ (unsigned)(((dictBufferCapacity - tail) * 100) / dictBufferCapacity));
+ }
+ DISPLAYLEVEL(2, "\r%79s\r", "");
+ return tail;
+}
+
+
+/**
+ * Parameters for FASTCOVER_tryParameters().
+ */
+typedef struct FASTCOVER_tryParameters_data_s {
+ const FASTCOVER_ctx_t* ctx;
+ COVER_best_t* best;
+ size_t dictBufferCapacity;
+ ZDICT_cover_params_t parameters;
+} FASTCOVER_tryParameters_data_t;
+
+
+/**
+ * Tries a set of parameters and updates the COVER_best_t with the results.
+ * This function is thread safe if zstd is compiled with multithreaded support.
+ * It takes its parameters as an *OWNING* opaque pointer to support threading.
+ */
+static void FASTCOVER_tryParameters(void *opaque)
+{
+ /* Save parameters as local variables */
+ FASTCOVER_tryParameters_data_t *const data = (FASTCOVER_tryParameters_data_t *)opaque;
+ const FASTCOVER_ctx_t *const ctx = data->ctx;
+ const ZDICT_cover_params_t parameters = data->parameters;
+ size_t dictBufferCapacity = data->dictBufferCapacity;
+ size_t totalCompressedSize = ERROR(GENERIC);
+ /* Initialize array to keep track of frequency of dmer within activeSegment */
+ U16* segmentFreqs = (U16 *)calloc(((U64)1 << ctx->f), sizeof(U16));
+ /* Allocate space for hash table, dict, and freqs */
+ BYTE *const dict = (BYTE * const)malloc(dictBufferCapacity);
+ U32 *freqs = (U32*) malloc(((U64)1 << ctx->f) * sizeof(U32));
+ if (!segmentFreqs || !dict || !freqs) {
+ DISPLAYLEVEL(1, "Failed to allocate buffers: out of memory\n");
+ goto _cleanup;
+ }
+ /* Copy the frequencies because we need to modify them */
+ memcpy(freqs, ctx->freqs, ((U64)1 << ctx->f) * sizeof(U32));
+ /* Build the dictionary */
+ { const size_t tail = FASTCOVER_buildDictionary(ctx, freqs, dict, dictBufferCapacity,
+ parameters, segmentFreqs);
+ const unsigned nbFinalizeSamples = (unsigned)(ctx->nbTrainSamples * ctx->accelParams.finalize / 100);
+ dictBufferCapacity = ZDICT_finalizeDictionary(
+ dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
+ ctx->samples, ctx->samplesSizes, nbFinalizeSamples, parameters.zParams);
+ if (ZDICT_isError(dictBufferCapacity)) {
+ DISPLAYLEVEL(1, "Failed to finalize dictionary\n");
+ goto _cleanup;
+ }
+ }
+ /* Check total compressed size */
+ totalCompressedSize = COVER_checkTotalCompressedSize(parameters, ctx->samplesSizes,
+ ctx->samples, ctx->offsets,
+ ctx->nbTrainSamples, ctx->nbSamples,
+ dict, dictBufferCapacity);
+_cleanup:
+ COVER_best_finish(data->best, totalCompressedSize, parameters, dict,
+ dictBufferCapacity);
+ free(data);
+ free(segmentFreqs);
+ free(dict);
+ free(freqs);
+}
+
+
+static void
+FASTCOVER_convertToCoverParams(ZDICT_fastCover_params_t fastCoverParams,
+ ZDICT_cover_params_t* coverParams)
+{
+ coverParams->k = fastCoverParams.k;
+ coverParams->d = fastCoverParams.d;
+ coverParams->steps = fastCoverParams.steps;
+ coverParams->nbThreads = fastCoverParams.nbThreads;
+ coverParams->splitPoint = fastCoverParams.splitPoint;
+ coverParams->zParams = fastCoverParams.zParams;
+}
+
+
+static void
+FASTCOVER_convertToFastCoverParams(ZDICT_cover_params_t coverParams,
+ ZDICT_fastCover_params_t* fastCoverParams,
+ unsigned f, unsigned accel)
+{
+ fastCoverParams->k = coverParams.k;
+ fastCoverParams->d = coverParams.d;
+ fastCoverParams->steps = coverParams.steps;
+ fastCoverParams->nbThreads = coverParams.nbThreads;
+ fastCoverParams->splitPoint = coverParams.splitPoint;
+ fastCoverParams->f = f;
+ fastCoverParams->accel = accel;
+ fastCoverParams->zParams = coverParams.zParams;
+}
+
+
+ZDICTLIB_API size_t
+ZDICT_trainFromBuffer_fastCover(void* dictBuffer, size_t dictBufferCapacity,
+ const void* samplesBuffer,
+ const size_t* samplesSizes, unsigned nbSamples,
+ ZDICT_fastCover_params_t parameters)
+{
+ BYTE* const dict = (BYTE*)dictBuffer;
+ FASTCOVER_ctx_t ctx;
+ ZDICT_cover_params_t coverParams;
+ FASTCOVER_accel_t accelParams;
+ /* Initialize global data */
+ g_displayLevel = parameters.zParams.notificationLevel;
+ /* Assign splitPoint and f if not provided */
+ parameters.splitPoint = 1.0;
+ parameters.f = parameters.f == 0 ? DEFAULT_F : parameters.f;
+ parameters.accel = parameters.accel == 0 ? DEFAULT_ACCEL : parameters.accel;
+ /* Convert to cover parameter */
+ memset(&coverParams, 0 , sizeof(coverParams));
+ FASTCOVER_convertToCoverParams(parameters, &coverParams);
+ /* Checks */
+ if (!FASTCOVER_checkParameters(coverParams, dictBufferCapacity, parameters.f,
+ parameters.accel)) {
+ DISPLAYLEVEL(1, "FASTCOVER parameters incorrect\n");
+ return ERROR(GENERIC);
+ }
+ if (nbSamples == 0) {
+ DISPLAYLEVEL(1, "FASTCOVER must have at least one input file\n");
+ return ERROR(GENERIC);
+ }
+ if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
+ DISPLAYLEVEL(1, "dictBufferCapacity must be at least %u\n",
+ ZDICT_DICTSIZE_MIN);
+ return ERROR(dstSize_tooSmall);
+ }
+ /* Assign corresponding FASTCOVER_accel_t to accelParams*/
+ accelParams = FASTCOVER_defaultAccelParameters[parameters.accel];
+ /* Initialize context */
+ if (!FASTCOVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples,
+ coverParams.d, parameters.splitPoint, parameters.f,
+ accelParams)) {
+ DISPLAYLEVEL(1, "Failed to initialize context\n");
+ return ERROR(GENERIC);
+ }
+ /* Build the dictionary */
+ DISPLAYLEVEL(2, "Building dictionary\n");
+ {
+ /* Initialize array to keep track of frequency of dmer within activeSegment */
+ U16* segmentFreqs = (U16 *)calloc(((U64)1 << parameters.f), sizeof(U16));
+ const size_t tail = FASTCOVER_buildDictionary(&ctx, ctx.freqs, dictBuffer,
+ dictBufferCapacity, coverParams, segmentFreqs);
+ const unsigned nbFinalizeSamples = (unsigned)(ctx.nbTrainSamples * ctx.accelParams.finalize / 100);
+ const size_t dictionarySize = ZDICT_finalizeDictionary(
+ dict, dictBufferCapacity, dict + tail, dictBufferCapacity - tail,
+ samplesBuffer, samplesSizes, nbFinalizeSamples, coverParams.zParams);
+ if (!ZSTD_isError(dictionarySize)) {
+ DISPLAYLEVEL(2, "Constructed dictionary of size %u\n",
+ (unsigned)dictionarySize);
+ }
+ FASTCOVER_ctx_destroy(&ctx);
+ free(segmentFreqs);
+ return dictionarySize;
+ }
+}
+
+
+ZDICTLIB_API size_t
+ZDICT_optimizeTrainFromBuffer_fastCover(
+ void* dictBuffer, size_t dictBufferCapacity,
+ const void* samplesBuffer,
+ const size_t* samplesSizes, unsigned nbSamples,
+ ZDICT_fastCover_params_t* parameters)
+{
+ ZDICT_cover_params_t coverParams;
+ FASTCOVER_accel_t accelParams;
+ /* constants */
+ const unsigned nbThreads = parameters->nbThreads;
+ const double splitPoint =
+ parameters->splitPoint <= 0.0 ? DEFAULT_SPLITPOINT : parameters->splitPoint;
+ const unsigned kMinD = parameters->d == 0 ? 6 : parameters->d;
+ const unsigned kMaxD = parameters->d == 0 ? 8 : parameters->d;
+ const unsigned kMinK = parameters->k == 0 ? 50 : parameters->k;
+ const unsigned kMaxK = parameters->k == 0 ? 2000 : parameters->k;
+ const unsigned kSteps = parameters->steps == 0 ? 40 : parameters->steps;
+ const unsigned kStepSize = MAX((kMaxK - kMinK) / kSteps, 1);
+ const unsigned kIterations =
+ (1 + (kMaxD - kMinD) / 2) * (1 + (kMaxK - kMinK) / kStepSize);
+ const unsigned f = parameters->f == 0 ? DEFAULT_F : parameters->f;
+ const unsigned accel = parameters->accel == 0 ? DEFAULT_ACCEL : parameters->accel;
+ /* Local variables */
+ const int displayLevel = parameters->zParams.notificationLevel;
+ unsigned iteration = 1;
+ unsigned d;
+ unsigned k;
+ COVER_best_t best;
+ POOL_ctx *pool = NULL;
+ /* Checks */
+ if (splitPoint <= 0 || splitPoint > 1) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect splitPoint\n");
+ return ERROR(GENERIC);
+ }
+ if (accel == 0 || accel > FASTCOVER_MAX_ACCEL) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect accel\n");
+ return ERROR(GENERIC);
+ }
+ if (kMinK < kMaxD || kMaxK < kMinK) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "Incorrect k\n");
+ return ERROR(GENERIC);
+ }
+ if (nbSamples == 0) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "FASTCOVER must have at least one input file\n");
+ return ERROR(GENERIC);
+ }
+ if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "dictBufferCapacity must be at least %u\n",
+ ZDICT_DICTSIZE_MIN);
+ return ERROR(dstSize_tooSmall);
+ }
+ if (nbThreads > 1) {
+ pool = POOL_create(nbThreads, 1);
+ if (!pool) {
+ return ERROR(memory_allocation);
+ }
+ }
+ /* Initialization */
+ COVER_best_init(&best);
+ memset(&coverParams, 0 , sizeof(coverParams));
+ FASTCOVER_convertToCoverParams(*parameters, &coverParams);
+ accelParams = FASTCOVER_defaultAccelParameters[accel];
+ /* Turn down global display level to clean up display at level 2 and below */
+ g_displayLevel = displayLevel == 0 ? 0 : displayLevel - 1;
+ /* Loop through d first because each new value needs a new context */
+ LOCALDISPLAYLEVEL(displayLevel, 2, "Trying %u different sets of parameters\n",
+ kIterations);
+ for (d = kMinD; d <= kMaxD; d += 2) {
+ /* Initialize the context for this value of d */
+ FASTCOVER_ctx_t ctx;
+ LOCALDISPLAYLEVEL(displayLevel, 3, "d=%u\n", d);
+ if (!FASTCOVER_ctx_init(&ctx, samplesBuffer, samplesSizes, nbSamples, d, splitPoint, f, accelParams)) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to initialize context\n");
+ COVER_best_destroy(&best);
+ POOL_free(pool);
+ return ERROR(GENERIC);
+ }
+ /* Loop through k reusing the same context */
+ for (k = kMinK; k <= kMaxK; k += kStepSize) {
+ /* Prepare the arguments */
+ FASTCOVER_tryParameters_data_t *data = (FASTCOVER_tryParameters_data_t *)malloc(
+ sizeof(FASTCOVER_tryParameters_data_t));
+ LOCALDISPLAYLEVEL(displayLevel, 3, "k=%u\n", k);
+ if (!data) {
+ LOCALDISPLAYLEVEL(displayLevel, 1, "Failed to allocate parameters\n");
+ COVER_best_destroy(&best);
+ FASTCOVER_ctx_destroy(&ctx);
+ POOL_free(pool);
+ return ERROR(GENERIC);
+ }
+ data->ctx = &ctx;
+ data->best = &best;
+ data->dictBufferCapacity = dictBufferCapacity;
+ data->parameters = coverParams;
+ data->parameters.k = k;
+ data->parameters.d = d;
+ data->parameters.splitPoint = splitPoint;
+ data->parameters.steps = kSteps;
+ data->parameters.zParams.notificationLevel = g_displayLevel;
+ /* Check the parameters */
+ if (!FASTCOVER_checkParameters(data->parameters, dictBufferCapacity,
+ data->ctx->f, accel)) {
+ DISPLAYLEVEL(1, "FASTCOVER parameters incorrect\n");
+ free(data);
+ continue;
+ }
+ /* Call the function and pass ownership of data to it */
+ COVER_best_start(&best);
+ if (pool) {
+ POOL_add(pool, &FASTCOVER_tryParameters, data);
+ } else {
+ FASTCOVER_tryParameters(data);
+ }
+ /* Print status */
+ LOCALDISPLAYUPDATE(displayLevel, 2, "\r%u%% ",
+ (unsigned)((iteration * 100) / kIterations));
+ ++iteration;
+ }
+ COVER_best_wait(&best);
+ FASTCOVER_ctx_destroy(&ctx);
+ }
+ LOCALDISPLAYLEVEL(displayLevel, 2, "\r%79s\r", "");
+ /* Fill the output buffer and parameters with output of the best parameters */
+ {
+ const size_t dictSize = best.dictSize;
+ if (ZSTD_isError(best.compressedSize)) {
+ const size_t compressedSize = best.compressedSize;
+ COVER_best_destroy(&best);
+ POOL_free(pool);
+ return compressedSize;
+ }
+ FASTCOVER_convertToFastCoverParams(best.parameters, parameters, f, accel);
+ memcpy(dictBuffer, best.dict, dictSize);
+ COVER_best_destroy(&best);
+ POOL_free(pool);
+ return dictSize;
+ }
+
+}
diff --git a/Utilities/cmzstd/lib/dictBuilder/zdict.c b/Utilities/cmzstd/lib/dictBuilder/zdict.c
new file mode 100644
index 000000000..c753da0db
--- /dev/null
+++ b/Utilities/cmzstd/lib/dictBuilder/zdict.c
@@ -0,0 +1,1111 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+
+/*-**************************************
+* Tuning parameters
+****************************************/
+#define MINRATIO 4 /* minimum nb of apparition to be selected in dictionary */
+#define ZDICT_MAX_SAMPLES_SIZE (2000U << 20)
+#define ZDICT_MIN_SAMPLES_SIZE (ZDICT_CONTENTSIZE_MIN * MINRATIO)
+
+
+/*-**************************************
+* Compiler Options
+****************************************/
+/* Unix Large Files support (>4GB) */
+#define _FILE_OFFSET_BITS 64
+#if (defined(__sun__) && (!defined(__LP64__))) /* Sun Solaris 32-bits requires specific definitions */
+# define _LARGEFILE_SOURCE
+#elif ! defined(__LP64__) /* No point defining Large file for 64 bit */
+# define _LARGEFILE64_SOURCE
+#endif
+
+
+/*-*************************************
+* Dependencies
+***************************************/
+#include <stdlib.h> /* malloc, free */
+#include <string.h> /* memset */
+#include <stdio.h> /* fprintf, fopen, ftello64 */
+#include <time.h> /* clock */
+
+#include "mem.h" /* read */
+#include "fse.h" /* FSE_normalizeCount, FSE_writeNCount */
+#define HUF_STATIC_LINKING_ONLY
+#include "huf.h" /* HUF_buildCTable, HUF_writeCTable */
+#include "zstd_internal.h" /* includes zstd.h */
+#include "xxhash.h" /* XXH64 */
+#include "divsufsort.h"
+#ifndef ZDICT_STATIC_LINKING_ONLY
+# define ZDICT_STATIC_LINKING_ONLY
+#endif
+#include "zdict.h"
+
+
+/*-*************************************
+* Constants
+***************************************/
+#define KB *(1 <<10)
+#define MB *(1 <<20)
+#define GB *(1U<<30)
+
+#define DICTLISTSIZE_DEFAULT 10000
+
+#define NOISELENGTH 32
+
+static const int g_compressionLevel_default = 3;
+static const U32 g_selectivity_default = 9;
+
+
+/*-*************************************
+* Console display
+***************************************/
+#define DISPLAY(...) { fprintf(stderr, __VA_ARGS__); fflush( stderr ); }
+#define DISPLAYLEVEL(l, ...) if (notificationLevel>=l) { DISPLAY(__VA_ARGS__); } /* 0 : no display; 1: errors; 2: default; 3: details; 4: debug */
+
+static clock_t ZDICT_clockSpan(clock_t nPrevious) { return clock() - nPrevious; }
+
+static void ZDICT_printHex(const void* ptr, size_t length)
+{
+ const BYTE* const b = (const BYTE*)ptr;
+ size_t u;
+ for (u=0; u<length; u++) {
+ BYTE c = b[u];
+ if (c<32 || c>126) c = '.'; /* non-printable char */
+ DISPLAY("%c", c);
+ }
+}
+
+
+/*-********************************************************
+* Helper functions
+**********************************************************/
+unsigned ZDICT_isError(size_t errorCode) { return ERR_isError(errorCode); }
+
+const char* ZDICT_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
+
+unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize)
+{
+ if (dictSize < 8) return 0;
+ if (MEM_readLE32(dictBuffer) != ZSTD_MAGIC_DICTIONARY) return 0;
+ return MEM_readLE32((const char*)dictBuffer + 4);
+}
+
+
+/*-********************************************************
+* Dictionary training functions
+**********************************************************/
+static unsigned ZDICT_NbCommonBytes (size_t val)
+{
+ if (MEM_isLittleEndian()) {
+ if (MEM_64bits()) {
+# if defined(_MSC_VER) && defined(_WIN64)
+ unsigned long r = 0;
+ _BitScanForward64( &r, (U64)val );
+ return (unsigned)(r>>3);
+# elif defined(__GNUC__) && (__GNUC__ >= 3)
+ return (__builtin_ctzll((U64)val) >> 3);
+# else
+ static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };
+ return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
+# endif
+ } else { /* 32 bits */
+# if defined(_MSC_VER)
+ unsigned long r=0;
+ _BitScanForward( &r, (U32)val );
+ return (unsigned)(r>>3);
+# elif defined(__GNUC__) && (__GNUC__ >= 3)
+ return (__builtin_ctz((U32)val) >> 3);
+# else
+ static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };
+ return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
+# endif
+ }
+ } else { /* Big Endian CPU */
+ if (MEM_64bits()) {
+# if defined(_MSC_VER) && defined(_WIN64)
+ unsigned long r = 0;
+ _BitScanReverse64( &r, val );
+ return (unsigned)(r>>3);
+# elif defined(__GNUC__) && (__GNUC__ >= 3)
+ return (__builtin_clzll(val) >> 3);
+# else
+ unsigned r;
+ const unsigned n32 = sizeof(size_t)*4; /* calculate this way due to compiler complaining in 32-bits mode */
+ if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; }
+ if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
+ r += (!val);
+ return r;
+# endif
+ } else { /* 32 bits */
+# if defined(_MSC_VER)
+ unsigned long r = 0;
+ _BitScanReverse( &r, (unsigned long)val );
+ return (unsigned)(r>>3);
+# elif defined(__GNUC__) && (__GNUC__ >= 3)
+ return (__builtin_clz((U32)val) >> 3);
+# else
+ unsigned r;
+ if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
+ r += (!val);
+ return r;
+# endif
+ } }
+}
+
+
+/*! ZDICT_count() :
+ Count the nb of common bytes between 2 pointers.
+ Note : this function presumes end of buffer followed by noisy guard band.
+*/
+static size_t ZDICT_count(const void* pIn, const void* pMatch)
+{
+ const char* const pStart = (const char*)pIn;
+ for (;;) {
+ size_t const diff = MEM_readST(pMatch) ^ MEM_readST(pIn);
+ if (!diff) {
+ pIn = (const char*)pIn+sizeof(size_t);
+ pMatch = (const char*)pMatch+sizeof(size_t);
+ continue;
+ }
+ pIn = (const char*)pIn+ZDICT_NbCommonBytes(diff);
+ return (size_t)((const char*)pIn - pStart);
+ }
+}
+
+
+typedef struct {
+ U32 pos;
+ U32 length;
+ U32 savings;
+} dictItem;
+
+static void ZDICT_initDictItem(dictItem* d)
+{
+ d->pos = 1;
+ d->length = 0;
+ d->savings = (U32)(-1);
+}
+
+
+#define LLIMIT 64 /* heuristic determined experimentally */
+#define MINMATCHLENGTH 7 /* heuristic determined experimentally */
+static dictItem ZDICT_analyzePos(
+ BYTE* doneMarks,
+ const int* suffix, U32 start,
+ const void* buffer, U32 minRatio, U32 notificationLevel)
+{
+ U32 lengthList[LLIMIT] = {0};
+ U32 cumulLength[LLIMIT] = {0};
+ U32 savings[LLIMIT] = {0};
+ const BYTE* b = (const BYTE*)buffer;
+ size_t maxLength = LLIMIT;
+ size_t pos = suffix[start];
+ U32 end = start;
+ dictItem solution;
+
+ /* init */
+ memset(&solution, 0, sizeof(solution));
+ doneMarks[pos] = 1;
+
+ /* trivial repetition cases */
+ if ( (MEM_read16(b+pos+0) == MEM_read16(b+pos+2))
+ ||(MEM_read16(b+pos+1) == MEM_read16(b+pos+3))
+ ||(MEM_read16(b+pos+2) == MEM_read16(b+pos+4)) ) {
+ /* skip and mark segment */
+ U16 const pattern16 = MEM_read16(b+pos+4);
+ U32 u, patternEnd = 6;
+ while (MEM_read16(b+pos+patternEnd) == pattern16) patternEnd+=2 ;
+ if (b[pos+patternEnd] == b[pos+patternEnd-1]) patternEnd++;
+ for (u=1; u<patternEnd; u++)
+ doneMarks[pos+u] = 1;
+ return solution;
+ }
+
+ /* look forward */
+ { size_t length;
+ do {
+ end++;
+ length = ZDICT_count(b + pos, b + suffix[end]);
+ } while (length >= MINMATCHLENGTH);
+ }
+
+ /* look backward */
+ { size_t length;
+ do {
+ length = ZDICT_count(b + pos, b + *(suffix+start-1));
+ if (length >=MINMATCHLENGTH) start--;
+ } while(length >= MINMATCHLENGTH);
+ }
+
+ /* exit if not found a minimum nb of repetitions */
+ if (end-start < minRatio) {
+ U32 idx;
+ for(idx=start; idx<end; idx++)
+ doneMarks[suffix[idx]] = 1;
+ return solution;
+ }
+
+ { int i;
+ U32 mml;
+ U32 refinedStart = start;
+ U32 refinedEnd = end;
+
+ DISPLAYLEVEL(4, "\n");
+ DISPLAYLEVEL(4, "found %3u matches of length >= %i at pos %7u ", (unsigned)(end-start), MINMATCHLENGTH, (unsigned)pos);
+ DISPLAYLEVEL(4, "\n");
+
+ for (mml = MINMATCHLENGTH ; ; mml++) {
+ BYTE currentChar = 0;
+ U32 currentCount = 0;
+ U32 currentID = refinedStart;
+ U32 id;
+ U32 selectedCount = 0;
+ U32 selectedID = currentID;
+ for (id =refinedStart; id < refinedEnd; id++) {
+ if (b[suffix[id] + mml] != currentChar) {
+ if (currentCount > selectedCount) {
+ selectedCount = currentCount;
+ selectedID = currentID;
+ }
+ currentID = id;
+ currentChar = b[ suffix[id] + mml];
+ currentCount = 0;
+ }
+ currentCount ++;
+ }
+ if (currentCount > selectedCount) { /* for last */
+ selectedCount = currentCount;
+ selectedID = currentID;
+ }
+
+ if (selectedCount < minRatio)
+ break;
+ refinedStart = selectedID;
+ refinedEnd = refinedStart + selectedCount;
+ }
+
+ /* evaluate gain based on new dict */
+ start = refinedStart;
+ pos = suffix[refinedStart];
+ end = start;
+ memset(lengthList, 0, sizeof(lengthList));
+
+ /* look forward */
+ { size_t length;
+ do {
+ end++;
+ length = ZDICT_count(b + pos, b + suffix[end]);
+ if (length >= LLIMIT) length = LLIMIT-1;
+ lengthList[length]++;
+ } while (length >=MINMATCHLENGTH);
+ }
+
+ /* look backward */
+ { size_t length = MINMATCHLENGTH;
+ while ((length >= MINMATCHLENGTH) & (start > 0)) {
+ length = ZDICT_count(b + pos, b + suffix[start - 1]);
+ if (length >= LLIMIT) length = LLIMIT - 1;
+ lengthList[length]++;
+ if (length >= MINMATCHLENGTH) start--;
+ }
+ }
+
+ /* largest useful length */
+ memset(cumulLength, 0, sizeof(cumulLength));
+ cumulLength[maxLength-1] = lengthList[maxLength-1];
+ for (i=(int)(maxLength-2); i>=0; i--)
+ cumulLength[i] = cumulLength[i+1] + lengthList[i];
+
+ for (i=LLIMIT-1; i>=MINMATCHLENGTH; i--) if (cumulLength[i]>=minRatio) break;
+ maxLength = i;
+
+ /* reduce maxLength in case of final into repetitive data */
+ { U32 l = (U32)maxLength;
+ BYTE const c = b[pos + maxLength-1];
+ while (b[pos+l-2]==c) l--;
+ maxLength = l;
+ }
+ if (maxLength < MINMATCHLENGTH) return solution; /* skip : no long-enough solution */
+
+ /* calculate savings */
+ savings[5] = 0;
+ for (i=MINMATCHLENGTH; i<=(int)maxLength; i++)
+ savings[i] = savings[i-1] + (lengthList[i] * (i-3));
+
+ DISPLAYLEVEL(4, "Selected dict at position %u, of length %u : saves %u (ratio: %.2f) \n",
+ (unsigned)pos, (unsigned)maxLength, (unsigned)savings[maxLength], (double)savings[maxLength] / maxLength);
+
+ solution.pos = (U32)pos;
+ solution.length = (U32)maxLength;
+ solution.savings = savings[maxLength];
+
+ /* mark positions done */
+ { U32 id;
+ for (id=start; id<end; id++) {
+ U32 p, pEnd, length;
+ U32 const testedPos = suffix[id];
+ if (testedPos == pos)
+ length = solution.length;
+ else {
+ length = (U32)ZDICT_count(b+pos, b+testedPos);
+ if (length > solution.length) length = solution.length;
+ }
+ pEnd = (U32)(testedPos + length);
+ for (p=testedPos; p<pEnd; p++)
+ doneMarks[p] = 1;
+ } } }
+
+ return solution;
+}
+
+
+static int isIncluded(const void* in, const void* container, size_t length)
+{
+ const char* const ip = (const char*) in;
+ const char* const into = (const char*) container;
+ size_t u;
+
+ for (u=0; u<length; u++) { /* works because end of buffer is a noisy guard band */
+ if (ip[u] != into[u]) break;
+ }
+
+ return u==length;
+}
+
+/*! ZDICT_tryMerge() :
+ check if dictItem can be merged, do it if possible
+ @return : id of destination elt, 0 if not merged
+*/
+static U32 ZDICT_tryMerge(dictItem* table, dictItem elt, U32 eltNbToSkip, const void* buffer)
+{
+ const U32 tableSize = table->pos;
+ const U32 eltEnd = elt.pos + elt.length;
+ const char* const buf = (const char*) buffer;
+
+ /* tail overlap */
+ U32 u; for (u=1; u<tableSize; u++) {
+ if (u==eltNbToSkip) continue;
+ if ((table[u].pos > elt.pos) && (table[u].pos <= eltEnd)) { /* overlap, existing > new */
+ /* append */
+ U32 const addedLength = table[u].pos - elt.pos;
+ table[u].length += addedLength;
+ table[u].pos = elt.pos;
+ table[u].savings += elt.savings * addedLength / elt.length; /* rough approx */
+ table[u].savings += elt.length / 8; /* rough approx bonus */
+ elt = table[u];
+ /* sort : improve rank */
+ while ((u>1) && (table[u-1].savings < elt.savings))
+ table[u] = table[u-1], u--;
+ table[u] = elt;
+ return u;
+ } }
+
+ /* front overlap */
+ for (u=1; u<tableSize; u++) {
+ if (u==eltNbToSkip) continue;
+
+ if ((table[u].pos + table[u].length >= elt.pos) && (table[u].pos < elt.pos)) { /* overlap, existing < new */
+ /* append */
+ int const addedLength = (int)eltEnd - (table[u].pos + table[u].length);
+ table[u].savings += elt.length / 8; /* rough approx bonus */
+ if (addedLength > 0) { /* otherwise, elt fully included into existing */
+ table[u].length += addedLength;
+ table[u].savings += elt.savings * addedLength / elt.length; /* rough approx */
+ }
+ /* sort : improve rank */
+ elt = table[u];
+ while ((u>1) && (table[u-1].savings < elt.savings))
+ table[u] = table[u-1], u--;
+ table[u] = elt;
+ return u;
+ }
+
+ if (MEM_read64(buf + table[u].pos) == MEM_read64(buf + elt.pos + 1)) {
+ if (isIncluded(buf + table[u].pos, buf + elt.pos + 1, table[u].length)) {
+ size_t const addedLength = MAX( (int)elt.length - (int)table[u].length , 1 );
+ table[u].pos = elt.pos;
+ table[u].savings += (U32)(elt.savings * addedLength / elt.length);
+ table[u].length = MIN(elt.length, table[u].length + 1);
+ return u;
+ }
+ }
+ }
+
+ return 0;
+}
+
+
+static void ZDICT_removeDictItem(dictItem* table, U32 id)
+{
+ /* convention : table[0].pos stores nb of elts */
+ U32 const max = table[0].pos;
+ U32 u;
+ if (!id) return; /* protection, should never happen */
+ for (u=id; u<max-1; u++)
+ table[u] = table[u+1];
+ table->pos--;
+}
+
+
+static void ZDICT_insertDictItem(dictItem* table, U32 maxSize, dictItem elt, const void* buffer)
+{
+ /* merge if possible */
+ U32 mergeId = ZDICT_tryMerge(table, elt, 0, buffer);
+ if (mergeId) {
+ U32 newMerge = 1;
+ while (newMerge) {
+ newMerge = ZDICT_tryMerge(table, table[mergeId], mergeId, buffer);
+ if (newMerge) ZDICT_removeDictItem(table, mergeId);
+ mergeId = newMerge;
+ }
+ return;
+ }
+
+ /* insert */
+ { U32 current;
+ U32 nextElt = table->pos;
+ if (nextElt >= maxSize) nextElt = maxSize-1;
+ current = nextElt-1;
+ while (table[current].savings < elt.savings) {
+ table[current+1] = table[current];
+ current--;
+ }
+ table[current+1] = elt;
+ table->pos = nextElt+1;
+ }
+}
+
+
+static U32 ZDICT_dictSize(const dictItem* dictList)
+{
+ U32 u, dictSize = 0;
+ for (u=1; u<dictList[0].pos; u++)
+ dictSize += dictList[u].length;
+ return dictSize;
+}
+
+
+static size_t ZDICT_trainBuffer_legacy(dictItem* dictList, U32 dictListSize,
+ const void* const buffer, size_t bufferSize, /* buffer must end with noisy guard band */
+ const size_t* fileSizes, unsigned nbFiles,
+ unsigned minRatio, U32 notificationLevel)
+{
+ int* const suffix0 = (int*)malloc((bufferSize+2)*sizeof(*suffix0));
+ int* const suffix = suffix0+1;
+ U32* reverseSuffix = (U32*)malloc((bufferSize)*sizeof(*reverseSuffix));
+ BYTE* doneMarks = (BYTE*)malloc((bufferSize+16)*sizeof(*doneMarks)); /* +16 for overflow security */
+ U32* filePos = (U32*)malloc(nbFiles * sizeof(*filePos));
+ size_t result = 0;
+ clock_t displayClock = 0;
+ clock_t const refreshRate = CLOCKS_PER_SEC * 3 / 10;
+
+# define DISPLAYUPDATE(l, ...) if (notificationLevel>=l) { \
+ if (ZDICT_clockSpan(displayClock) > refreshRate) \
+ { displayClock = clock(); DISPLAY(__VA_ARGS__); \
+ if (notificationLevel>=4) fflush(stderr); } }
+
+ /* init */
+ DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
+ if (!suffix0 || !reverseSuffix || !doneMarks || !filePos) {
+ result = ERROR(memory_allocation);
+ goto _cleanup;
+ }
+ if (minRatio < MINRATIO) minRatio = MINRATIO;
+ memset(doneMarks, 0, bufferSize+16);
+
+ /* limit sample set size (divsufsort limitation)*/
+ if (bufferSize > ZDICT_MAX_SAMPLES_SIZE) DISPLAYLEVEL(3, "sample set too large : reduced to %u MB ...\n", (unsigned)(ZDICT_MAX_SAMPLES_SIZE>>20));
+ while (bufferSize > ZDICT_MAX_SAMPLES_SIZE) bufferSize -= fileSizes[--nbFiles];
+
+ /* sort */
+ DISPLAYLEVEL(2, "sorting %u files of total size %u MB ...\n", nbFiles, (unsigned)(bufferSize>>20));
+ { int const divSuftSortResult = divsufsort((const unsigned char*)buffer, suffix, (int)bufferSize, 0);
+ if (divSuftSortResult != 0) { result = ERROR(GENERIC); goto _cleanup; }
+ }
+ suffix[bufferSize] = (int)bufferSize; /* leads into noise */
+ suffix0[0] = (int)bufferSize; /* leads into noise */
+ /* build reverse suffix sort */
+ { size_t pos;
+ for (pos=0; pos < bufferSize; pos++)
+ reverseSuffix[suffix[pos]] = (U32)pos;
+ /* note filePos tracks borders between samples.
+ It's not used at this stage, but planned to become useful in a later update */
+ filePos[0] = 0;
+ for (pos=1; pos<nbFiles; pos++)
+ filePos[pos] = (U32)(filePos[pos-1] + fileSizes[pos-1]);
+ }
+
+ DISPLAYLEVEL(2, "finding patterns ... \n");
+ DISPLAYLEVEL(3, "minimum ratio : %u \n", minRatio);
+
+ { U32 cursor; for (cursor=0; cursor < bufferSize; ) {
+ dictItem solution;
+ if (doneMarks[cursor]) { cursor++; continue; }
+ solution = ZDICT_analyzePos(doneMarks, suffix, reverseSuffix[cursor], buffer, minRatio, notificationLevel);
+ if (solution.length==0) { cursor++; continue; }
+ ZDICT_insertDictItem(dictList, dictListSize, solution, buffer);
+ cursor += solution.length;
+ DISPLAYUPDATE(2, "\r%4.2f %% \r", (double)cursor / bufferSize * 100);
+ } }
+
+_cleanup:
+ free(suffix0);
+ free(reverseSuffix);
+ free(doneMarks);
+ free(filePos);
+ return result;
+}
+
+
+static void ZDICT_fillNoise(void* buffer, size_t length)
+{
+ unsigned const prime1 = 2654435761U;
+ unsigned const prime2 = 2246822519U;
+ unsigned acc = prime1;
+ size_t p=0;;
+ for (p=0; p<length; p++) {
+ acc *= prime2;
+ ((unsigned char*)buffer)[p] = (unsigned char)(acc >> 21);
+ }
+}
+
+
+typedef struct
+{
+ ZSTD_CDict* dict; /* dictionary */
+ ZSTD_CCtx* zc; /* working context */
+ void* workPlace; /* must be ZSTD_BLOCKSIZE_MAX allocated */
+} EStats_ress_t;
+
+#define MAXREPOFFSET 1024
+
+static void ZDICT_countEStats(EStats_ress_t esr, ZSTD_parameters params,
+ unsigned* countLit, unsigned* offsetcodeCount, unsigned* matchlengthCount, unsigned* litlengthCount, U32* repOffsets,
+ const void* src, size_t srcSize,
+ U32 notificationLevel)
+{
+ size_t const blockSizeMax = MIN (ZSTD_BLOCKSIZE_MAX, 1 << params.cParams.windowLog);
+ size_t cSize;
+
+ if (srcSize > blockSizeMax) srcSize = blockSizeMax; /* protection vs large samples */
+ { size_t const errorCode = ZSTD_compressBegin_usingCDict(esr.zc, esr.dict);
+ if (ZSTD_isError(errorCode)) { DISPLAYLEVEL(1, "warning : ZSTD_compressBegin_usingCDict failed \n"); return; }
+
+ }
+ cSize = ZSTD_compressBlock(esr.zc, esr.workPlace, ZSTD_BLOCKSIZE_MAX, src, srcSize);
+ if (ZSTD_isError(cSize)) { DISPLAYLEVEL(3, "warning : could not compress sample size %u \n", (unsigned)srcSize); return; }
+
+ if (cSize) { /* if == 0; block is not compressible */
+ const seqStore_t* const seqStorePtr = ZSTD_getSeqStore(esr.zc);
+
+ /* literals stats */
+ { const BYTE* bytePtr;
+ for(bytePtr = seqStorePtr->litStart; bytePtr < seqStorePtr->lit; bytePtr++)
+ countLit[*bytePtr]++;
+ }
+
+ /* seqStats */
+ { U32 const nbSeq = (U32)(seqStorePtr->sequences - seqStorePtr->sequencesStart);
+ ZSTD_seqToCodes(seqStorePtr);
+
+ { const BYTE* codePtr = seqStorePtr->ofCode;
+ U32 u;
+ for (u=0; u<nbSeq; u++) offsetcodeCount[codePtr[u]]++;
+ }
+
+ { const BYTE* codePtr = seqStorePtr->mlCode;
+ U32 u;
+ for (u=0; u<nbSeq; u++) matchlengthCount[codePtr[u]]++;
+ }
+
+ { const BYTE* codePtr = seqStorePtr->llCode;
+ U32 u;
+ for (u=0; u<nbSeq; u++) litlengthCount[codePtr[u]]++;
+ }
+
+ if (nbSeq >= 2) { /* rep offsets */
+ const seqDef* const seq = seqStorePtr->sequencesStart;
+ U32 offset1 = seq[0].offset - 3;
+ U32 offset2 = seq[1].offset - 3;
+ if (offset1 >= MAXREPOFFSET) offset1 = 0;
+ if (offset2 >= MAXREPOFFSET) offset2 = 0;
+ repOffsets[offset1] += 3;
+ repOffsets[offset2] += 1;
+ } } }
+}
+
+static size_t ZDICT_totalSampleSize(const size_t* fileSizes, unsigned nbFiles)
+{
+ size_t total=0;
+ unsigned u;
+ for (u=0; u<nbFiles; u++) total += fileSizes[u];
+ return total;
+}
+
+typedef struct { U32 offset; U32 count; } offsetCount_t;
+
+static void ZDICT_insertSortCount(offsetCount_t table[ZSTD_REP_NUM+1], U32 val, U32 count)
+{
+ U32 u;
+ table[ZSTD_REP_NUM].offset = val;
+ table[ZSTD_REP_NUM].count = count;
+ for (u=ZSTD_REP_NUM; u>0; u--) {
+ offsetCount_t tmp;
+ if (table[u-1].count >= table[u].count) break;
+ tmp = table[u-1];
+ table[u-1] = table[u];
+ table[u] = tmp;
+ }
+}
+
+/* ZDICT_flatLit() :
+ * rewrite `countLit` to contain a mostly flat but still compressible distribution of literals.
+ * necessary to avoid generating a non-compressible distribution that HUF_writeCTable() cannot encode.
+ */
+static void ZDICT_flatLit(unsigned* countLit)
+{
+ int u;
+ for (u=1; u<256; u++) countLit[u] = 2;
+ countLit[0] = 4;
+ countLit[253] = 1;
+ countLit[254] = 1;
+}
+
+#define OFFCODE_MAX 30 /* only applicable to first block */
+static size_t ZDICT_analyzeEntropy(void* dstBuffer, size_t maxDstSize,
+ unsigned compressionLevel,
+ const void* srcBuffer, const size_t* fileSizes, unsigned nbFiles,
+ const void* dictBuffer, size_t dictBufferSize,
+ unsigned notificationLevel)
+{
+ unsigned countLit[256];
+ HUF_CREATE_STATIC_CTABLE(hufTable, 255);
+ unsigned offcodeCount[OFFCODE_MAX+1];
+ short offcodeNCount[OFFCODE_MAX+1];
+ U32 offcodeMax = ZSTD_highbit32((U32)(dictBufferSize + 128 KB));
+ unsigned matchLengthCount[MaxML+1];
+ short matchLengthNCount[MaxML+1];
+ unsigned litLengthCount[MaxLL+1];
+ short litLengthNCount[MaxLL+1];
+ U32 repOffset[MAXREPOFFSET];
+ offsetCount_t bestRepOffset[ZSTD_REP_NUM+1];
+ EStats_ress_t esr = { NULL, NULL, NULL };
+ ZSTD_parameters params;
+ U32 u, huffLog = 11, Offlog = OffFSELog, mlLog = MLFSELog, llLog = LLFSELog, total;
+ size_t pos = 0, errorCode;
+ size_t eSize = 0;
+ size_t const totalSrcSize = ZDICT_totalSampleSize(fileSizes, nbFiles);
+ size_t const averageSampleSize = totalSrcSize / (nbFiles + !nbFiles);
+ BYTE* dstPtr = (BYTE*)dstBuffer;
+
+ /* init */
+ DEBUGLOG(4, "ZDICT_analyzeEntropy");
+ if (offcodeMax>OFFCODE_MAX) { eSize = ERROR(dictionaryCreation_failed); goto _cleanup; } /* too large dictionary */
+ for (u=0; u<256; u++) countLit[u] = 1; /* any character must be described */
+ for (u=0; u<=offcodeMax; u++) offcodeCount[u] = 1;
+ for (u=0; u<=MaxML; u++) matchLengthCount[u] = 1;
+ for (u=0; u<=MaxLL; u++) litLengthCount[u] = 1;
+ memset(repOffset, 0, sizeof(repOffset));
+ repOffset[1] = repOffset[4] = repOffset[8] = 1;
+ memset(bestRepOffset, 0, sizeof(bestRepOffset));
+ if (compressionLevel==0) compressionLevel = g_compressionLevel_default;
+ params = ZSTD_getParams(compressionLevel, averageSampleSize, dictBufferSize);
+
+ esr.dict = ZSTD_createCDict_advanced(dictBuffer, dictBufferSize, ZSTD_dlm_byRef, ZSTD_dct_rawContent, params.cParams, ZSTD_defaultCMem);
+ esr.zc = ZSTD_createCCtx();
+ esr.workPlace = malloc(ZSTD_BLOCKSIZE_MAX);
+ if (!esr.dict || !esr.zc || !esr.workPlace) {
+ eSize = ERROR(memory_allocation);
+ DISPLAYLEVEL(1, "Not enough memory \n");
+ goto _cleanup;
+ }
+
+ /* collect stats on all samples */
+ for (u=0; u<nbFiles; u++) {
+ ZDICT_countEStats(esr, params,
+ countLit, offcodeCount, matchLengthCount, litLengthCount, repOffset,
+ (const char*)srcBuffer + pos, fileSizes[u],
+ notificationLevel);
+ pos += fileSizes[u];
+ }
+
+ /* analyze, build stats, starting with literals */
+ { size_t maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
+ if (HUF_isError(maxNbBits)) {
+ eSize = ERROR(GENERIC);
+ DISPLAYLEVEL(1, " HUF_buildCTable error \n");
+ goto _cleanup;
+ }
+ if (maxNbBits==8) { /* not compressible : will fail on HUF_writeCTable() */
+ DISPLAYLEVEL(2, "warning : pathological dataset : literals are not compressible : samples are noisy or too regular \n");
+ ZDICT_flatLit(countLit); /* replace distribution by a fake "mostly flat but still compressible" distribution, that HUF_writeCTable() can encode */
+ maxNbBits = HUF_buildCTable (hufTable, countLit, 255, huffLog);
+ assert(maxNbBits==9);
+ }
+ huffLog = (U32)maxNbBits;
+ }
+
+ /* looking for most common first offsets */
+ { U32 offset;
+ for (offset=1; offset<MAXREPOFFSET; offset++)
+ ZDICT_insertSortCount(bestRepOffset, offset, repOffset[offset]);
+ }
+ /* note : the result of this phase should be used to better appreciate the impact on statistics */
+
+ total=0; for (u=0; u<=offcodeMax; u++) total+=offcodeCount[u];
+ errorCode = FSE_normalizeCount(offcodeNCount, Offlog, offcodeCount, total, offcodeMax);
+ if (FSE_isError(errorCode)) {
+ eSize = ERROR(GENERIC);
+ DISPLAYLEVEL(1, "FSE_normalizeCount error with offcodeCount \n");
+ goto _cleanup;
+ }
+ Offlog = (U32)errorCode;
+
+ total=0; for (u=0; u<=MaxML; u++) total+=matchLengthCount[u];
+ errorCode = FSE_normalizeCount(matchLengthNCount, mlLog, matchLengthCount, total, MaxML);
+ if (FSE_isError(errorCode)) {
+ eSize = ERROR(GENERIC);
+ DISPLAYLEVEL(1, "FSE_normalizeCount error with matchLengthCount \n");
+ goto _cleanup;
+ }
+ mlLog = (U32)errorCode;
+
+ total=0; for (u=0; u<=MaxLL; u++) total+=litLengthCount[u];
+ errorCode = FSE_normalizeCount(litLengthNCount, llLog, litLengthCount, total, MaxLL);
+ if (FSE_isError(errorCode)) {
+ eSize = ERROR(GENERIC);
+ DISPLAYLEVEL(1, "FSE_normalizeCount error with litLengthCount \n");
+ goto _cleanup;
+ }
+ llLog = (U32)errorCode;
+
+ /* write result to buffer */
+ { size_t const hhSize = HUF_writeCTable(dstPtr, maxDstSize, hufTable, 255, huffLog);
+ if (HUF_isError(hhSize)) {
+ eSize = ERROR(GENERIC);
+ DISPLAYLEVEL(1, "HUF_writeCTable error \n");
+ goto _cleanup;
+ }
+ dstPtr += hhSize;
+ maxDstSize -= hhSize;
+ eSize += hhSize;
+ }
+
+ { size_t const ohSize = FSE_writeNCount(dstPtr, maxDstSize, offcodeNCount, OFFCODE_MAX, Offlog);
+ if (FSE_isError(ohSize)) {
+ eSize = ERROR(GENERIC);
+ DISPLAYLEVEL(1, "FSE_writeNCount error with offcodeNCount \n");
+ goto _cleanup;
+ }
+ dstPtr += ohSize;
+ maxDstSize -= ohSize;
+ eSize += ohSize;
+ }
+
+ { size_t const mhSize = FSE_writeNCount(dstPtr, maxDstSize, matchLengthNCount, MaxML, mlLog);
+ if (FSE_isError(mhSize)) {
+ eSize = ERROR(GENERIC);
+ DISPLAYLEVEL(1, "FSE_writeNCount error with matchLengthNCount \n");
+ goto _cleanup;
+ }
+ dstPtr += mhSize;
+ maxDstSize -= mhSize;
+ eSize += mhSize;
+ }
+
+ { size_t const lhSize = FSE_writeNCount(dstPtr, maxDstSize, litLengthNCount, MaxLL, llLog);
+ if (FSE_isError(lhSize)) {
+ eSize = ERROR(GENERIC);
+ DISPLAYLEVEL(1, "FSE_writeNCount error with litlengthNCount \n");
+ goto _cleanup;
+ }
+ dstPtr += lhSize;
+ maxDstSize -= lhSize;
+ eSize += lhSize;
+ }
+
+ if (maxDstSize<12) {
+ eSize = ERROR(GENERIC);
+ DISPLAYLEVEL(1, "not enough space to write RepOffsets \n");
+ goto _cleanup;
+ }
+# if 0
+ MEM_writeLE32(dstPtr+0, bestRepOffset[0].offset);
+ MEM_writeLE32(dstPtr+4, bestRepOffset[1].offset);
+ MEM_writeLE32(dstPtr+8, bestRepOffset[2].offset);
+#else
+ /* at this stage, we don't use the result of "most common first offset",
+ as the impact of statistics is not properly evaluated */
+ MEM_writeLE32(dstPtr+0, repStartValue[0]);
+ MEM_writeLE32(dstPtr+4, repStartValue[1]);
+ MEM_writeLE32(dstPtr+8, repStartValue[2]);
+#endif
+ eSize += 12;
+
+_cleanup:
+ ZSTD_freeCDict(esr.dict);
+ ZSTD_freeCCtx(esr.zc);
+ free(esr.workPlace);
+
+ return eSize;
+}
+
+
+
+size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,
+ const void* customDictContent, size_t dictContentSize,
+ const void* samplesBuffer, const size_t* samplesSizes,
+ unsigned nbSamples, ZDICT_params_t params)
+{
+ size_t hSize;
+#define HBUFFSIZE 256 /* should prove large enough for all entropy headers */
+ BYTE header[HBUFFSIZE];
+ int const compressionLevel = (params.compressionLevel == 0) ? g_compressionLevel_default : params.compressionLevel;
+ U32 const notificationLevel = params.notificationLevel;
+
+ /* check conditions */
+ DEBUGLOG(4, "ZDICT_finalizeDictionary");
+ if (dictBufferCapacity < dictContentSize) return ERROR(dstSize_tooSmall);
+ if (dictContentSize < ZDICT_CONTENTSIZE_MIN) return ERROR(srcSize_wrong);
+ if (dictBufferCapacity < ZDICT_DICTSIZE_MIN) return ERROR(dstSize_tooSmall);
+
+ /* dictionary header */
+ MEM_writeLE32(header, ZSTD_MAGIC_DICTIONARY);
+ { U64 const randomID = XXH64(customDictContent, dictContentSize, 0);
+ U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
+ U32 const dictID = params.dictID ? params.dictID : compliantID;
+ MEM_writeLE32(header+4, dictID);
+ }
+ hSize = 8;
+
+ /* entropy tables */
+ DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
+ DISPLAYLEVEL(2, "statistics ... \n");
+ { size_t const eSize = ZDICT_analyzeEntropy(header+hSize, HBUFFSIZE-hSize,
+ compressionLevel,
+ samplesBuffer, samplesSizes, nbSamples,
+ customDictContent, dictContentSize,
+ notificationLevel);
+ if (ZDICT_isError(eSize)) return eSize;
+ hSize += eSize;
+ }
+
+ /* copy elements in final buffer ; note : src and dst buffer can overlap */
+ if (hSize + dictContentSize > dictBufferCapacity) dictContentSize = dictBufferCapacity - hSize;
+ { size_t const dictSize = hSize + dictContentSize;
+ char* dictEnd = (char*)dictBuffer + dictSize;
+ memmove(dictEnd - dictContentSize, customDictContent, dictContentSize);
+ memcpy(dictBuffer, header, hSize);
+ return dictSize;
+ }
+}
+
+
+static size_t ZDICT_addEntropyTablesFromBuffer_advanced(
+ void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
+ const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
+ ZDICT_params_t params)
+{
+ int const compressionLevel = (params.compressionLevel == 0) ? g_compressionLevel_default : params.compressionLevel;
+ U32 const notificationLevel = params.notificationLevel;
+ size_t hSize = 8;
+
+ /* calculate entropy tables */
+ DISPLAYLEVEL(2, "\r%70s\r", ""); /* clean display line */
+ DISPLAYLEVEL(2, "statistics ... \n");
+ { size_t const eSize = ZDICT_analyzeEntropy((char*)dictBuffer+hSize, dictBufferCapacity-hSize,
+ compressionLevel,
+ samplesBuffer, samplesSizes, nbSamples,
+ (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize,
+ notificationLevel);
+ if (ZDICT_isError(eSize)) return eSize;
+ hSize += eSize;
+ }
+
+ /* add dictionary header (after entropy tables) */
+ MEM_writeLE32(dictBuffer, ZSTD_MAGIC_DICTIONARY);
+ { U64 const randomID = XXH64((char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize, 0);
+ U32 const compliantID = (randomID % ((1U<<31)-32768)) + 32768;
+ U32 const dictID = params.dictID ? params.dictID : compliantID;
+ MEM_writeLE32((char*)dictBuffer+4, dictID);
+ }
+
+ if (hSize + dictContentSize < dictBufferCapacity)
+ memmove((char*)dictBuffer + hSize, (char*)dictBuffer + dictBufferCapacity - dictContentSize, dictContentSize);
+ return MIN(dictBufferCapacity, hSize+dictContentSize);
+}
+
+/* Hidden declaration for dbio.c */
+size_t ZDICT_trainFromBuffer_unsafe_legacy(
+ void* dictBuffer, size_t maxDictSize,
+ const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
+ ZDICT_legacy_params_t params);
+/*! ZDICT_trainFromBuffer_unsafe_legacy() :
+* Warning : `samplesBuffer` must be followed by noisy guard band.
+* @return : size of dictionary, or an error code which can be tested with ZDICT_isError()
+*/
+size_t ZDICT_trainFromBuffer_unsafe_legacy(
+ void* dictBuffer, size_t maxDictSize,
+ const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
+ ZDICT_legacy_params_t params)
+{
+ U32 const dictListSize = MAX(MAX(DICTLISTSIZE_DEFAULT, nbSamples), (U32)(maxDictSize/16));
+ dictItem* const dictList = (dictItem*)malloc(dictListSize * sizeof(*dictList));
+ unsigned const selectivity = params.selectivityLevel == 0 ? g_selectivity_default : params.selectivityLevel;
+ unsigned const minRep = (selectivity > 30) ? MINRATIO : nbSamples >> selectivity;
+ size_t const targetDictSize = maxDictSize;
+ size_t const samplesBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
+ size_t dictSize = 0;
+ U32 const notificationLevel = params.zParams.notificationLevel;
+
+ /* checks */
+ if (!dictList) return ERROR(memory_allocation);
+ if (maxDictSize < ZDICT_DICTSIZE_MIN) { free(dictList); return ERROR(dstSize_tooSmall); } /* requested dictionary size is too small */
+ if (samplesBuffSize < ZDICT_MIN_SAMPLES_SIZE) { free(dictList); return ERROR(dictionaryCreation_failed); } /* not enough source to create dictionary */
+
+ /* init */
+ ZDICT_initDictItem(dictList);
+
+ /* build dictionary */
+ ZDICT_trainBuffer_legacy(dictList, dictListSize,
+ samplesBuffer, samplesBuffSize,
+ samplesSizes, nbSamples,
+ minRep, notificationLevel);
+
+ /* display best matches */
+ if (params.zParams.notificationLevel>= 3) {
+ unsigned const nb = MIN(25, dictList[0].pos);
+ unsigned const dictContentSize = ZDICT_dictSize(dictList);
+ unsigned u;
+ DISPLAYLEVEL(3, "\n %u segments found, of total size %u \n", (unsigned)dictList[0].pos-1, dictContentSize);
+ DISPLAYLEVEL(3, "list %u best segments \n", nb-1);
+ for (u=1; u<nb; u++) {
+ unsigned const pos = dictList[u].pos;
+ unsigned const length = dictList[u].length;
+ U32 const printedLength = MIN(40, length);
+ if ((pos > samplesBuffSize) || ((pos + length) > samplesBuffSize)) {
+ free(dictList);
+ return ERROR(GENERIC); /* should never happen */
+ }
+ DISPLAYLEVEL(3, "%3u:%3u bytes at pos %8u, savings %7u bytes |",
+ u, length, pos, (unsigned)dictList[u].savings);
+ ZDICT_printHex((const char*)samplesBuffer+pos, printedLength);
+ DISPLAYLEVEL(3, "| \n");
+ } }
+
+
+ /* create dictionary */
+ { unsigned dictContentSize = ZDICT_dictSize(dictList);
+ if (dictContentSize < ZDICT_CONTENTSIZE_MIN) { free(dictList); return ERROR(dictionaryCreation_failed); } /* dictionary content too small */
+ if (dictContentSize < targetDictSize/4) {
+ DISPLAYLEVEL(2, "! warning : selected content significantly smaller than requested (%u < %u) \n", dictContentSize, (unsigned)maxDictSize);
+ if (samplesBuffSize < 10 * targetDictSize)
+ DISPLAYLEVEL(2, "! consider increasing the number of samples (total size : %u MB)\n", (unsigned)(samplesBuffSize>>20));
+ if (minRep > MINRATIO) {
+ DISPLAYLEVEL(2, "! consider increasing selectivity to produce larger dictionary (-s%u) \n", selectivity+1);
+ DISPLAYLEVEL(2, "! note : larger dictionaries are not necessarily better, test its efficiency on samples \n");
+ }
+ }
+
+ if ((dictContentSize > targetDictSize*3) && (nbSamples > 2*MINRATIO) && (selectivity>1)) {
+ unsigned proposedSelectivity = selectivity-1;
+ while ((nbSamples >> proposedSelectivity) <= MINRATIO) { proposedSelectivity--; }
+ DISPLAYLEVEL(2, "! note : calculated dictionary significantly larger than requested (%u > %u) \n", dictContentSize, (unsigned)maxDictSize);
+ DISPLAYLEVEL(2, "! consider increasing dictionary size, or produce denser dictionary (-s%u) \n", proposedSelectivity);
+ DISPLAYLEVEL(2, "! always test dictionary efficiency on real samples \n");
+ }
+
+ /* limit dictionary size */
+ { U32 const max = dictList->pos; /* convention : nb of useful elts within dictList */
+ U32 currentSize = 0;
+ U32 n; for (n=1; n<max; n++) {
+ currentSize += dictList[n].length;
+ if (currentSize > targetDictSize) { currentSize -= dictList[n].length; break; }
+ }
+ dictList->pos = n;
+ dictContentSize = currentSize;
+ }
+
+ /* build dict content */
+ { U32 u;
+ BYTE* ptr = (BYTE*)dictBuffer + maxDictSize;
+ for (u=1; u<dictList->pos; u++) {
+ U32 l = dictList[u].length;
+ ptr -= l;
+ if (ptr<(BYTE*)dictBuffer) { free(dictList); return ERROR(GENERIC); } /* should not happen */
+ memcpy(ptr, (const char*)samplesBuffer+dictList[u].pos, l);
+ } }
+
+ dictSize = ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, maxDictSize,
+ samplesBuffer, samplesSizes, nbSamples,
+ params.zParams);
+ }
+
+ /* clean up */
+ free(dictList);
+ return dictSize;
+}
+
+
+/* ZDICT_trainFromBuffer_legacy() :
+ * issue : samplesBuffer need to be followed by a noisy guard band.
+ * work around : duplicate the buffer, and add the noise */
+size_t ZDICT_trainFromBuffer_legacy(void* dictBuffer, size_t dictBufferCapacity,
+ const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
+ ZDICT_legacy_params_t params)
+{
+ size_t result;
+ void* newBuff;
+ size_t const sBuffSize = ZDICT_totalSampleSize(samplesSizes, nbSamples);
+ if (sBuffSize < ZDICT_MIN_SAMPLES_SIZE) return 0; /* not enough content => no dictionary */
+
+ newBuff = malloc(sBuffSize + NOISELENGTH);
+ if (!newBuff) return ERROR(memory_allocation);
+
+ memcpy(newBuff, samplesBuffer, sBuffSize);
+ ZDICT_fillNoise((char*)newBuff + sBuffSize, NOISELENGTH); /* guard band, for end of buffer condition */
+
+ result =
+ ZDICT_trainFromBuffer_unsafe_legacy(dictBuffer, dictBufferCapacity, newBuff,
+ samplesSizes, nbSamples, params);
+ free(newBuff);
+ return result;
+}
+
+
+size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
+ const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
+{
+ ZDICT_fastCover_params_t params;
+ DEBUGLOG(3, "ZDICT_trainFromBuffer");
+ memset(&params, 0, sizeof(params));
+ params.d = 8;
+ params.steps = 4;
+ /* Default to level 6 since no compression level information is available */
+ params.zParams.compressionLevel = 3;
+#if defined(DEBUGLEVEL) && (DEBUGLEVEL>=1)
+ params.zParams.notificationLevel = DEBUGLEVEL;
+#endif
+ return ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, dictBufferCapacity,
+ samplesBuffer, samplesSizes, nbSamples,
+ &params);
+}
+
+size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
+ const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples)
+{
+ ZDICT_params_t params;
+ memset(&params, 0, sizeof(params));
+ return ZDICT_addEntropyTablesFromBuffer_advanced(dictBuffer, dictContentSize, dictBufferCapacity,
+ samplesBuffer, samplesSizes, nbSamples,
+ params);
+}
diff --git a/Utilities/cmzstd/lib/dictBuilder/zdict.h b/Utilities/cmzstd/lib/dictBuilder/zdict.h
new file mode 100644
index 000000000..d57d59f01
--- /dev/null
+++ b/Utilities/cmzstd/lib/dictBuilder/zdict.h
@@ -0,0 +1,267 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+
+#ifndef DICTBUILDER_H_001
+#define DICTBUILDER_H_001
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+
+/*====== Dependencies ======*/
+#include <stddef.h> /* size_t */
+
+
+/* ===== ZDICTLIB_API : control library symbols visibility ===== */
+#ifndef ZDICTLIB_VISIBILITY
+# if defined(__GNUC__) && (__GNUC__ >= 4)
+# define ZDICTLIB_VISIBILITY __attribute__ ((visibility ("default")))
+# else
+# define ZDICTLIB_VISIBILITY
+# endif
+#endif
+#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
+# define ZDICTLIB_API __declspec(dllexport) ZDICTLIB_VISIBILITY
+#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
+# define ZDICTLIB_API __declspec(dllimport) ZDICTLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
+#else
+# define ZDICTLIB_API ZDICTLIB_VISIBILITY
+#endif
+
+
+/*! ZDICT_trainFromBuffer():
+ * Train a dictionary from an array of samples.
+ * Redirect towards ZDICT_optimizeTrainFromBuffer_fastCover() single-threaded, with d=8, steps=4,
+ * f=20, and accel=1.
+ * Samples must be stored concatenated in a single flat buffer `samplesBuffer`,
+ * supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.
+ * The resulting dictionary will be saved into `dictBuffer`.
+ * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
+ * or an error code, which can be tested with ZDICT_isError().
+ * Note: ZDICT_trainFromBuffer() requires about 9 bytes of memory for each input byte.
+ * Tips: In general, a reasonable dictionary has a size of ~ 100 KB.
+ * It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.
+ * In general, it's recommended to provide a few thousands samples, though this can vary a lot.
+ * It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
+ */
+ZDICTLIB_API size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
+ const void* samplesBuffer,
+ const size_t* samplesSizes, unsigned nbSamples);
+
+
+/*====== Helper functions ======*/
+ZDICTLIB_API unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize); /**< extracts dictID; @return zero if error (not a valid dictionary) */
+ZDICTLIB_API unsigned ZDICT_isError(size_t errorCode);
+ZDICTLIB_API const char* ZDICT_getErrorName(size_t errorCode);
+
+
+
+#ifdef ZDICT_STATIC_LINKING_ONLY
+
+/* ====================================================================================
+ * The definitions in this section are considered experimental.
+ * They should never be used with a dynamic library, as they may change in the future.
+ * They are provided for advanced usages.
+ * Use them only in association with static linking.
+ * ==================================================================================== */
+
+typedef struct {
+ int compressionLevel; /* optimize for a specific zstd compression level; 0 means default */
+ unsigned notificationLevel; /* Write log to stderr; 0 = none (default); 1 = errors; 2 = progression; 3 = details; 4 = debug; */
+ unsigned dictID; /* force dictID value; 0 means auto mode (32-bits random value) */
+} ZDICT_params_t;
+
+/*! ZDICT_cover_params_t:
+ * k and d are the only required parameters.
+ * For others, value 0 means default.
+ */
+typedef struct {
+ unsigned k; /* Segment size : constraint: 0 < k : Reasonable range [16, 2048+] */
+ unsigned d; /* dmer size : constraint: 0 < d <= k : Reasonable range [6, 16] */
+ unsigned steps; /* Number of steps : Only used for optimization : 0 means default (40) : Higher means more parameters checked */
+ unsigned nbThreads; /* Number of threads : constraint: 0 < nbThreads : 1 means single-threaded : Only used for optimization : Ignored if ZSTD_MULTITHREAD is not defined */
+ double splitPoint; /* Percentage of samples used for training: Only used for optimization : the first nbSamples * splitPoint samples will be used to training, the last nbSamples * (1 - splitPoint) samples will be used for testing, 0 means default (1.0), 1.0 when all samples are used for both training and testing */
+ ZDICT_params_t zParams;
+} ZDICT_cover_params_t;
+
+typedef struct {
+ unsigned k; /* Segment size : constraint: 0 < k : Reasonable range [16, 2048+] */
+ unsigned d; /* dmer size : constraint: 0 < d <= k : Reasonable range [6, 16] */
+ unsigned f; /* log of size of frequency array : constraint: 0 < f <= 31 : 1 means default(20)*/
+ unsigned steps; /* Number of steps : Only used for optimization : 0 means default (40) : Higher means more parameters checked */
+ unsigned nbThreads; /* Number of threads : constraint: 0 < nbThreads : 1 means single-threaded : Only used for optimization : Ignored if ZSTD_MULTITHREAD is not defined */
+ double splitPoint; /* Percentage of samples used for training: Only used for optimization : the first nbSamples * splitPoint samples will be used to training, the last nbSamples * (1 - splitPoint) samples will be used for testing, 0 means default (0.75), 1.0 when all samples are used for both training and testing */
+ unsigned accel; /* Acceleration level: constraint: 0 < accel <= 10, higher means faster and less accurate, 0 means default(1) */
+ ZDICT_params_t zParams;
+} ZDICT_fastCover_params_t;
+
+/*! ZDICT_trainFromBuffer_cover():
+ * Train a dictionary from an array of samples using the COVER algorithm.
+ * Samples must be stored concatenated in a single flat buffer `samplesBuffer`,
+ * supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.
+ * The resulting dictionary will be saved into `dictBuffer`.
+ * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
+ * or an error code, which can be tested with ZDICT_isError().
+ * Note: ZDICT_trainFromBuffer_cover() requires about 9 bytes of memory for each input byte.
+ * Tips: In general, a reasonable dictionary has a size of ~ 100 KB.
+ * It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.
+ * In general, it's recommended to provide a few thousands samples, though this can vary a lot.
+ * It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
+ */
+ZDICTLIB_API size_t ZDICT_trainFromBuffer_cover(
+ void *dictBuffer, size_t dictBufferCapacity,
+ const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,
+ ZDICT_cover_params_t parameters);
+
+/*! ZDICT_optimizeTrainFromBuffer_cover():
+ * The same requirements as above hold for all the parameters except `parameters`.
+ * This function tries many parameter combinations and picks the best parameters.
+ * `*parameters` is filled with the best parameters found,
+ * dictionary constructed with those parameters is stored in `dictBuffer`.
+ *
+ * All of the parameters d, k, steps are optional.
+ * If d is non-zero then we don't check multiple values of d, otherwise we check d = {6, 8}.
+ * if steps is zero it defaults to its default value.
+ * If k is non-zero then we don't check multiple values of k, otherwise we check steps values in [50, 2000].
+ *
+ * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
+ * or an error code, which can be tested with ZDICT_isError().
+ * On success `*parameters` contains the parameters selected.
+ * Note: ZDICT_optimizeTrainFromBuffer_cover() requires about 8 bytes of memory for each input byte and additionally another 5 bytes of memory for each byte of memory for each thread.
+ */
+ZDICTLIB_API size_t ZDICT_optimizeTrainFromBuffer_cover(
+ void* dictBuffer, size_t dictBufferCapacity,
+ const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
+ ZDICT_cover_params_t* parameters);
+
+/*! ZDICT_trainFromBuffer_fastCover():
+ * Train a dictionary from an array of samples using a modified version of COVER algorithm.
+ * Samples must be stored concatenated in a single flat buffer `samplesBuffer`,
+ * supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.
+ * d and k are required.
+ * All other parameters are optional, will use default values if not provided
+ * The resulting dictionary will be saved into `dictBuffer`.
+ * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
+ * or an error code, which can be tested with ZDICT_isError().
+ * Note: ZDICT_trainFromBuffer_fastCover() requires about 1 bytes of memory for each input byte and additionally another 6 * 2^f bytes of memory .
+ * Tips: In general, a reasonable dictionary has a size of ~ 100 KB.
+ * It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.
+ * In general, it's recommended to provide a few thousands samples, though this can vary a lot.
+ * It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
+ */
+ZDICTLIB_API size_t ZDICT_trainFromBuffer_fastCover(void *dictBuffer,
+ size_t dictBufferCapacity, const void *samplesBuffer,
+ const size_t *samplesSizes, unsigned nbSamples,
+ ZDICT_fastCover_params_t parameters);
+
+/*! ZDICT_optimizeTrainFromBuffer_fastCover():
+ * The same requirements as above hold for all the parameters except `parameters`.
+ * This function tries many parameter combinations (specifically, k and d combinations)
+ * and picks the best parameters. `*parameters` is filled with the best parameters found,
+ * dictionary constructed with those parameters is stored in `dictBuffer`.
+ * All of the parameters d, k, steps, f, and accel are optional.
+ * If d is non-zero then we don't check multiple values of d, otherwise we check d = {6, 8}.
+ * if steps is zero it defaults to its default value.
+ * If k is non-zero then we don't check multiple values of k, otherwise we check steps values in [50, 2000].
+ * If f is zero, default value of 20 is used.
+ * If accel is zero, default value of 1 is used.
+ *
+ * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
+ * or an error code, which can be tested with ZDICT_isError().
+ * On success `*parameters` contains the parameters selected.
+ * Note: ZDICT_optimizeTrainFromBuffer_fastCover() requires about 1 byte of memory for each input byte and additionally another 6 * 2^f bytes of memory for each thread.
+ */
+ZDICTLIB_API size_t ZDICT_optimizeTrainFromBuffer_fastCover(void* dictBuffer,
+ size_t dictBufferCapacity, const void* samplesBuffer,
+ const size_t* samplesSizes, unsigned nbSamples,
+ ZDICT_fastCover_params_t* parameters);
+
+/*! ZDICT_finalizeDictionary():
+ * Given a custom content as a basis for dictionary, and a set of samples,
+ * finalize dictionary by adding headers and statistics.
+ *
+ * Samples must be stored concatenated in a flat buffer `samplesBuffer`,
+ * supplied with an array of sizes `samplesSizes`, providing the size of each sample in order.
+ *
+ * dictContentSize must be >= ZDICT_CONTENTSIZE_MIN bytes.
+ * maxDictSize must be >= dictContentSize, and must be >= ZDICT_DICTSIZE_MIN bytes.
+ *
+ * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`),
+ * or an error code, which can be tested by ZDICT_isError().
+ * Note: ZDICT_finalizeDictionary() will push notifications into stderr if instructed to, using notificationLevel>0.
+ * Note 2: dictBuffer and dictContent can overlap
+ */
+#define ZDICT_CONTENTSIZE_MIN 128
+#define ZDICT_DICTSIZE_MIN 256
+ZDICTLIB_API size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,
+ const void* dictContent, size_t dictContentSize,
+ const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
+ ZDICT_params_t parameters);
+
+typedef struct {
+ unsigned selectivityLevel; /* 0 means default; larger => select more => larger dictionary */
+ ZDICT_params_t zParams;
+} ZDICT_legacy_params_t;
+
+/*! ZDICT_trainFromBuffer_legacy():
+ * Train a dictionary from an array of samples.
+ * Samples must be stored concatenated in a single flat buffer `samplesBuffer`,
+ * supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.
+ * The resulting dictionary will be saved into `dictBuffer`.
+ * `parameters` is optional and can be provided with values set to 0 to mean "default".
+ * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
+ * or an error code, which can be tested with ZDICT_isError().
+ * Tips: In general, a reasonable dictionary has a size of ~ 100 KB.
+ * It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.
+ * In general, it's recommended to provide a few thousands samples, though this can vary a lot.
+ * It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
+ * Note: ZDICT_trainFromBuffer_legacy() will send notifications into stderr if instructed to, using notificationLevel>0.
+ */
+ZDICTLIB_API size_t ZDICT_trainFromBuffer_legacy(
+ void *dictBuffer, size_t dictBufferCapacity,
+ const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,
+ ZDICT_legacy_params_t parameters);
+
+/* Deprecation warnings */
+/* It is generally possible to disable deprecation warnings from compiler,
+ for example with -Wno-deprecated-declarations for gcc
+ or _CRT_SECURE_NO_WARNINGS in Visual.
+ Otherwise, it's also possible to manually define ZDICT_DISABLE_DEPRECATE_WARNINGS */
+#ifdef ZDICT_DISABLE_DEPRECATE_WARNINGS
+# define ZDICT_DEPRECATED(message) ZDICTLIB_API /* disable deprecation warnings */
+#else
+# define ZDICT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */
+# define ZDICT_DEPRECATED(message) [[deprecated(message)]] ZDICTLIB_API
+# elif (ZDICT_GCC_VERSION >= 405) || defined(__clang__)
+# define ZDICT_DEPRECATED(message) ZDICTLIB_API __attribute__((deprecated(message)))
+# elif (ZDICT_GCC_VERSION >= 301)
+# define ZDICT_DEPRECATED(message) ZDICTLIB_API __attribute__((deprecated))
+# elif defined(_MSC_VER)
+# define ZDICT_DEPRECATED(message) ZDICTLIB_API __declspec(deprecated(message))
+# else
+# pragma message("WARNING: You need to implement ZDICT_DEPRECATED for this compiler")
+# define ZDICT_DEPRECATED(message) ZDICTLIB_API
+# endif
+#endif /* ZDICT_DISABLE_DEPRECATE_WARNINGS */
+
+ZDICT_DEPRECATED("use ZDICT_finalizeDictionary() instead")
+size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
+ const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples);
+
+
+#endif /* ZDICT_STATIC_LINKING_ONLY */
+
+#if defined (__cplusplus)
+}
+#endif
+
+#endif /* DICTBUILDER_H_001 */
diff --git a/Utilities/cmzstd/lib/zstd.h b/Utilities/cmzstd/lib/zstd.h
new file mode 100644
index 000000000..b18fc8a44
--- /dev/null
+++ b/Utilities/cmzstd/lib/zstd.h
@@ -0,0 +1,1766 @@
+/*
+ * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under both the BSD-style license (found in the
+ * LICENSE file in the root directory of this source tree) and the GPLv2 (found
+ * in the COPYING file in the root directory of this source tree).
+ * You may select, at your option, one of the above-listed licenses.
+ */
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#ifndef ZSTD_H_235446
+#define ZSTD_H_235446
+
+/* ====== Dependency ======*/
+#include <stddef.h> /* size_t */
+
+
+/* ===== ZSTDLIB_API : control library symbols visibility ===== */
+#ifndef ZSTDLIB_VISIBILITY
+# if defined(__GNUC__) && (__GNUC__ >= 4)
+# define ZSTDLIB_VISIBILITY __attribute__ ((visibility ("default")))
+# else
+# define ZSTDLIB_VISIBILITY
+# endif
+#endif
+#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
+# define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBILITY
+#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
+# define ZSTDLIB_API __declspec(dllimport) ZSTDLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
+#else
+# define ZSTDLIB_API ZSTDLIB_VISIBILITY
+#endif
+
+
+/*******************************************************************************
+ Introduction
+
+ zstd, short for Zstandard, is a fast lossless compression algorithm, targeting
+ real-time compression scenarios at zlib-level and better compression ratios.
+ The zstd compression library provides in-memory compression and decompression
+ functions.
+
+ The library supports regular compression levels from 1 up to ZSTD_maxCLevel(),
+ which is currently 22. Levels >= 20, labeled `--ultra`, should be used with
+ caution, as they require more memory. The library also offers negative
+ compression levels, which extend the range of speed vs. ratio preferences.
+ The lower the level, the faster the speed (at the cost of compression).
+
+ Compression can be done in:
+ - a single step (described as Simple API)
+ - a single step, reusing a context (described as Explicit context)
+ - unbounded multiple steps (described as Streaming compression)
+
+ The compression ratio achievable on small data can be highly improved using
+ a dictionary. Dictionary compression can be performed in:
+ - a single step (described as Simple dictionary API)
+ - a single step, reusing a dictionary (described as Bulk-processing
+ dictionary API)
+
+ Advanced experimental functions can be accessed using
+ `#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h.
+
+ Advanced experimental APIs should never be used with a dynamically-linked
+ library. They are not "stable"; their definitions or signatures may change in
+ the future. Only static linking is allowed.
+*******************************************************************************/
+
+/*------ Version ------*/
+#define ZSTD_VERSION_MAJOR 1
+#define ZSTD_VERSION_MINOR 3
+#define ZSTD_VERSION_RELEASE 8
+
+#define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
+ZSTDLIB_API unsigned ZSTD_versionNumber(void); /**< to check runtime library version */
+
+#define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE
+#define ZSTD_QUOTE(str) #str
+#define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str)
+#define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION)
+ZSTDLIB_API const char* ZSTD_versionString(void); /* requires v1.3.0+ */
+
+/***************************************
+* Default constant
+***************************************/
+#ifndef ZSTD_CLEVEL_DEFAULT
+# define ZSTD_CLEVEL_DEFAULT 3
+#endif
+
+/***************************************
+* Simple API
+***************************************/
+/*! ZSTD_compress() :
+ * Compresses `src` content as a single zstd compressed frame into already allocated `dst`.
+ * Hint : compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`.
+ * @return : compressed size written into `dst` (<= `dstCapacity),
+ * or an error code if it fails (which can be tested using ZSTD_isError()). */
+ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ int compressionLevel);
+
+/*! ZSTD_decompress() :
+ * `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames.
+ * `dstCapacity` is an upper bound of originalSize to regenerate.
+ * If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data.
+ * @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),
+ * or an errorCode if it fails (which can be tested using ZSTD_isError()). */
+ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity,
+ const void* src, size_t compressedSize);
+
+/*! ZSTD_getFrameContentSize() : requires v1.3.0+
+ * `src` should point to the start of a ZSTD encoded frame.
+ * `srcSize` must be at least as large as the frame header.
+ * hint : any size >= `ZSTD_frameHeaderSize_max` is large enough.
+ * @return : - decompressed size of `src` frame content, if known
+ * - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
+ * - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small)
+ * note 1 : a 0 return value means the frame is valid but "empty".
+ * note 2 : decompressed size is an optional field, it may not be present, typically in streaming mode.
+ * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.
+ * In which case, it's necessary to use streaming mode to decompress data.
+ * Optionally, application can rely on some implicit limit,
+ * as ZSTD_decompress() only needs an upper bound of decompressed size.
+ * (For example, data could be necessarily cut into blocks <= 16 KB).
+ * note 3 : decompressed size is always present when compression is completed using single-pass functions,
+ * such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict().
+ * note 4 : decompressed size can be very large (64-bits value),
+ * potentially larger than what local system can handle as a single memory segment.
+ * In which case, it's necessary to use streaming mode to decompress data.
+ * note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified.
+ * Always ensure return value fits within application's authorized limits.
+ * Each application can set its own limits.
+ * note 6 : This function replaces ZSTD_getDecompressedSize() */
+#define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1)
+#define ZSTD_CONTENTSIZE_ERROR (0ULL - 2)
+ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize);
+
+/*! ZSTD_getDecompressedSize() :
+ * NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize().
+ * Both functions work the same way, but ZSTD_getDecompressedSize() blends
+ * "empty", "unknown" and "error" results to the same return value (0),
+ * while ZSTD_getFrameContentSize() gives them separate return values.
+ * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */
+ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);
+
+
+/*====== Helper functions ======*/
+#define ZSTD_COMPRESSBOUND(srcSize) ((srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0)) /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */
+ZSTDLIB_API size_t ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */
+ZSTDLIB_API unsigned ZSTD_isError(size_t code); /*!< tells if a `size_t` function result is an error code */
+ZSTDLIB_API const char* ZSTD_getErrorName(size_t code); /*!< provides readable string from an error code */
+ZSTDLIB_API int ZSTD_maxCLevel(void); /*!< maximum compression level available */
+
+
+/***************************************
+* Explicit context
+***************************************/
+/*= Compression context
+ * When compressing many times,
+ * it is recommended to allocate a context just once, and re-use it for each successive compression operation.
+ * This will make workload friendlier for system's memory.
+ * Use one context per thread for parallel execution in multi-threaded environments. */
+typedef struct ZSTD_CCtx_s ZSTD_CCtx;
+ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void);
+ZSTDLIB_API size_t ZSTD_freeCCtx(ZSTD_CCtx* cctx);
+
+/*! ZSTD_compressCCtx() :
+ * Same as ZSTD_compress(), using an explicit ZSTD_CCtx
+ * The function will compress at requested compression level,
+ * ignoring any other parameter */
+ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ int compressionLevel);
+
+/*= Decompression context
+ * When decompressing many times,
+ * it is recommended to allocate a context only once,
+ * and re-use it for each successive compression operation.
+ * This will make workload friendlier for system's memory.
+ * Use one context per thread for parallel execution. */
+typedef struct ZSTD_DCtx_s ZSTD_DCtx;
+ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void);
+ZSTDLIB_API size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx);
+
+/*! ZSTD_decompressDCtx() :
+ * Same as ZSTD_decompress(),
+ * requires an allocated ZSTD_DCtx.
+ * Compatible with sticky parameters.
+ */
+ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize);
+
+
+/**************************
+* Simple dictionary API
+***************************/
+/*! ZSTD_compress_usingDict() :
+ * Compression at an explicit compression level using a Dictionary.
+ * A dictionary can be any arbitrary data segment (also called a prefix),
+ * or a buffer with specified information (see dictBuilder/zdict.h).
+ * Note : This function loads the dictionary, resulting in significant startup delay.
+ * It's intended for a dictionary used only once.
+ * Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */
+ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const void* dict,size_t dictSize,
+ int compressionLevel);
+
+/*! ZSTD_decompress_usingDict() :
+ * Decompression using a known Dictionary.
+ * Dictionary must be identical to the one used during compression.
+ * Note : This function loads the dictionary, resulting in significant startup delay.
+ * It's intended for a dictionary used only once.
+ * Note : When `dict == NULL || dictSize < 8` no dictionary is used. */
+ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const void* dict,size_t dictSize);
+
+
+/***********************************
+ * Bulk processing dictionary API
+ **********************************/
+typedef struct ZSTD_CDict_s ZSTD_CDict;
+
+/*! ZSTD_createCDict() :
+ * When compressing multiple messages / blocks using the same dictionary, it's recommended to load it only once.
+ * ZSTD_createCDict() will create a digested dictionary, ready to start future compression operations without startup cost.
+ * ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
+ * `dictBuffer` can be released after ZSTD_CDict creation, because its content is copied within CDict.
+ * Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate `dictBuffer` content.
+ * Note : A ZSTD_CDict can be created from an empty dictBuffer, but it is inefficient when used to compress small data. */
+ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize,
+ int compressionLevel);
+
+/*! ZSTD_freeCDict() :
+ * Function frees memory allocated by ZSTD_createCDict(). */
+ZSTDLIB_API size_t ZSTD_freeCDict(ZSTD_CDict* CDict);
+
+/*! ZSTD_compress_usingCDict() :
+ * Compression using a digested Dictionary.
+ * Recommended when same dictionary is used multiple times.
+ * Note : compression level is _decided at dictionary creation time_,
+ * and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */
+ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const ZSTD_CDict* cdict);
+
+
+typedef struct ZSTD_DDict_s ZSTD_DDict;
+
+/*! ZSTD_createDDict() :
+ * Create a digested dictionary, ready to start decompression operation without startup delay.
+ * dictBuffer can be released after DDict creation, as its content is copied inside DDict. */
+ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize);
+
+/*! ZSTD_freeDDict() :
+ * Function frees memory allocated with ZSTD_createDDict() */
+ZSTDLIB_API size_t ZSTD_freeDDict(ZSTD_DDict* ddict);
+
+/*! ZSTD_decompress_usingDDict() :
+ * Decompression using a digested Dictionary.
+ * Recommended when same dictionary is used multiple times. */
+ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const ZSTD_DDict* ddict);
+
+
+/****************************
+* Streaming
+****************************/
+
+typedef struct ZSTD_inBuffer_s {
+ const void* src; /**< start of input buffer */
+ size_t size; /**< size of input buffer */
+ size_t pos; /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */
+} ZSTD_inBuffer;
+
+typedef struct ZSTD_outBuffer_s {
+ void* dst; /**< start of output buffer */
+ size_t size; /**< size of output buffer */
+ size_t pos; /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */
+} ZSTD_outBuffer;
+
+
+
+/*-***********************************************************************
+* Streaming compression - HowTo
+*
+* A ZSTD_CStream object is required to track streaming operation.
+* Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.
+* ZSTD_CStream objects can be reused multiple times on consecutive compression operations.
+* It is recommended to re-use ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.
+*
+* For parallel execution, use one separate ZSTD_CStream per thread.
+*
+* note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing.
+*
+* Parameters are sticky : when starting a new compression on the same context,
+* it will re-use the same sticky parameters as previous compression session.
+* When in doubt, it's recommended to fully initialize the context before usage.
+* Use ZSTD_initCStream() to set the parameter to a selected compression level.
+* Use advanced API (ZSTD_CCtx_setParameter(), etc.) to set more specific parameters.
+*
+* Use ZSTD_compressStream() as many times as necessary to consume input stream.
+* The function will automatically update both `pos` fields within `input` and `output`.
+* Note that the function may not consume the entire input,
+* for example, because the output buffer is already full,
+* in which case `input.pos < input.size`.
+* The caller must check if input has been entirely consumed.
+* If not, the caller must make some room to receive more compressed data,
+* and then present again remaining input data.
+* @return : a size hint, preferred nb of bytes to use as input for next function call
+* or an error code, which can be tested using ZSTD_isError().
+* Note 1 : it's just a hint, to help latency a little, any value will work fine.
+* Note 2 : size hint is guaranteed to be <= ZSTD_CStreamInSize()
+*
+* At any moment, it's possible to flush whatever data might remain stuck within internal buffer,
+* using ZSTD_flushStream(). `output->pos` will be updated.
+* Note that, if `output->size` is too small, a single invocation of ZSTD_flushStream() might not be enough (return code > 0).
+* In which case, make some room to receive more compressed data, and call again ZSTD_flushStream().
+* @return : 0 if internal buffers are entirely flushed,
+* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),
+* or an error code, which can be tested using ZSTD_isError().
+*
+* ZSTD_endStream() instructs to finish a frame.
+* It will perform a flush and write frame epilogue.
+* The epilogue is required for decoders to consider a frame completed.
+* flush() operation is the same, and follows same rules as ZSTD_flushStream().
+* @return : 0 if frame fully completed and fully flushed,
+* >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),
+* or an error code, which can be tested using ZSTD_isError().
+*
+* *******************************************************************/
+
+typedef ZSTD_CCtx ZSTD_CStream; /**< CCtx and CStream are now effectively same object (>= v1.3.0) */
+ /* Continue to distinguish them for compatibility with older versions <= v1.2.0 */
+/*===== ZSTD_CStream management functions =====*/
+ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void);
+ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs);
+
+/*===== Streaming compression functions =====*/
+ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel);
+ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input);
+ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
+ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
+
+ZSTDLIB_API size_t ZSTD_CStreamInSize(void); /**< recommended size for input buffer */
+ZSTDLIB_API size_t ZSTD_CStreamOutSize(void); /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block in all circumstances. */
+
+
+
+/*-***************************************************************************
+* Streaming decompression - HowTo
+*
+* A ZSTD_DStream object is required to track streaming operations.
+* Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.
+* ZSTD_DStream objects can be re-used multiple times.
+*
+* Use ZSTD_initDStream() to start a new decompression operation.
+* @return : recommended first input size
+* Alternatively, use advanced API to set specific properties.
+*
+* Use ZSTD_decompressStream() repetitively to consume your input.
+* The function will update both `pos` fields.
+* If `input.pos < input.size`, some input has not been consumed.
+* It's up to the caller to present again remaining data.
+* The function tries to flush all data decoded immediately, respecting output buffer size.
+* If `output.pos < output.size`, decoder has flushed everything it could.
+* But if `output.pos == output.size`, there might be some data left within internal buffers.,
+* In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer.
+* Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX.
+* @return : 0 when a frame is completely decoded and fully flushed,
+* or an error code, which can be tested using ZSTD_isError(),
+* or any other value > 0, which means there is still some decoding or flushing to do to complete current frame :
+* the return value is a suggested next input size (just a hint for better latency)
+* that will never request more than the remaining frame size.
+* *******************************************************************************/
+
+typedef ZSTD_DCtx ZSTD_DStream; /**< DCtx and DStream are now effectively same object (>= v1.3.0) */
+ /* For compatibility with versions <= v1.2.0, prefer differentiating them. */
+/*===== ZSTD_DStream management functions =====*/
+ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void);
+ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds);
+
+/*===== Streaming decompression functions =====*/
+ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds);
+ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input);
+
+ZSTDLIB_API size_t ZSTD_DStreamInSize(void); /*!< recommended size for input buffer */
+ZSTDLIB_API size_t ZSTD_DStreamOutSize(void); /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */
+
+#endif /* ZSTD_H_235446 */
+
+
+
+
+/****************************************************************************************
+ * ADVANCED AND EXPERIMENTAL FUNCTIONS
+ ****************************************************************************************
+ * The definitions in the following section are considered experimental.
+ * They are provided for advanced scenarios.
+ * They should never be used with a dynamic library, as prototypes may change in the future.
+ * Use them only in association with static linking.
+ * ***************************************************************************************/
+
+#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
+#define ZSTD_H_ZSTD_STATIC_LINKING_ONLY
+
+
+/****************************************************************************************
+ * Candidate API for promotion to stable status
+ ****************************************************************************************
+ * The following symbols and constants form the "staging area" :
+ * they are considered to join "stable API" by v1.4.0.
+ * The proposal is written so that it can be made stable "as is",
+ * though it's still possible to suggest improvements.
+ * Staging is in fact last chance for changes,
+ * the API is locked once reaching "stable" status.
+ * ***************************************************************************************/
+
+
+/* === Constants === */
+
+/* all magic numbers are supposed read/written to/from files/memory using little-endian convention */
+#define ZSTD_MAGICNUMBER 0xFD2FB528 /* valid since v0.8.0 */
+#define ZSTD_MAGIC_DICTIONARY 0xEC30A437 /* valid since v0.7.0 */
+#define ZSTD_MAGIC_SKIPPABLE_START 0x184D2A50 /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */
+#define ZSTD_MAGIC_SKIPPABLE_MASK 0xFFFFFFF0
+
+#define ZSTD_BLOCKSIZELOG_MAX 17
+#define ZSTD_BLOCKSIZE_MAX (1<<ZSTD_BLOCKSIZELOG_MAX)
+
+
+/* === query limits === */
+
+ZSTDLIB_API int ZSTD_minCLevel(void); /*!< minimum negative compression level allowed */
+
+
+/* === frame size === */
+
+/*! ZSTD_findFrameCompressedSize() :
+ * `src` should point to the start of a ZSTD frame or skippable frame.
+ * `srcSize` must be >= first frame size
+ * @return : the compressed size of the first frame starting at `src`,
+ * suitable to pass as `srcSize` to `ZSTD_decompress` or similar,
+ * or an error code if input is invalid */
+ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize);
+
+
+/* === Memory management === */
+
+/*! ZSTD_sizeof_*() :
+ * These functions give the _current_ memory usage of selected object.
+ * Note that object memory usage can evolve (increase or decrease) over time. */
+ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx);
+ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx);
+ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs);
+ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds);
+ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict);
+ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);
+
+
+/***************************************
+* Advanced compression API
+***************************************/
+
+/* API design :
+ * Parameters are pushed one by one into an existing context,
+ * using ZSTD_CCtx_set*() functions.
+ * Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame.
+ * "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` !
+ * They do not apply to "simple" one-shot variants such as ZSTD_compressCCtx()
+ *
+ * It's possible to reset all parameters to "default" using ZSTD_CCtx_reset().
+ *
+ * This API supercedes all other "advanced" API entry points in the experimental section.
+ * In the future, we expect to remove from experimental API entry points which are redundant with this API.
+ */
+
+
+/* Compression strategies, listed from fastest to strongest */
+typedef enum { ZSTD_fast=1,
+ ZSTD_dfast=2,
+ ZSTD_greedy=3,
+ ZSTD_lazy=4,
+ ZSTD_lazy2=5,
+ ZSTD_btlazy2=6,
+ ZSTD_btopt=7,
+ ZSTD_btultra=8,
+ ZSTD_btultra2=9
+ /* note : new strategies _might_ be added in the future.
+ Only the order (from fast to strong) is guaranteed */
+} ZSTD_strategy;
+
+
+typedef enum {
+
+ /* compression parameters */
+ ZSTD_c_compressionLevel=100, /* Update all compression parameters according to pre-defined cLevel table
+ * Default level is ZSTD_CLEVEL_DEFAULT==3.
+ * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT.
+ * Note 1 : it's possible to pass a negative compression level.
+ * Note 2 : setting a level sets all default values of other compression parameters */
+ ZSTD_c_windowLog=101, /* Maximum allowed back-reference distance, expressed as power of 2.
+ * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX.
+ * Special: value 0 means "use default windowLog".
+ * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT
+ * requires explicitly allowing such window size at decompression stage if using streaming. */
+ ZSTD_c_hashLog=102, /* Size of the initial probe table, as a power of 2.
+ * Resulting memory usage is (1 << (hashLog+2)).
+ * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX.
+ * Larger tables improve compression ratio of strategies <= dFast,
+ * and improve speed of strategies > dFast.
+ * Special: value 0 means "use default hashLog". */
+ ZSTD_c_chainLog=103, /* Size of the multi-probe search table, as a power of 2.
+ * Resulting memory usage is (1 << (chainLog+2)).
+ * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX.
+ * Larger tables result in better and slower compression.
+ * This parameter is useless when using "fast" strategy.
+ * It's still useful when using "dfast" strategy,
+ * in which case it defines a secondary probe table.
+ * Special: value 0 means "use default chainLog". */
+ ZSTD_c_searchLog=104, /* Number of search attempts, as a power of 2.
+ * More attempts result in better and slower compression.
+ * This parameter is useless when using "fast" and "dFast" strategies.
+ * Special: value 0 means "use default searchLog". */
+ ZSTD_c_minMatch=105, /* Minimum size of searched matches.
+ * Note that Zstandard can still find matches of smaller size,
+ * it just tweaks its search algorithm to look for this size and larger.
+ * Larger values increase compression and decompression speed, but decrease ratio.
+ * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX.
+ * Note that currently, for all strategies < btopt, effective minimum is 4.
+ * , for all strategies > fast, effective maximum is 6.
+ * Special: value 0 means "use default minMatchLength". */
+ ZSTD_c_targetLength=106, /* Impact of this field depends on strategy.
+ * For strategies btopt, btultra & btultra2:
+ * Length of Match considered "good enough" to stop search.
+ * Larger values make compression stronger, and slower.
+ * For strategy fast:
+ * Distance between match sampling.
+ * Larger values make compression faster, and weaker.
+ * Special: value 0 means "use default targetLength". */
+ ZSTD_c_strategy=107, /* See ZSTD_strategy enum definition.
+ * The higher the value of selected strategy, the more complex it is,
+ * resulting in stronger and slower compression.
+ * Special: value 0 means "use default strategy". */
+
+ /* LDM mode parameters */
+ ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching.
+ * This parameter is designed to improve compression ratio
+ * for large inputs, by finding large matches at long distance.
+ * It increases memory usage and window size.
+ * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB
+ * except when expressly set to a different value. */
+ ZSTD_c_ldmHashLog=161, /* Size of the table for long distance matching, as a power of 2.
+ * Larger values increase memory usage and compression ratio,
+ * but decrease compression speed.
+ * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX
+ * default: windowlog - 7.
+ * Special: value 0 means "automatically determine hashlog". */
+ ZSTD_c_ldmMinMatch=162, /* Minimum match size for long distance matcher.
+ * Larger/too small values usually decrease compression ratio.
+ * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX.
+ * Special: value 0 means "use default value" (default: 64). */
+ ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution.
+ * Larger values improve collision resolution but decrease compression speed.
+ * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX.
+ * Special: value 0 means "use default value" (default: 3). */
+ ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table.
+ * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN).
+ * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage.
+ * Larger values improve compression speed.
+ * Deviating far from default value will likely result in a compression ratio decrease.
+ * Special: value 0 means "automatically determine hashRateLog". */
+
+ /* frame parameters */
+ ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1)
+ * Content size must be known at the beginning of compression.
+ * This is automatically the case when using ZSTD_compress2(),
+ * For streaming variants, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */
+ ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */
+ ZSTD_c_dictIDFlag=202, /* When applicable, dictionary's ID is written into frame header (default:1) */
+
+ /* multi-threading parameters */
+ /* These parameters are only useful if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD).
+ * They return an error otherwise. */
+ ZSTD_c_nbWorkers=400, /* Select how many threads will be spawned to compress in parallel.
+ * When nbWorkers >= 1, triggers asynchronous mode when used with ZSTD_compressStream*() :
+ * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller,
+ * while compression work is performed in parallel, within worker threads.
+ * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end :
+ * in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call).
+ * More workers improve speed, but also increase memory usage.
+ * Default value is `0`, aka "single-threaded mode" : no worker is spawned, compression is performed inside Caller's thread, all invocations are blocking */
+ ZSTD_c_jobSize=401, /* Size of a compression job. This value is enforced only when nbWorkers >= 1.
+ * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads.
+ * 0 means default, which is dynamically determined based on compression parameters.
+ * Job size must be a minimum of overlap size, or 1 MB, whichever is largest.
+ * The minimum size is automatically and transparently enforced */
+ ZSTD_c_overlapLog=402, /* Control the overlap size, as a fraction of window size.
+ * The overlap size is an amount of data reloaded from previous job at the beginning of a new job.
+ * It helps preserve compression ratio, while each job is compressed in parallel.
+ * This value is enforced only when nbWorkers >= 1.
+ * Larger values increase compression ratio, but decrease speed.
+ * Possible values range from 0 to 9 :
+ * - 0 means "default" : value will be determined by the library, depending on strategy
+ * - 1 means "no overlap"
+ * - 9 means "full overlap", using a full window size.
+ * Each intermediate rank increases/decreases load size by a factor 2 :
+ * 9: full window; 8: w/2; 7: w/4; 6: w/8; 5:w/16; 4: w/32; 3:w/64; 2:w/128; 1:no overlap; 0:default
+ * default value varies between 6 and 9, depending on strategy */
+
+ /* note : additional experimental parameters are also available
+ * within the experimental section of the API.
+ * At the time of this writing, they include :
+ * ZSTD_c_rsyncable
+ * ZSTD_c_format
+ * ZSTD_c_forceMaxWindow
+ * ZSTD_c_forceAttachDict
+ * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
+ * note : never ever use experimentalParam? names directly;
+ * also, the enums values themselves are unstable and can still change.
+ */
+ ZSTD_c_experimentalParam1=500,
+ ZSTD_c_experimentalParam2=10,
+ ZSTD_c_experimentalParam3=1000,
+ ZSTD_c_experimentalParam4=1001
+} ZSTD_cParameter;
+
+
+typedef struct {
+ size_t error;
+ int lowerBound;
+ int upperBound;
+} ZSTD_bounds;
+
+/*! ZSTD_cParam_getBounds() :
+ * All parameters must belong to an interval with lower and upper bounds,
+ * otherwise they will either trigger an error or be automatically clamped.
+ * @return : a structure, ZSTD_bounds, which contains
+ * - an error status field, which must be tested using ZSTD_isError()
+ * - lower and upper bounds, both inclusive
+ */
+ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam);
+
+/*! ZSTD_CCtx_setParameter() :
+ * Set one compression parameter, selected by enum ZSTD_cParameter.
+ * All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds().
+ * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).
+ * Setting a parameter is generally only possible during frame initialization (before starting compression).
+ * Exception : when using multi-threading mode (nbWorkers >= 1),
+ * the following parameters can be updated _during_ compression (within same frame):
+ * => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy.
+ * new parameters will be active for next job only (after a flush()).
+ * @return : an error code (which can be tested using ZSTD_isError()).
+ */
+ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value);
+
+/*! ZSTD_CCtx_setPledgedSrcSize() :
+ * Total input data size to be compressed as a single frame.
+ * Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag.
+ * This value will also be controlled at end of frame, and trigger an error if not respected.
+ * @result : 0, or an error code (which can be tested with ZSTD_isError()).
+ * Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame.
+ * In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN.
+ * ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame.
+ * Note 2 : pledgedSrcSize is only valid once, for the next frame.
+ * It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN.
+ * Note 3 : Whenever all input data is provided and consumed in a single round,
+ * for example with ZSTD_compress2(),
+ * or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end),
+ * this value is automatically overriden by srcSize instead.
+ */
+ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize);
+
+/*! ZSTD_CCtx_loadDictionary() :
+ * Create an internal CDict from `dict` buffer.
+ * Decompression will have to use same dictionary.
+ * @result : 0, or an error code (which can be tested with ZSTD_isError()).
+ * Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary,
+ * meaning "return to no-dictionary mode".
+ * Note 1 : Dictionary is sticky, it will be used for all future compressed frames.
+ * To return to "no-dictionary" situation, load a NULL dictionary (or reset parameters).
+ * Note 2 : Loading a dictionary involves building tables.
+ * It's also a CPU consuming operation, with non-negligible impact on latency.
+ * Tables are dependent on compression parameters, and for this reason,
+ * compression parameters can no longer be changed after loading a dictionary.
+ * Note 3 :`dict` content will be copied internally.
+ * Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead.
+ * In such a case, dictionary buffer must outlive its users.
+ * Note 4 : Use ZSTD_CCtx_loadDictionary_advanced()
+ * to precisely select how dictionary content must be interpreted. */
+ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);
+
+/*! ZSTD_CCtx_refCDict() :
+ * Reference a prepared dictionary, to be used for all next compressed frames.
+ * Note that compression parameters are enforced from within CDict,
+ * and supercede any compression parameter previously set within CCtx.
+ * The dictionary will remain valid for future compressed frames using same CCtx.
+ * @result : 0, or an error code (which can be tested with ZSTD_isError()).
+ * Special : Referencing a NULL CDict means "return to no-dictionary mode".
+ * Note 1 : Currently, only one dictionary can be managed.
+ * Referencing a new dictionary effectively "discards" any previous one.
+ * Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */
+ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);
+
+/*! ZSTD_CCtx_refPrefix() :
+ * Reference a prefix (single-usage dictionary) for next compressed frame.
+ * A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end).
+ * Decompression will need same prefix to properly regenerate data.
+ * Compressing with a prefix is similar in outcome as performing a diff and compressing it,
+ * but performs much faster, especially during decompression (compression speed is tunable with compression level).
+ * @result : 0, or an error code (which can be tested with ZSTD_isError()).
+ * Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary
+ * Note 1 : Prefix buffer is referenced. It **must** outlive compression.
+ * Its content must remain unmodified during compression.
+ * Note 2 : If the intention is to diff some large src data blob with some prior version of itself,
+ * ensure that the window size is large enough to contain the entire source.
+ * See ZSTD_c_windowLog.
+ * Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters.
+ * It's a CPU consuming operation, with non-negligible impact on latency.
+ * If there is a need to use the same prefix multiple times, consider loadDictionary instead.
+ * Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dm_rawContent).
+ * Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */
+ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx,
+ const void* prefix, size_t prefixSize);
+
+
+typedef enum {
+ ZSTD_reset_session_only = 1,
+ ZSTD_reset_parameters = 2,
+ ZSTD_reset_session_and_parameters = 3
+} ZSTD_ResetDirective;
+
+/*! ZSTD_CCtx_reset() :
+ * There are 2 different things that can be reset, independently or jointly :
+ * - The session : will stop compressing current frame, and make CCtx ready to start a new one.
+ * Useful after an error, or to interrupt any ongoing compression.
+ * Any internal data not yet flushed is cancelled.
+ * Compression parameters and dictionary remain unchanged.
+ * They will be used to compress next frame.
+ * Resetting session never fails.
+ * - The parameters : changes all parameters back to "default".
+ * This removes any reference to any dictionary too.
+ * Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing)
+ * otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError())
+ * - Both : similar to resetting the session, followed by resetting parameters.
+ */
+ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset);
+
+
+
+/*! ZSTD_compress2() :
+ * Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API.
+ * ZSTD_compress2() always starts a new frame.
+ * Should cctx hold data from a previously unfinished frame, everything about it is forgotten.
+ * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()
+ * - The function is always blocking, returns when compression is completed.
+ * Hint : compression runs faster if `dstCapacity` >= `ZSTD_compressBound(srcSize)`.
+ * @return : compressed size written into `dst` (<= `dstCapacity),
+ * or an error code if it fails (which can be tested using ZSTD_isError()).
+ */
+ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize);
+
+typedef enum {
+ ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */
+ ZSTD_e_flush=1, /* flush any data provided so far,
+ * it creates (at least) one new block, that can be decoded immediately on reception;
+ * frame will continue: any future data can still reference previously compressed data, improving compression. */
+ ZSTD_e_end=2 /* flush any remaining data _and_ close current frame.
+ * note that frame is only closed after compressed data is fully flushed (return value == 0).
+ * After that point, any additional data starts a new frame.
+ * note : each frame is independent (does not reference any content from previous frame). */
+} ZSTD_EndDirective;
+
+/*! ZSTD_compressStream2() :
+ * Behaves about the same as ZSTD_compressStream, with additional control on end directive.
+ * - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()
+ * - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode)
+ * - outpot->pos must be <= dstCapacity, input->pos must be <= srcSize
+ * - outpot->pos and input->pos will be updated. They are guaranteed to remain below their respective limit.
+ * - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller.
+ * - When nbWorkers>=1, function is non-blocking : it just acquires a copy of input, and distributes jobs to internal worker threads, flush whatever is available,
+ * and then immediately returns, just indicating that there is some data remaining to be flushed.
+ * The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte.
+ * - Exception : if the first call requests a ZSTD_e_end directive and provides enough dstCapacity, the function delegates to ZSTD_compress2() which is always blocking.
+ * - @return provides a minimum amount of data remaining to be flushed from internal buffers
+ * or an error code, which can be tested using ZSTD_isError().
+ * if @return != 0, flush is not fully completed, there is still some data left within internal buffers.
+ * This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers.
+ * For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed.
+ * - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0),
+ * only ZSTD_e_end or ZSTD_e_flush operations are allowed.
+ * Before starting a new compression job, or changing compression parameters,
+ * it is required to fully flush internal buffers.
+ */
+ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
+ ZSTD_outBuffer* output,
+ ZSTD_inBuffer* input,
+ ZSTD_EndDirective endOp);
+
+
+
+/* ============================== */
+/* Advanced decompression API */
+/* ============================== */
+
+/* The advanced API pushes parameters one by one into an existing DCtx context.
+ * Parameters are sticky, and remain valid for all following frames
+ * using the same DCtx context.
+ * It's possible to reset parameters to default values using ZSTD_DCtx_reset().
+ * Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream().
+ * Therefore, no new decompression function is necessary.
+ */
+
+
+typedef enum {
+
+ ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which
+ * the streaming API will refuse to allocate memory buffer
+ * in order to protect the host from unreasonable memory requirements.
+ * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.
+ * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) */
+
+ /* note : additional experimental parameters are also available
+ * within the experimental section of the API.
+ * At the time of this writing, they include :
+ * ZSTD_c_format
+ * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
+ * note : never ever use experimentalParam? names directly
+ */
+ ZSTD_d_experimentalParam1=1000
+
+} ZSTD_dParameter;
+
+
+/*! ZSTD_dParam_getBounds() :
+ * All parameters must belong to an interval with lower and upper bounds,
+ * otherwise they will either trigger an error or be automatically clamped.
+ * @return : a structure, ZSTD_bounds, which contains
+ * - an error status field, which must be tested using ZSTD_isError()
+ * - both lower and upper bounds, inclusive
+ */
+ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam);
+
+/*! ZSTD_DCtx_setParameter() :
+ * Set one compression parameter, selected by enum ZSTD_dParameter.
+ * All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds().
+ * Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).
+ * Setting a parameter is only possible during frame initialization (before starting decompression).
+ * @return : 0, or an error code (which can be tested using ZSTD_isError()).
+ */
+ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value);
+
+
+/*! ZSTD_DCtx_loadDictionary() :
+ * Create an internal DDict from dict buffer,
+ * to be used to decompress next frames.
+ * The dictionary remains valid for all future frames, until explicitly invalidated.
+ * @result : 0, or an error code (which can be tested with ZSTD_isError()).
+ * Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary,
+ * meaning "return to no-dictionary mode".
+ * Note 1 : Loading a dictionary involves building tables,
+ * which has a non-negligible impact on CPU usage and latency.
+ * It's recommended to "load once, use many times", to amortize the cost
+ * Note 2 :`dict` content will be copied internally, so `dict` can be released after loading.
+ * Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead.
+ * Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of
+ * how dictionary content is loaded and interpreted.
+ */
+ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);
+
+/*! ZSTD_DCtx_refDDict() :
+ * Reference a prepared dictionary, to be used to decompress next frames.
+ * The dictionary remains active for decompression of future frames using same DCtx.
+ * @result : 0, or an error code (which can be tested with ZSTD_isError()).
+ * Note 1 : Currently, only one dictionary can be managed.
+ * Referencing a new dictionary effectively "discards" any previous one.
+ * Special: referencing a NULL DDict means "return to no-dictionary mode".
+ * Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx.
+ */
+ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);
+
+/*! ZSTD_DCtx_refPrefix() :
+ * Reference a prefix (single-usage dictionary) to decompress next frame.
+ * This is the reverse operation of ZSTD_CCtx_refPrefix(),
+ * and must use the same prefix as the one used during compression.
+ * Prefix is **only used once**. Reference is discarded at end of frame.
+ * End of frame is reached when ZSTD_decompressStream() returns 0.
+ * @result : 0, or an error code (which can be tested with ZSTD_isError()).
+ * Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary
+ * Note 2 : Prefix buffer is referenced. It **must** outlive decompression.
+ * Prefix buffer must remain unmodified up to the end of frame,
+ * reached when ZSTD_decompressStream() returns 0.
+ * Note 3 : By default, the prefix is treated as raw content (ZSTD_dm_rawContent).
+ * Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section)
+ * Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost.
+ * A full dictionary is more costly, as it requires building tables.
+ */
+ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx,
+ const void* prefix, size_t prefixSize);
+
+/*! ZSTD_DCtx_reset() :
+ * Return a DCtx to clean state.
+ * Session and parameters can be reset jointly or separately.
+ * Parameters can only be reset when no active frame is being decompressed.
+ * @return : 0, or an error code, which can be tested with ZSTD_isError()
+ */
+ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset);
+
+
+
+/****************************************************************************************
+ * experimental API (static linking only)
+ ****************************************************************************************
+ * The following symbols and constants
+ * are not planned to join "stable API" status in the near future.
+ * They can still change in future versions.
+ * Some of them are planned to remain in the static_only section indefinitely.
+ * Some of them might be removed in the future (especially when redundant with existing stable functions)
+ * ***************************************************************************************/
+
+#define ZSTD_FRAMEHEADERSIZE_PREFIX 5 /* minimum input size required to query frame header size */
+#define ZSTD_FRAMEHEADERSIZE_MIN 6
+#define ZSTD_FRAMEHEADERSIZE_MAX 18 /* can be useful for static allocation */
+#define ZSTD_SKIPPABLEHEADERSIZE 8
+
+/* compression parameter bounds */
+#define ZSTD_WINDOWLOG_MAX_32 30
+#define ZSTD_WINDOWLOG_MAX_64 31
+#define ZSTD_WINDOWLOG_MAX ((int)(sizeof(size_t) == 4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64))
+#define ZSTD_WINDOWLOG_MIN 10
+#define ZSTD_HASHLOG_MAX ((ZSTD_WINDOWLOG_MAX < 30) ? ZSTD_WINDOWLOG_MAX : 30)
+#define ZSTD_HASHLOG_MIN 6
+#define ZSTD_CHAINLOG_MAX_32 29
+#define ZSTD_CHAINLOG_MAX_64 30
+#define ZSTD_CHAINLOG_MAX ((int)(sizeof(size_t) == 4 ? ZSTD_CHAINLOG_MAX_32 : ZSTD_CHAINLOG_MAX_64))
+#define ZSTD_CHAINLOG_MIN ZSTD_HASHLOG_MIN
+#define ZSTD_SEARCHLOG_MAX (ZSTD_WINDOWLOG_MAX-1)
+#define ZSTD_SEARCHLOG_MIN 1
+#define ZSTD_MINMATCH_MAX 7 /* only for ZSTD_fast, other strategies are limited to 6 */
+#define ZSTD_MINMATCH_MIN 3 /* only for ZSTD_btopt+, faster strategies are limited to 4 */
+#define ZSTD_TARGETLENGTH_MAX ZSTD_BLOCKSIZE_MAX
+#define ZSTD_TARGETLENGTH_MIN 0 /* note : comparing this constant to an unsigned results in a tautological test */
+#define ZSTD_STRATEGY_MIN ZSTD_fast
+#define ZSTD_STRATEGY_MAX ZSTD_btultra2
+
+
+#define ZSTD_OVERLAPLOG_MIN 0
+#define ZSTD_OVERLAPLOG_MAX 9
+
+#define ZSTD_WINDOWLOG_LIMIT_DEFAULT 27 /* by default, the streaming decoder will refuse any frame
+ * requiring larger than (1<<ZSTD_WINDOWLOG_LIMIT_DEFAULT) window size,
+ * to preserve host's memory from unreasonable requirements.
+ * This limit can be overriden using ZSTD_DCtx_setParameter(,ZSTD_d_windowLogMax,).
+ * The limit does not apply for one-pass decoders (such as ZSTD_decompress()), since no additional memory is allocated */
+
+
+/* LDM parameter bounds */
+#define ZSTD_LDM_HASHLOG_MIN ZSTD_HASHLOG_MIN
+#define ZSTD_LDM_HASHLOG_MAX ZSTD_HASHLOG_MAX
+#define ZSTD_LDM_MINMATCH_MIN 4
+#define ZSTD_LDM_MINMATCH_MAX 4096
+#define ZSTD_LDM_BUCKETSIZELOG_MIN 1
+#define ZSTD_LDM_BUCKETSIZELOG_MAX 8
+#define ZSTD_LDM_HASHRATELOG_MIN 0
+#define ZSTD_LDM_HASHRATELOG_MAX (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN)
+
+/* internal */
+#define ZSTD_HASHLOG3_MAX 17
+
+
+/* --- Advanced types --- */
+
+typedef struct ZSTD_CCtx_params_s ZSTD_CCtx_params;
+
+typedef struct {
+ unsigned windowLog; /**< largest match distance : larger == more compression, more memory needed during decompression */
+ unsigned chainLog; /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */
+ unsigned hashLog; /**< dispatch table : larger == faster, more memory */
+ unsigned searchLog; /**< nb of searches : larger == more compression, slower */
+ unsigned minMatch; /**< match length searched : larger == faster decompression, sometimes less compression */
+ unsigned targetLength; /**< acceptable match size for optimal parser (only) : larger == more compression, slower */
+ ZSTD_strategy strategy; /**< see ZSTD_strategy definition above */
+} ZSTD_compressionParameters;
+
+typedef struct {
+ int contentSizeFlag; /**< 1: content size will be in frame header (when known) */
+ int checksumFlag; /**< 1: generate a 32-bits checksum using XXH64 algorithm at end of frame, for error detection */
+ int noDictIDFlag; /**< 1: no dictID will be saved into frame header (dictID is only useful for dictionary compression) */
+} ZSTD_frameParameters;
+
+typedef struct {
+ ZSTD_compressionParameters cParams;
+ ZSTD_frameParameters fParams;
+} ZSTD_parameters;
+
+typedef enum {
+ ZSTD_dct_auto = 0, /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */
+ ZSTD_dct_rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */
+ ZSTD_dct_fullDict = 2 /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */
+} ZSTD_dictContentType_e;
+
+typedef enum {
+ ZSTD_dlm_byCopy = 0, /**< Copy dictionary content internally */
+ ZSTD_dlm_byRef = 1, /**< Reference dictionary content -- the dictionary buffer must outlive its users. */
+} ZSTD_dictLoadMethod_e;
+
+typedef enum {
+ /* Opened question : should we have a format ZSTD_f_auto ?
+ * Today, it would mean exactly the same as ZSTD_f_zstd1.
+ * But, in the future, should several formats become supported,
+ * on the compression side, it would mean "default format".
+ * On the decompression side, it would mean "automatic format detection",
+ * so that ZSTD_f_zstd1 would mean "accept *only* zstd frames".
+ * Since meaning is a little different, another option could be to define different enums for compression and decompression.
+ * This question could be kept for later, when there are actually multiple formats to support,
+ * but there is also the question of pinning enum values, and pinning value `0` is especially important */
+ ZSTD_f_zstd1 = 0, /* zstd frame format, specified in zstd_compression_format.md (default) */
+ ZSTD_f_zstd1_magicless = 1, /* Variant of zstd frame format, without initial 4-bytes magic number.
+ * Useful to save 4 bytes per generated frame.
+ * Decoder cannot recognise automatically this format, requiring this instruction. */
+} ZSTD_format_e;
+
+typedef enum {
+ /* Note: this enum and the behavior it controls are effectively internal
+ * implementation details of the compressor. They are expected to continue
+ * to evolve and should be considered only in the context of extremely
+ * advanced performance tuning.
+ *
+ * Zstd currently supports the use of a CDict in two ways:
+ *
+ * - The contents of the CDict can be copied into the working context. This
+ * means that the compression can search both the dictionary and input
+ * while operating on a single set of internal tables. This makes
+ * the compression faster per-byte of input. However, the initial copy of
+ * the CDict's tables incurs a fixed cost at the beginning of the
+ * compression. For small compressions (< 8 KB), that copy can dominate
+ * the cost of the compression.
+ *
+ * - The CDict's tables can be used in-place. In this model, compression is
+ * slower per input byte, because the compressor has to search two sets of
+ * tables. However, this model incurs no start-up cost (as long as the
+ * working context's tables can be reused). For small inputs, this can be
+ * faster than copying the CDict's tables.
+ *
+ * Zstd has a simple internal heuristic that selects which strategy to use
+ * at the beginning of a compression. However, if experimentation shows that
+ * Zstd is making poor choices, it is possible to override that choice with
+ * this enum.
+ */
+ ZSTD_dictDefaultAttach = 0, /* Use the default heuristic. */
+ ZSTD_dictForceAttach = 1, /* Never copy the dictionary. */
+ ZSTD_dictForceCopy = 2, /* Always copy the dictionary. */
+} ZSTD_dictAttachPref_e;
+
+
+/***************************************
+* Frame size functions
+***************************************/
+
+/*! ZSTD_findDecompressedSize() :
+ * `src` should point the start of a series of ZSTD encoded and/or skippable frames
+ * `srcSize` must be the _exact_ size of this series
+ * (i.e. there should be a frame boundary exactly at `srcSize` bytes after `src`)
+ * @return : - decompressed size of all data in all successive frames
+ * - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN
+ * - if an error occurred: ZSTD_CONTENTSIZE_ERROR
+ *
+ * note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode.
+ * When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.
+ * In which case, it's necessary to use streaming mode to decompress data.
+ * note 2 : decompressed size is always present when compression is done with ZSTD_compress()
+ * note 3 : decompressed size can be very large (64-bits value),
+ * potentially larger than what local system can handle as a single memory segment.
+ * In which case, it's necessary to use streaming mode to decompress data.
+ * note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified.
+ * Always ensure result fits within application's authorized limits.
+ * Each application can set its own limits.
+ * note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to
+ * read each contained frame header. This is fast as most of the data is skipped,
+ * however it does mean that all frame data must be present and valid. */
+ZSTDLIB_API unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize);
+
+/*! ZSTD_frameHeaderSize() :
+ * srcSize must be >= ZSTD_FRAMEHEADERSIZE_PREFIX.
+ * @return : size of the Frame Header,
+ * or an error code (if srcSize is too small) */
+ZSTDLIB_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize);
+
+
+/***************************************
+* Memory management
+***************************************/
+
+/*! ZSTD_estimate*() :
+ * These functions make it possible to estimate memory usage
+ * of a future {D,C}Ctx, before its creation.
+ * ZSTD_estimateCCtxSize() will provide a budget large enough for any compression level up to selected one.
+ * It will also consider src size to be arbitrarily "large", which is worst case.
+ * If srcSize is known to always be small, ZSTD_estimateCCtxSize_usingCParams() can provide a tighter estimation.
+ * ZSTD_estimateCCtxSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel.
+ * ZSTD_estimateCCtxSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParam_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1.
+ * Note : CCtx size estimation is only correct for single-threaded compression. */
+ZSTDLIB_API size_t ZSTD_estimateCCtxSize(int compressionLevel);
+ZSTDLIB_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams);
+ZSTDLIB_API size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params);
+ZSTDLIB_API size_t ZSTD_estimateDCtxSize(void);
+
+/*! ZSTD_estimateCStreamSize() :
+ * ZSTD_estimateCStreamSize() will provide a budget large enough for any compression level up to selected one.
+ * It will also consider src size to be arbitrarily "large", which is worst case.
+ * If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation.
+ * ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel.
+ * ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParam_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1.
+ * Note : CStream size estimation is only correct for single-threaded compression.
+ * ZSTD_DStream memory budget depends on window Size.
+ * This information can be passed manually, using ZSTD_estimateDStreamSize,
+ * or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame();
+ * Note : if streaming is init with function ZSTD_init?Stream_usingDict(),
+ * an internal ?Dict will be created, which additional size is not estimated here.
+ * In this case, get total size by adding ZSTD_estimate?DictSize */
+ZSTDLIB_API size_t ZSTD_estimateCStreamSize(int compressionLevel);
+ZSTDLIB_API size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams);
+ZSTDLIB_API size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params);
+ZSTDLIB_API size_t ZSTD_estimateDStreamSize(size_t windowSize);
+ZSTDLIB_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize);
+
+/*! ZSTD_estimate?DictSize() :
+ * ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict().
+ * ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced().
+ * Note : dictionaries created by reference (`ZSTD_dlm_byRef`) are logically smaller.
+ */
+ZSTDLIB_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel);
+ZSTDLIB_API size_t ZSTD_estimateCDictSize_advanced(size_t dictSize, ZSTD_compressionParameters cParams, ZSTD_dictLoadMethod_e dictLoadMethod);
+ZSTDLIB_API size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod);
+
+/*! ZSTD_initStatic*() :
+ * Initialize an object using a pre-allocated fixed-size buffer.
+ * workspace: The memory area to emplace the object into.
+ * Provided pointer *must be 8-bytes aligned*.
+ * Buffer must outlive object.
+ * workspaceSize: Use ZSTD_estimate*Size() to determine
+ * how large workspace must be to support target scenario.
+ * @return : pointer to object (same address as workspace, just different type),
+ * or NULL if error (size too small, incorrect alignment, etc.)
+ * Note : zstd will never resize nor malloc() when using a static buffer.
+ * If the object requires more memory than available,
+ * zstd will just error out (typically ZSTD_error_memory_allocation).
+ * Note 2 : there is no corresponding "free" function.
+ * Since workspace is allocated externally, it must be freed externally too.
+ * Note 3 : cParams : use ZSTD_getCParams() to convert a compression level
+ * into its associated cParams.
+ * Limitation 1 : currently not compatible with internal dictionary creation, triggered by
+ * ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict().
+ * Limitation 2 : static cctx currently not compatible with multi-threading.
+ * Limitation 3 : static dctx is incompatible with legacy support.
+ */
+ZSTDLIB_API ZSTD_CCtx* ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize);
+ZSTDLIB_API ZSTD_CStream* ZSTD_initStaticCStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticCCtx() */
+
+ZSTDLIB_API ZSTD_DCtx* ZSTD_initStaticDCtx(void* workspace, size_t workspaceSize);
+ZSTDLIB_API ZSTD_DStream* ZSTD_initStaticDStream(void* workspace, size_t workspaceSize); /**< same as ZSTD_initStaticDCtx() */
+
+ZSTDLIB_API const ZSTD_CDict* ZSTD_initStaticCDict(
+ void* workspace, size_t workspaceSize,
+ const void* dict, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_compressionParameters cParams);
+
+ZSTDLIB_API const ZSTD_DDict* ZSTD_initStaticDDict(
+ void* workspace, size_t workspaceSize,
+ const void* dict, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType);
+
+
+/*! Custom memory allocation :
+ * These prototypes make it possible to pass your own allocation/free functions.
+ * ZSTD_customMem is provided at creation time, using ZSTD_create*_advanced() variants listed below.
+ * All allocation/free operations will be completed using these custom variants instead of regular <stdlib.h> ones.
+ */
+typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size);
+typedef void (*ZSTD_freeFunction) (void* opaque, void* address);
+typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem;
+static ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL }; /**< this constant defers to stdlib's functions */
+
+ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx_advanced(ZSTD_customMem customMem);
+ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem);
+ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem);
+ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem);
+
+ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_compressionParameters cParams,
+ ZSTD_customMem customMem);
+
+ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize,
+ ZSTD_dictLoadMethod_e dictLoadMethod,
+ ZSTD_dictContentType_e dictContentType,
+ ZSTD_customMem customMem);
+
+
+
+/***************************************
+* Advanced compression functions
+***************************************/
+
+/*! ZSTD_createCDict_byReference() :
+ * Create a digested dictionary for compression
+ * Dictionary content is just referenced, not duplicated.
+ * As a consequence, `dictBuffer` **must** outlive CDict,
+ * and its content must remain unmodified throughout the lifetime of CDict. */
+ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_byReference(const void* dictBuffer, size_t dictSize, int compressionLevel);
+
+/*! ZSTD_getCParams() :
+* @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize.
+* `estimatedSrcSize` value is optional, select 0 if not known */
+ZSTDLIB_API ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);
+
+/*! ZSTD_getParams() :
+* same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`.
+* All fields of `ZSTD_frameParameters` are set to default : contentSize=1, checksum=0, noDictID=0 */
+ZSTDLIB_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);
+
+/*! ZSTD_checkCParams() :
+* Ensure param values remain within authorized range */
+ZSTDLIB_API size_t ZSTD_checkCParams(ZSTD_compressionParameters params);
+
+/*! ZSTD_adjustCParams() :
+ * optimize params for a given `srcSize` and `dictSize`.
+ * both values are optional, select `0` if unknown. */
+ZSTDLIB_API ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize);
+
+/*! ZSTD_compress_advanced() :
+ * Same as ZSTD_compress_usingDict(), with fine-tune control over compression parameters (by structure) */
+ZSTDLIB_API size_t ZSTD_compress_advanced(ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const void* dict,size_t dictSize,
+ ZSTD_parameters params);
+
+/*! ZSTD_compress_usingCDict_advanced() :
+ * Same as ZSTD_compress_usingCDict(), with fine-tune control over frame parameters */
+ZSTDLIB_API size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity,
+ const void* src, size_t srcSize,
+ const ZSTD_CDict* cdict,
+ ZSTD_frameParameters fParams);
+
+
+/*! ZSTD_CCtx_loadDictionary_byReference() :
+ * Same as ZSTD_CCtx_loadDictionary(), but dictionary content is referenced, instead of being copied into CCtx.
+ * It saves some memory, but also requires that `dict` outlives its usage within `cctx` */
+ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);
+
+/*! ZSTD_CCtx_loadDictionary_advanced() :
+ * Same as ZSTD_CCtx_loadDictionary(), but gives finer control over
+ * how to load the dictionary (by copy ? by reference ?)
+ * and how to interpret it (automatic ? force raw mode ? full mode only ?) */
+ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType);
+
+/*! ZSTD_CCtx_refPrefix_advanced() :
+ * Same as ZSTD_CCtx_refPrefix(), but gives finer control over
+ * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */
+ZSTDLIB_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType);
+
+/* === experimental parameters === */
+/* these parameters can be used with ZSTD_setParameter()
+ * they are not guaranteed to remain supported in the future */
+
+ /* Enables rsyncable mode,
+ * which makes compressed files more rsync friendly
+ * by adding periodic synchronization points to the compressed data.
+ * The target average block size is ZSTD_c_jobSize / 2.
+ * It's possible to modify the job size to increase or decrease
+ * the granularity of the synchronization point.
+ * Once the jobSize is smaller than the window size,
+ * it will result in compression ratio degradation.
+ * NOTE 1: rsyncable mode only works when multithreading is enabled.
+ * NOTE 2: rsyncable performs poorly in combination with long range mode,
+ * since it will decrease the effectiveness of synchronization points,
+ * though mileage may vary.
+ * NOTE 3: Rsyncable mode limits maximum compression speed to ~400 MB/s.
+ * If the selected compression level is already running significantly slower,
+ * the overall speed won't be significantly impacted.
+ */
+ #define ZSTD_c_rsyncable ZSTD_c_experimentalParam1
+
+/* Select a compression format.
+ * The value must be of type ZSTD_format_e.
+ * See ZSTD_format_e enum definition for details */
+#define ZSTD_c_format ZSTD_c_experimentalParam2
+
+/* Force back-reference distances to remain < windowSize,
+ * even when referencing into Dictionary content (default:0) */
+#define ZSTD_c_forceMaxWindow ZSTD_c_experimentalParam3
+
+/* Controls whether the contents of a CDict
+ * are used in place, or copied into the working context.
+ * Accepts values from the ZSTD_dictAttachPref_e enum.
+ * See the comments on that enum for an explanation of the feature. */
+#define ZSTD_c_forceAttachDict ZSTD_c_experimentalParam4
+
+/*! ZSTD_CCtx_getParameter() :
+ * Get the requested compression parameter value, selected by enum ZSTD_cParameter,
+ * and store it into int* value.
+ * @return : 0, or an error code (which can be tested with ZSTD_isError()).
+ */
+ZSTDLIB_API size_t ZSTD_CCtx_getParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value);
+
+
+/*! ZSTD_CCtx_params :
+ * Quick howto :
+ * - ZSTD_createCCtxParams() : Create a ZSTD_CCtx_params structure
+ * - ZSTD_CCtxParam_setParameter() : Push parameters one by one into
+ * an existing ZSTD_CCtx_params structure.
+ * This is similar to
+ * ZSTD_CCtx_setParameter().
+ * - ZSTD_CCtx_setParametersUsingCCtxParams() : Apply parameters to
+ * an existing CCtx.
+ * These parameters will be applied to
+ * all subsequent frames.
+ * - ZSTD_compressStream2() : Do compression using the CCtx.
+ * - ZSTD_freeCCtxParams() : Free the memory.
+ *
+ * This can be used with ZSTD_estimateCCtxSize_advanced_usingCCtxParams()
+ * for static allocation of CCtx for single-threaded compression.
+ */
+ZSTDLIB_API ZSTD_CCtx_params* ZSTD_createCCtxParams(void);
+ZSTDLIB_API size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params);
+
+/*! ZSTD_CCtxParams_reset() :
+ * Reset params to default values.
+ */
+ZSTDLIB_API size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params);
+
+/*! ZSTD_CCtxParams_init() :
+ * Initializes the compression parameters of cctxParams according to
+ * compression level. All other parameters are reset to their default values.
+ */
+ZSTDLIB_API size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel);
+
+/*! ZSTD_CCtxParams_init_advanced() :
+ * Initializes the compression and frame parameters of cctxParams according to
+ * params. All other parameters are reset to their default values.
+ */
+ZSTDLIB_API size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params);
+
+/*! ZSTD_CCtxParam_setParameter() :
+ * Similar to ZSTD_CCtx_setParameter.
+ * Set one compression parameter, selected by enum ZSTD_cParameter.
+ * Parameters must be applied to a ZSTD_CCtx using ZSTD_CCtx_setParametersUsingCCtxParams().
+ * @result : 0, or an error code (which can be tested with ZSTD_isError()).
+ */
+ZSTDLIB_API size_t ZSTD_CCtxParam_setParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int value);
+
+/*! ZSTD_CCtxParam_getParameter() :
+ * Similar to ZSTD_CCtx_getParameter.
+ * Get the requested value of one compression parameter, selected by enum ZSTD_cParameter.
+ * @result : 0, or an error code (which can be tested with ZSTD_isError()).
+ */
+ZSTDLIB_API size_t ZSTD_CCtxParam_getParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int* value);
+
+/*! ZSTD_CCtx_setParametersUsingCCtxParams() :
+ * Apply a set of ZSTD_CCtx_params to the compression context.
+ * This can be done even after compression is started,
+ * if nbWorkers==0, this will have no impact until a new compression is started.
+ * if nbWorkers>=1, new parameters will be picked up at next job,
+ * with a few restrictions (windowLog, pledgedSrcSize, nbWorkers, jobSize, and overlapLog are not updated).
+ */
+ZSTDLIB_API size_t ZSTD_CCtx_setParametersUsingCCtxParams(
+ ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params);
+
+/*! ZSTD_compressStream2_simpleArgs() :
+ * Same as ZSTD_compressStream2(),
+ * but using only integral types as arguments.
+ * This variant might be helpful for binders from dynamic languages
+ * which have troubles handling structures containing memory pointers.
+ */
+ZSTDLIB_API size_t ZSTD_compressStream2_simpleArgs (
+ ZSTD_CCtx* cctx,
+ void* dst, size_t dstCapacity, size_t* dstPos,
+ const void* src, size_t srcSize, size_t* srcPos,
+ ZSTD_EndDirective endOp);
+
+
+/***************************************
+* Advanced decompression functions
+***************************************/
+
+/*! ZSTD_isFrame() :
+ * Tells if the content of `buffer` starts with a valid Frame Identifier.
+ * Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
+ * Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
+ * Note 3 : Skippable Frame Identifiers are considered valid. */
+ZSTDLIB_API unsigned ZSTD_isFrame(const void* buffer, size_t size);
+
+/*! ZSTD_createDDict_byReference() :
+ * Create a digested dictionary, ready to start decompression operation without startup delay.
+ * Dictionary content is referenced, and therefore stays in dictBuffer.
+ * It is important that dictBuffer outlives DDict,
+ * it must remain read accessible throughout the lifetime of DDict */
+ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize);
+
+
+/*! ZSTD_getDictID_fromDict() :
+ * Provides the dictID stored within dictionary.
+ * if @return == 0, the dictionary is not conformant with Zstandard specification.
+ * It can still be loaded, but as a content-only dictionary. */
+ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize);
+
+/*! ZSTD_getDictID_fromDDict() :
+ * Provides the dictID of the dictionary loaded into `ddict`.
+ * If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
+ * Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
+ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict);
+
+/*! ZSTD_getDictID_fromFrame() :
+ * Provides the dictID required to decompressed the frame stored within `src`.
+ * If @return == 0, the dictID could not be decoded.
+ * This could for one of the following reasons :
+ * - The frame does not require a dictionary to be decoded (most common case).
+ * - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden information.
+ * Note : this use case also happens when using a non-conformant dictionary.
+ * - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`).
+ * - This is not a Zstandard frame.
+ * When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */
+ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize);
+
+/*! ZSTD_DCtx_loadDictionary_byReference() :
+ * Same as ZSTD_DCtx_loadDictionary(),
+ * but references `dict` content instead of copying it into `dctx`.
+ * This saves memory if `dict` remains around.,
+ * However, it's imperative that `dict` remains accessible (and unmodified) while being used, so it must outlive decompression. */
+ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);
+
+/*! ZSTD_DCtx_loadDictionary_advanced() :
+ * Same as ZSTD_DCtx_loadDictionary(),
+ * but gives direct control over
+ * how to load the dictionary (by copy ? by reference ?)
+ * and how to interpret it (automatic ? force raw mode ? full mode only ?). */
+ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType);
+
+/*! ZSTD_DCtx_refPrefix_advanced() :
+ * Same as ZSTD_DCtx_refPrefix(), but gives finer control over
+ * how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */
+ZSTDLIB_API size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType);
+
+/*! ZSTD_DCtx_setMaxWindowSize() :
+ * Refuses allocating internal buffers for frames requiring a window size larger than provided limit.
+ * This protects a decoder context from reserving too much memory for itself (potential attack scenario).
+ * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.
+ * By default, a decompression context accepts all window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT)
+ * @return : 0, or an error code (which can be tested using ZSTD_isError()).
+ */
+ZSTDLIB_API size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize);
+
+/* ZSTD_d_format
+ * experimental parameter,
+ * allowing selection between ZSTD_format_e input compression formats
+ */
+#define ZSTD_d_format ZSTD_d_experimentalParam1
+
+/*! ZSTD_DCtx_setFormat() :
+ * Instruct the decoder context about what kind of data to decode next.
+ * This instruction is mandatory to decode data without a fully-formed header,
+ * such ZSTD_f_zstd1_magicless for example.
+ * @return : 0, or an error code (which can be tested using ZSTD_isError()). */
+ZSTDLIB_API size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format);
+
+/*! ZSTD_decompressStream_simpleArgs() :
+ * Same as ZSTD_decompressStream(),
+ * but using only integral types as arguments.
+ * This can be helpful for binders from dynamic languages
+ * which have troubles handling structures containing memory pointers.
+ */
+ZSTDLIB_API size_t ZSTD_decompressStream_simpleArgs (
+ ZSTD_DCtx* dctx,
+ void* dst, size_t dstCapacity, size_t* dstPos,
+ const void* src, size_t srcSize, size_t* srcPos);
+
+
+/********************************************************************
+* Advanced streaming functions
+* Warning : most of these functions are now redundant with the Advanced API.
+* Once Advanced API reaches "stable" status,
+* redundant functions will be deprecated, and then at some point removed.
+********************************************************************/
+
+/*===== Advanced Streaming compression functions =====*/
+ZSTDLIB_API size_t ZSTD_initCStream_srcSize(ZSTD_CStream* zcs, int compressionLevel, unsigned long long pledgedSrcSize); /**< pledgedSrcSize must be correct. If it is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN. Note that, for compatibility with older programs, "0" also disables frame content size field. It may be enabled in the future. */
+ZSTDLIB_API size_t ZSTD_initCStream_usingDict(ZSTD_CStream* zcs, const void* dict, size_t dictSize, int compressionLevel); /**< creates of an internal CDict (incompatible with static CCtx), except if dict == NULL or dictSize < 8, in which case no dict is used. Note: dict is loaded with ZSTD_dm_auto (treated as a full zstd dictionary if it begins with ZSTD_MAGIC_DICTIONARY, else as raw content) and ZSTD_dlm_byCopy.*/
+ZSTDLIB_API size_t ZSTD_initCStream_advanced(ZSTD_CStream* zcs, const void* dict, size_t dictSize,
+ ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize must be correct. If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN. dict is loaded with ZSTD_dm_auto and ZSTD_dlm_byCopy. */
+ZSTDLIB_API size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict); /**< note : cdict will just be referenced, and must outlive compression session */
+ZSTDLIB_API size_t ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs, const ZSTD_CDict* cdict, ZSTD_frameParameters fParams, unsigned long long pledgedSrcSize); /**< same as ZSTD_initCStream_usingCDict(), with control over frame parameters. pledgedSrcSize must be correct. If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN. */
+
+/*! ZSTD_resetCStream() :
+ * start a new frame, using same parameters from previous frame.
+ * This is typically useful to skip dictionary loading stage, since it will re-use it in-place.
+ * Note that zcs must be init at least once before using ZSTD_resetCStream().
+ * If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN.
+ * If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end.
+ * For the time being, pledgedSrcSize==0 is interpreted as "srcSize unknown" for compatibility with older programs,
+ * but it will change to mean "empty" in future version, so use macro ZSTD_CONTENTSIZE_UNKNOWN instead.
+ * @return : 0, or an error code (which can be tested using ZSTD_isError())
+ */
+ZSTDLIB_API size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize);
+
+
+typedef struct {
+ unsigned long long ingested; /* nb input bytes read and buffered */
+ unsigned long long consumed; /* nb input bytes actually compressed */
+ unsigned long long produced; /* nb of compressed bytes generated and buffered */
+ unsigned long long flushed; /* nb of compressed bytes flushed : not provided; can be tracked from caller side */
+ unsigned currentJobID; /* MT only : latest started job nb */
+ unsigned nbActiveWorkers; /* MT only : nb of workers actively compressing at probe time */
+} ZSTD_frameProgression;
+
+/* ZSTD_getFrameProgression() :
+ * tells how much data has been ingested (read from input)
+ * consumed (input actually compressed) and produced (output) for current frame.
+ * Note : (ingested - consumed) is amount of input data buffered internally, not yet compressed.
+ * Aggregates progression inside active worker threads.
+ */
+ZSTDLIB_API ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx);
+
+/*! ZSTD_toFlushNow() :
+ * Tell how many bytes are ready to be flushed immediately.
+ * Useful for multithreading scenarios (nbWorkers >= 1).
+ * Probe the oldest active job, defined as oldest job not yet entirely flushed,
+ * and check its output buffer.
+ * @return : amount of data stored in oldest job and ready to be flushed immediately.
+ * if @return == 0, it means either :
+ * + there is no active job (could be checked with ZSTD_frameProgression()), or
+ * + oldest job is still actively compressing data,
+ * but everything it has produced has also been flushed so far,
+ * therefore flush speed is limited by production speed of oldest job
+ * irrespective of the speed of concurrent (and newer) jobs.
+ */
+ZSTDLIB_API size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx);
+
+
+/*===== Advanced Streaming decompression functions =====*/
+ZSTDLIB_API size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize); /**< note: no dictionary will be used if dict == NULL or dictSize < 8 */
+ZSTDLIB_API size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const ZSTD_DDict* ddict); /**< note : ddict is referenced, it must outlive decompression session */
+ZSTDLIB_API size_t ZSTD_resetDStream(ZSTD_DStream* zds); /**< re-use decompression parameters from previous init; saves dictionary loading */
+
+
+/*********************************************************************
+* Buffer-less and synchronous inner streaming functions
+*
+* This is an advanced API, giving full control over buffer management, for users which need direct control over memory.
+* But it's also a complex one, with several restrictions, documented below.
+* Prefer normal streaming API for an easier experience.
+********************************************************************* */
+
+/**
+ Buffer-less streaming compression (synchronous mode)
+
+ A ZSTD_CCtx object is required to track streaming operations.
+ Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource.
+ ZSTD_CCtx object can be re-used multiple times within successive compression operations.
+
+ Start by initializing a context.
+ Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression,
+ or ZSTD_compressBegin_advanced(), for finer parameter control.
+ It's also possible to duplicate a reference context which has already been initialized, using ZSTD_copyCCtx()
+
+ Then, consume your input using ZSTD_compressContinue().
+ There are some important considerations to keep in mind when using this advanced function :
+ - ZSTD_compressContinue() has no internal buffer. It uses externally provided buffers only.
+ - Interface is synchronous : input is consumed entirely and produces 1+ compressed blocks.
+ - Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario.
+ Worst case evaluation is provided by ZSTD_compressBound().
+ ZSTD_compressContinue() doesn't guarantee recover after a failed compression.
+ - ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog).
+ It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks)
+ - ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps.
+ In which case, it will "discard" the relevant memory section from its history.
+
+ Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum.
+ It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame.
+ Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders.
+
+ `ZSTD_CCtx` object can be re-used (ZSTD_compressBegin()) to compress again.
+*/
+
+/*===== Buffer-less streaming compression functions =====*/
+ZSTDLIB_API size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel);
+ZSTDLIB_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel);
+ZSTDLIB_API size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize : If srcSize is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN */
+ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */
+ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict, ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize); /* compression parameters are already set within cdict. pledgedSrcSize must be correct. If srcSize is not known, use macro ZSTD_CONTENTSIZE_UNKNOWN */
+ZSTDLIB_API size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**< note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN */
+
+ZSTDLIB_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
+ZSTDLIB_API size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
+
+
+/*-
+ Buffer-less streaming decompression (synchronous mode)
+
+ A ZSTD_DCtx object is required to track streaming operations.
+ Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it.
+ A ZSTD_DCtx object can be re-used multiple times.
+
+ First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader().
+ Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough.
+ Data fragment must be large enough to ensure successful decoding.
+ `ZSTD_frameHeaderSize_max` bytes is guaranteed to always be large enough.
+ @result : 0 : successful decoding, the `ZSTD_frameHeader` structure is correctly filled.
+ >0 : `srcSize` is too small, please provide at least @result bytes on next attempt.
+ errorCode, which can be tested using ZSTD_isError().
+
+ It fills a ZSTD_frameHeader structure with important information to correctly decode the frame,
+ such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`).
+ Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information.
+ As a consequence, check that values remain within valid application range.
+ For example, do not allocate memory blindly, check that `windowSize` is within expectation.
+ Each application can set its own limits, depending on local restrictions.
+ For extended interoperability, it is recommended to support `windowSize` of at least 8 MB.
+
+ ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize` bytes.
+ ZSTD_decompressContinue() is very sensitive to contiguity,
+ if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place,
+ or that previous contiguous segment is large enough to properly handle maximum back-reference distance.
+ There are multiple ways to guarantee this condition.
+
+ The most memory efficient way is to use a round buffer of sufficient size.
+ Sufficient size is determined by invoking ZSTD_decodingBufferSize_min(),
+ which can @return an error code if required value is too large for current system (in 32-bits mode).
+ In a round buffer methodology, ZSTD_decompressContinue() decompresses each block next to previous one,
+ up to the moment there is not enough room left in the buffer to guarantee decoding another full block,
+ which maximum size is provided in `ZSTD_frameHeader` structure, field `blockSizeMax`.
+ At which point, decoding can resume from the beginning of the buffer.
+ Note that already decoded data stored in the buffer should be flushed before being overwritten.
+
+ There are alternatives possible, for example using two or more buffers of size `windowSize` each, though they consume more memory.
+
+ Finally, if you control the compression process, you can also ignore all buffer size rules,
+ as long as the encoder and decoder progress in "lock-step",
+ aka use exactly the same buffer sizes, break contiguity at the same place, etc.
+
+ Once buffers are setup, start decompression, with ZSTD_decompressBegin().
+ If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict().
+
+ Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively.
+ ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue().
+ ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail.
+
+ @result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity).
+ It can be zero : it just means ZSTD_decompressContinue() has decoded some metadata item.
+ It can also be an error code, which can be tested with ZSTD_isError().
+
+ A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero.
+ Context can then be reset to start a new decompression.
+
+ Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType().
+ This information is not required to properly decode a frame.
+
+ == Special case : skippable frames ==
+
+ Skippable frames allow integration of user-defined data into a flow of concatenated frames.
+ Skippable frames will be ignored (skipped) by decompressor.
+ The format of skippable frames is as follows :
+ a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F
+ b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits
+ c) Frame Content - any content (User Data) of length equal to Frame Size
+ For skippable frames ZSTD_getFrameHeader() returns zfhPtr->frameType==ZSTD_skippableFrame.
+ For skippable frames ZSTD_decompressContinue() always returns 0 : it only skips the content.
+*/
+
+/*===== Buffer-less streaming decompression functions =====*/
+typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_frameType_e;
+typedef struct {
+ unsigned long long frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */
+ unsigned long long windowSize; /* can be very large, up to <= frameContentSize */
+ unsigned blockSizeMax;
+ ZSTD_frameType_e frameType; /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */
+ unsigned headerSize;
+ unsigned dictID;
+ unsigned checksumFlag;
+} ZSTD_frameHeader;
+
+/** ZSTD_getFrameHeader() :
+ * decode Frame Header, or requires larger `srcSize`.
+ * @return : 0, `zfhPtr` is correctly filled,
+ * >0, `srcSize` is too small, value is wanted `srcSize` amount,
+ * or an error code, which can be tested using ZSTD_isError() */
+ZSTDLIB_API size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize); /**< doesn't consume input */
+/*! ZSTD_getFrameHeader_advanced() :
+ * same as ZSTD_getFrameHeader(),
+ * with added capability to select a format (like ZSTD_f_zstd1_magicless) */
+ZSTDLIB_API size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format);
+ZSTDLIB_API size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize); /**< when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN */
+
+ZSTDLIB_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx);
+ZSTDLIB_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);
+ZSTDLIB_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);
+
+ZSTDLIB_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx);
+ZSTDLIB_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
+
+/* misc */
+ZSTDLIB_API void ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx);
+typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e;
+ZSTDLIB_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx);
+
+
+
+
+/* ============================ */
+/** Block level API */
+/* ============================ */
+
+/*!
+ Block functions produce and decode raw zstd blocks, without frame metadata.
+ Frame metadata cost is typically ~18 bytes, which can be non-negligible for very small blocks (< 100 bytes).
+ User will have to take in charge required information to regenerate data, such as compressed and content sizes.
+
+ A few rules to respect :
+ - Compressing and decompressing require a context structure
+ + Use ZSTD_createCCtx() and ZSTD_createDCtx()
+ - It is necessary to init context before starting
+ + compression : any ZSTD_compressBegin*() variant, including with dictionary
+ + decompression : any ZSTD_decompressBegin*() variant, including with dictionary
+ + copyCCtx() and copyDCtx() can be used too
+ - Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX == 128 KB
+ + If input is larger than a block size, it's necessary to split input data into multiple blocks
+ + For inputs larger than a single block, really consider using regular ZSTD_compress() instead.
+ Frame metadata is not that costly, and quickly becomes negligible as source size grows larger.
+ - When a block is considered not compressible enough, ZSTD_compressBlock() result will be zero.
+ In which case, nothing is produced into `dst` !
+ + User must test for such outcome and deal directly with uncompressed data
+ + ZSTD_decompressBlock() doesn't accept uncompressed data as input !!!
+ + In case of multiple successive blocks, should some of them be uncompressed,
+ decoder must be informed of their existence in order to follow proper history.
+ Use ZSTD_insertBlock() for such a case.
+*/
+
+/*===== Raw zstd block functions =====*/
+ZSTDLIB_API size_t ZSTD_getBlockSize (const ZSTD_CCtx* cctx);
+ZSTDLIB_API size_t ZSTD_compressBlock (ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
+ZSTDLIB_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
+ZSTDLIB_API size_t ZSTD_insertBlock (ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize); /**< insert uncompressed block into `dctx` history. Useful for multi-blocks decompression. */
+
+
+#endif /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */
+
+#if defined (__cplusplus)
+}
+#endif
diff --git a/packaging/cmake.spec b/packaging/cmake.spec
index 17d399bf2..75f8226cf 100644
--- a/packaging/cmake.spec
+++ b/packaging/cmake.spec
@@ -45,8 +45,7 @@ export LDFLAGS="-ltinfo"
--no-system-curl \
--no-system-jsoncpp \
--no-system-librhash \
- --no-system-libuv \
- --no-system-form
+ --no-system-libuv
%__make VERBOSE=1 %{?_smp_mflags}
%install